@hyperwindmill/caretaker-cli 0.27.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/web/scheduler/telegram.d.ts +27 -0
- package/dist/cli/web/scheduler/telegram.d.ts.map +1 -1
- package/dist/cli/web/scheduler/telegram.js +133 -78
- package/dist/cli/web/scheduler/telegram_media.d.ts +73 -0
- package/dist/cli/web/scheduler/telegram_media.d.ts.map +1 -0
- package/dist/cli/web/scheduler/telegram_media.js +90 -0
- package/dist/cli/web/scheduler/telegram_window.d.ts +68 -0
- package/dist/cli/web/scheduler/telegram_window.d.ts.map +1 -0
- package/dist/cli/web/scheduler/telegram_window.js +144 -0
- package/dist/harness/acp_policy.d.ts +1 -1
- package/dist/harness/acp_policy.d.ts.map +1 -1
- package/dist/harness/acp_pool.d.ts +1 -1
- package/dist/harness/acp_pool.d.ts.map +1 -1
- package/dist/harness/acp_pool.js +5 -1
- package/dist/tui/agents.d.ts +1 -1
- package/dist/tui/agents.d.ts.map +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.d.ts.map +1 -1
- package/dist/tui/chat.d.ts +1 -1
- package/dist/tui/chat.d.ts.map +1 -1
- package/dist/tui/logo.d.ts +1 -1
- package/dist/tui/logo.d.ts.map +1 -1
- package/dist/tui/mcp_servers.d.ts +1 -1
- package/dist/tui/mcp_servers.d.ts.map +1 -1
- package/dist/tui/plugins.d.ts +1 -1
- package/dist/tui/plugins.d.ts.map +1 -1
- package/dist/tui/providers.d.ts +1 -1
- package/dist/tui/providers.d.ts.map +1 -1
- package/dist/webview/standalone.js +5116 -3783
- package/dist/webview/standalone.js.map +4 -4
- package/dist/webview/vad/ort-wasm-simd-threaded.mjs +48 -47
- package/dist/webview/vad/ort-wasm-simd-threaded.wasm +0 -0
- package/package.json +33 -33
|
@@ -1,7 +1,34 @@
|
|
|
1
|
+
import * as harness from '../../../harness/index.js';
|
|
2
|
+
import type { ToolAttachmentRecord } from '../../../session/types.js';
|
|
3
|
+
import type { ServiceConfig } from '../../../types.js';
|
|
4
|
+
import { type PendingChat } from './telegram_window.js';
|
|
5
|
+
import { type TgUpdate } from './telegram_media.js';
|
|
1
6
|
import type { SchedulerStrategy } from './strategy.js';
|
|
2
7
|
export declare function saveTelegramOffset(taskId: string, updateId: number): Promise<void>;
|
|
3
8
|
export declare function loadTelegramOffset(taskId: string): Promise<number | undefined>;
|
|
4
9
|
export declare function splitMessage(text: string, maxLen?: number): string[];
|
|
10
|
+
/**
|
|
11
|
+
* Background loop step execution run specifically formatted for interactive Telegram conversations.
|
|
12
|
+
*/
|
|
13
|
+
export declare function executeTelegramTaskRun(task: ServiceConfig, chat: PendingChat, deps?: {
|
|
14
|
+
run?: typeof harness.run;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
export interface TickDeps {
|
|
17
|
+
downloadImage: (sessionId: string, media: {
|
|
18
|
+
fileId: string;
|
|
19
|
+
fileSize?: number;
|
|
20
|
+
}) => Promise<ToolAttachmentRecord>;
|
|
21
|
+
notify: (chatId: number, text: string) => Promise<void>;
|
|
22
|
+
isLocked: (chatId: number) => boolean;
|
|
23
|
+
runChat: (chat: PendingChat) => Promise<void>;
|
|
24
|
+
now: () => number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* One tick of the accumulation window: fold the new updates into the per-chat
|
|
28
|
+
* buffer, then deliver every window that is ready. Split out of the poller so
|
|
29
|
+
* it can be driven without the Telegram API.
|
|
30
|
+
*/
|
|
31
|
+
export declare function accumulateAndFlush(taskId: string, updates: TgUpdate[], allowedChats: Set<string>, deps: TickDeps): Promise<void>;
|
|
5
32
|
export declare function runTelegramPollerTick(): Promise<void>;
|
|
6
33
|
export declare const TelegramStrategy: SchedulerStrategy;
|
|
7
34
|
//# sourceMappingURL=telegram.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telegram.d.ts","sourceRoot":"","sources":["../../../../src/cli/web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,IAAI,CAAC,CAAC;IACxD,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;IACtC,OAAO,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,GAAG,EAAE,MAAM,MAAM,CAAC;CACnB;AASD;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,QAAQ,EAAE,EACnB,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,EACzB,IAAI,EAAE,QAAQ,GACb,OAAO,CAAC,IAAI,CAAC,CA6Ff;AAiDD,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiB3D;AAED,eAAO,MAAM,gBAAgB,EAAE,iBAK9B,CAAC"}
|
|
@@ -1,39 +1,20 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import {
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
5
|
import * as harness from '../../../harness/index.js';
|
|
6
6
|
import { loadAgents, loadConfig } from '../../../store/json.js';
|
|
7
7
|
import { __forTesting, readSession, createSession, appendMessage, userMessage, } from '../../../session/store.js';
|
|
8
8
|
import { decrypt, isEncrypted } from '../../../lib/encryption.js';
|
|
9
9
|
import { schedulerLogsDir, ensureSchedulerLogsDir } from './logs.js';
|
|
10
10
|
import { runningTasks } from './locks.js';
|
|
11
|
+
import { atomicWriteFile, buildMergedPrompt, decideFlush, isAtCapacity, loadPendingState, savePendingState, telegramSessionId, } from './telegram_window.js';
|
|
12
|
+
import { classifyMessage, downloadImage, messageText, selectImage, senderLabel, FileTooLargeError, } from './telegram_media.js';
|
|
11
13
|
export async function saveTelegramOffset(taskId, updateId) {
|
|
12
14
|
// The offset is committed before any run is logged, so this can be the very
|
|
13
15
|
// first write into scheduler-logs/ — the dir may not exist yet.
|
|
14
16
|
await ensureSchedulerLogsDir();
|
|
15
|
-
|
|
16
|
-
const tmpPath = `${path}.tmp.${process.pid}.${Date.now()}`;
|
|
17
|
-
await writeFile(tmpPath, String(updateId), 'utf8');
|
|
18
|
-
// Same rationale as store/json.ts writeJson: retry rename on Windows-style
|
|
19
|
-
// transient lock errors before propagating.
|
|
20
|
-
const maxAttempts = process.platform === 'win32' ? 5 : 1;
|
|
21
|
-
let lastErr;
|
|
22
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
23
|
-
try {
|
|
24
|
-
await rename(tmpPath, path);
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
catch (err) {
|
|
28
|
-
lastErr = err;
|
|
29
|
-
const code = err.code;
|
|
30
|
-
const retryable = code === 'EACCES' || code === 'EPERM' || code === 'EBUSY';
|
|
31
|
-
if (attempt === maxAttempts || !retryable)
|
|
32
|
-
break;
|
|
33
|
-
await new Promise((r) => setTimeout(r, 50 * 2 ** (attempt - 1)));
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
throw lastErr;
|
|
17
|
+
await atomicWriteFile(join(schedulerLogsDir(), `${taskId}.offset`), String(updateId));
|
|
37
18
|
}
|
|
38
19
|
export async function loadTelegramOffset(taskId) {
|
|
39
20
|
const path = join(schedulerLogsDir(), `${taskId}.offset`);
|
|
@@ -133,27 +114,21 @@ const pollingTasks = new Set();
|
|
|
133
114
|
/**
|
|
134
115
|
* Background loop step execution run specifically formatted for interactive Telegram conversations.
|
|
135
116
|
*/
|
|
136
|
-
async function executeTelegramTaskRun(task,
|
|
117
|
+
export async function executeTelegramTaskRun(task, chat, deps = {}) {
|
|
137
118
|
let token = task.telegramBotToken?.trim() || '';
|
|
138
119
|
if (token && isEncrypted(token)) {
|
|
139
120
|
token = decrypt(token);
|
|
140
121
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
chat_id: msg.chat.id,
|
|
145
|
-
text: '⚠️ A session is already in progress in this chat. Please wait for it to complete.',
|
|
146
|
-
}).catch((err) => {
|
|
147
|
-
console.warn(`[scheduler/telegram] Failed to send busy notice to chat ${msg.chat.id}:`, err);
|
|
148
|
-
});
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
122
|
+
// No busy check here: the caller never flushes a window whose chat is
|
|
123
|
+
// locked, it holds the entries for the next tick instead.
|
|
124
|
+
const compoundLockKey = `${task.id}:${chat.chatId}`;
|
|
151
125
|
runningTasks.add(compoundLockKey);
|
|
152
126
|
const runId = `run_${randomUUID().slice(0, 8)}`;
|
|
153
|
-
const fromUser =
|
|
154
|
-
console.log(`[scheduler/telegram] Starting run ${runId} for user ${fromUser} in chat ${
|
|
127
|
+
const fromUser = chat.entries[0]?.fromLabel ?? 'User';
|
|
128
|
+
console.log(`[scheduler/telegram] Starting run ${runId} for user ${fromUser} in chat ${chat.chatId}`);
|
|
155
129
|
const runMessages = [];
|
|
156
|
-
const chatId =
|
|
130
|
+
const chatId = chat.chatId;
|
|
131
|
+
const promptAttachments = chat.entries.flatMap((e) => e.attachments);
|
|
157
132
|
let typingInterval = null;
|
|
158
133
|
const sendTyping = () => {
|
|
159
134
|
void tgApi(token, 'sendChatAction', { chat_id: chatId, action: 'typing' }).catch((err) => {
|
|
@@ -200,11 +175,8 @@ async function executeTelegramTaskRun(task, msg, updateId) {
|
|
|
200
175
|
const tools = await harness.resolveAgentTools(agent, harness.tools);
|
|
201
176
|
const workingDir = task.workingDir || agent.workingDir || process.cwd();
|
|
202
177
|
// Resolve the prompt format exactly as in the previous repository
|
|
203
|
-
const from = msg.from?.username
|
|
204
|
-
? `@${msg.from.username}`
|
|
205
|
-
: (msg.from?.first_name ?? 'unknown');
|
|
206
178
|
// Reconstruct conversation history using standard stable Chat Sessions
|
|
207
|
-
const sessionId =
|
|
179
|
+
const sessionId = telegramSessionId(chatId);
|
|
208
180
|
let sessionMeta;
|
|
209
181
|
let historyMessages = [];
|
|
210
182
|
const path = __forTesting.sessionPath(agent.id, sessionId);
|
|
@@ -221,20 +193,25 @@ async function executeTelegramTaskRun(task, msg, updateId) {
|
|
|
221
193
|
});
|
|
222
194
|
}
|
|
223
195
|
const isNewSession = historyMessages.length === 0;
|
|
224
|
-
const effectivePrompt = isNewSession
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
196
|
+
const effectivePrompt = buildMergedPrompt(chat, isNewSession);
|
|
197
|
+
// Persist the user prompt in the stable session history. The attachments
|
|
198
|
+
// ride the record too, so later turns replay the images.
|
|
199
|
+
const startMsg = userMessage(effectivePrompt, {
|
|
200
|
+
attachments: promptAttachments.length > 0 ? promptAttachments : undefined,
|
|
201
|
+
});
|
|
229
202
|
await appendMessage(sessionMeta, startMsg);
|
|
230
203
|
runMessages.push(startMsg);
|
|
231
|
-
await harness.run({
|
|
204
|
+
await (deps.run ?? harness.run)({
|
|
232
205
|
agent: { ...agent, permissionMode: 'bypassPermissions' }, // unattended: mirror the auto-approve confirm gate
|
|
233
206
|
provider,
|
|
234
207
|
tools,
|
|
235
208
|
prompt: effectivePrompt,
|
|
209
|
+
promptAttachments: promptAttachments.length > 0 ? promptAttachments : undefined,
|
|
236
210
|
history: historyMessages,
|
|
237
211
|
workingDir,
|
|
212
|
+
// Without this the harness resolves attachments under
|
|
213
|
+
// attachments/default/ and silently drops every image.
|
|
214
|
+
sessionId,
|
|
238
215
|
}, {
|
|
239
216
|
onMessage: async (msg) => {
|
|
240
217
|
// Persist all generated loop turns directly inside standard stable Session store!
|
|
@@ -316,6 +293,98 @@ async function executeTelegramTaskRun(task, msg, updateId) {
|
|
|
316
293
|
runningTasks.delete(compoundLockKey);
|
|
317
294
|
}
|
|
318
295
|
}
|
|
296
|
+
const UNSUPPORTED_NOTICE = "\u26a0\ufe0f I can only read text and images. I haven't passed that file to the agent.";
|
|
297
|
+
const TOO_LARGE_NOTICE = '\u26a0\ufe0f That image is too large for me to fetch (20 MB limit).';
|
|
298
|
+
const DOWNLOAD_FAILED_NOTICE = "\u26a0\ufe0f I couldn't download that image. Try sending it again.";
|
|
299
|
+
const OVER_CAPACITY_NOTICE = "\u26a0\ufe0f That's more than I can take in one go. I've kept what came first and skipped the rest \u2014 send it again after my reply.";
|
|
300
|
+
/**
|
|
301
|
+
* One tick of the accumulation window: fold the new updates into the per-chat
|
|
302
|
+
* buffer, then deliver every window that is ready. Split out of the poller so
|
|
303
|
+
* it can be driven without the Telegram API.
|
|
304
|
+
*/
|
|
305
|
+
export async function accumulateAndFlush(taskId, updates, allowedChats, deps) {
|
|
306
|
+
const state = await loadPendingState(taskId);
|
|
307
|
+
const now = deps.now();
|
|
308
|
+
for (const update of updates) {
|
|
309
|
+
const msg = update.message;
|
|
310
|
+
if (!msg)
|
|
311
|
+
continue;
|
|
312
|
+
// Authorization comes before any download: an unauthorized chat must not
|
|
313
|
+
// be able to put bytes on our disk.
|
|
314
|
+
const chatIdStr = String(msg.chat.id);
|
|
315
|
+
if (allowedChats.size > 0 && !allowedChats.has(chatIdStr)) {
|
|
316
|
+
console.log(`[scheduler/telegram] Skipping message in unauthorized chat ${chatIdStr}`);
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
const kind = classifyMessage(msg);
|
|
320
|
+
if (kind === 'service')
|
|
321
|
+
continue;
|
|
322
|
+
if (kind === 'unsupported') {
|
|
323
|
+
await deps.notify(msg.chat.id, UNSUPPORTED_NOTICE);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
let chat = state.chats[chatIdStr];
|
|
327
|
+
if (!chat) {
|
|
328
|
+
chat = {
|
|
329
|
+
chatId: msg.chat.id,
|
|
330
|
+
chatLabel: msg.chat.title ?? msg.chat.username ?? chatIdStr,
|
|
331
|
+
chatType: msg.chat.type,
|
|
332
|
+
entries: [],
|
|
333
|
+
firstAt: now,
|
|
334
|
+
};
|
|
335
|
+
state.chats[chatIdStr] = chat;
|
|
336
|
+
}
|
|
337
|
+
const media = selectImage(msg);
|
|
338
|
+
if (isAtCapacity(chat, media !== null)) {
|
|
339
|
+
await deps.notify(msg.chat.id, OVER_CAPACITY_NOTICE);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
let attachments = [];
|
|
343
|
+
if (media) {
|
|
344
|
+
try {
|
|
345
|
+
attachments = [await deps.downloadImage(telegramSessionId(msg.chat.id), media)];
|
|
346
|
+
}
|
|
347
|
+
catch (err) {
|
|
348
|
+
console.error(`[scheduler/telegram] Image download failed for chat ${chatIdStr}:`, err);
|
|
349
|
+
await deps.notify(msg.chat.id, err instanceof FileTooLargeError ? TOO_LARGE_NOTICE : DOWNLOAD_FAILED_NOTICE);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (chat.entries.length === 0)
|
|
354
|
+
chat.firstAt = now;
|
|
355
|
+
chat.entries.push({
|
|
356
|
+
updateId: update.update_id,
|
|
357
|
+
fromLabel: senderLabel(msg),
|
|
358
|
+
text: messageText(msg),
|
|
359
|
+
attachments,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
// Every chat is considered, including ones with no new update: hold expiry
|
|
363
|
+
// and post-lock delivery both happen on ticks that bring no traffic.
|
|
364
|
+
const toRun = [];
|
|
365
|
+
for (const [key, chat] of Object.entries(state.chats)) {
|
|
366
|
+
// The allowlist is the only access boundary, so it is re-checked here
|
|
367
|
+
// too: a chat revoked while its window was held must not still run.
|
|
368
|
+
if (allowedChats.size > 0 && !allowedChats.has(key)) {
|
|
369
|
+
delete state.chats[key];
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (deps.isLocked(chat.chatId))
|
|
373
|
+
continue;
|
|
374
|
+
if (decideFlush(chat, now) !== 'flush')
|
|
375
|
+
continue;
|
|
376
|
+
toRun.push({ ...chat, entries: chat.entries });
|
|
377
|
+
chat.entries = [];
|
|
378
|
+
chat.lastFlushAt = now;
|
|
379
|
+
}
|
|
380
|
+
// The window is consumed before the run, never after it: a failed run is
|
|
381
|
+
// reported in the chat by the run itself, and retrying it forever against a
|
|
382
|
+
// broken provider would burn tokens on every tick.
|
|
383
|
+
await savePendingState(taskId, state);
|
|
384
|
+
await Promise.all(toRun.map((chat) => deps.runChat(chat).catch((err) => {
|
|
385
|
+
console.error(`[scheduler/telegram] Run failed for chat ${chat.chatId}:`, err);
|
|
386
|
+
})));
|
|
387
|
+
}
|
|
319
388
|
async function executeTelegramPoller(task) {
|
|
320
389
|
if (pollingTasks.has(task.id))
|
|
321
390
|
return;
|
|
@@ -333,38 +402,24 @@ async function executeTelegramPoller(task) {
|
|
|
333
402
|
.filter(Boolean));
|
|
334
403
|
const offset = await loadTelegramOffset(task.id);
|
|
335
404
|
const updates = await tgGetUpdates(token, offset !== undefined ? offset + 1 : undefined);
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
// sequentially (preserves order, avoids "session already in progress" drops),
|
|
343
|
-
// while different chats progress in parallel.
|
|
344
|
-
const byChat = new Map();
|
|
345
|
-
for (const update of updates) {
|
|
346
|
-
const msg = update.message;
|
|
347
|
-
if (!msg || !msg.text)
|
|
348
|
-
continue;
|
|
349
|
-
const chatIdStr = String(msg.chat.id);
|
|
350
|
-
if (allowedChats.size > 0 && !allowedChats.has(chatIdStr)) {
|
|
351
|
-
console.log(`[scheduler/telegram] Skipping message in unauthorized chat ${chatIdStr}`);
|
|
352
|
-
continue;
|
|
353
|
-
}
|
|
354
|
-
const list = byChat.get(msg.chat.id) ?? [];
|
|
355
|
-
list.push({ update, msg });
|
|
356
|
-
byChat.set(msg.chat.id, list);
|
|
405
|
+
// No early return on an empty poll: a held window expires, and a window
|
|
406
|
+
// parked behind a running chat is delivered, on ticks with no new updates.
|
|
407
|
+
if (updates.length > 0) {
|
|
408
|
+
// Save the highest offset immediately to prevent reprocessing on subsequent ticks
|
|
409
|
+
const highestUpdate = updates[updates.length - 1];
|
|
410
|
+
await saveTelegramOffset(task.id, highestUpdate.update_id);
|
|
357
411
|
}
|
|
358
|
-
await
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
412
|
+
await accumulateAndFlush(task.id, updates, allowedChats, {
|
|
413
|
+
downloadImage: (sessionId, media) => downloadImage(token, sessionId, media),
|
|
414
|
+
notify: async (chatId, text) => {
|
|
415
|
+
await tgApi(token, 'sendMessage', { chat_id: chatId, text }).catch((err) => {
|
|
416
|
+
console.warn(`[scheduler/telegram] Failed to notify chat ${chatId}:`, err);
|
|
417
|
+
});
|
|
418
|
+
},
|
|
419
|
+
isLocked: (chatId) => runningTasks.has(`${task.id}:${chatId}`),
|
|
420
|
+
runChat: (chat) => executeTelegramTaskRun(task, chat),
|
|
421
|
+
now: () => Date.now(),
|
|
422
|
+
});
|
|
368
423
|
}
|
|
369
424
|
catch (err) {
|
|
370
425
|
console.error(`[scheduler/telegram] Polling error for task "${task.name}":`, err);
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { ToolAttachmentRecord } from '../../../session/types.js';
|
|
2
|
+
export interface TgPhotoSize {
|
|
3
|
+
file_id: string;
|
|
4
|
+
file_size?: number;
|
|
5
|
+
}
|
|
6
|
+
export interface TgDocument {
|
|
7
|
+
file_id: string;
|
|
8
|
+
file_size?: number;
|
|
9
|
+
mime_type?: string;
|
|
10
|
+
file_name?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface TgMessage {
|
|
13
|
+
message_id: number;
|
|
14
|
+
date: number;
|
|
15
|
+
chat: {
|
|
16
|
+
id: number;
|
|
17
|
+
type: string;
|
|
18
|
+
title?: string;
|
|
19
|
+
first_name?: string;
|
|
20
|
+
username?: string;
|
|
21
|
+
};
|
|
22
|
+
from?: {
|
|
23
|
+
id: number;
|
|
24
|
+
first_name: string;
|
|
25
|
+
username?: string;
|
|
26
|
+
};
|
|
27
|
+
text?: string;
|
|
28
|
+
caption?: string;
|
|
29
|
+
photo?: TgPhotoSize[];
|
|
30
|
+
document?: TgDocument;
|
|
31
|
+
video?: unknown;
|
|
32
|
+
audio?: unknown;
|
|
33
|
+
voice?: unknown;
|
|
34
|
+
sticker?: unknown;
|
|
35
|
+
animation?: unknown;
|
|
36
|
+
}
|
|
37
|
+
export interface TgUpdate {
|
|
38
|
+
update_id: number;
|
|
39
|
+
message?: TgMessage;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* `content` is a message the agent should answer, `unsupported` is media the
|
|
43
|
+
* user deliberately sent that we cannot deliver (it gets a spoken refusal),
|
|
44
|
+
* `service` is everything Telegram puts on the same channel that nobody is
|
|
45
|
+
* waiting for — joins, leaves, pins — which stays silent.
|
|
46
|
+
*/
|
|
47
|
+
export type MessageClass = 'content' | 'unsupported' | 'service';
|
|
48
|
+
export declare function classifyMessage(msg: TgMessage): MessageClass;
|
|
49
|
+
/** The largest photo size Telegram offers, or the image document. */
|
|
50
|
+
export declare function selectImage(msg: TgMessage): {
|
|
51
|
+
fileId: string;
|
|
52
|
+
fileSize?: number;
|
|
53
|
+
} | null;
|
|
54
|
+
export declare function messageText(msg: TgMessage): string | undefined;
|
|
55
|
+
export declare function senderLabel(msg: TgMessage): string;
|
|
56
|
+
/** Telegram's bot API will not serve a download above this. */
|
|
57
|
+
export declare const MAX_FILE_BYTES: number;
|
|
58
|
+
export declare class FileTooLargeError extends Error {
|
|
59
|
+
readonly size: number;
|
|
60
|
+
constructor(size: number);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Fetches the image and stores it in the chat's session attachment folder, so
|
|
64
|
+
* it is on disk before the window decides whether the turn runs now or in
|
|
65
|
+
* three minutes. `fetchImpl` keeps the tests off the network.
|
|
66
|
+
*/
|
|
67
|
+
export declare function downloadImage(token: string, sessionId: string, media: {
|
|
68
|
+
fileId: string;
|
|
69
|
+
fileSize?: number;
|
|
70
|
+
}, deps?: {
|
|
71
|
+
fetchImpl?: typeof fetch;
|
|
72
|
+
}): Promise<ToolAttachmentRecord>;
|
|
73
|
+
//# sourceMappingURL=telegram_media.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telegram_media.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/telegram_media.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,SAAS;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE;QACJ,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,IAAI,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,WAAW,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE,UAAU,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,QAAQ;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,CAAC;CACrB;AAED;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,aAAa,GAAG,SAAS,CAAC;AAMjE,wBAAgB,eAAe,CAAC,GAAG,EAAE,SAAS,GAAG,YAAY,CAiB5D;AAED,qEAAqE;AACrE,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CASxF;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAG9D;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,GAAG,MAAM,CAGlD;AAED,+DAA+D;AAC/D,eAAO,MAAM,cAAc,QAAmB,CAAC;AAE/C,qBAAa,iBAAkB,SAAQ,KAAK;aACd,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM;CAMzC;AAYD;;;;GAIG;AACH,wBAAsB,aAAa,CACjC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,GAAE;IAAE,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;CAAO,GACtC,OAAO,CAAC,oBAAoB,CAAC,CA8B/B"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { basename, extname } from 'node:path';
|
|
2
|
+
import { saveAttachment } from '../../../session/store.js';
|
|
3
|
+
function isImageDocument(doc) {
|
|
4
|
+
return !!doc?.mime_type?.startsWith('image/');
|
|
5
|
+
}
|
|
6
|
+
export function classifyMessage(msg) {
|
|
7
|
+
// Unsupported media is checked before the caption on purpose: delivering a
|
|
8
|
+
// video's caption without the video would have the agent answer about
|
|
9
|
+
// something it cannot see.
|
|
10
|
+
const hasUnsupported = !!msg.video ||
|
|
11
|
+
!!msg.audio ||
|
|
12
|
+
!!msg.voice ||
|
|
13
|
+
!!msg.sticker ||
|
|
14
|
+
!!msg.animation ||
|
|
15
|
+
(!!msg.document && !isImageDocument(msg.document));
|
|
16
|
+
if (hasUnsupported)
|
|
17
|
+
return 'unsupported';
|
|
18
|
+
if (messageText(msg) || (msg.photo && msg.photo.length > 0) || isImageDocument(msg.document)) {
|
|
19
|
+
return 'content';
|
|
20
|
+
}
|
|
21
|
+
return 'service';
|
|
22
|
+
}
|
|
23
|
+
/** The largest photo size Telegram offers, or the image document. */
|
|
24
|
+
export function selectImage(msg) {
|
|
25
|
+
if (msg.photo && msg.photo.length > 0) {
|
|
26
|
+
const largest = msg.photo[msg.photo.length - 1];
|
|
27
|
+
return { fileId: largest.file_id, fileSize: largest.file_size };
|
|
28
|
+
}
|
|
29
|
+
if (isImageDocument(msg.document)) {
|
|
30
|
+
return { fileId: msg.document.file_id, fileSize: msg.document.file_size };
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
export function messageText(msg) {
|
|
35
|
+
const raw = (msg.text ?? msg.caption ?? '').trim();
|
|
36
|
+
return raw.length > 0 ? raw : undefined;
|
|
37
|
+
}
|
|
38
|
+
export function senderLabel(msg) {
|
|
39
|
+
if (msg.from?.username)
|
|
40
|
+
return `@${msg.from.username}`;
|
|
41
|
+
return msg.from?.first_name || 'unknown';
|
|
42
|
+
}
|
|
43
|
+
/** Telegram's bot API will not serve a download above this. */
|
|
44
|
+
export const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
45
|
+
export class FileTooLargeError extends Error {
|
|
46
|
+
size;
|
|
47
|
+
constructor(size) {
|
|
48
|
+
super(`image is ${(size / 1024 / 1024).toFixed(1)} MB, over the ${MAX_FILE_BYTES / 1024 / 1024} MB Telegram download limit`);
|
|
49
|
+
this.size = size;
|
|
50
|
+
this.name = 'FileTooLargeError';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const MIME_BY_EXT = {
|
|
54
|
+
'.png': 'image/png',
|
|
55
|
+
'.jpg': 'image/jpeg',
|
|
56
|
+
'.jpeg': 'image/jpeg',
|
|
57
|
+
'.webp': 'image/webp',
|
|
58
|
+
'.gif': 'image/gif',
|
|
59
|
+
'.bmp': 'image/bmp',
|
|
60
|
+
'.heic': 'image/heic',
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Fetches the image and stores it in the chat's session attachment folder, so
|
|
64
|
+
* it is on disk before the window decides whether the turn runs now or in
|
|
65
|
+
* three minutes. `fetchImpl` keeps the tests off the network.
|
|
66
|
+
*/
|
|
67
|
+
export async function downloadImage(token, sessionId, media, deps = {}) {
|
|
68
|
+
if (media.fileSize !== undefined && media.fileSize > MAX_FILE_BYTES) {
|
|
69
|
+
throw new FileTooLargeError(media.fileSize);
|
|
70
|
+
}
|
|
71
|
+
const doFetch = deps.fetchImpl ?? fetch;
|
|
72
|
+
const metaRes = await doFetch(`https://api.telegram.org/bot${token}/getFile`, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: { 'Content-Type': 'application/json' },
|
|
75
|
+
body: JSON.stringify({ file_id: media.fileId }),
|
|
76
|
+
});
|
|
77
|
+
const meta = (await metaRes.json());
|
|
78
|
+
if (!meta.ok || !meta.result?.file_path) {
|
|
79
|
+
throw new Error(`Telegram API getFile failed: ${meta.description ?? 'no file_path'}`);
|
|
80
|
+
}
|
|
81
|
+
const filePath = meta.result.file_path;
|
|
82
|
+
const fileRes = await doFetch(`https://api.telegram.org/file/bot${token}/${filePath}`);
|
|
83
|
+
if (!fileRes.ok) {
|
|
84
|
+
throw new Error(`Telegram file download failed with status ${fileRes.status}`);
|
|
85
|
+
}
|
|
86
|
+
const buf = Buffer.from(await fileRes.arrayBuffer());
|
|
87
|
+
const ext = (extname(filePath) || '.jpg').toLowerCase();
|
|
88
|
+
const id = await saveAttachment(sessionId, buf, ext);
|
|
89
|
+
return { mime: MIME_BY_EXT[ext] ?? 'image/jpeg', id, name: basename(filePath) };
|
|
90
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { ToolAttachmentRecord } from '../../../session/types.js';
|
|
2
|
+
/** How long a caption-less image waits for text in a cold chat. */
|
|
3
|
+
export declare const HOLD_MS = 180000;
|
|
4
|
+
/** How recently the chat must have flushed to count as warm. */
|
|
5
|
+
export declare const WARM_MS = 120000;
|
|
6
|
+
export declare const MAX_ENTRIES = 20;
|
|
7
|
+
/** A Telegram media group holds up to 10 items; a full album must survive. */
|
|
8
|
+
export declare const MAX_IMAGES = 10;
|
|
9
|
+
/** One received Telegram message, with its images already on disk. */
|
|
10
|
+
export interface PendingEntry {
|
|
11
|
+
updateId: number;
|
|
12
|
+
/** "@user", first_name, or "unknown". */
|
|
13
|
+
fromLabel: string;
|
|
14
|
+
/** msg.text ?? msg.caption, trimmed; absent when empty. */
|
|
15
|
+
text?: string;
|
|
16
|
+
attachments: ToolAttachmentRecord[];
|
|
17
|
+
}
|
|
18
|
+
/** The accumulation window of a single chat. */
|
|
19
|
+
export interface PendingChat {
|
|
20
|
+
chatId: number;
|
|
21
|
+
/** title ?? username ?? String(chatId). */
|
|
22
|
+
chatLabel: string;
|
|
23
|
+
chatType: string;
|
|
24
|
+
entries: PendingEntry[];
|
|
25
|
+
/** ms epoch of the oldest buffered entry. */
|
|
26
|
+
firstAt: number;
|
|
27
|
+
/** ms epoch of the last flush for this chat. */
|
|
28
|
+
lastFlushAt?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface PendingState {
|
|
31
|
+
v: 1;
|
|
32
|
+
chats: Record<string, PendingChat>;
|
|
33
|
+
}
|
|
34
|
+
export type FlushDecision = 'flush' | 'hold' | 'idle';
|
|
35
|
+
/** The session every message of a chat lands in, on every surface that touches it. */
|
|
36
|
+
export declare function telegramSessionId(chatId: number): string;
|
|
37
|
+
/**
|
|
38
|
+
* Whether the window should be delivered now. Text always goes straight
|
|
39
|
+
* through; an image on its own waits for a caption, unless the chat flushed
|
|
40
|
+
* recently enough that the agent already has the context in its history.
|
|
41
|
+
*/
|
|
42
|
+
export declare function decideFlush(chat: PendingChat, now: number): FlushDecision;
|
|
43
|
+
/**
|
|
44
|
+
* Whether one more message would overflow the window. The image cap applies
|
|
45
|
+
* only to a message that carries an image: refusing the text typed under a
|
|
46
|
+
* full album would drop the very question that flushes the window.
|
|
47
|
+
*/
|
|
48
|
+
export declare function isAtCapacity(chat: PendingChat, incomingHasImage: boolean): boolean;
|
|
49
|
+
export declare function noTextLine(count: number): string;
|
|
50
|
+
/**
|
|
51
|
+
* The single user turn a flushed window becomes. One entry from one sender
|
|
52
|
+
* reproduces the legacy format byte for byte.
|
|
53
|
+
*/
|
|
54
|
+
export declare function buildMergedPrompt(chat: PendingChat, isNewSession: boolean): string;
|
|
55
|
+
export declare function pendingStatePath(taskId: string): string;
|
|
56
|
+
/**
|
|
57
|
+
* tmp + rename, with the Windows-style transient lock retry. Shared with
|
|
58
|
+
* saveTelegramOffset so the retry policy lives in one place.
|
|
59
|
+
*/
|
|
60
|
+
export declare function atomicWriteFile(path: string, contents: string): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* The buffer must survive a restart: the Telegram offset is committed before
|
|
63
|
+
* an entry is buffered, so losing the file loses the message. Anything
|
|
64
|
+
* unreadable degrades to an empty window rather than wedging the poller.
|
|
65
|
+
*/
|
|
66
|
+
export declare function loadPendingState(taskId: string): Promise<PendingState>;
|
|
67
|
+
export declare function savePendingState(taskId: string, state: PendingState): Promise<void>;
|
|
68
|
+
//# sourceMappingURL=telegram_window.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telegram_window.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/telegram_window.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAGtE,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