dsh-tg-bridge 1.19.11 → 1.20.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.
Files changed (50) hide show
  1. package/bridge.mjs +37 -2735
  2. package/callbacks.mjs +419 -0
  3. package/commands-registry.mjs +35 -0
  4. package/commands.mjs +96 -0
  5. package/control/agents.mjs +66 -0
  6. package/control/agentsets.mjs +115 -0
  7. package/control/cmd-agents.mjs +365 -0
  8. package/control/cmd-bridge.mjs +321 -0
  9. package/control/cmd-plugin.mjs +281 -0
  10. package/control/cmd-session.mjs +265 -0
  11. package/control/cmd-skills.mjs +236 -0
  12. package/control/cmd-task.mjs +247 -0
  13. package/control/cmd-views.mjs +403 -0
  14. package/control/models.mjs +199 -0
  15. package/control/plugins.mjs +162 -0
  16. package/control/release.mjs +156 -0
  17. package/control/sessions.mjs +108 -0
  18. package/control/tasks.mjs +98 -0
  19. package/control.mjs +33 -2695
  20. package/docs/REFACTORING.md +57 -32
  21. package/handle-message.mjs +483 -0
  22. package/help-explain.mjs +43 -43
  23. package/i18n/en/core.mjs +218 -0
  24. package/i18n/en/ctrl.mjs +434 -0
  25. package/i18n/en.mjs +8 -650
  26. package/i18n/ru/core.mjs +218 -0
  27. package/i18n/ru/ctrl.mjs +434 -0
  28. package/i18n/ru.mjs +8 -650
  29. package/i18n/zh/core.mjs +218 -0
  30. package/i18n/zh/ctrl.mjs +434 -0
  31. package/i18n/zh.mjs +8 -650
  32. package/job-loops.mjs +68 -0
  33. package/keyboards.mjs +43 -0
  34. package/keys.mjs +17 -0
  35. package/media.mjs +239 -0
  36. package/menu-card.mjs +223 -223
  37. package/package.json +38 -2
  38. package/panel.mjs +193 -175
  39. package/paths.mjs +46 -0
  40. package/profile-view.mjs +112 -0
  41. package/progress.mjs +284 -0
  42. package/queue.mjs +194 -0
  43. package/run-command.mjs +57 -0
  44. package/scan-secrets.mjs +9 -1
  45. package/secrets.mjs +80 -0
  46. package/state.mjs +139 -0
  47. package/steer.mjs +165 -0
  48. package/telegram.mjs +172 -0
  49. package/topics.mjs +158 -0
  50. package/turn.mjs +240 -0
package/bridge.mjs CHANGED
@@ -30,6 +30,14 @@ import { inlineText } from './media-text.mjs';
30
30
  import { createAlbumBuffer } from './albums.mjs';
31
31
  import { turnArgs } from './cli-args.mjs';
32
32
  import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
33
+ import { mediaPrompt, readVoiceIntoText } from './media.mjs';
34
+ import { busyNotices, clearBusyNotice, steerAvailable, steerMediaMessage, steerRunningTurn } from './steer.mjs';
35
+ import { MAX_PARALLEL, approvals, bufferAlbum, enqueue, lastPrompt, queues, rewindUsed, setMessageHandler } from './queue.mjs';
36
+ import { applyAsetJob, settingsChipOf, turnProfileOf } from './profile-view.mjs';
37
+ import { handleMessage } from './handle-message.mjs';
38
+ import { boundSetOf, handleCallback, handleCardPress, renderTaskCard, taskRows } from './callbacks.mjs';
39
+ import { runCommandFromButton } from './run-command.mjs';
40
+ import { startJobLoops } from './job-loops.mjs';
33
41
  import { ensureProfile } from './profiles.mjs';
34
42
  import { firstLiveModel, describeVerdicts, probeHint, probeModel } from './model-probe.mjs';
35
43
  import { explainFailure } from './failures.mjs';
@@ -51,44 +59,32 @@ import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.m
51
59
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
52
60
  import { sessionFile } from './thoughts.mjs';
53
61
  import { MENU_PREFIX, commandForName, isMenuPress, keyboardCommand, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
62
+ import {
63
+ APP, CLI_JS, CRED, DIR, DONE_FILE, DONE_TTL_MS, DSH_HOME, EXE, GOAL_CMD, HOME, LOG,
64
+ PENDING_DIR, PID_FILE, RESTART_MARKER, RESTART_NOTICE, SAY, SELF_DIR, STATE, STEER_DIR,
65
+ THOUGHT_DIR,
66
+ } from './paths.mjs';
67
+ import {
68
+ ack, config, done, log, pendingPath, pendingUpdates, saveDone, saveState, state, writeAtomic, writePending,
69
+ } from './state.mjs';
70
+ import { findToken, providerKeys, readSecret, token } from './secrets.mjs';
71
+ import { GENERAL_SAFE, commandOf, immediateCommandOf, langFor, lastTurnTarget, setBotUsername } from './commands.mjs';
72
+ import { sessionKey, threadOf } from './keys.mjs';
73
+ import { speedOf, startProgress } from './progress.mjs';
74
+ import { activeTurns, killTurn, liveSessions, profileOf, runTurn, runTurnLive, turnStartedAt, typingLoop } from './turn.mjs';
75
+ import { approvalKeyboard, continueKeyboard, errorKeyboard } from './keyboards.mjs';
76
+ import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, noteSeed, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
77
+ import { downloadFile, send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
54
78
 
55
- const HOME = homedir();
56
- const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
57
- // State, config and logs live here. DSH_TG_HOME lets a checkout run with its own
58
- // directory instead of the default ~/.dsh/tg-bridge.
59
- const DIR = process.env.DSH_TG_HOME || join(DSH_HOME, 'tg-bridge');
60
- // Code directory can differ from DIR when the bridge is started by the DSH
61
- // plugin (code lives in the profile's node_modules, state stays in DIR).
62
- const SELF_DIR = dirname(fileURLToPath(import.meta.url));
63
- const GOAL_CMD = join(SELF_DIR, 'goal.mjs');
64
- const STATE = join(DIR, 'state.json');
65
- const LOG = join(DIR, 'bridge.log');
66
- const CRED = join(DSH_HOME, '.credentials.yaml');
67
- const PENDING_DIR = join(DIR, 'pending');
68
- const STEER_DIR = join(DIR, 'steer');
69
- const THOUGHT_DIR = join(DIR, 'thoughts');
70
- // The helper the agent calls to confirm an addition in the chat while the turn
71
- // is still running. Lives next to the bridge so an installed copy works too.
72
- const SAY = join(DIR, 'say.mjs');
73
- const DONE_FILE = join(DIR, 'done.json');
74
- const RESTART_MARKER = join(DIR, 'restart.pending');
75
- // `/restart confirm` leaves a note here for the process that replaces it: the
76
- // old code exits ~300 ms after spawning the new one, and without this the chat
77
- // saw "Перезапускаю мост…" and then silence — no proof the bot came back.
78
- const RESTART_NOTICE = join(fileURLToPath(new URL('.', import.meta.url)), 'restart-notice.json');
79
- const DONE_TTL_MS = 24 * 60 * 60 * 1000;
80
- // dsh.cmd runs the Electron binary as Node against this CLI entrypoint; the
81
- // bridge mirrors that exactly so no shell quoting of task text is needed.
82
- const APP = join(process.env.LOCALAPPDATA || '', 'Programs', 'DeepSeek Harness');
83
- const EXE = join(APP, 'DeepSeek Harness.exe');
84
- const CLI_JS = join(APP, 'resources', 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js');
79
+ setMessageHandler(handleMessage);
85
80
 
86
- mkdirSync(DIR, { recursive: true });
81
+ /**
82
+ * Run a command the same way a typed one runs, for a button that stands for it.
83
+ * The callback handlers below need this: a press must reach `handleControl` with
84
+ * exactly the context a typed command gets.
85
+ */
87
86
 
88
- // Single instance: the watchdog task re-runs this every few minutes, so a live
89
- // pid means another bridge already owns the bot's getUpdates loop (two pollers
90
- // make Telegram answer 409 and both go silent).
91
- const PID_FILE = join(DIR, 'bridge.pid');
87
+ mkdirSync(DIR, { recursive: true });
92
88
  try {
93
89
  const other = Number(readFileSync(PID_FILE, 'utf8').trim());
94
90
  if (Number.isInteger(other) && other > 0 && other !== process.pid) {
@@ -122,2710 +118,16 @@ process.on('exit', (code) => {
122
118
  } catch {}
123
119
  });
124
120
 
125
- const config = {
126
- allowedUserIds: [],
127
- profile: 'headless',
128
- cwd: join(HOME, 'Documents', 'deepseek-harness', 'default-workspace'),
129
- turnTimeoutMs: 20 * 60 * 1000,
130
- };
131
- /** Turns currently running, keyed like sessions — `/stop` kills one. */
132
- const activeTurns = new Map();
133
- /** Session id each running turn actually adopted, learned from its `session` event. */
134
- const liveSessions = new Map();
135
- /** Wall-clock start of the running turn per session key, for the queue notice. */
136
- const turnStartedAt = new Map();
137
- try {
138
- Object.assign(config, JSON.parse(readFileSync(join(DIR, 'config.json'), 'utf8')));
139
- } catch {}
140
- // Old installs wrote these paths relative to the bridge directory, but turns
141
- // run from the project cwd, where "./transcribe.py" does not exist. Resolve
142
- // once at load so voice and vision work regardless of the topic's directory.
143
- if (config.voice?.script && !isAbsolute(config.voice.script)) config.voice.script = join(DIR, config.voice.script);
144
- if (config.vision?.patch && !isAbsolute(config.vision.patch)) config.vision.patch = join(DIR, config.vision.patch);
145
-
146
- const state = (() => {
147
- if (!existsSync(STATE)) return { offset: 0, sessions: {} };
148
- try {
149
- // Strip a UTF-8 BOM: PowerShell's Set-Content adds one and JSON.parse rejects it.
150
- return JSON.parse(readFileSync(STATE, 'utf8').replace(/^\uFEFF/, ''));
151
- } catch {
152
- return { offset: 0, sessions: {} };
153
- }
154
- })();
155
- /** Atomic write: temp file, fsync, rename — a torn state.json loses sessions. */
156
- function writeAtomic(path, text) {
157
- const tmp = `${path}.tmp-${process.pid}`;
158
- const fd = openSync(tmp, 'w');
159
- try {
160
- writeFd(fd, text, 'utf8');
161
- fsyncSync(fd);
162
- } finally {
163
- closeSync(fd);
164
- }
165
- renameSync(tmp, path);
166
- }
167
-
168
- function saveState() {
169
- writeAtomic(STATE, JSON.stringify(state, null, 2));
170
- }
171
-
172
- /**
173
- * Which profile runs this topic's turns. `/profile <name>` binds one topic to
174
- * its own plugin set and model; every other topic keeps the install default.
175
- */
176
- function profileOf(key) {
177
- return (state.profiles && state.profiles[key]) || config.profile || 'headless';
178
- }
179
-
180
- /**
181
- * One line for the progress head saying which settings this topic overrides.
182
- * Empty for every install that never binds a set: the panel stays as it was.
183
- * An unreadable agentsets.json must not cost the turn its panel, so this never
184
- * throws.
185
- */
186
- function settingsChipOf(key) {
187
- try {
188
- const id = state.agentsets?.[key];
189
- if (!id) return '';
190
- const store = new AgentsetStore(join(DIR, 'agentsets.json')).load();
191
- const set = store.get(id);
192
- if (!set) return '';
193
- const profile = profileOf(key);
194
- const patch = readFileSync(join(DSH_HOME, 'profiles', profile, 'cordis.patch.yml'), 'utf8');
195
- const resolved = resolveSettings({
196
- set,
197
- override: state.settings?.[key] || null,
198
- profile: profileValues(profileRowOf(profile, patch)),
199
- models: modelsOf(profile),
200
- efforts: parseReasoningEfforts(patch, set.model || modelOf(profile).model) || [],
201
- permissions: parsePermissionPresets(patch)?.presets?.map((p) => p.id) || [],
202
- presets: parseAgentPresets(patch)?.presets?.map((p) => p.id) || [],
203
- });
204
- return settingsChip(resolved, { name: set.name || set.id });
205
- } catch {
206
- return '';
207
- }
208
- }
209
-
210
- /** What the profile itself says, as `resolveSettings` wants it. */
211
- function profileRowOf(profile, patch = '') {
212
- const text = patch || readFileSync(join(DSH_HOME, 'profiles', profile, 'cordis.patch.yml'), 'utf8');
213
- const model = modelOf(profile);
214
- const named = parsePermissionPresets(text);
215
- return profileValues({
216
- model,
217
- // The preset the table actually starts in, not just the first row: a
218
- // profile whose default is read-only must not read as workspace-write.
219
- permissions: /defaultPreset:\s*(\S+)/.exec(text)?.[1] || named?.presets?.find((p) => p.sandbox)?.id || '',
220
- preset: parseAgentPresets(text)?.selected || '',
221
- effort: '',
222
- });
223
- }
224
-
225
- /**
226
- * The profile a turn actually runs under. A bound set becomes a profile of its
227
- * own (`aset-profile.mjs`), because DSH has no per-topic override; without a set
228
- * the answer is the topic's or the install's profile, unchanged.
229
- * `keep` tells the sweep every profile still in use.
230
- */
231
- function turnProfileOf(key) {
232
- const base = profileOf(key);
233
- try {
234
- const id = state.agentsets?.[key];
235
- if (!id) return base;
236
- const store = new AgentsetStore(join(DIR, 'agentsets.json')).load();
237
- const set = store.get(id);
238
- if (!set) return base;
239
- const derived = materialiseProfile(set, base);
240
- if (!derived) return base;
241
- const keep = Object.keys(state.agentsets || {})
242
- .map((topic) => {
243
- const bound = state.agentsets[topic];
244
- const other = store.get(bound);
245
- return other ? materialiseProfile(other, profileOf(topic)) : '';
246
- })
247
- .filter(Boolean);
248
- pruneDerived(keep);
249
- return derived;
250
- } catch (error) {
251
- // A broken store must not cost the turn: the profile runs as it would have.
252
- log(`aset profile failed for ${key}: ${error.message}`);
253
- return base;
254
- }
255
- }
256
-
257
- /**
258
- * Bind, unbind or edit a set for one topic — the single implementation behind
259
- * `/agentset`, the card's buttons and the job a running turn drops.
260
- */
261
- function applyAsetJob(job) {
262
- const { chatId, threadId = 0, action = 'use', id = '', field = '', value } = job || {};
263
- if (!chatId) return { ok: false, text: 'no chat' };
264
- const key = sessionKey(String(chatId), Number(threadId) || 0);
265
- const store = new AgentsetStore(join(DIR, 'agentsets.json')).load();
266
- if (!state.agentsets) state.agentsets = {};
267
- if (action === 'off') {
268
- if (!state.agentsets[key]) return { ok: true, changed: false, text: 'no set bound' };
269
- delete state.agentsets[key];
270
- if (state.settings) delete state.settings[key];
271
- return { ok: true, changed: true, text: 'set off' };
272
- }
273
- const set = store.get(id);
274
- if (!set) return { ok: false, text: `no set ${id}` };
275
- if (action === 'use') {
276
- state.agentsets[key] = id;
277
- return { ok: true, changed: true, text: `bound ${id}`, setId: id };
278
- }
279
- if (action === 'edit') return { ok: false, text: 'edit goes through /agentset' };
280
- return { ok: false, text: `unknown action ${action}` };
281
- }
282
-
283
- /**
284
-
285
- /**
286
- * A task list as one message plus one button per task. The label carries the
287
- * state, the payload carries only the number, so the card survives a relabel and
288
- * stays inside Telegram's 64-byte callback limit.
289
- */
290
- function renderTaskCard(goal, lang) {
291
- const { done, total } = progressOf(goal);
292
- const lines = [t(lang, 'goal.set', { text: goal.text })];
293
- goal.tasks.forEach((task, i) => lines.push(`${task.done ? '✅' : '⬜'} ${i + 1}. ${task.text}`));
294
- lines.push(t(lang, 'goal.progress', { done, total }), '', t(lang, 'task.tapHint'));
295
- return lines.join('\n');
296
- }
297
-
298
- function taskRows(goal) {
299
- if (!goal || goal.done) return [];
300
- const rows = [];
301
- for (let i = 0; i < Math.min(goal.tasks.length, 90); i += 3) {
302
- rows.push(goal.tasks.slice(i, i + 3).map((task, k) => ({ text: `${task.done ? '✅' : '⬜'} ${i + k + 1}`, data: `t:${i + k + 1}` })));
303
- }
304
- return rows;
305
- }
306
-
307
- // The agent updates the topic goal list by dropping a job file (goal.mjs);
308
- // the bridge is the only writer of state.json, so there is no lock race.
309
- const GOAL_DIR = join(DIR, 'goal-jobs');
310
- setInterval(() => {
311
- try {
312
- if (drainGoalJobs(state, GOAL_DIR, join(GOAL_DIR, 'done'))) saveState();
313
- } catch (error) {
314
- log(`goal job failed: ${error.message}`);
315
- }
316
- }, 2000).unref();
317
-
318
- // `/agentset` dropped as a job by a running turn (aset-jobs.mjs). The apply
319
- // function is the same one that answers `/agentset` in the chat, so a job and a
320
- // typed command cannot drift apart.
321
- const ASET_DIR = join(DIR, 'aset-jobs');
322
- setInterval(() => {
323
- try {
324
- const results = drainAsetJobs(DIR, (job) => applyAsetJob(job));
325
- for (const result of results) {
326
- log(`aset job ${result.job?.setId || result.job?.id || '?'} -> ${result.ok ? 'ok' : 'refused'}`);
327
- if (result.changed) saveState();
328
- if (result.job?.chatId) {
329
- Promise.resolve(send(String(result.job.chatId), result.text, Number(result.job.threadId) || 0))
330
- .catch((error) => log(`aset job answer failed: ${error.message}`));
331
- }
332
- }
333
- } catch (error) {
334
- log(`aset job failed: ${error.message}`);
335
- }
336
- }, 2000).unref();
337
-
338
- // Reminders: a turn is one short-lived process, so the only clock that can
339
- // outlive a message is this one. A reminder that came due while the bridge was
340
- // down fires on the first tick after it starts; one created for a topic that
341
- // has since been deleted still tries, and the delivery error is logged.
342
- setInterval(() => {
343
- try {
344
- const now = Date.now();
345
- const rows = Array.isArray(state.reminders) ? state.reminders : [];
346
- const ready = rows.filter((row) => row && Number(row.at) <= now);
347
- if (ready.length === 0) return;
348
- const ids = new Set(ready.map((row) => row.id));
349
- state.reminders = rows.filter((row) => !ids.has(row.id));
350
- saveState();
351
- for (const row of ready) {
352
- Promise.resolve(send(String(row.chatId), t(row.lang || config.lang || 'en', 'ctrl.remind.due', { text: row.text }), Number(row.threadId) || 0))
353
- .then(() => log(`reminder ${row.id} delivered`))
354
- .catch((error) => log(`reminder ${row.id} delivery failed: ${error.message}`));
355
- }
356
- } catch (error) {
357
- log(`reminder loop failed: ${error.message}`);
358
- }
359
- }, 20_000).unref();
360
-
361
- function log(line) {
362
- const text = `${new Date().toISOString()} ${line}\n`;
363
- try { appendFileSync(LOG, text, 'utf8'); } catch {}
364
- process.stdout.write(text);
365
- }
366
-
367
- // ---------------------------------------------------------------- журнал ходов
368
- //
369
- // A restart used to swallow whatever message was mid-flight: `offset` advanced
370
- // before the turn ran, so nothing ever replayed it. The journal is written
371
- // BEFORE the offset moves and deleted only after the answer reached Telegram,
372
- // which is the one order that survives a crash (Hermes' update_admission).
373
-
374
- /** update ids already answered, persisted, TTL-bound. */
375
- const done = (() => {
376
- try {
377
- const raw = JSON.parse(readFileSync(DONE_FILE, 'utf8'));
378
- const cutoff = Date.now() - DONE_TTL_MS;
379
- return new Map(Object.entries(raw).filter(([, at]) => Number(at) > cutoff));
380
- } catch {
381
- return new Map();
382
- }
383
- })();
384
-
385
- function saveDone() {
386
- try {
387
- writeAtomic(DONE_FILE, JSON.stringify(Object.fromEntries(done), null, 0));
388
- } catch (error) {
389
- log(`done.json write failed: ${error.message}`);
390
- }
391
- }
392
-
393
- function pendingPath(updateId) {
394
- return join(PENDING_DIR, `${updateId}.json`);
395
- }
396
-
397
- /** Persist one update before it is processed. */
398
- function writePending(update) {
399
- try {
400
- mkdirSync(PENDING_DIR, { recursive: true });
401
- writeAtomic(pendingPath(update.update_id), JSON.stringify(update));
402
- return true;
403
- } catch (error) {
404
- log(`pending write failed for ${update.update_id}: ${error.message}`);
405
- return false;
406
- }
407
- }
408
-
409
- /** Mark answered: remember the id and drop the file. Called AFTER the send. */
410
- function ack(updateId) {
411
- done.set(String(updateId), Date.now());
412
- saveDone();
413
- try {
414
- unlinkSync(pendingPath(updateId));
415
- } catch {}
416
- }
417
121
 
418
- /** Ids of pending updates still owed an answer, oldest first. */
419
- function pendingUpdates() {
420
- try {
421
- mkdirSync(PENDING_DIR, { recursive: true });
422
- const cutoff = Date.now() - DONE_TTL_MS;
423
- const out = [];
424
- for (const file of readdirSync(PENDING_DIR)) {
425
- if (!file.endsWith('.json')) continue;
426
- const id = Number(file.replace(/\.json$/, ''));
427
- const full = join(PENDING_DIR, file);
428
- let stat;
429
- try {
430
- stat = statSync(full);
431
- } catch {
432
- continue;
433
- }
434
- // Older than the TTL: Telegram will not replay it either, drop it.
435
- if (stat.mtimeMs < cutoff) {
436
- try { unlinkSync(full); } catch {}
437
- continue;
438
- }
439
- if (!Number.isInteger(id) || done.has(String(id))) {
440
- try { unlinkSync(full); } catch {}
441
- continue;
442
- }
443
- try {
444
- out.push({ update: JSON.parse(readFileSync(full, 'utf8')), id });
445
- } catch {
446
- try { unlinkSync(full); } catch {}
447
- }
448
- }
449
- return out.sort((a, b) => a.id - b.id);
450
- } catch {
451
- return [];
452
- }
453
- }
454
122
 
455
- function readSecret(name) {
456
- const yaml = readFileSync(CRED, 'utf8');
457
- const re = new RegExp(`^\\s*${name}:\\s*["']?([^"'\\s]+)`, 'm');
458
- const m = yaml.match(re);
459
- return m ? m[1] : '';
460
- }
461
123
 
462
- /**
463
- * Env vars for the provider keys this install needs.
464
- *
465
- * A headless turn inherits the bridge's environment, and the credentials
466
- * service only resolves providers the app knows about. Extra providers are
467
- * therefore declared per install in `config.json` as
468
- * `"providerKeys": ["MY_PROVIDER_API_KEY"]`, and each name is read from
469
- * `~/.dsh/.credentials.yaml` under the same name. Nothing is hardcoded: an
470
- * install that runs on the app's own providers sets an empty list and gets
471
- * exactly the inherited environment.
472
- */
473
- function providerKeys(cfg) {
474
- const out = {};
475
- const names = Array.isArray(cfg.providerKeys) ? cfg.providerKeys : [];
476
- for (const name of names) {
477
- if (!/^[A-Z][A-Z0-9_]*$/.test(String(name))) continue;
478
- try {
479
- const value = readSecret(name) || (process.env[name] || '').trim();
480
- if (value) out[name] = value;
481
- } catch {}
482
- }
483
- return out;
484
- }
124
+ startJobLoops();
485
125
 
486
- /**
487
- * The bot token can be stored under three names: the plain one that `dsh-tg
488
- * init` writes, the suffixed one DSH generates when the secret is added through
489
- * the app, or an env var. Checking only the suffixed name made a fresh install
490
- * fail with "token not found" even though init had just written it.
491
- */
492
- function findToken() {
493
- const env = (process.env.DSH_TELEGRAM_BOT_TOKEN || '').trim();
494
- if (env) return env;
495
- // The suffixed name carries a random id of the machine that created the
496
- // secret (DSH_TELEGRAM_BOT_TOKEN_<hex>), so it must not be spelled out here:
497
- // any install is free to carry its own suffix. Try the plain name first, then
498
- // whatever suffixed variants the credentials file actually holds.
499
- const suffixes = [];
500
- try {
501
- for (const m of readFileSync(CRED, 'utf8').matchAll(/^\s*(DSH_TELEGRAM_BOT_TOKEN_[A-Z0-9_]+):/gm)) suffixes.push(m[1]);
502
- } catch {}
503
- for (const name of ['DSH_TELEGRAM_BOT_TOKEN', ...suffixes]) {
504
- try {
505
- const value = readSecret(name);
506
- if (value) return value;
507
- } catch {}
508
- }
509
- try {
510
- const m = readFileSync(CRED, 'utf8').match(/^\s*(DSH_TELEGRAM_BOT_TOKEN[A-Z0-9_]*):\s*["']?([^"'\s]+)/m);
511
- if (m) return m[2];
512
- } catch {}
513
- return '';
514
- }
515
- const token = findToken();
516
126
  if (!token) {
517
127
  log('FATAL: bot token not found — run `node cli.mjs init --token <t> --user <id>` or set DSH_TELEGRAM_BOT_TOKEN');
518
128
  process.exit(1);
519
129
  }
520
- const api = (method) => `https://api.telegram.org/bot${token}/${method}`;
521
-
522
- /**
523
- * Telegram API call with retries.
524
- *
525
- * The log filled with `poll error: fetch failed` for an hour while
526
- * api.telegram.org was reachable over IPv4: Node's fetch tries the AAAA record
527
- * first and fails, and a single failed attempt used to drop the message or the
528
- * reply entirely. Three attempts with backoff turn a flaky network into a
529
- * short delay instead of silence.
530
- */
531
- async function tg(method, body, timeoutMs = 60000, attempts = 3) {
532
- let lastError;
533
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
534
- try {
535
- const res = await fetch(api(method), {
536
- method: 'POST',
537
- headers: { 'content-type': 'application/json' },
538
- body: JSON.stringify(body ?? {}),
539
- signal: AbortSignal.timeout(timeoutMs),
540
- });
541
- const json = await res.json().catch(() => ({}));
542
- if (!json.ok) throw new Error(`${method}: ${json.description || res.status}`);
543
- return json.result;
544
- } catch (error) {
545
- lastError = error;
546
- const retryable = /fetch failed|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|502|503|504/i.test(String(error?.message ?? error));
547
- if (!retryable || attempt === attempts) break;
548
- await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
549
- }
550
- }
551
- throw lastError;
552
- }
553
-
554
- function threadOf(msg) {
555
- const id = msg.message_thread_id ?? msg.reply_to_message?.message_thread_id;
556
- return Number.isInteger(id) && id > 0 ? id : 0;
557
- }
558
-
559
- /** One DSH session per chat, and per topic inside a forum supergroup. */
560
- function sessionKey(chatId, threadId) {
561
- return threadId > 0 ? `${chatId}:${threadId}` : String(chatId);
562
- }
563
-
564
- /**
565
- * Last topic this chat actually worked in.
566
- *
567
- * Mirrors Hermes' `_recover_telegram_topic_thread_id`: when a message arrives
568
- * without a thread id (Telegram omits it for General and for clients that have
569
- * not bound the topic yet), routing it to the root session silently forks the
570
- * conversation. Recovering the newest bound topic keeps one project in one
571
- * place instead of scattering it between General and its topic.
572
- */
573
- function newestBoundTopic(chatId) {
574
- let newest = 0;
575
- let at = 0;
576
- for (const key of Object.keys(state.sessions ?? {})) {
577
- const match = new RegExp(`^${chatId}:(\\d+)$`).exec(key);
578
- if (!match) continue;
579
- const stamped = state.topicTouched?.[match[1]] ?? 0;
580
- if (stamped > at) {
581
- at = stamped;
582
- newest = Number(match[1]);
583
- }
584
- }
585
- return newest;
586
- }
587
-
588
- /** Remember that a topic is active, for {@link newestBoundTopic}. */
589
- function touchTopic(threadId) {
590
- if (!(threadId > 0)) return;
591
- state.topicTouched = state.topicTouched ?? {};
592
- state.topicTouched[String(threadId)] = Date.now();
593
- }
594
-
595
- /**
596
- * Recent topic seeds, so a duplicate of the same text arriving in the General
597
- * chat can be recognised instead of starting a second turn.
598
- *
599
- * Telegram delivers a brand-new topic's text twice: once as the topic message
600
- * and once as a plain group message. Both used to run a turn, which is why a
601
- * prompt written in General got answered in General while its topic stayed
602
- * empty.
603
- */
604
- const recentSeeds = new Map();
605
-
606
- function noteSeed(text, threadId) {
607
- const key = String(text ?? '').trim().slice(0, 200);
608
- if (!key) return;
609
- recentSeeds.set(key, { threadId, at: Date.now() });
610
- for (const [candidate, value] of recentSeeds) {
611
- if (Date.now() - value.at > 600000) recentSeeds.delete(candidate);
612
- }
613
- }
614
-
615
- /** Topic id whose seed carried this same text within the last ten minutes, or 0. */
616
- function topicSeededRecently(text) {
617
- const key = String(text ?? '').trim().slice(0, 200);
618
- if (!key) return 0;
619
- const hit = recentSeeds.get(key);
620
- return hit && Date.now() - hit.at < 600000 ? hit.threadId : 0;
621
- }
622
-
623
- /**
624
- * Download a Telegram file into the bridge dir under a stable name.
625
- * Voice notes arrive as OGG/Opus, which the local ASR CLI does not decode,
626
- * so the caller passes the name it wants (including the extension).
627
- */
628
- /** Upload a local file to the chat: archives, PDFs, screenshots, builds. */
629
- async function sendFile(chatId, threadId, filePath, caption = '') {
630
- const buf = readFileSync(filePath);
631
- const form = new FormData();
632
- form.set('chat_id', String(chatId));
633
- if (threadId > 0) form.set('message_thread_id', String(threadId));
634
- if (caption) form.set('caption', caption.slice(0, 1000));
635
- form.set('document', new Blob([buf]), basename(filePath));
636
- const res = await fetch(`https://api.telegram.org/bot${token}/sendDocument`, { method: 'POST', body: form });
637
- const json = await res.json().catch(() => ({}));
638
- if (!json.ok) throw new Error(`sendDocument: ${json.description || res.status}`);
639
- log(`sent file ${basename(filePath)} (${buf.length} B) chat=${chatId}`);
640
- return json.result;
641
- }
642
-
643
- async function downloadFile(fileId, fileName) {
644
- const file = await tg('getFile', { file_id: fileId });
645
- const res = await fetch(`https://api.telegram.org/file/bot${token}/${file.file_path}`);
646
- if (!res.ok) throw new Error(`file download failed: ${res.status}`);
647
- const path = join(DIR, fileName);
648
- writeFileSync(path, Buffer.from(await res.arrayBuffer()));
649
- return path;
650
- }
651
-
652
- /**
653
- * Transcribe a local audio file with the speech backend from config.
654
- *
655
- * Two shapes are supported:
656
- * - faster-whisper script: `voice.python` + `voice.script` + `voice.model`
657
- * (the local setup: `~/.venv-whisper`, models from the HF cache);
658
- * - any whisper.cpp-style CLI: `voice.command` + `voice.args`, with `{file}`.
659
- * Either way the transcript comes back on stdout, diagnostics on stderr.
660
- */
661
- function transcribe(file, voice) {
662
- const useScript = Boolean(voice.python && voice.script);
663
- const command = useScript ? voice.python : voice.command;
664
- const args = useScript
665
- ? [
666
- voice.script,
667
- file,
668
- '--model', voice.model || 'small',
669
- '--language', voice.language || 'auto',
670
- '--beam', String(voice.beam ?? 1),
671
- '--threads', String(voice.threads ?? 0),
672
- ]
673
- : (voice.args ?? []).map((arg) => String(arg).replaceAll('{file}', file));
674
- if (!useScript && !(voice.args ?? []).some((arg) => String(arg).includes('{file}'))) args.push(file);
675
- return new Promise((resolve) => {
676
- const child = spawn(command, args, {
677
- cwd: voice.cwd || DIR,
678
- windowsHide: true,
679
- env: { ...process.env },
680
- });
681
- if (voice.timeoutMs) {
682
- const timer = setTimeout(() => child.kill(), voice.timeoutMs);
683
- child.on('close', () => clearTimeout(timer));
684
- }
685
- let stdout = '';
686
- let stderr = '';
687
- child.stdout.setEncoding('utf8');
688
- child.stderr.setEncoding('utf8');
689
- child.stdout.on('data', (buf) => { stdout += buf; });
690
- child.stderr.on('data', (buf) => { stderr += buf; });
691
- child.on('error', (err) => resolve({ text: '', error: `${command}: ${err.message}` }));
692
- child.on('close', (code) => {
693
- // whisper.cpp writes timestamps and `[BLANK_AUDIO]` markers; keep only speech.
694
- const text = stdout
695
- .split(/\r?\n/)
696
- .map((line) => line.replace(/^\s*\[[\d:.,\s>-]+\]\s*/, '').replace(/\[BLANK_AUDIO\]/gi, '').trim())
697
- .filter(Boolean)
698
- .join(' ')
699
- .replace(/\s+/g, ' ')
700
- .trim();
701
- resolve({ text, error: code === 0 ? '' : `${voice.command} exit ${code}: ${stderr.trim().slice(-300)}` });
702
- });
703
- });
704
- }
705
-
706
- /** <audio file> -> transcript, wrapping every failure in a spoken-to text message. */
707
- async function voiceToText(msg, voice) {
708
- const media = msg.voice || msg.audio || msg.document || msg.video_note;
709
- const file_id = media?.file_id;
710
- if (!file_id) return { text: '', error: 'no audio file in message' };
711
- // Voice notes are Opus-in-OGG: the extension follows the source so the
712
- // decoder picks the right container.
713
- const ext = msg.voice ? 'ogg' : msg.audio ? (msg.audio.mime_type?.includes('wav') ? 'wav' : 'mp3') : 'ogg';
714
- const path = await downloadFile(file_id, `voice-${Date.now()}.${ext}`);
715
- const result = await transcribe(path, voice);
716
- try { unlinkSync(path); } catch {}
717
- return result;
718
- }
719
-
720
- /** Bot username from getMe, needed to unwrap `/cmd@bot` in groups. */
721
- let botUsername = '';
722
-
723
- /**
724
- * Normalized command name (`/new`), or '' for ordinary text.
725
- * In groups Telegram delivers `/new@deepifiya_bot`, which must still count.
726
- *
727
- * The pattern deliberately allows `-` and `.`: `/app-restart-confirm` and
728
- * `/app.restart.confirm` are what people actually type when they recall a
729
- * multi-word command, and returning '' for them silently ran a whole AI turn
730
- * instead (a real miss on 2026-10-20). Punctuation is dropped from the name.
731
- */
732
- function commandOf(text) {
733
- const match = /^\/([A-Za-z0-9_.-]+)(?:@([A-Za-z0-9_]+))?$/.exec(text);
734
- if (match === null) return '';
735
- if (match[2] && botUsername && match[2].toLowerCase() !== botUsername.toLowerCase()) return '';
736
- return `/${match[1].toLowerCase().replace(/[.-]+/g, '')}`;
737
- }
738
-
739
- /**
740
- * Commands that may run from the General topic without changing anything there.
741
- *
742
- * The lobby rule moves a General message into the newest topic; for these that is
743
- * the whole point (you want the status of the work you are looking at, and `/stop`
744
- * must work from anywhere). Everything else is answered in General with the name
745
- * of the topic it would have changed.
746
- */
747
- const GENERAL_SAFE = new Set([
748
- 'status', 'sessions', 'branches', 'jobs', 'version', 'doctor', 'logs',
749
- 'stop', 'help', 'menu', 'prices', 'thoughts',
750
- ]);
751
-
752
- /** Canonical immediate command name for a message, or '' when it must queue. */
753
- function immediateCommandOf(text) {
754
- const trimmed = String(text ?? '').trim();
755
- if (!trimmed.startsWith('/')) return '';
756
- const [head, ...rest] = trimmed.split(/\s+/);
757
- const collapsed = commandOf(head).replace(/^\//, '');
758
- return immediateKind(collapsed, rest);
759
- }
760
-
761
- /**
762
- * Language for a chat and topic.
763
- *
764
- * Extracting the formatting helpers into `format.mjs` took this function with
765
- * them, and the two `langFor` call sites stayed behind — so `send()` threw
766
- * `langFor is not defined` on its first line and the restart notice never
767
- * reached the chat. Nothing caught it: the error was logged and swallowed by
768
- * the outer `try`, and the process kept running. It is a one-line wrapper, and
769
- * the tests below pin the call sites so a missing name fails there instead.
770
- */
771
- function langFor(chatId, threadId = 0) {
772
- return resolveLang(state, sessionKey(chatId, threadId), null, config);
773
- }
774
-
775
- /**
776
- * Where a release notice goes: the last chat a turn ran in.
777
- *
778
- * `state.sessions[key]` is a session id, not a record, so the order is by last
779
- * use — the bridge records it in `state.lastKey` whenever it starts a turn. With
780
- * no session at all (a fresh install that never talked) a notice is pointless,
781
- * and nothing is sent.
782
- */
783
- function lastTurnTarget() {
784
- const key = typeof state.lastKey === 'string' ? state.lastKey : '';
785
- const [chat, thread] = key.split(':');
786
- const chatId = Number(chat);
787
- if (!Number.isInteger(chatId) || chatId <= 0) return null;
788
- return { chatId, threadId: Number(thread) || 0 };
789
- }
790
-
791
- /**
792
- * The forum topic's own title, for a card that has to say where it is.
793
- *
794
- * One API call per topic, then cached for the life of the process: a rename
795
- * shows up on the next restart, which is a fair trade for not calling Telegram
796
- * on every panel edit. A failure caches the empty name — a card is not worth a
797
- * retry storm — and the caller renders the id alone.
798
- */
799
- const topicNames = new Map();
800
- function topicName(chatId, threadId) {
801
- const cacheKey = sessionKey(chatId, threadId);
802
- if (topicNames.has(cacheKey)) return topicNames.get(cacheKey);
803
- topicNames.set(cacheKey, '');
804
- tg('getForumTopic', { chat_id: chatId, message_thread_id: threadId })
805
- .then((res) => {
806
- const name = String(res?.name || '').trim();
807
- if (name) topicNames.set(cacheKey, name);
808
- })
809
- .catch(() => {});
810
- return '';
811
- }
812
-
813
- /**
814
- * Run a command that a button stands for, exactly as if it had been typed.
815
- *
816
- * The panel has no second implementation of anything: a press calls this, and
817
- * this calls `handleControl` with the same context a typed command gets. What
818
- * a button cannot do is money or state the person did not mean — so a press
819
- * never falls through to an AI turn.
820
- */
821
- /**
822
- * A message that carries buttons. Inline rows are the usual case; a persistent
823
- * reply keyboard (`/menu on`) and taking it away again are the two other markup
824
- * shapes a person can end up with, so every call site hands its intent here
825
- * instead of building `reply_markup` itself.
826
- */
827
- async function sendWithMarkup(chatId, threadId, text, extra = {}) {
828
- const thread = threadId > 0 ? { message_thread_id: threadId } : {};
829
- if (extra.removeKeyboard) {
830
- return tg('sendMessage', {
831
- chat_id: chatId,
832
- text,
833
- reply_markup: { remove_keyboard: true },
834
- ...thread,
835
- }).catch(() => {});
836
- }
837
- if (extra.persistent) {
838
- return tg('sendMessage', {
839
- chat_id: chatId,
840
- text,
841
- reply_markup: { keyboard: extra.persistent, resize_keyboard: true, is_persistent: true },
842
- ...thread,
843
- }).catch(() => {});
844
- }
845
- if (extra.keyboard) {
846
- return tg('sendMessage', {
847
- chat_id: chatId,
848
- text,
849
- disable_web_page_preview: true,
850
- reply_markup: { inline_keyboard: extra.keyboard },
851
- ...thread,
852
- }).catch(() => {});
853
- }
854
- return send(chatId, text, threadId);
855
- }
856
-
857
- async function runCommandFromButton(typed, { chatId, threadId, key }) {
858
- const lang = langFor(chatId, threadId);
859
- const [head, ...rest] = typed.trim().split(/\s+/);
860
- const arg = rest.join(' ');
861
- const handled = await handleControl({
862
- command: head,
863
- arg,
864
- text: typed,
865
- lang,
866
- chatId,
867
- threadId,
868
- key,
869
- state,
870
- config,
871
- activeTurns,
872
- saveState,
873
- log,
874
- send,
875
- jobs: () => ({
876
- active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
877
- queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
878
- max: MAX_PARALLEL,
879
- }),
880
- api: tg,
881
- sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
882
- // A report meant to be read once (/thoughts) can ask for a message that
883
- // removes itself. Without this the chat is told it will disappear while the
884
- // message is a normal one — a promise nothing was keeping.
885
- ephemeral: (out) => sendEphemeral(chatId, out, threadId),
886
- seedTopic: ensureTopicSeed,
887
- profile: profileOf(key),
888
- reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
889
- stopTurn: (k) => {
890
- const child = activeTurns.get(k);
891
- if (!child) return false;
892
- try {
893
- child.kill();
894
- activeTurns.delete(k);
895
- return true;
896
- } catch {
897
- return false;
898
- }
899
- },
900
- });
901
- if (!handled) await send(chatId, t(lang, 'bridge.cb.unknown'), threadId);
902
- }
903
-
904
- async function send(chatId, text, threadId = 0, replyTo = 0) {
905
- // Who is reading: the topic's language decides even the fallback line, so an
906
- // English or Chinese topic never sees a Russian placeholder.
907
- const lang = langFor(chatId, threadId);
908
- const plain = config.plainText === true;
909
- const parts = plain
910
- ? chunk(toPlainText(text) || t(lang, 'bridge.progress.empty'), 3800)
911
- : markdownParts(text);
912
- let lastId = 0;
913
- for (const part of parts) {
914
- const html = plain ? '' : toTelegramHtml(part);
915
- const body = { chat_id: chatId, text: html || part, disable_web_page_preview: true };
916
- if (html) body.parse_mode = 'HTML';
917
- // Without message_thread_id every reply lands in the General topic, which is
918
- // the whole point of carrying the thread through.
919
- if (threadId > 0) body.message_thread_id = threadId;
920
- if (replyTo > 0) body.reply_to_message_id = replyTo;
921
- let res;
922
- try {
923
- res = await tg('sendMessage', body);
924
- } catch (error) {
925
- // The fallback must start from the markdown, not from the HTML: resending
926
- // the markup as plain text is exactly how the person ends up reading
927
- // `<b>` and `<code>` instead of a sentence.
928
- if (!html) throw error;
929
- log(`html send failed (${String(error.message).slice(0, 120)}); resending as plain text`);
930
- delete body.parse_mode;
931
- for (const piece of chunk(toPlainText(part) || t(lang, 'bridge.progress.empty'), 3800)) {
932
- body.text = piece;
933
- res = await tg('sendMessage', body);
934
- }
935
- }
936
- log(`sent chat=${chatId}${threadId ? ` topic=${threadId}` : ''} msg=${res.message_id} len=${body.text.length}${html ? ' html' : ''}`);
937
- lastId = res.message_id;
938
- }
939
- return lastId;
940
- }
941
-
942
- /**
943
- * Send a message that deletes itself after `ttlMs`.
944
- *
945
- * Reports read once and forgotten (`/thoughts`, an unknown command showing the
946
- * menu) should not stay in the scrollback forever. The API cannot edit plain
947
- * text into a spoiler, so the choice is between two kinds of litter: a long
948
- * reply or a "gone" tombstone. A tombstone wins.
949
- */
950
- async function sendEphemeral(chatId, text, threadId = 0, replyTo = 0, ttlMs = 180000) {
951
- const id = await send(chatId, text, threadId, replyTo);
952
- if (!id) return id;
953
- const timer = setTimeout(() => {
954
- tg('deleteMessage', { chat_id: chatId, message_id: id })
955
- .catch((error) => log(`ephemeral delete failed msg=${id}: ${String(error.message).slice(0, 80)}`));
956
- }, ttlMs);
957
- timer.unref?.();
958
- return id;
959
- }
960
-
961
- /** Remember which topics already got their seed message, so it happens once. */
962
- function topicSeeded(threadId) {
963
- return Boolean(state.seededTopics?.[String(threadId)]);
964
- }
965
-
966
- /**
967
- * Seed a newly created forum topic with the person's own message and pin it.
968
- *
969
- * Telegram creates a topic with only a service message ("Topic created"), so
970
- * the thread looks empty: a title with nothing under it. Posting the incoming
971
- * text there (a) removes the blank, (b) gives the chat something to scroll
972
- * back to, and (c) pins the thread to the top of the topic list, which is the
973
- * behaviour the owner asked for.
974
- *
975
- * Returns the seeded message id, or 0 when nothing was done.
976
- */
977
- async function ensureTopicSeed(chatId, threadId, text) {
978
- if (topicSeeded(threadId)) return 0;
979
- const body = { chat_id: chatId, text: String(text ?? '').slice(0, 4000), message_thread_id: threadId, disable_web_page_preview: true };
980
- let messageId = 0;
981
- try {
982
- const res = await tg('sendMessage', body);
983
- messageId = res.message_id;
984
- } catch (error) {
985
- log(`topic ${threadId} seed failed: ${error.message}`);
986
- return 0;
987
- }
988
- if (config.pinTopicSeed !== false) {
989
- try {
990
- await tg('pinChatMessage', { chat_id: chatId, message_id: messageId, disable_notification: false });
991
- } catch (error) {
992
- log(`topic ${threadId} pin failed: ${error.message}`);
993
- }
994
- }
995
- state.seededTopics = state.seededTopics ?? {};
996
- state.seededTopics[String(threadId)] = messageId;
997
- saveState();
998
- noteSeed(text, threadId);
999
- return messageId;
1000
- }
1001
-
1002
- /**
1003
- * Write one line about a new topic into the General chat, so the main stream
1004
- * reads as a log of what was started instead of a wall of prompts. The full
1005
- * text lives in the topic itself; this is only the pointer.
1006
- */
1007
- async function logTopicToGeneral(chatId, threadId, text, lang = config.lang || 'en') {
1008
- if (config.topicLog === false) return;
1009
- const head = String(text ?? '').replace(/\s+/g, ' ').trim();
1010
- const preview = head.length > 90 ? `${head.slice(0, 90)}…` : head;
1011
- try {
1012
- await tg('sendMessage', {
1013
- chat_id: chatId,
1014
- text: t(lang, 'msg.topicLog', { preview }),
1015
- disable_web_page_preview: true,
1016
- });
1017
- log(`topic ${threadId} logged to General`);
1018
- } catch (error) {
1019
- log(`topic ${threadId} General log failed: ${error.message}`);
1020
- }
1021
- }
1022
-
1023
- /** Run one DSH headless turn; resolve {sessionId, text, error}. */
1024
- function runTurn(task, sessionId, key = '', onEvent = null, extraArgs = [], cwd = '', profile = config.profile, lang = config.lang || 'en', env = {}) {
1025
- return new Promise((resolve) => {
1026
- const args = turnArgs({ cli: CLI_JS, profile, extraArgs, sessionId, task });
1027
- const child = spawn(EXE, args, {
1028
- // Per-topic project directory: a topic can be bound to one repository so
1029
- // "work in my-app" stops meaning "cd in every command".
1030
- cwd: cwd && existsSync(cwd) ? cwd : config.cwd,
1031
- env: {
1032
- ...process.env,
1033
- DSH_TG_KEY: key,
1034
- DSH_TG_CHAT: String(key).split(':')[0] || '',
1035
- DSH_TG_THREAD: String(key).split(':')[1] || '0',
1036
- // Per-turn extras: the path of this turn's note file, so `say.mjs`
1037
- // never has to guess which topic a line belongs to.
1038
- ...env,
1039
- ELECTRON_RUN_AS_NODE: '1',
1040
- // Provider keys the profile cannot resolve on its own. Configured per
1041
- // install (`providerKeys`, see config.example.json); a key listed in
1042
- // `~/.dsh/.credentials.yaml` is passed by its own name.
1043
- ...providerKeys(config),
1044
- },
1045
- windowsHide: true,
1046
- });
1047
- if (key) activeTurns.set(key, child);
1048
- let stdout = '';
1049
- let stderr = '';
1050
- let sid = sessionId || '';
1051
- let finalText = '';
1052
- const timer = config.turnTimeoutMs > 0 ? setTimeout(() => child.kill(), config.turnTimeoutMs) : null;
1053
- child.stdout.setEncoding('utf8');
1054
- child.stderr.setEncoding('utf8');
1055
- child.stdout.on('data', (buf) => {
1056
- stdout += buf;
1057
- // Any byte from the CLI is proof of life: the model may think for minutes
1058
- // before the next structured event, and a silent turn is not a hung one.
1059
- if (onEvent) { try { onEvent({ type: 'activity' }); } catch {} }
1060
- let idx;
1061
- while ((idx = stdout.indexOf('\n')) !== -1) {
1062
- const line = stdout.slice(0, idx).trim();
1063
- stdout = stdout.slice(idx + 1);
1064
- if (!line.startsWith('{')) continue;
1065
- try {
1066
- const ev = JSON.parse(line);
1067
- if (ev.type === 'session' && ev.sessionId) sid = ev.sessionId;
1068
- if (ev.type === 'final' && typeof ev.text === 'string') finalText = ev.text;
1069
- if (ev.type === 'error') finalText = finalText || t(lang, 'bridge.error.inline', { msg: ev.message || JSON.stringify(ev) });
1070
- // Every event is forwarded so the bridge can show live progress; a
1071
- // silent turn used to look identical to a hung one.
1072
- if (onEvent) {
1073
- try {
1074
- onEvent(ev);
1075
- } catch {}
1076
- }
1077
- } catch {}
1078
- }
1079
- });
1080
- child.stderr.on('data', (buf) => {
1081
- stderr += buf;
1082
- if (onEvent) { try { onEvent({ type: 'activity' }); } catch {} }
1083
- });
1084
- // A missing or moved DSH app used to emit `error` with no listener, which
1085
- // kills the process — every turn, forever. The turn now fails with a line
1086
- // that says which path was expected and how to point the bridge elsewhere.
1087
- child.on('error', (error) => {
1088
- clearTimeout(timer);
1089
- if (key) activeTurns.delete(key);
1090
- const hint = error?.code === 'ENOENT'
1091
- ? t(lang, 'bridge.error.noApp', { path: EXE })
1092
- : t(lang, 'bridge.error.spawn', { msg: error?.message || String(error) });
1093
- log(`turn spawn failed: ${error?.message || error}`);
1094
- resolve({ sessionId: sid, text: '', error: hint });
1095
- });
1096
- child.on('close', (code) => {
1097
- clearTimeout(timer);
1098
- if (key) activeTurns.delete(key);
1099
- // No live process means no agent to steer; a job written now would wait
1100
- // for the next turn instead of the current one.
1101
- if (key) liveSessions.delete(key);
1102
- // Keep the whole diagnostic: the CLI prints the useful phrase
1103
- // ("pending (waiting for service: speechToText)") on the lines AFTER the
1104
- // one-line summary, and trimming early hid the real cause from the chat.
1105
- // A bare "exit 1" with an empty stderr told the person nothing, so fall
1106
- // back to the tail of stdout, where the CLI puts its own error line.
1107
- let error = '';
1108
- if (code !== 0) {
1109
- const errText = stderr.trim();
1110
- const outTail = stdout
1111
- .split(/\r?\n/)
1112
- .filter((line) => line.trim() !== '' && !line.trim().startsWith('{'))
1113
- .join('\n')
1114
- .trim();
1115
- error = errText || outTail.slice(-1200) || t(lang, 'bridge.error.cliDied', { code });
1116
- }
1117
- resolve({ sessionId: sid, text: finalText, error });
1118
- });
1119
- });
1120
- }
1121
-
1122
- async function typingLoop(chatId, threadId, stopFlag) {
1123
- while (!stopFlag.done) {
1124
- try {
1125
- const body = { chat_id: chatId, action: 'typing' };
1126
- if (threadId > 0) body.message_thread_id = threadId;
1127
- await tg('sendChatAction', body);
1128
- } catch {}
1129
- await new Promise((r) => setTimeout(r, 4500));
1130
- }
1131
- }
1132
130
 
1133
- /** Kill the CLI child of one turn, if it is still alive. */
1134
- function killTurn(key) {
1135
- const child = activeTurns.get(key);
1136
- if (!child) return false;
1137
- try {
1138
- child.kill();
1139
- activeTurns.delete(key);
1140
- log(`killed hung turn for ${key}`);
1141
- return true;
1142
- } catch (error) {
1143
- log(`kill failed for ${key}: ${error.message}`);
1144
- return false;
1145
- }
1146
- }
1147
-
1148
-
1149
- /**
1150
- * Average generation speed of a turn, in tokens per second, or 0 when unknown.
1151
- *
1152
- * Output tokens over wall time, not over "time spent generating": the bridge
1153
- * sees one stream and cannot separate thinking from tool calls, and the honest
1154
- * question the number answers is "is this turn moving", not "how fast is the
1155
- * provider". A turn younger than a couple of seconds says nothing — one token
1156
- * in one second is not a measurement.
1157
- */
1158
- function speedOf(outputTokens, ms) {
1159
- if (!Number.isFinite(outputTokens) || outputTokens <= 0) return 0;
1160
- if (!Number.isFinite(ms) || ms < 3000) return 0;
1161
- return Math.round(outputTokens / (ms / 1000));
1162
- }
1163
-
1164
- /**
1165
- * One editable status message per turn.
1166
- *
1167
- * Hermes shows the working steps; without them a long turn is indistinguishable
1168
- * from a freeze. The message is created once, then rewritten (at most every few
1169
- * seconds — Telegram rate-limits edits) with the latest step and a counter, and
1170
- * finally turned into a short summary. Errors are edited into the same message
1171
- * so the person always sees one continuous trace instead of scattered notes.
1172
- *
1173
- * Reasoning is folded into the same message as a collapsed block, so a turn that
1174
- * thinks for ten minutes still leaves one line in the chat — and the whole trail
1175
- * one tap away.
1176
- */
1177
- async function startProgress(chatId, threadId, lang = config.lang || 'en', task = '', chip = '', thoughtFile = '') {
1178
- const started = Date.now();
1179
- const panelKey = sessionKey(chatId, threadId);
1180
- const steps = [];
1181
- const thinkingParts = [];
1182
- /** Last reported token usage for this turn, for the cache line. */
1183
- const usage = { inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 };
1184
- let messageId = 0;
1185
- let lastEdit = 0;
1186
- let dirty = false;
1187
- let timer = null;
1188
-
1189
- // Short "💭" notes the agent appends with `say.mjs --thought`. The progress
1190
- // message shows the last two, so the person sees the decision trail without
1191
- // a second stream of chat messages. The path is unique per turn (see
1192
- // startTurn) so two turns never share one file.
1193
- const notes = thoughtFile || join(THOUGHT_DIR, `${chatId}_${threadId || 0}.jsonl`);
1194
- let thoughts = [];
1195
- try {
1196
- mkdirSync(THOUGHT_DIR, { recursive: true });
1197
- writeFileSync(notes, '');
1198
- } catch {}
1199
- const thoughtTimer = setInterval(() => {
1200
- let next = [];
1201
- try {
1202
- next = readFileSync(notes, 'utf8')
1203
- .split('\n')
1204
- .filter(Boolean)
1205
- .slice(-2)
1206
- .map((line) => {
1207
- try { return String(JSON.parse(line).text || '').slice(0, 140); } catch { return ''; }
1208
- })
1209
- .filter(Boolean);
1210
- } catch {}
1211
- if (next.join('\n') !== thoughts.join('\n')) {
1212
- thoughts = next;
1213
- schedule();
1214
- }
1215
- }, 3000);
1216
- thoughtTimer.unref?.();
1217
-
1218
- const panel = (final = false) => {
1219
- // The cache line belongs to the outcome, not to every intermediate edit.
1220
- const cache = final && usage.cacheReadTokens
1221
- ? t(lang, 'status.cacheLine', {
1222
- pct: Math.round((usage.cacheReadTokens / Math.max(1, usage.cacheReadTokens + (usage.inputTokens ?? 0))) * 100),
1223
- k: Math.round(usage.cacheReadTokens / 1000),
1224
- })
1225
- : '';
1226
- return progressPanel({
1227
- lang,
1228
- // Two topics run at once in a group, so a card that does not name its topic
1229
- // is unattributable the moment it scrolls: the same 💭 line in the wrong
1230
- // place looks like a cross-topic bug, and half the time it is one. The
1231
- // name comes from Telegram, cached: one API call per topic per process.
1232
- topic: threadId ? t(lang, 'bridge.progress.topic', { n: threadId, name: topicName(chatId, threadId) || t(lang, 'bridge.progress.topicNoName') }) : '',
1233
- seconds: Math.round((Date.now() - started) / 1000),
1234
- // How fast this turn is actually generating, in tokens per second. The
1235
- // number is the turn's average — output tokens over wall time — because
1236
- // that is what "долго" means to the reader: a slow provider and a turn
1237
- // that spends its minutes in tools look identical without it.
1238
- speed: speedOf(usage.outputTokens, Date.now() - started),
1239
- final,
1240
- steps,
1241
- thoughts,
1242
- thinking: thinkingParts.join('\n\n'),
1243
- // `/thoughts off` keeps the block out of the chat and leaves the counter;
1244
- // the log itself is a file the command sends on demand.
1245
- reasoning: state.thinkBlock?.[panelKey] === 'counter' ? 'counter' : 'block',
1246
- task,
1247
- chip,
1248
- cache,
1249
- });
1250
- };
1251
-
1252
- /** Send or edit the panel; `plainText` and a rejected parse fall back to text. */
1253
- const post = async (method, payload, view, keyboard = undefined) => {
1254
- const markup = config.plainText !== true;
1255
- const body = markup
1256
- ? { ...payload, text: view.html, parse_mode: 'HTML' }
1257
- : { ...payload, text: view.plain };
1258
- if (keyboard !== undefined) body.reply_markup = keyboard ?? { inline_keyboard: [] };
1259
- if (!markup) return tg(method, body);
1260
- try {
1261
- return await tg(method, body);
1262
- } catch (error) {
1263
- log(`${method} html failed (${String(error.message).slice(0, 100)}); retrying as plain text`);
1264
- const plain = { ...payload, text: view.plain };
1265
- if (keyboard !== undefined) plain.reply_markup = keyboard ?? { inline_keyboard: [] };
1266
- return tg(method, plain);
1267
- }
1268
- };
1269
-
1270
- try {
1271
- const res = await post('sendMessage', {
1272
- chat_id: chatId,
1273
- disable_web_page_preview: true,
1274
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
1275
- }, panel());
1276
- messageId = res.message_id;
1277
- } catch (error) {
1278
- log(`progress message failed: ${error.message}`);
1279
- }
1280
-
1281
- let lastView = '';
1282
- const edit = async (text, keyboard = undefined, view = null) => {
1283
- if (!messageId) return;
1284
- // Re-sending identical text counts as an edit on the phone (the block
1285
- // collapses and the list re-lays-out), so a no-op must not reach Telegram.
1286
- if (view && keyboard === undefined && view.html === lastView) {
1287
- dirty = false;
1288
- return;
1289
- }
1290
- const payload = {
1291
- chat_id: chatId,
1292
- message_id: messageId,
1293
- disable_web_page_preview: true,
1294
- };
1295
- try {
1296
- if (view) await post('editMessageText', payload, view, keyboard);
1297
- else {
1298
- // Plain text (errors, notes): whatever the caller passes is literal, so
1299
- // it must not be run through the HTML parser.
1300
- const body = { ...payload, text };
1301
- if (keyboard !== undefined) body.reply_markup = keyboard ?? { inline_keyboard: [] };
1302
- await tg('editMessageText', body);
1303
- }
1304
- lastView = view ? view.html : text;
1305
- lastEdit = Date.now();
1306
- } catch (error) {
1307
- // "message is not modified" and rate limits are expected: ignore quietly.
1308
- dirty = false;
1309
- }
1310
- };
1311
-
1312
- function schedule() {
1313
- dirty = true;
1314
- if (timer) return;
1315
- timer = setTimeout(async () => {
1316
- timer = null;
1317
- if (!dirty) return;
1318
- dirty = false;
1319
- await edit('', undefined, panel());
1320
- }, 5000);
1321
- timer.unref?.();
1322
- }
1323
-
1324
- return {
1325
- /** Keep the clock moving during long model thinking: the elapsed time is
1326
- * proof of life, and a frozen counter is what reads as a hang. */
1327
- heartbeat() {
1328
- dirty = true;
1329
- schedule();
1330
- },
1331
- handle(event) {
1332
- if (event.type === 'tool_call') {
1333
- addStep(steps, stepLine(event));
1334
- schedule();
1335
- return;
1336
- }
1337
- // The CLI emits one `thinking` event per committed assistant step, so the
1338
- // panel grows a paragraph at a time — visible while the turn runs, and
1339
- // still there, collapsed, when it ends.
1340
- if (event.type === 'thinking' && event.text) {
1341
- thinkingParts.push(String(event.text));
1342
- // A turn can think for a long time; only the tail of the stream is ever
1343
- // shown, so the head is dropped before it becomes a memory leak.
1344
- if (thinkingParts.join('\n\n').length > 24000) {
1345
- const kept = thinkingParts.join('\n\n').slice(-24000);
1346
- thinkingParts.length = 0;
1347
- thinkingParts.push(kept);
1348
- }
1349
- schedule();
1350
- return;
1351
- }
1352
- // Usage rides on the status events; keep the latest numbers so the final
1353
- // line can show the cache hit rate of this very turn, and so the head can
1354
- // show how fast it is going — "долго" is usually either a slow provider or
1355
- // a turn that spends its time in tools, and the panel could not tell them
1356
- // apart.
1357
- if (event.type === 'status' && event.usage) {
1358
- if (Number.isFinite(event.usage.inputTokens)) usage.inputTokens = event.usage.inputTokens;
1359
- if (Number.isFinite(event.usage.cacheReadTokens)) usage.cacheReadTokens = event.usage.cacheReadTokens;
1360
- if (Number.isFinite(event.usage.outputTokens)) usage.outputTokens = event.usage.outputTokens;
1361
- schedule();
1362
- return;
1363
- }
1364
- if (event.type === 'status' && event.phase === 'step_start') {
1365
- schedule();
1366
- return;
1367
- }
1368
- if (event.type === 'text' && event.text) {
1369
- const first = String(event.text).replace(/\s+/g, ' ').trim().slice(0, 120);
1370
- if (first) {
1371
- steps.push(t(lang, 'bridge.progress.text', { text: first }));
1372
- schedule();
1373
- }
1374
- }
1375
- },
1376
- async finish(result) {
1377
- clearTimeout(timer);
1378
- clearInterval(thoughtTimer);
1379
- if (result?.error) {
1380
- // A failed turn leaves the status message as the error report and swaps
1381
- // «Стоп» for «Повторить»: the person's next move is a retry, not a stop.
1382
- const failedFor = Math.round((Date.now() - started) / 1000);
1383
- const unit = lang === 'en' ? 's' : lang === 'zh' ? '秒' : 'с';
1384
- // A turn stopped by the clock is not a failure to redo: the session and
1385
- // everything it produced are still there, so the useful button is
1386
- // «Продолжить», which asks the agent to pick up where it stopped.
1387
- const timedOut = result.reason === 'timeout';
1388
- const text = timedOut
1389
- ? `⏱ ${t(lang, 'msg.turnHardCap', { minutes: result.minutes ?? '?' })}`
1390
- : `⚠️ ${t(lang, 'status.failed')} · ${failedFor} ${unit}\n${String(result.error).slice(0, 1200)}`;
1391
- await edit(text, timedOut ? continueKeyboard(sessionKey(chatId, threadId), lang) : errorKeyboard(sessionKey(chatId, threadId), lang));
1392
- return true;
1393
- }
1394
- await edit('', null, panel(true));
1395
- return false;
1396
- },
1397
- };
1398
- }
1399
-
1400
- /**
1401
- * Turn a voice note or an audio file into text, echoing the transcript into the
1402
- * chat so the person sees what was understood before the answer lands.
1403
- *
1404
- * Returns '' when nothing was recognised: the failure is already reported in
1405
- * the chat by then, so callers only have to stop.
1406
- */
1407
- async function readVoiceIntoText(msg, chatId, threadId, lang) {
1408
- // Status line first, then replace it with the transcript. One message that
1409
- // visibly turns "🎤 Расшифровываю…" into "🎤 <текст>" tells the person the
1410
- // audio is being read and, when it is done, exactly what was understood —
1411
- // before the agent's reply lands.
1412
- let statusId = 0;
1413
- if (config.voice?.echo !== false) {
1414
- try {
1415
- const res = await tg('sendMessage', {
1416
- chat_id: chatId,
1417
- text: t(lang, 'msg.transcribing'),
1418
- disable_web_page_preview: true,
1419
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
1420
- ...(msg.message_id ? { reply_to_message_id: msg.message_id } : {}),
1421
- });
1422
- statusId = res.message_id;
1423
- } catch (error) {
1424
- log(`voice status failed: ${error.message}`);
1425
- }
1426
- }
1427
- const editOrSend = async (shown, fallback) => {
1428
- if (statusId) {
1429
- await tg('editMessageText', { chat_id: chatId, message_id: statusId, text: shown })
1430
- .catch((err) => log(`voice status edit failed: ${err.message}`));
1431
- } else if (config.voice?.echo !== false) {
1432
- await send(chatId, fallback, threadId, msg.message_id);
1433
- }
1434
- };
1435
- let heard = '';
1436
- let error = '';
1437
- try {
1438
- ({ text: heard, error } = await voiceToText(msg, config.voice));
1439
- } catch (err) {
1440
- const fail = t(lang, 'msg.voiceDownloadFailed', { err: err.message });
1441
- await editOrSend(`⚠️ ${fail}`, fail);
1442
- return '';
1443
- }
1444
- if (!heard) {
1445
- const fail = t(lang, 'msg.voiceNotRecognized', { detail: error ? `: ${error}` : '' });
1446
- await editOrSend(`⚠️ ${fail}`, fail);
1447
- return '';
1448
- }
1449
- log(`voice -> text len=${heard.length}${error ? ` (warn: ${error})` : ''}`);
1450
- const preview = heard.length > 1200 ? `${heard.slice(0, 1200)}…` : heard;
1451
- if (statusId || config.voice?.echo !== false) await editOrSend(`🎤 ${preview}`, `🎤 ${preview}`);
1452
- return heard;
1453
- }
1454
-
1455
- /**
1456
- * Attachments -> the prompt text that hands them to the turn.
1457
- *
1458
- * Takes a list because Telegram delivers an album as several messages sharing
1459
- * one `media_group_id`; the bridge collects them and builds a single hand-over.
1460
- * Every supported attachment becomes the same kind of text here, so a normal
1461
- * turn and a mid-turn steer describe a file identically. `extraArgs` carries
1462
- * per-turn flags (the opt-in vision overlay); a steer cannot apply them to a
1463
- * running turn and leaves it empty.
1464
- */
1465
- async function mediaPrompt(msgs, chatId, threadId, lang, opts = {}) {
1466
- const list = Array.isArray(msgs) ? msgs : [msgs];
1467
- const voiceReady = Boolean(config.voice?.python && config.voice?.script) || Boolean(config.voice?.command);
1468
- const voiceOn = Boolean(config.voice?.enabled) && voiceReady;
1469
- const parts = [];
1470
- let extraArgs = [];
1471
- /** Profile the turn must run on (only an opt-in photo overlay overrides it). */
1472
- let profile = '';
1473
- let caption = '';
1474
- let photo = false;
1475
- for (const msg of list) {
1476
- if (!caption && (msg.caption || '').trim()) caption = msg.caption.trim();
1477
- if (msg.voice || msg.audio) {
1478
- if (!voiceOn) {
1479
- log('audio ignored: voice transcription is off or misconfigured');
1480
- continue;
1481
- }
1482
- const heard = await readVoiceIntoText(msg, chatId, threadId, lang);
1483
- if (heard) parts.push(heard);
1484
- continue;
1485
- }
1486
- // An audio file sent as a document is a voice note with a different
1487
- // wrapper: transcribe it instead of handing over a path nobody can listen to.
1488
- if (msg.document?.mime_type?.startsWith('audio/') && voiceOn) {
1489
- const heard = await readVoiceIntoText({ ...msg, audio: msg.document }, chatId, threadId, lang);
1490
- if (heard) parts.push(heard);
1491
- continue;
1492
- }
1493
- // Photo handling: the turn's own model reads the file through `read_image`.
1494
- // A headless turn on the plain `headless` profile read the Chinese captions
1495
- // off a 720×1560 screenshot and answered with them verbatim, so the vision
1496
- // overlay is opt-in (`vision.enabled`) instead of being applied to every
1497
- // photo — switching each one to a second, billed model was the workaround
1498
- // for a text-only default that no longer applies.
1499
- if (msg.photo) {
1500
- const fileId = msg.photo[msg.photo.length - 1].file_id;
1501
- const file = await tg('getFile', { file_id: fileId });
1502
- const path = join(DIR, `photo-${Date.now()}-${parts.length}.jpg`);
1503
- const bin = await fetch(`https://api.telegram.org/file/bot${token}/${file.file_path}`);
1504
- writeFileSync(path, Buffer.from(await bin.arrayBuffer()));
1505
- parts.push(t(lang, 'prompt.photo', { path }));
1506
- photo = true;
1507
- if (config.vision?.enabled && config.vision?.patch && existsSync(config.vision.patch)) {
1508
- // The desktop host CLI dropped `--patch` (it answers "unknown option"
1509
- // and exits 1 with no output), so the overlay is materialised once as a
1510
- // profile carrying the same model and the turn switches profile instead.
1511
- const visionProfile = ensureProfile(config.vision.patch);
1512
- if (visionProfile) {
1513
- profile = visionProfile;
1514
- log(`photo turn uses profile ${visionProfile} (overlay ${config.vision.patch})`);
1515
- }
1516
- }
1517
- continue;
1518
- }
1519
- // Documents (PDF, zip, source, csv), video and video notes: save under
1520
- // inbox/ and hand the path to the turn. Text-like files are also pasted in
1521
- // as content, so a steer can use them without a tool round-trip.
1522
- const doc = msg.document || msg.video || msg.video_note || msg.animation;
1523
- if (!doc) continue;
1524
- const safe = (doc.file_name || `file-${Date.now()}`).replace(/[^\w.\-]+/g, '_');
1525
- const inbox = join(DIR, 'inbox');
1526
- mkdirSync(inbox, { recursive: true });
1527
- const path = join(inbox, `${Date.now()}-${parts.length}-${safe}`);
1528
- const file = await tg('getFile', { file_id: doc.file_id });
1529
- const bin = await fetch(`https://api.telegram.org/file/bot${token}/${file.file_path}`);
1530
- if (!bin.ok) throw new Error(`document download failed: ${bin.status}`);
1531
- writeFileSync(path, Buffer.from(await bin.arrayBuffer()));
1532
- const type = doc.mime_type || 'unknown';
1533
- const size = doc.file_size || '?';
1534
- const body = msg.document ? inlineText(path, safe) : '';
1535
- parts.push(body
1536
- ? t(lang, 'prompt.fileText', { path, type, size, body })
1537
- : t(lang, 'prompt.file', { path, type, size }));
1538
- log(`document saved ${path} bytes=${doc.file_size || 0}${body ? ` inline=${body.length}` : ''}`);
1539
- }
1540
- let text = parts.filter(Boolean).join('\n\n');
1541
- // A steer cannot apply the vision overlay to a turn that is already running,
1542
- // so the model gets a path and an honest line instead of a silently
1543
- // unreadable image. If the turn died while the file was being fetched, the
1544
- // text is about to become a turn of its own — and there the image *is*
1545
- // readable, so the disclaimer would be a lie.
1546
- const liveNow = opts.stillRunning ? opts.stillRunning() : true;
1547
- if (text && photo && opts.steer && liveNow) text += `\n\n${t(lang, 'prompt.photoMidTurn')}`;
1548
- if (text && caption) text += `\n\n${t(lang, 'prompt.note', { note: caption })}`;
1549
- return { text, extraArgs, profile };
1550
- }
1551
-
1552
- async function handleMessage(msg, album = null) {
1553
- const chatId = msg.chat.id;
1554
- const from = msg.from?.id;
1555
-
1556
- // 1. Never react to our own output: the bot's seeded topic message comes back
1557
- // through getUpdates as a normal group message and used to start a turn.
1558
- if (msg.from?.is_bot) {
1559
- log(`ignored own/service message from bot ${from} (chat ${chatId})`);
1560
- return;
1561
- }
1562
- // 2. Service messages (topic created, pins, joins) carry no task text.
1563
- const attachments = album && album.length ? album : [msg];
1564
- if (!msg.text && !msg.caption && !attachments.some((m) => m.voice || m.audio || m.photo || m.document || m.video || m.video_note || m.animation)) {
1565
- log(`ignored service message chat=${chatId} thread=${msg.message_thread_id ?? 0}`);
1566
- return;
1567
- }
1568
-
1569
- let threadId = threadOf(msg);
1570
- // Whether the person typed in the General topic (the "All" stream), before the
1571
- // lobby rule below moves the message into a topic.
1572
- const typedInGeneral = threadId === 0;
1573
- // 3. The General-chat twin of an already-seeded topic: keep the log line,
1574
- // skip the turn — the topic message already owns this work.
1575
- const twin = threadId === 0 ? topicSeededRecently(msg.text ?? msg.caption ?? '') : 0;
1576
- if (twin > 0) {
1577
- log(`duplicate of topic ${twin} seen in General; answering in the topic instead`);
1578
- threadId = twin;
1579
- }
1580
-
1581
- // 4. Lobby rule (Hermes' topic mode): the General thread is where topics are
1582
- // started, not where work runs. A message with no thread id goes to the
1583
- // most recently active topic instead of forking a root session — that is
1584
- // exactly how a prompt typed in General used to be answered in General
1585
- // while its topic stayed empty.
1586
- if (threadId === 0 && config.generalLobby !== false) {
1587
- const recovered = newestBoundTopic(chatId);
1588
- if (recovered > 0) {
1589
- log(`General message recovered into topic ${recovered}`);
1590
- threadId = recovered;
1591
- }
1592
- }
1593
- // The topic a General message was moved into, or 0 when it stayed where it was.
1594
- const recoveredTopic = typedInGeneral && threadId > 0 ? threadId : 0;
1595
- touchTopic(threadId);
1596
-
1597
- const key = sessionKey(chatId, threadId);
1598
- // Language for everything this turn shows: topic choice, config, then Telegram.
1599
- const learned = !state.lang?.[key];
1600
- const lang = resolveLang(state, key, msg, config);
1601
- // First message in a topic teaches the bridge what it speaks, and the button
1602
- // presses that follow have no message of their own — keep the answer.
1603
- if (learned && state.lang?.[key]) saveState();
1604
- const where = `${chatId}${threadId ? ` topic=${threadId}` : ''}`;
1605
- if (!config.allowedUserIds.includes(from) && !config.allowedUserIds.includes(chatId)) {
1606
- log(`ignored message from ${from} (chat ${chatId})`);
1607
- return;
1608
- }
1609
- let text = (msg.text || msg.caption || '').trim();
1610
- // Voice notes, audio files, photos and documents: transcribe or download
1611
- // locally, then treat the resulting text exactly like typed text. The same
1612
- // helper feeds the mid-turn steer path, so an attachment means the same
1613
- // thing whether the turn is idle or already running.
1614
- //
1615
- // A file almost always arrives with a caption, so the presence of text must
1616
- // not be taken as "no attachment": that dropped every captioned document.
1617
- let extraArgs = [];
1618
- let turnProfile = '';
1619
- if (!msg.text && attachments.some((m) => m.voice || m.audio || m.photo || m.document || m.video || m.video_note || m.animation)) {
1620
- const built = await mediaPrompt(attachments, chatId, threadId, lang);
1621
- if (built.text) text = built.text;
1622
- extraArgs = built.extraArgs;
1623
- turnProfile = built.profile || '';
1624
- }
1625
- if (!text) return;
1626
- log(`in ${where} from=${from} len=${text.length}${msg.is_topic_message ? ' topic-message' : ''}`);
1627
- // A bound set replaces the profile for this turn only: the media route above
1628
- // still wins, because it carries a per-turn model the person chose out loud.
1629
- if (!turnProfile) turnProfile = turnProfileOf(key);
1630
-
1631
- // A brand-new forum topic starts empty: the title says what the person wants
1632
- // but the thread itself has no message, so scrolling back shows a blank
1633
- // hole. Seed it with the incoming text and pin the seed, which also pins the
1634
- // topic to the top of the list — the owner asked for exactly that.
1635
- //
1636
- // Seeding runs once per topic: a message written inside an existing topic is
1637
- // already visible there, and seeding it again would duplicate the person's
1638
- // own words.
1639
- if (threadId > 0 && msg.is_topic_message && !topicSeeded(threadId)) {
1640
- const seed = await ensureTopicSeed(chatId, threadId, text);
1641
- if (seed) {
1642
- log(`topic ${threadId} seeded with message=${seed}`);
1643
- await logTopicToGeneral(chatId, threadId, text, lang);
1644
- }
1645
- }
1646
-
1647
- // A tap on the persistent keyboard (`/menu on`) arrives as its own label,
1648
- // with no slash: "Меню", "Статус", "Стоп", "Новый". Only while the keyboard is
1649
- // on — the same word typed by hand is a prompt, not a command. The label is
1650
- // matched in every language, because the keyboard outlives a /lang switch.
1651
- if (state.menu?.[key]) {
1652
- const mapped = ['ru', 'en', 'zh']
1653
- .map((code) => keyboardCommand(text, { t: (k, v) => t(code, k, v) }))
1654
- .find(Boolean);
1655
- if (mapped) {
1656
- log(`menu key "${text}" -> ${mapped} for ${key}`);
1657
- text = mapped;
1658
- }
1659
- }
1660
-
1661
- const space = text.indexOf(' ');
1662
- const head = space === -1 ? text : text.slice(0, space);
1663
- const command = commandOf(head);
1664
- const arg = space === -1 ? '' : text.slice(space + 1).trim();
1665
-
1666
- // `/apprestart.confirm` (no space) is a real way to mistype the service
1667
- // command and used to fall through to a full AI turn. Map the collapsed
1668
- // forms onto the canonical command + argument instead.
1669
- //
1670
- // Heads are matched WITHOUT their punctuation, so `/apprestart.confirm` and
1671
- // `/app-restart-confirm` both arrive here as "apprestartconfirm".
1672
- const collapsed = command.replace(/^\//, '').replace(/[.-]+/g, '');
1673
- const known = new Set(CONTROL_COMMANDS);
1674
- let effective = known.has(collapsed) ? `/${collapsed}` : '';
1675
- let effectiveArg = arg;
1676
- if (collapsed === 'apprestart' || collapsed === 'apprestartconfirm') {
1677
- effective = '/app';
1678
- // The dotted/solid form already says "restart", so confirm is the only
1679
- // missing word: `/apprestart.confirm` must mean `/app restart confirm`.
1680
- effectiveArg = arg || 'restart confirm';
1681
- } else if (collapsed === 'restartconfirm') {
1682
- effective = '/restart';
1683
- effectiveArg = arg || 'confirm';
1684
- }
1685
- if (effective && effective !== command) {
1686
- log(`command alias: ${head} -> ${effective} ${effectiveArg}`);
1687
- }
1688
- if (effectiveArg === 'restartconfirm' || effectiveArg === 'restart.confirm') effectiveArg = 'restart confirm';
1689
-
1690
- // General is the lobby: a prompt written there runs in the most recently active
1691
- // topic so one project stays in one place. A command that CHANGES things must
1692
- // not silently change a topic the person is not looking at — `/new` there wiped
1693
- // the session of another topic and `/rewind` rolled one back, and the answer
1694
- // appeared in that topic rather than where it was typed. Reading commands and
1695
- // `/stop` still follow the work, because that is what the lobby is for.
1696
- if (recoveredTopic > 0 && effective && !GENERAL_SAFE.has(effective.slice(1))) {
1697
- const named = topicName(chatId, recoveredTopic) || `#${recoveredTopic}`;
1698
- log(`refused ${effective} in General; it belongs to topic ${recoveredTopic}`);
1699
- await send(chatId, t(lang, 'msg.generalGuard', { cmd: effective, topic: named }), 0);
1700
- return;
1701
- }
1702
-
1703
- // An unknown slash command must never become an AI turn: it burns money and
1704
- // answers something the person did not ask. Answer with the menu instead.
1705
- if (command && !effective) {
1706
- log(`unknown command ${head} from ${from}`);
1707
- // Ephemeral: a mistyped command is usually a typo of a real one, so the menu
1708
- // appears long enough to pick from it and then clears itself.
1709
- await sendEphemeral(
1710
- chatId,
1711
- `${t(lang, 'msg.unknownCommand', { cmd: head })}
1712
-
1713
- ${t(lang, 'help.body')}`,
1714
- threadId,
1715
- msg.message_id
1716
- );
1717
- return;
1718
- }
1719
-
1720
- if (effective) {
1721
- const handled = await handleControl({
1722
- command: effective,
1723
- lang,
1724
- arg: effectiveArg,
1725
- text,
1726
- chatId,
1727
- threadId,
1728
- key,
1729
- state,
1730
- config,
1731
- activeTurns,
1732
- saveState,
1733
- log,
1734
- send,
1735
- // What `/jobs` shows: the turns that hold a slot right now and how many
1736
- // wait behind them. `queues` counts a topic that is running too, so the
1737
- // waiters are the keys without an active turn.
1738
- jobs: () => ({
1739
- active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
1740
- queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
1741
- max: MAX_PARALLEL,
1742
- }),
1743
- api: tg,
1744
- sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
1745
- seedTopic: ensureTopicSeed,
1746
- profile: profileOf(key),
1747
- prices: (filter) => {
1748
- const route = modelOf(profileOf(key));
1749
- // A provider page is optional: without `pricesUrl` the answer comes from
1750
- // the public models.dev catalog, so no install is tied to one vendor.
1751
- return renderPrices(filter, {
1752
- model: route.model,
1753
- provider: route.provider,
1754
- pageUrl: config.pricesUrl || '',
1755
- lang,
1756
- });
1757
- },
1758
- reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
1759
- stopTurn: (k) => {
1760
- const child = activeTurns.get(k);
1761
- if (!child) return false;
1762
- try {
1763
- child.kill();
1764
- activeTurns.delete(k);
1765
- return true;
1766
- } catch {
1767
- return false;
1768
- }
1769
- },
1770
- });
1771
- if (handled) return;
1772
- }
1773
-
1774
- // Remember this prompt so the «Повторить» button after a failure has
1775
- // something to resend. Bounded: only the latest prompt per topic matters.
1776
- lastPrompt.set(key, msg);
1777
-
1778
- const stop = { done: false };
1779
- const typing = typingLoop(chatId, threadId, stop);
1780
- const started = Date.now();
1781
- // Capture the session BEFORE the turn starts. A second message for the same
1782
- // topic can overwrite `state.sessions[key]` while this turn is still running
1783
- // (two messages a few seconds apart, or a copy-paste), and the late writer
1784
- // then attached a fresh session id to a conversation that already had one.
1785
- const sessionAtStart = state.sessions[key];
1786
- // Remember the topic a turn is running in: it is where a release notice goes,
1787
- // since a notice is about the install and the install serves every topic.
1788
- if (state.lastKey !== key) {
1789
- state.lastKey = key;
1790
- saveState();
1791
- }
1792
- // Project directory bound to this topic (set with /cd); config.cwd otherwise.
1793
- const cwd = (state.cwd && state.cwd[key]) || config.cwd;
1794
- // What the person actually wrote, before any injected block: the progress
1795
- // message echoes it back so the first thing they see names their task, not a
1796
- // generic spinner.
1797
- const request = text;
1798
-
1799
- // Desktop-style goal: the topic's goal and task list travel with every turn,
1800
- // so a fresh session after /new still knows what the project is aiming at.
1801
- // Without a goal the turn still gets the one line that says how to start one:
1802
- // a plan nobody can see is not a plan, and the agent cannot ask a question it
1803
- // does not know exists.
1804
- const topicGoal = goalOf(state, key);
1805
- if (topicGoal) text = `${renderPromptBlock(topicGoal, key, GOAL_CMD)}\n\n---\n\n${text}`;
1806
- else text = `${t(lang, 'prompt.taskHint', { goal: GOAL_CMD, key })}\n\n---\n\n${text}`;
1807
-
1808
- // Working notes: the agent writes a 💭 line at each decision point with
1809
- // `say.mjs --thought`, and the progress message shows the last two. Off means
1810
- // no instruction at all, so nothing is written and nothing is displayed.
1811
- //
1812
- // Each turn gets a file of its own, named `<chat>_<thread>_<turn>.jsonl`, and
1813
- // its path travels with the turn: two topics working at once used to share
1814
- // one note file, so each saw the other's lines and `say.mjs` had to guess
1815
- // which topic a note belonged to. The bridge keeps a stable alias for the
1816
- // topic (what older tools and the panel read) pointing at this turn's file.
1817
- const turnId = `${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
1818
- const thoughtFile = join(THOUGHT_DIR, `${chatId}_${threadId || 0}_${turnId}.jsonl`);
1819
- // The alias is the plain topic name too; it is written as the turn's file so
1820
- // a reader that never heard of DSH_TG_THOUGHT still finds this turn's notes.
1821
- const thoughtEnv = { DSH_TG_THOUGHT: thoughtFile };
1822
- if (reasoningOf(state, config, key)) {
1823
- text = `${t(lang, 'prompt.reasoning', { say: join(DIR, 'say.mjs') })}\n\n---\n\n${text}`;
1824
- }
1825
-
1826
- // Live progress: one status message per turn, rewritten as the agent works.
1827
- // Without it a long turn and a hung turn looked exactly alike in the chat.
1828
- const progress = await startProgress(chatId, threadId, lang, request, settingsChipOf(key), thoughtFile);
1829
- // Turn telemetry for the log: what the agent did, how much it cost, on which
1830
- // model. Without it /logs shows only "in" and "sent" — useless when asking
1831
- // "why did this take 9 minutes".
1832
- const telemetry = { steps: 0, tools: 0, inputTokens: 0, cacheReadTokens: 0, model: modelOf(profileOf(key)).model };
1833
- const onEvent = (event) => {
1834
- try {
1835
- // The id of the session this process actually works in. A new topic has
1836
- // no id until the CLI emits one, and steering needs it before that.
1837
- if (event.type === 'session' && event.sessionId) liveSessions.set(key, event.sessionId);
1838
- progress.handle(event);
1839
- if (event.type === 'tool_call') {
1840
- telemetry.tools += 1;
1841
- telemetry.steps += 1;
1842
- log(` tool[${telemetry.steps}] ${(stepLine(event) || event.tool || 'tool').slice(0, 140)}`);
1843
- } else if (event.type === 'tool_result') {
1844
- const failed = event.status && event.status !== 'completed';
1845
- log(` tool[${telemetry.steps}] ${failed ? 'ERROR' : 'ok'} ${String(event.tool || '').slice(0, 40)}`);
1846
- } else if (event.type === 'status' && event.usage) {
1847
- if (Number.isFinite(event.usage.inputTokens)) telemetry.inputTokens = event.usage.inputTokens;
1848
- if (Number.isFinite(event.usage.cacheReadTokens)) telemetry.cacheReadTokens = event.usage.cacheReadTokens;
1849
- }
1850
- } catch {}
1851
- };
1852
- let result = await runTurnLive(text, sessionAtStart, key, { onEvent, onAbort: () => killTurn(key), onHeartbeat: () => progress.heartbeat(), env: thoughtEnv, extraArgs, cwd, lang, profile: turnProfile });
1853
- if (result.error && /unknown id|not found|не найдена|was recorded in/i.test(result.error) && sessionAtStart) {
1854
- delete state.sessions[key];
1855
- log(`session dropped for ${where}: recorded in another directory, starting fresh`);
1856
- result = await runTurnLive(text, '', key, { onEvent, onAbort: () => killTurn(key), onHeartbeat: () => progress.heartbeat(), env: thoughtEnv, extraArgs, cwd, lang, profile: turnProfile });
1857
- }
1858
- // Provider failover: the headless profile has no failover plugin, so one busy
1859
- // route ("all providers are busy", 503, or a turn that emits nothing at all)
1860
- // used to end as silence. Retry the SAME prompt on the next model in the
1861
- // chain before giving up — the person cares about an answer, not the vendor.
1862
- const chain = Array.isArray(config.fallbackModels) ? config.fallbackModels : [];
1863
- // A dead paid balance is not a "busy provider": it must trigger the free
1864
- // chain as well, otherwise the bridge sits on AUTH 403 and gives up.
1865
- const FALLBACK_TRIGGERS = /RATE_LIMIT|503|all providers|нет активности|EMPTY_RESPONSE|TIMEOUT|overloaded|AUTH|403|insufficient_user_quota|quota|UNKNOWN_MODEL|MISSING_CREDENTIAL/i;
1866
- const QUOTA_LIKE = /insufficient_user_quota|AUTH\b|\b403\b|\b401\b|quota|balance|баланс|payment|billing/i;
1867
- // "get_channel_failed / all providers are busy" is the provider's own channel
1868
- // pool, not the model: when it is down, it is down for every model in the
1869
- // chain. One probe then answers in seconds what four full turns spent 741
1870
- // seconds discovering.
1871
- const CHANNEL_DOWN = /get_channel_failed|all providers|no providers|503/i;
1872
- const tried = [];
1873
- for (const entry of chain) {
1874
- if (!result.error || !FALLBACK_TRIGGERS.test(result.error)) break;
1875
- if (!entry.patch || !existsSync(entry.patch)) continue;
1876
- // The provider's channel pool is down: every model in the chain will answer
1877
- // the same 503. Ask once, quickly, and say so instead of burning a turn per
1878
- // model. A probe that DOES answer proves the pool is back — then the chain
1879
- // goes on, and the fallback at hand is tried as usual.
1880
- if (tried.length >= 1 && CHANNEL_DOWN.test(result.error)) {
1881
- const verdict = await probeModel(config.primaryModel || 'deepseek-v4.1-flash-1017');
1882
- log(`channel down after ${tried.length} model(s): probe says ${verdict.kind}; not trying ${entry.model}`);
1883
- if (!verdict.ok) break;
1884
- }
1885
- const quotaLike = QUOTA_LIKE.test(result.error);
1886
- // Quota failures never deserve a retry of the same model: the balance is
1887
- // gone, so waiting is pure loss. Anything else gets one retry at most.
1888
- const reason = quotaLike ? t(lang, 'bridge.fallback.quota') : t(lang, 'bridge.fallback.noAnswer');
1889
- tried.push(`${entry.model}: ${String(result.error).slice(0, 120)}`);
1890
- log(`fallback to ${entry.model} for ${where} reason=${quotaLike ? 'quota' : 'transient'} after: ${String(result.error).slice(0, 120)}`);
1891
- telemetry.model = entry.model;
1892
- await send(chatId, t(lang, 'bridge.fallback.switched', {
1893
- reason,
1894
- model: entry.model,
1895
- free: entry.free ? ' (free)' : '',
1896
- }), threadId);
1897
- result = await runTurnLive(text, sessionAtStart, key, {
1898
- onEvent,
1899
- onAbort: () => killTurn(key),
1900
- onHeartbeat: () => progress.heartbeat(), env: thoughtEnv,
1901
- // Same overlay problem as the vision turn: the host CLI has no --patch.
1902
- // A patch file that is missing or unreadable must not turn into an empty
1903
- // --profile argument, so the topic's own profile is the fallback.
1904
- profile: ensureProfile(entry.patch) || profileOf(key) || config.profile,
1905
- cwd,
1906
- lang,
1907
- });
1908
- if (!result.error) break;
1909
- }
1910
- // Every model refused. Before saying "all models are unavailable", ask each
1911
- // channel directly with a 1-token request: a 503 storm usually clears within
1912
- // seconds, and the verdict tells the person whether the balance is gone or the
1913
- // provider is merely busy — the old message always claimed quota.
1914
- let probeKind = '';
1915
- if (result.error && FALLBACK_TRIGGERS.test(result.error)) {
1916
- const models = [config.primaryModel || 'deepseek-v4.1-flash-1017', ...chain.map((entry) => entry.model)];
1917
- const { live, verdicts } = await firstLiveModel(models);
1918
- if (live) {
1919
- log(`probe: ${live.model} answers after ${verdicts.length} check(s), retrying the turn there`);
1920
- const entry = chain.find((item) => item.model === live.model);
1921
- result = await runTurnLive(text, sessionAtStart, key, {
1922
- onEvent,
1923
- onAbort: () => killTurn(key),
1924
- onHeartbeat: () => progress.heartbeat(),
1925
- profile: entry ? ensureProfile(entry.patch) : turnProfile,
1926
- cwd,
1927
- lang,
1928
- });
1929
- } else {
1930
- // Nothing answers: the verdict is the only useful part of the failure.
1931
- probeKind = describeVerdicts(verdicts);
1932
- log(`probe: no channel answers (${verdicts.map((v) => `${v.model}:${v.kind}`).join(', ')})`);
1933
- }
1934
- }
1935
- // Every model refused — or the provider's own channel pool was down and the
1936
- // chain stopped early, which is the same answer to the person: one message
1937
- // naming the causes, not a cascade of errors.
1938
- if (result.error && tried.length > 0 && (probeKind || tried.length >= (Array.isArray(config.fallbackModels) ? config.fallbackModels.length : 0))) {
1939
- log(`all fallbacks exhausted for ${where}: ${tried.length} probe=${probeKind || 'n/a'}`);
1940
- const verdictLine = probeKind ? `\n${probeHint(probeKind, lang)}` : '';
1941
- result = {
1942
- sessionId: result.sessionId,
1943
- text: '',
1944
- error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }) + verdictLine,
1945
- };
1946
- }
1947
- // A session opened in the desktop UI holds its write handle, so the CLI
1948
- // refuses to adopt it. Retry once, then continue in a fresh session instead
1949
- // of failing the user's message.
1950
- if (result.error && /already owned by an active write handle/i.test(result.error)) {
1951
- await new Promise((resolve) => setTimeout(resolve, 3000));
1952
- result = await runTurnLive(text, state.sessions[key] ?? sessionAtStart, key, { onEvent, onAbort: () => killTurn(key), onHeartbeat: () => progress.heartbeat(), env: thoughtEnv, extraArgs, cwd, lang, profile: turnProfile });
1953
- if (result.error && /already owned by an active write handle/i.test(result.error)) {
1954
- delete state.sessions[key];
1955
- saveState();
1956
- result = await runTurnLive(text, '', key, { onEvent, onAbort: () => killTurn(key), onHeartbeat: () => progress.heartbeat(), env: thoughtEnv, extraArgs, cwd, lang, profile: turnProfile });
1957
- if (!result.error) result.text = `${t(lang, 'bridge.fallback.sessionBusy')}\n\n${result.text}`;
1958
- }
1959
- }
1960
- stop.done = true;
1961
- await typing;
1962
- // Name the cause once, in a short stable code, so a screenshot of the error is
1963
- // enough to find the fix — and every code has a concrete next step, not "try again".
1964
- if (result.error) result.error = explainFailure(result.error, lang);
1965
- await progress.finish(result);
1966
-
1967
- // Never move a topic onto a different session once it has one. A retry that
1968
- // fell back to a fresh session (busy write handle, stale id) is reported in
1969
- // the reply, but persisting it would silently fork the conversation and drop
1970
- // the project context the next message depends on.
1971
- if (result.sessionId && !result.error) {
1972
- if (!sessionAtStart) {
1973
- state.sessions[key] = result.sessionId;
1974
- saveState();
1975
- } else if (result.sessionId !== sessionAtStart) {
1976
- log(`kept session ${sessionAtStart} for ${where} (turn ran in ${result.sessionId})`);
1977
- state.sessions[key] = sessionAtStart;
1978
- saveState();
1979
- }
1980
- }
1981
- const seconds = Math.round((Date.now() - started) / 1000);
1982
- const cachePct = telemetry.cacheReadTokens
1983
- ? Math.round((telemetry.cacheReadTokens / Math.max(1, telemetry.cacheReadTokens + telemetry.inputTokens)) * 100)
1984
- : 0;
1985
- const summary = `tools=${telemetry.tools} tokens=${telemetry.inputTokens} cache=${cachePct}% model=${telemetry.model} cwd=${cwd}`;
1986
- if (result.error) {
1987
- // The status message already carries the failure (progress.finish turned it
1988
- // into the error report), so only the log gets the detail here — a second
1989
- // ⚠️ message would just duplicate it.
1990
- log(`turn failed ${where} ${seconds}s ${summary} :: ${result.error.slice(0, 400)}`);
1991
- return;
1992
- }
1993
- log(`turn ok ${where} ${seconds}s session=${result.sessionId} ${summary}`);
1994
- await send(chatId, result.text || t(lang, 'bridge.progress.emptyReply'), threadId);
1995
- }
1996
-
1997
- // `probeHint` lives in model-probe.mjs: this file used it at the call site and
1998
- // defined it below, and the hint never reached the person.
1999
-
2000
-
2001
- // Per-topic turn queues: one turn at a time inside a topic, different topics run
2002
- // in parallel. Bounded, because every turn is a full Electron process.
2003
- const queues = new Map();
2004
- const waiting = [];
2005
- let running = 0;
2006
- const MAX_PARALLEL = 3;
2007
-
2008
- function acquire() {
2009
- if (running < MAX_PARALLEL) {
2010
- running += 1;
2011
- return Promise.resolve();
2012
- }
2013
- return new Promise((resolve) => waiting.push(resolve));
2014
- }
2015
-
2016
- function release() {
2017
- const next = waiting.shift();
2018
- if (next) next();
2019
- else running -= 1;
2020
- }
2021
-
2022
- /**
2023
- * Deferred restart: exit only when nothing is in flight.
2024
- *
2025
- * Killing the bridge from inside a turn kills that turn, so a code update used
2026
- * to mean a lost answer. The protocol is: a `restart.pending` marker appears →
2027
- * the bridge finishes the current work, lets the supervisor start a fresh
2028
- * process, and only exits when the queue is empty. Exit code 75 is the signal a
2029
- * supervisor recognises as "please start me again".
2030
- */
2031
- function maybeExitForRestart() {
2032
- if (!existsSync(RESTART_MARKER)) return;
2033
- if (running > 0 || queues.size > 0) return;
2034
- log('restart.pending honoured: exiting 75 for the supervisor');
2035
- try { unlinkSync(RESTART_MARKER); } catch {}
2036
- setTimeout(() => process.exit(75), 300).unref?.();
2037
- }
2038
-
2039
- /**
2040
- * Queue notices, one per topic. A notice exists only while the person is
2041
- * waiting: the moment the queued turn starts it is deleted, so a long session
2042
- * does not leave a column of "идёт уже 7 мин" messages behind (it did).
2043
- */
2044
- const busyNotices = new Map();
2045
-
2046
- async function clearBusyNotice(key) {
2047
- const notice = busyNotices.get(key);
2048
- if (!notice) return;
2049
- busyNotices.delete(key);
2050
- try {
2051
- await tg('deleteMessage', { chat_id: notice.chatId, message_id: notice.messageId });
2052
- } catch (error) {
2053
- log(`busy notice delete failed: ${error.message}`);
2054
- }
2055
- }
2056
-
2057
- /**
2058
- * Whether this profile can receive mid-turn steers. The bridge only writes a
2059
- * job when the `steer-inbox` plugin is actually wired into the profile; without
2060
- * it the file would sit unread until it expired, and the message would be lost.
2061
- * In that case the message queues the old way.
2062
- */
2063
- let steerReady;
2064
- function steerAvailable(profile = config.profile || 'headless') {
2065
- if (steerReady !== undefined && steerReady.profile === profile) return steerReady.ready;
2066
- try {
2067
- const patch = readFileSync(join(DSH_HOME, 'profiles', profile, 'cordis.patch.yml'), 'utf8');
2068
- steerReady = { profile, ready: /steer-inbox/.test(patch) };
2069
- } catch {
2070
- steerReady = { profile, ready: false };
2071
- }
2072
- return steerReady.ready;
2073
- }
2074
-
2075
- /**
2076
- * Hand a message to the turn that is already running.
2077
- *
2078
- * The turn is a separate process, so the bridge writes a job the `steer-inbox`
2079
- * plugin picks up and feeds to `agent.steer()` — next-step input. The agent is
2080
- * told (in the job, by the plugin) to send one short line into the chat via
2081
- * say.mjs; the fallback below covers a model that stays silent.
2082
- */
2083
- function steerRunningTurn(msg, text, sessionId, thread) {
2084
- const key = sessionKey(msg.chat.id, thread);
2085
- const lang = resolveLang(state, key, msg, config);
2086
- const job = writeSteerJob(STEER_DIR, {
2087
- sessionId,
2088
- text,
2089
- chatId: msg.chat.id,
2090
- threadId: thread,
2091
- lang,
2092
- say: SAY,
2093
- });
2094
- log(`steer ${job.id} -> ${sessionId} (${text.length} chars)`);
2095
- // Confirm the moment the job is written, not 90 seconds later. The plugin
2096
- // hands it to the running agent at its next step, and a step can be a
2097
- // six-minute test run: without this line the addition looked lost, which is
2098
- // exactly what "steer стала хуже" describes. The wait notice below then only
2099
- // speaks when the job really has not been picked up.
2100
- send(msg.chat.id, t(lang, 'steer.queued'), thread).catch(() => {});
2101
- watchSteer(job, msg, text, thread, lang);
2102
- return job;
2103
- }
2104
-
2105
- /**
2106
- * Follow one steer job until it is either acknowledged by the model or taken by
2107
- * the plugin.
2108
- *
2109
- * Two failure modes need cover: a model that stays silent (one neutral line
2110
- * after 90 s), and a job that never reached the agent because the turn ended
2111
- * first — that addition must become its own turn instead of expiring unseen in
2112
- * the directory.
2113
- */
2114
- function watchSteer(job, msg, text, thread, lang) {
2115
- const key = sessionKey(msg.chat.id, thread);
2116
- const acked = () => existsSync(join(STEER_DIR, 'acks', `${job.id}.json`));
2117
- const consumed = () => existsSync(join(STEER_DIR, 'done', `${job.id}.json`));
2118
- const check = async (attempt) => {
2119
- try {
2120
- if (acked() || consumed()) return;
2121
- if (activeTurns.has(key)) {
2122
- if (attempt === 0) {
2123
- log(`steer ${job.id} unacknowledged after 90s; sending fallback`);
2124
- await send(msg.chat.id, t(lang, 'steer.ackFallback'), thread);
2125
- }
2126
- setTimeout(() => check(attempt + 1), 60_000).unref?.();
2127
- return;
2128
- }
2129
- // The turn is over and the plugin never picked the job up: deliver it as
2130
- // a turn of its own, otherwise the person's addition is silently lost.
2131
- const pending = join(STEER_DIR, `${job.id}.json`);
2132
- if (!existsSync(pending)) return;
2133
- try { unlinkSync(pending); } catch {}
2134
- log(`steer ${job.id} not consumed by the turn; re-queued as a new turn`);
2135
- enqueue(key, () => handleMessage({
2136
- chat: msg.chat,
2137
- from: msg.from,
2138
- message_id: 0,
2139
- message_thread_id: thread || undefined,
2140
- is_topic_message: thread > 0,
2141
- text,
2142
- }));
2143
- } catch (error) {
2144
- log(`steer watch failed for ${job.id}: ${error.message}`);
2145
- }
2146
- };
2147
- setTimeout(() => check(0), 90_000).unref?.();
2148
- }
2149
-
2150
- /**
2151
- * Attachment sent while a turn is running: transcribe/download it first, then
2152
- * steer the resulting text into the same turn. Echoing the transcript is the
2153
- * only confirmation the person gets that the audio was understood, so the
2154
- * helper does that before the steer is written.
2155
- */
2156
- async function steerMediaMessage(msgs, sessionId, key, thread, lang) {
2157
- const list = Array.isArray(msgs) ? msgs : [msgs];
2158
- const first = list[0];
2159
- const wasRunning = activeTurns.has(key);
2160
- const built = await mediaPrompt(list, first.chat.id, thread, lang, {
2161
- steer: true,
2162
- stillRunning: () => activeTurns.has(key),
2163
- });
2164
- if (!built.text) {
2165
- log('steer media produced no text; nothing injected');
2166
- return;
2167
- }
2168
- if (activeTurns.has(key)) {
2169
- steerRunningTurn(first, built.text, sessionId, thread);
2170
- return;
2171
- }
2172
- // Transcribing and downloading take seconds; the turn this addition was meant
2173
- // for may already be gone. Writing the job anyway left the addition in the
2174
- // directory until `watchSteer` noticed — a minute of silence for a voice note
2175
- // that arrived half a second too late. The prepared text (transcript, file
2176
- // path, caption) is already the whole request, so run it as its own turn.
2177
- log(`steer media: turn ended during prep (was ${wasRunning ? 'running' : 'gone'}), delivering as a turn (${key})`);
2178
- enqueue(key, () => handleMessage({
2179
- chat: first.chat,
2180
- from: first.from,
2181
- message_id: 0,
2182
- message_thread_id: thread || undefined,
2183
- is_topic_message: thread > 0,
2184
- text: built.text,
2185
- }));
2186
- }
2187
-
2188
- // ------------------------------------------------------------------ albums
2189
- //
2190
- // Telegram delivers an album as one update per file, a few hundred ms apart,
2191
- // all sharing a `media_group_id`. Left alone, ten photos became ten steers (or
2192
- // ten turns): the person picked ten files and meant one request. Collect the
2193
- // group and hand it over once.
2194
-
2195
- /** Quiet time after the last item before the album is handed over. */
2196
- const ALBUM_QUIET_MS = 1200;
2197
- /** Hard ceiling: a slow upload must not hold the batch forever. */
2198
- const ALBUM_MAX_MS = 4000;
2199
-
2200
- const albumBuffer = createAlbumBuffer({
2201
- quietMs: ALBUM_QUIET_MS,
2202
- maxMs: ALBUM_MAX_MS,
2203
- onFlush: (msgs) => {
2204
- void deliverAlbum(msgs);
2205
- },
2206
- });
2207
-
2208
- function bufferAlbum(msg) {
2209
- albumBuffer.push(`${msg.chat.id}:${threadOf(msg)}:${msg.media_group_id}`, msg);
2210
- }
2211
-
2212
- /** One album -> one steer when a turn runs, otherwise one turn. */
2213
- async function deliverAlbum(msgs) {
2214
- const first = msgs[0];
2215
- const key = sessionKey(first.chat.id, threadOf(first));
2216
- const thread = threadOf(first);
2217
- const lang = resolveLang(state, key, first, config);
2218
- const sessionId = liveSessions.get(key) || state.sessions[key];
2219
- log(`album ${first.media_group_id}: ${msgs.length} item(s) in ${key}`);
2220
- // Decide at flush time, not at send time: the buffer holds the photos for up
2221
- // to four seconds, and a turn that ended in that window must still get an
2222
- // answer rather than a silent drop. `steerMediaMessage` re-checks on its own
2223
- // and quotes the built prompt into a turn when the steered turn is gone.
2224
- if (config.steerDuringTurn !== false && steerAvailable(profileOf(key)) && sessionId) {
2225
- try {
2226
- await steerMediaMessage(msgs, sessionId, key, thread, lang);
2227
- return;
2228
- } catch (error) {
2229
- log(`album steer failed, queueing a normal turn: ${error.message}`);
2230
- }
2231
- }
2232
- enqueue(key, () => handleMessage(first, msgs));
2233
- }
2234
-
2235
- function enqueue(key, task, onBusy) {
2236
- const prev = queues.get(key) || Promise.resolve();
2237
- const queued = queues.has(key);
2238
- const run = prev
2239
- .then(() => acquire())
2240
- .then(async () => {
2241
- // The person was told "your message is queued"; that notice has done its
2242
- // job the moment the turn starts and must not linger in the chat.
2243
- await clearBusyNotice(key);
2244
- // Remember when the turn actually started: the queue notice has to say
2245
- // "идёт уже 24 мин", not just "занято" — silence is what reads as a hang.
2246
- turnStartedAt.set(key, Date.now());
2247
- return task();
2248
- })
2249
- .catch((error) => log(`turn queue error ${key}: ${error.message}`))
2250
- .finally(() => {
2251
- turnStartedAt.delete(key);
2252
- clearBusyNotice(key).catch(() => {});
2253
- release();
2254
- if (queues.get(key) === run) queues.delete(key);
2255
- // A deferred restart waits for exactly this moment: the answer is out and
2256
- // the queue is empty.
2257
- maybeExitForRestart();
2258
- });
2259
- // Say "this topic is busy" instead of leaving the person staring at silence:
2260
- // a second message in the same topic waits for the first turn, which can be
2261
- // minutes, and looked exactly like a hang.
2262
- if (queued && typeof onBusy === 'function') {
2263
- try {
2264
- Promise.resolve(onBusy()).catch(() => {});
2265
- } catch {}
2266
- }
2267
- queues.set(key, run);
2268
- return run;
2269
- }
2270
-
2271
- // ------------------------------------------------------------------ кнопки UI
2272
- //
2273
- // One place decides what each button means. The callback payload is short
2274
- // (`stop`, `retry`, `ap:a:1`) because Telegram caps it at 64 bytes; the context
2275
- // a press needs (which turn, which approval) lives in `uiState` below.
2276
-
2277
- /** Last prompt per session key, so «Повторить» can resend it. */
2278
- const lastPrompt = new Map();
2279
-
2280
- /** Pending approval requests: id -> { key, chatId, threadId, resolve, timer. */
2281
- const approvals = new Map();
2282
- // A rewind card is used once - a fast double tap must not cut twice.
2283
- const rewindUsed = new Set();
2284
- let approvalSeq = 0;
2285
-
2286
- function errorKeyboard(key, lang = config.lang || 'en') {
2287
- return {
2288
- inline_keyboard: [
2289
- [
2290
- { text: `🔁 ${t(lang, 'btn.retry')}`, callback_data: 'retry' },
2291
- { text: `🩺 ${t(lang, 'btn.doctor')}`, callback_data: 'doctor' },
2292
- ],
2293
- ],
2294
- };
2295
- }
2296
-
2297
- /** A turn stopped by the clock: the work is not lost, so offer to go on. */
2298
- function continueKeyboard(key, lang = config.lang || 'en') {
2299
- return {
2300
- inline_keyboard: [
2301
- [
2302
- { text: `⏵ ${t(lang, 'btn.continue')}`, callback_data: 'resume' },
2303
- { text: `🩺 ${t(lang, 'btn.doctor')}`, callback_data: 'doctor' },
2304
- ],
2305
- ],
2306
- };
2307
- }
2308
-
2309
- function approvalKeyboard(requestId, lang = config.lang || 'en') {
2310
- return {
2311
- inline_keyboard: [
2312
- [
2313
- { text: t(lang, 'bridge.approval.allow'), callback_data: `ap:y:${requestId}` },
2314
- { text: t(lang, 'bridge.approval.deny'), callback_data: `ap:n:${requestId}` },
2315
- ],
2316
- [{ text: t(lang, 'bridge.approval.always'), callback_data: `ap:a:${requestId}` }],
2317
- ],
2318
- };
2319
- }
2320
-
2321
- /**
2322
- * Ask the person to confirm one action.
2323
- *
2324
- * The turn waits here until a button is pressed or the timeout fires, so a
2325
- * prompt must never be left unanswered: an unanswered approval would hang the
2326
- * queue forever.
2327
- */
2328
- function requestApproval(chatId, threadId, key, prompt) {
2329
- const id = String(++approvalSeq);
2330
- // The language of the topic the approval arrived in: an English chat must not
2331
- // get Russian buttons on the question that decides whether the agent acts.
2332
- const lang = langFor(chatId, threadId);
2333
- return new Promise((resolve) => {
2334
- const timer = setTimeout(() => {
2335
- if (!approvals.has(id)) return;
2336
- approvals.delete(id);
2337
- resolve({ allowed: false, remember: false, expired: true });
2338
- }, Number(config.approvalTimeoutMs ?? 600000));
2339
- timer.unref?.();
2340
- approvals.set(id, { chatId, threadId, key, resolve, timer, prompt });
2341
- void tg('sendMessage', {
2342
- chat_id: chatId,
2343
- text: `${t(lang, 'bridge.approval.title')}\n${prompt}`,
2344
- reply_markup: approvalKeyboard(id, lang),
2345
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2346
- }).catch((error) => {
2347
- log(`approval prompt failed: ${error.message}`);
2348
- clearTimeout(timer);
2349
- approvals.delete(id);
2350
- resolve({ allowed: false, remember: false, expired: true });
2351
- });
2352
- });
2353
- }
2354
-
2355
- /** Answer a button press: acknowledge, act, and describe the outcome. */
2356
- async function handleCallback(query) {
2357
- const data = String(query.data || '');
2358
- const chatId = query.message?.chat?.id;
2359
- const messageId = query.message?.message_id;
2360
- const threadId = query.message?.message_thread_id ?? 0;
2361
- const key = sessionKey(chatId, threadId);
2362
- const lang = resolveLang(state, key, null, config);
2363
- const answer = (text, show = false) =>
2364
- tg('answerCallbackQuery', { callback_query_id: query.id, text, show_alert: show }).catch(() => {});
2365
-
2366
- // A button is a message without a sender the rest of the code can check, and
2367
- // the chat itself may be a group. Anything that changes configuration must
2368
- // come from an allowed user, exactly like the message path at the top of the
2369
- // poll loop. The refusal is deliberately the same as "unknown button".
2370
- const presser = query.from?.id;
2371
- if (!config.allowedUserIds.includes(presser) && !config.allowedUserIds.includes(chatId)) {
2372
- log(`ignored callback from ${presser} (chat ${chatId})`);
2373
- await answer(t(lang, 'bridge.cb.unknown'));
2374
- return;
2375
- }
2376
-
2377
- // Trim the buttons of the pressed message first: a button that already did
2378
- // its job must not be pressable a second time.
2379
- const clearKeyboard = () =>
2380
- tg('editMessageReplyMarkup', { chat_id: chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } }).catch(() => {});
2381
-
2382
- if (data.startsWith('m:')) {
2383
- // The settings card. Its own answer path, because a tap that redraws or
2384
- // flips one setting must not go through the defaults below (`clearKeyboard`
2385
- // would strip the tabs it is about to draw again).
2386
- await handleCardPress(query, { chatId, messageId, threadId, key, lang });
2387
- return;
2388
- }
2389
-
2390
- if (isRewindPress(data)) {
2391
- // A rewind button. What it acts on is read here, not taken from the card:
2392
- // between drawing "go back 2" and the press, the session may have moved on,
2393
- // and the answer says so instead of cutting the wrong turns.
2394
- const sessionId = state.sessions[key] || '';
2395
- const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
2396
- const line = answerRewindPress(data, {
2397
- used: rewindUsed,
2398
- lang,
2399
- t,
2400
- ctx: {
2401
- sessionId,
2402
- busy: activeTurns.has(key),
2403
- file: sessionPath,
2404
- cut: (steps) => cutSession(sessionPath, steps, applyRewind),
2405
- undo: () => {
2406
- const backup = newestBackup(sessionPath);
2407
- if (!backup) return { error: 'nothing' };
2408
- try {
2409
- restoreBackup(backup, sessionPath);
2410
- return { backup };
2411
- } catch (error) {
2412
- return { error: error.message };
2413
- }
2414
- },
2415
- },
2416
- });
2417
- // The card becomes the one line answering the press, and keeps no buttons.
2418
- await tg('editMessageText', {
2419
- chat_id: chatId,
2420
- message_id: messageId,
2421
- text: line,
2422
- reply_markup: { inline_keyboard: [] },
2423
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2424
- }).catch(() => {});
2425
- await answer(t(lang, 'bridge.cb.done'));
2426
- log(`rewind press ${data} for ${key}`);
2427
- return;
2428
- }
2429
-
2430
- // A search result's plus button. The name came from the registry and the
2431
- // command is the one the hint under the list names, so a tap installs exactly
2432
- // what was read — no hidden second path into pnpm.
2433
- if (data.startsWith('pl:i:')) {
2434
- const wanted = data.slice(5);
2435
- if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
2436
- await answer(t(lang, 'bridge.cb.unknown'));
2437
- return;
2438
- }
2439
- await clearKeyboard();
2440
- await answer(`/plugin add ${wanted}`);
2441
- log(`plugin install via button: ${wanted}`);
2442
- await runCommandFromButton(`/plugin add ${wanted}`, { chatId, threadId, key, lang });
2443
- return;
2444
- }
2445
-
2446
- // The up arrow on the update card. Same shape as the plus of a search result:
2447
- // the name was printed by the command that read the registry, and the tap runs
2448
- // `/plugin update <name>` — nothing else.
2449
- if (data.startsWith('pl:u:')) {
2450
- const wanted = data.slice(5);
2451
- if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
2452
- await answer(t(lang, 'bridge.cb.unknown'));
2453
- return;
2454
- }
2455
- await clearKeyboard();
2456
- await answer(`/plugin update ${wanted}`);
2457
- log(`plugin update via button: ${wanted}`);
2458
- await runCommandFromButton(`/plugin update ${wanted}`, { chatId, threadId, key, lang });
2459
- return;
2460
- }
2461
-
2462
- if (data.startsWith('fk:')) {
2463
- // A branch button from /branches. It does what `/resume <id>` does, so the
2464
- // topic moves onto that branch and the answer comes from the command
2465
- // itself — one implementation, one sentence.
2466
- const wanted = data.slice(3);
2467
- if (!/^session-[0-9a-f-]{36}$/.test(wanted)) {
2468
- await answer(t(lang, 'bridge.cb.unknown'));
2469
- return;
2470
- }
2471
- await clearKeyboard();
2472
- await runCommandFromButton(`/resume ${wanted.slice(8)}`, { chatId, threadId, key, lang });
2473
- return;
2474
- }
2475
-
2476
- if (isMenuPress(data)) {
2477
- // The panel is a set of cards: the hub, then one page per section. Moving
2478
- // between them edits this message, so browsing costs no new messages. A
2479
- // command press is exactly a typed command, so it goes through the same
2480
- // `handleControl`; the card is replaced by whatever that command answers.
2481
- const target = menuTarget(data);
2482
- if (target.kind === 'hub' || target.kind === 'section') {
2483
- const card = renderPanel({ t: (k, v) => t(lang, k, v), page: target.page || '' });
2484
- await tg('editMessageText', {
2485
- chat_id: chatId,
2486
- message_id: messageId,
2487
- text: card.text,
2488
- reply_markup: { inline_keyboard: card.keyboard },
2489
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2490
- }).catch(() => {});
2491
- await answer(t(lang, 'bridge.cb.done'));
2492
- return;
2493
- }
2494
- if (target.kind === 'close') {
2495
- // The card collapses into one line that can be deleted by hand, and the
2496
- // buttons go with it: a panel that stays open is a panel that lies about
2497
- // being closed.
2498
- await tg('editMessageText', {
2499
- chat_id: chatId,
2500
- message_id: messageId,
2501
- text: t(lang, 'ctrl.menu.closed'),
2502
- reply_markup: { inline_keyboard: [] },
2503
- ...(threadId > 0 ? { thread_id: threadId, message_thread_id: threadId } : {}),
2504
- }).catch(() => {});
2505
- await answer(t(lang, 'ctrl.menu.closedToast'));
2506
- log(`menu closed for ${key}`);
2507
- return;
2508
- }
2509
- const name = target.kind === 'command' ? target.name : '';
2510
- await clearKeyboard();
2511
- // `/new` and `/stop` change something when typed alone, and a stray tap on
2512
- // them is a command nobody asked for — so they open their explanation.
2513
- const typed = runsUnasked(name) && CONTROL_COMMANDS.includes(name)
2514
- ? commandForName(name, { t: (k, v) => t(lang, k, v) })
2515
- : `/help ${name}`;
2516
- await answer(typed || t(lang, 'bridge.cb.unknown'));
2517
- if (!typed) return;
2518
- log(`menu press /${name} for ${key}`);
2519
- await runCommandFromButton(typed, { chatId, threadId, key, lang });
2520
- return;
2521
- }
2522
-
2523
- if (data === 'stop') {
2524
- const killed = killTurn(key);
2525
- await clearKeyboard();
2526
- await answer(t(lang, killed ? 'bridge.cb.stopping' : 'bridge.cb.nothingToStop'));
2527
- log(`stop via button for ${key}: ${killed ? 'killed' : 'nothing'}`);
2528
- if (killed) await send(chatId, t(lang, 'bridge.cb.turnStopped'), threadId);
2529
- return;
2530
- }
2531
-
2532
- if (data === 'logs') {
2533
- await answer(t(lang, 'bridge.cb.showingLog'));
2534
- try {
2535
- const lines = readFileSync(LOG, 'utf8').split(/\r?\n/).filter(Boolean).slice(-12);
2536
- await send(chatId, lines.join('\n') || t(lang, 'bridge.cb.logEmpty'), threadId);
2537
- } catch (error) {
2538
- await send(chatId, t(lang, 'bridge.cb.logUnreadable', { err: error.message }), threadId);
2539
- }
2540
- return;
2541
- }
2542
-
2543
- if (data === 'doctor') {
2544
- await answer(t(lang, 'bridge.cb.checking'));
2545
- await send(chatId, t(lang, 'bridge.cb.doctorHint'), threadId);
2546
- return;
2547
- }
2548
-
2549
- if (data === 'resume') {
2550
- // Not a retry: the session already holds everything the turn produced.
2551
- // A continuation prompt asks the agent to check the state and go on.
2552
- await clearKeyboard();
2553
- await answer(t(lang, 'btn.continue'));
2554
- log(`resume via button for ${key}`);
2555
- const thread = threadId || 0;
2556
- enqueue(key, () => handleMessage({
2557
- chat: { id: chatId },
2558
- from: { id: config.allowedUserIds[0] },
2559
- message_id: 0,
2560
- message_thread_id: thread || undefined,
2561
- is_topic_message: thread > 0,
2562
- text: t(lang, 'prompt.continueTurn'),
2563
- }));
2564
- return;
2565
- }
2566
-
2567
- if (data === 'retry') {
2568
- const original = lastPrompt.get(key);
2569
- if (!original) {
2570
- await answer(t(lang, 'bridge.cb.nothingToRetry'));
2571
- await clearKeyboard();
2572
- return;
2573
- }
2574
- await clearKeyboard();
2575
- await answer(t(lang, 'bridge.cb.retrying'));
2576
- log(`retry via button for ${key}`);
2577
- enqueue(key, () => handleMessage({ ...original, message_id: original.message_id }));
2578
- return;
2579
- }
2580
-
2581
- if (data.startsWith('t:')) {
2582
- // A task card. The whole message is redrawn from state, so a double tap or
2583
- // two people pressing converge on one truth instead of stacking ✅ marks.
2584
- const n = Number(data.slice(2));
2585
- const goal = toggleTask(state, key, n);
2586
- if (!goal) {
2587
- await answer(t(lang, 'bridge.cb.taskStale'));
2588
- return;
2589
- }
2590
- saveState();
2591
- const text = renderTaskCard(goal, lang);
2592
- await tg('editMessageText', {
2593
- chat_id: chatId,
2594
- message_id: messageId,
2595
- text,
2596
- reply_markup: { inline_keyboard: taskRows(goal) },
2597
- }).catch(() => {});
2598
- await answer(t(lang, goal.tasks[n - 1]?.done ? 'bridge.cb.taskDone' : 'bridge.cb.taskUndone'));
2599
- log(`task ${n} toggled for ${key}`);
2600
- return;
2601
- }
2602
-
2603
- if (data.startsWith('ap:')) {
2604
- const [, verdict, requestId] = data.split(':');
2605
- const pending = approvals.get(requestId);
2606
- if (!pending) {
2607
- await answer(t(lang, 'bridge.cb.approvalStale'));
2608
- await clearKeyboard();
2609
- return;
2610
- }
2611
- clearTimeout(pending.timer);
2612
- approvals.delete(requestId);
2613
- await clearKeyboard();
2614
- const allowed = verdict === 'y' || verdict === 'a';
2615
- const remember = verdict === 'a';
2616
- pending.resolve({ allowed, remember, expired: false });
2617
- await answer(t(lang, allowed ? (remember ? 'bridge.cb.allowedAlways' : 'bridge.cb.allowed') : 'bridge.cb.denied'));
2618
- log(`approval ${verdict} for request ${requestId}`);
2619
- return;
2620
- }
2621
-
2622
- await answer(t(lang, 'bridge.cb.unknown'));
2623
- }
2624
-
2625
- /**
2626
- * Answer a button from the settings card.
2627
- *
2628
- * Two kinds of press, one rule: the card is a view of the commands.
2629
- *
2630
- * - A tab (`m:agent`) redraws the same message as another page.
2631
- * - A switch or a door (`m:reasoning:on`, `m:model`) runs the command a person
2632
- * would have typed, through `handleControl`, and then replaces the card with
2633
- * one plain line saying what changed. The card does not stay: a menu left in
2634
- * the history is what the person asked to avoid, and one line is easier to
2635
- * delete than a twelve-row keyboard.
2636
- *
2637
- * The press carries no text of its own, which is why `handleMessage` is not this
2638
- * path's entry point: it would journal, queue and spend a turn on a tap.
2639
- */
2640
- async function handleCardPress(query, ctx) {
2641
- const { chatId, messageId, threadId, key, lang } = ctx;
2642
- const data = String(query.data || '');
2643
- const current = settingsCurrent({ config, state, key, reasoningOf });
2644
- const updateMode = state.update?.mode || 'check';
2645
- const wanted = commandFor({ t: (k, vars) => t(lang, k, vars), current, updateMode }, data);
2646
-
2647
- if (!wanted) {
2648
- await tg('answerCallbackQuery', { callback_query_id: query.id, text: t(lang, 'settings.card.stale') }).catch(() => {});
2649
- return;
2650
- }
2651
-
2652
- if (wanted.page) {
2653
- const card = renderSettingsCard({
2654
- page: wanted.page,
2655
- t: (k, vars) => t(lang, k, vars),
2656
- current,
2657
- updateMode,
2658
- bound: boundSetOf(key),
2659
- });
2660
- await tg('editMessageText', {
2661
- chat_id: chatId,
2662
- message_id: messageId,
2663
- text: card.text,
2664
- reply_markup: { inline_keyboard: card.keyboard },
2665
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2666
- }).catch((error) => log(`settings card redraw failed: ${error.message}`));
2667
- await tg('answerCallbackQuery', { callback_query_id: query.id }).catch(() => {});
2668
- return;
2669
- }
2670
-
2671
- // Run the command. Whatever it answers goes in the log and, by default, not
2672
- // in the chat: the one line below is the chat's share of this press. Only a
2673
- // command that failed says more than that.
2674
- const replies = [];
2675
- const [head, ...rest] = wanted.command.split(/\s+/);
2676
- const handled = await handleControl({
2677
- command: head,
2678
- arg: rest.join(' '),
2679
- text: wanted.command,
2680
- lang,
2681
- chatId,
2682
- threadId,
2683
- key,
2684
- state,
2685
- config,
2686
- activeTurns,
2687
- saveState,
2688
- log,
2689
- send: (text) => {
2690
- replies.push(String(text ?? ''));
2691
- return Promise.resolve(0);
2692
- },
2693
- reply: (text) => {
2694
- replies.push(String(text ?? ''));
2695
- return Promise.resolve(0);
2696
- },
2697
- jobs: () => ({ active: [], queued: 0, max: MAX_PARALLEL }),
2698
- api: tg,
2699
- sendFile: () => Promise.resolve(0),
2700
- profile: profileOf(key),
2701
- prices: () => Promise.resolve(''),
2702
- }).catch((error) => {
2703
- log(`settings press ${data} failed: ${error.message}`);
2704
- replies.push(error.message);
2705
- return true;
2706
- });
2707
-
2708
- const changed = Boolean(wanted.value);
2709
- const answerText = changed
2710
- ? t(lang, 'settings.card.changed', { label: wanted.label, value: wanted.value })
2711
- : t(lang, 'settings.card.door', { command: wanted.command });
2712
-
2713
- // The card becomes the line: the buttons go away with the text they described.
2714
- await tg('editMessageText', {
2715
- chat_id: chatId,
2716
- message_id: messageId,
2717
- text: answerText,
2718
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2719
- }).catch(() => {});
2720
- await tg('answerCallbackQuery', { callback_query_id: query.id }).catch(() => {});
2721
-
2722
- // A door that opened to nothing (an unknown set id, a command that is not
2723
- // allowed here) still has something to say; it goes under the line, once.
2724
- if (!handled) log(`settings press ${data}: no handler answered`);
2725
- const notLine = replies.filter(Boolean).filter((r) => r !== answerText);
2726
- if (notLine.length > 0 && !changed) {
2727
- await send(chatId, notLine[0], threadId).catch(() => {});
2728
- }
2729
- }
2730
-
2731
- /**
2732
- * The set bound to this topic, for the card that names it. Read through the
2733
- * agentset store the commands use, so the card never keeps a second copy.
2734
- */
2735
- function boundSetOf(key) {
2736
- const id = state.agentsets?.[key];
2737
- if (!id) return null;
2738
- try {
2739
- return new AgentsetStore(join(DIR, 'agentsets.json')).load().get(id) || null;
2740
- } catch {
2741
- return null;
2742
- }
2743
- }
2744
-
2745
- /**
2746
- * Turn runner with an IDLE deadline and a live progress sink.
2747
- *
2748
- * A fixed wall-clock limit is wrong for this work: a real build or a long
2749
- * research pass legitimately outlives any short cap, and killing it at 7
2750
- * minutes threw away finished work (the 422s failure on 2026-10-21). What
2751
- * actually matters is SILENCE — a turn that emits no event for N seconds is
2752
- * stuck. Every CLI event therefore refreshes the deadline.
2753
- *
2754
- * Returns {sessionId, text, error}: the error carrying "no activity" when the
2755
- * idle window expires.
2756
- */
2757
- function runTurnLive(task, sessionId, key, options = {}) {
2758
- const idleMs = Number(options.idleMs ?? config.turnIdleMs ?? 300000);
2759
- // A tool can legitimately run for many minutes (install, build, test suite)
2760
- // while the model emits nothing at all. Silence during a tool call is work,
2761
- // not a hang, so it gets its own much longer window.
2762
- const toolIdleMs = Number(options.toolIdleMs ?? config.turnToolIdleMs ?? 30 * 60 * 1000);
2763
- const hardMs = Number(options.hardMs ?? config.turnTimeoutMs ?? 1800000);
2764
- const onEvent = options.onEvent;
2765
-
2766
- return new Promise((resolve) => {
2767
- let done = false;
2768
- let idleTimer;
2769
- let lastType = '';
2770
- let sessionSeen = sessionId || '';
2771
-
2772
- const finish = (value) => {
2773
- if (done) return;
2774
- done = true;
2775
- clearTimeout(idleTimer);
2776
- clearTimeout(hardTimer);
2777
- resolve(value);
2778
- };
2779
-
2780
- const armIdle = (windowMs = idleMs) => {
2781
- clearTimeout(idleTimer);
2782
- idleTimer = setTimeout(() => {
2783
- // Silence is NOT a hang: the model can think for many minutes, and a
2784
- // long task may take hours. Keep the turn alive, refresh the visible
2785
- // clock so the person sees progress, and re-arm.
2786
- log(`turn quiet ${Math.round(windowMs / 1000)}s for ${key}; heartbeat`);
2787
- if (options.onHeartbeat) { try { options.onHeartbeat(); } catch {} }
2788
- armIdle(windowMs);
2789
- }, windowMs);
2790
- };
2791
-
2792
- // Generous absolute ceiling: protects the queue from a turn that keeps
2793
- // emitting trivia forever, without punishing real long work.
2794
- // Optional absolute ceiling. 0 (the default now) means "no cap": a real
2795
- // task may take hours, and the turn ends when the CLI exits or the person
2796
- // presses Стоп — not when a timer decides.
2797
- const hardTimer = hardMs > 0 ? setTimeout(() => {
2798
- log(`turn hard cap ${Math.round(hardMs / 60000)}min for ${key}; aborting`);
2799
- finish({
2800
- sessionId: sessionSeen,
2801
- text: '',
2802
- reason: 'timeout',
2803
- minutes: Math.round(hardMs / 60000),
2804
- error: `turn exceeded ${Math.round(hardMs / 60000)} min`,
2805
- });
2806
- if (options.onAbort) options.onAbort();
2807
- }, hardMs) : null;
2808
-
2809
- armIdle();
2810
-
2811
- runTurn(task, sessionId, key, (event) => {
2812
- if (event.type === 'activity') {
2813
- armIdle(lastType === 'tool_call' ? toolIdleMs : idleMs);
2814
- return;
2815
- }
2816
- lastType = event.type;
2817
- armIdle(event.type === 'tool_call' ? toolIdleMs : idleMs);
2818
- if (event.type === 'session' && event.sessionId) sessionSeen = event.sessionId;
2819
- if (onEvent) {
2820
- try {
2821
- onEvent(event);
2822
- } catch {}
2823
- }
2824
- }, options.extraArgs ?? [], options.cwd ?? '', options.profile || profileOf(key), options.lang ?? config.lang ?? 'en', options.env ?? {})
2825
- .then((result) => finish({ ...result, sessionId: result.sessionId || sessionSeen }))
2826
- .catch((error) => finish({ sessionId: sessionSeen, text: '', error: String(error?.message ?? error) }));
2827
- });
2828
- }
2829
131
 
2830
132
  async function main() {
2831
133
  log('bridge started');
@@ -2849,7 +151,7 @@ async function main() {
2849
151
  }
2850
152
  try {
2851
153
  const me = await tg('getMe');
2852
- botUsername = me.username || '';
154
+ setBotUsername(me.username || '');
2853
155
  log(`bot @${me.username}`);
2854
156
  // Confirm the restart in the topic it was asked from, not in the DM: the
2855
157
  // person who typed `/restart confirm` was looking at that thread.
@@ -2887,8 +189,8 @@ async function main() {
2887
189
  // inside handleMessage: the steer branch below reaches the running agent
2888
190
  // without going through handleMessage, so a stranger the bot can see used
2889
191
  // to be able to inject text into the owner's live turn.
2890
- if (!allowedSender(msg)) {
2891
- log(`ignored update from ${msg.from?.id} (chat ${msg.chat?.id}${msg.message_thread_id ? ` topic=${msg.message_thread_id}` : ''})`);
192
+ if (!allowedSender(msg, config)) {
193
+ log(`ignored update from ${msg.from?.id} (chat ${msg.chat?.id}${msg.message_thread_id ? ` topic=${msg.message_thread_id}` : ''}) allowlist=${JSON.stringify(config.allowedUserIds ?? [])}`);
2892
194
  ack(update.update_id);
2893
195
  return;
2894
196
  }
@@ -2927,7 +229,7 @@ async function main() {
2927
229
  if (activeTurns.has(queueKey) && sessionId) {
2928
230
  if (steerText && !steerMedia) {
2929
231
  try {
2930
- const job = steerRunningTurn(msg, steerText, sessionId, thread);
232
+ const job = steerRunningTurn(msg, steerText, sessionId, thread, deliverTurn);
2931
233
  log(`steer handled outside the queue: ${job.id}`);
2932
234
  ack(update.update_id);
2933
235
  } catch (error) {
@@ -2941,7 +243,7 @@ async function main() {
2941
243
  // the voicemail in a directory nobody reads again.
2942
244
  ack(update.update_id);
2943
245
  const lang = resolveLang(state, queueKey, msg, config);
2944
- void steerMediaMessage(msg, sessionId, queueKey, thread, lang).catch((error) => {
246
+ void steerMediaMessage(msg, sessionId, queueKey, thread, lang, deliverTurn).catch((error) => {
2945
247
  // The attachment could not be prepared (download, transcription). It
2946
248
  // still deserves an answer, so let the normal path take it: it retries
2947
249
  // the same work and reports the failure itself.