dsh-tg-bridge 1.46.0 → 1.47.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.
@@ -1,479 +1,488 @@
1
- // Every button press: the router, the settings card, the rewind ticket, the
2
- // task card. One place, because a press may mean a control command, a card
3
- // update or an approval, and only one handler may claim it.
4
- import { CONTROL_COMMANDS } from './control.mjs';
5
- import { isFallbackPress, pressTarget } from '../model/fallback-card.mjs';
6
- import { progressOf, toggleTask } from '../work/goals.mjs';
7
- import { handleMessage } from './handle-message.mjs';
8
- import { resolveLang, t } from '../core/i18n.mjs';
9
- import { handleLoadPress } from '../work/load-guard.mjs';
10
- import { sessionKey } from '../core/keys.mjs';
11
- import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
12
- import { DSH_HOME, LOG } from '../core/paths.mjs';
13
- import { approvals, enqueue, lastPrompt, redeliver, rewindUsed } from '../turn/queue.mjs';
14
- import { answerRewindPress, cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
15
- import { applyRewind, newestBackup, restoreBackup } from '../work/rewind.mjs';
16
- import { diffPressRouter } from '../control/cmd-diff.mjs';
17
- import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/model-card.mjs';
18
- import { runCommandFromButton } from '../core/run-command.mjs';
19
- import { handleCardPress } from '../profile/settings-press.mjs';
20
- import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
21
- import { handleFilePress } from './file-press.mjs';
22
- import { handleMcpPress } from './mcp-press.mjs';
23
- import { handlePlanPress } from './plan-press.mjs';
24
- import { handleEditPress } from './edit-press.mjs';
25
- import { handleTourPress } from './tour-press.mjs';
26
- import { config, done, log, saveState, state } from '../core/state.mjs';
27
- import { inlineKeyboard, send, sendFile, tg, tgFast } from './telegram.mjs';
28
- import { sessionFile } from './thoughts.mjs';
29
- import { activeTurns, killTurn, profileOf } from '../turn/turn.mjs';
30
- import { QUIET_MS, quietGuard } from './quiet-guard.mjs';
31
- import { readFileSync } from 'node:fs';
32
- import { join } from 'node:path';
33
-
34
- /** Answer a button press: acknowledge, act, and describe the outcome. */
35
- export async function handleCallback(query) {
36
- const data = String(query.data || '');
37
- const chatId = query.message?.chat?.id;
38
- const messageId = query.message?.message_id;
39
- const threadId = query.message?.message_thread_id ?? 0;
40
- const key = sessionKey(chatId, threadId);
41
- const lang = resolveLang(state, key, null, config);
42
- const answerRaw = (text, show = false) =>
43
- tgFast('answerCallbackQuery', { callback_query_id: query.id, text, show_alert: show }).catch(() => false);
44
-
45
- // A press must end in something. Silence is the one outcome a person cannot
46
- // tell from a broken bot, and it was the one outcome the code could produce
47
- // without a trace: a handler that returned without saying anything left the
48
- // spinner turning for a few seconds and no line in the log at all. The guard
49
- // turns that case into one honest line, once, whether the handler is still
50
- // running or already gone.
51
- const guard = quietGuard({
52
- onSlow: () => {
53
- log(`callback ${data} from ${query.from?.id} in ${chatId}/${threadId}: nothing answered in ${QUIET_MS / 1000}s`);
54
- void tgFast('answerCallbackQuery', { callback_query_id: query.id, text: t(lang, 'bridge.cb.slow') }).catch(() => {});
55
- void send(chatId, t(lang, 'bridge.cb.slowLine', { sec: QUIET_MS / 1000 }), threadId).catch(() => {});
56
- },
57
- });
58
- const answer = guard.wrap(answerRaw);
59
-
60
- // A button is a message without a sender the rest of the code can check, and
61
- // the chat itself may be a group. Anything that changes configuration must
62
- // come from an allowed user, exactly like the message path at the top of the
63
- // poll loop. The refusal is deliberately the same as "unknown button".
64
- const presser = query.from?.id;
65
- if (!config.allowedUserIds.includes(presser) && !config.allowedUserIds.includes(chatId)) {
66
- log(`ignored callback from ${presser} (chat ${chatId})`);
67
- await answer(t(lang, 'bridge.cb.unknown'));
68
- return;
69
- }
70
- // Every accepted press is named in the log before it is handled: a button that
71
- // answers nothing was indistinguishable from a button that never arrived.
72
- log(`callback ${data} from ${presser} in ${chatId}/${threadId}`);
73
-
74
- // Trim the buttons of the pressed message first: a button that already did
75
- // its job must not be pressable a second time.
76
- const clearKeyboard = () => {
77
- guard.mark();
78
- return tgFast('editMessageReplyMarkup', { chat_id: chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } }).catch(() => {});
79
- };
80
-
81
- if (data.startsWith('m:')) {
82
- // The settings card. Its own answer path, because a tap that redraws or
83
- // flips one setting must not go through the defaults below (`clearKeyboard`
84
- // would strip the tabs it is about to draw again).
85
- await handleCardPress(query, { chatId, messageId, threadId, key, lang, answer });
86
- return;
87
- }
88
-
89
- // `/dsh`'s own two presses. Each types the command the card advertised, so the
90
- // install path and the confirmation in front of it exist exactly once — a
91
- // button that called npm itself would be a second way to replace the harness.
92
- if (data.startsWith('ds:')) {
93
- await clearKeyboard();
94
- await answer(t(lang, 'bridge.cb.done'));
95
- await runCommandFromButton(`/dsh ${data === 'ds:confirm' ? 'update confirm' : 'update'}`, { chatId, threadId, key, lang });
96
- return;
97
- }
98
-
99
- // `/mcp`'s own presses: open one server, confirm or cancel an add. The press
100
- // re-reads the profile rather than trusting the card, so a confirmed add can
101
- // never overwrite an edit made after the preview.
102
- // The plan card's two presses: Approve replays the request with plan mode off,
103
- // Keep planning asks for a revision. The id on the card decides whether a press
104
- // still belongs to the topic's current plan.
105
- if (data.startsWith('pm:')) {
106
- guard.mark();
107
- const claimed = await handlePlanPress({ data, key, lang, chatId, threadId, answer, clearKeyboard, redeliver, log });
108
- if (claimed) return;
109
- }
110
-
111
- if (data.startsWith('mc:')) {
112
- guard.mark();
113
- const claimed = await handleMcpPress({ data, key, lang, chatId, threadId, messageId, answer });
114
- if (claimed) return;
115
- }
116
-
117
- // `/compact`'s one press: the card explains where compaction lives and offers
118
- // the thing that does work here, which is a fresh session. It types the command
119
- // rather than doing the work, so `/new` keeps exactly one implementation.
120
- if (data === 'cp:new') {
121
- await clearKeyboard();
122
- await answer(t(lang, 'bridge.cb.done'));
123
- await runCommandFromButton('/new', { chatId, threadId, key, lang });
124
- return;
125
- }
126
-
127
- if (isRewindPress(data)) {
128
- // A rewind button. What it acts on is read here, not taken from the card:
129
- // between drawing "go back 2" and the press, the session may have moved on,
130
- // and the answer says so instead of cutting the wrong turns.
131
- const sessionId = state.sessions[key] || '';
132
- const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
133
- const line = answerRewindPress(data, {
134
- used: rewindUsed,
135
- lang,
136
- // Bound, not the raw `t`: this helper calls `t(key, vars)` with one
137
- // argument, so the unbound import read the key as a language and returned
138
- // the string "undefined" — which is what every rewind button answered on
139
- // 2026-11-01 until the binding was fixed here.
140
- t: (k, vars) => t(lang, k, vars),
141
- ctx: {
142
- sessionId,
143
- busy: activeTurns.has(key),
144
- file: sessionPath,
145
- cut: (steps) => cutSession(sessionPath, steps, applyRewind),
146
- undo: () => {
147
- const backup = newestBackup(sessionPath);
148
- if (!backup) return { error: 'nothing' };
149
- try {
150
- restoreBackup(backup, sessionPath);
151
- return { backup };
152
- } catch (error) {
153
- return { error: error.message };
154
- }
155
- },
156
- },
157
- });
158
- // The card becomes the one line answering the press, and keeps no buttons.
159
- await tg('editMessageText', {
160
- chat_id: chatId,
161
- message_id: messageId,
162
- text: line,
163
- reply_markup: { inline_keyboard: [] },
164
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
165
- }).catch(() => {});
166
- await answer(t(lang, 'bridge.cb.done'));
167
- log(`rewind press ${data} for ${key}`);
168
- return;
169
- }
170
-
171
- // A search result's plus button. The name came from the registry and the
172
- // command is the one the hint under the list names, so a tap installs exactly
173
- // what was read — no hidden second path into pnpm.
174
- if (data.startsWith('pl:i:')) {
175
- const wanted = data.slice(5);
176
- if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
177
- await answer(t(lang, 'bridge.cb.unknown'));
178
- return;
179
- }
180
- await clearKeyboard();
181
- await answer(`/plugin add ${wanted}`);
182
- log(`plugin install via button: ${wanted}`);
183
- await runCommandFromButton(`/plugin add ${wanted}`, { chatId, threadId, key, lang });
184
- return;
185
- }
186
-
187
- // The up arrow on the update card. Same shape as the plus of a search result:
188
- // the name was printed by the command that read the registry, and the tap runs
189
- // `/plugin update <name>` — nothing else.
190
- if (data.startsWith('pl:u:')) {
191
- const wanted = data.slice(5);
192
- if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
193
- await answer(t(lang, 'bridge.cb.unknown'));
194
- return;
195
- }
196
- await clearKeyboard();
197
- await answer(`/plugin update ${wanted}`);
198
- log(`plugin update via button: ${wanted}`);
199
- await runCommandFromButton(`/plugin update ${wanted}`, { chatId, threadId, key, lang });
200
- return;
201
- }
202
-
203
- if (data.startsWith('fk:')) {
204
- // A branch button from /branches. It does what `/resume <id>` does, so the
205
- // topic moves onto that branch and the answer comes from the command
206
- // itself — one implementation, one sentence.
207
- const wanted = data.slice(3);
208
- if (!/^session-[0-9a-f-]{36}$/.test(wanted)) {
209
- await answer(t(lang, 'bridge.cb.unknown'));
210
- return;
211
- }
212
- await clearKeyboard();
213
- await runCommandFromButton(`/resume ${wanted.slice(8)}`, { chatId, threadId, key, lang });
214
- return;
215
- }
216
-
217
- // A parallel-slot button from the /jobs card. It runs the command the card
218
- // advertises, so validation and storage live in one place and a tap cannot
219
- // write a value `/jobs <n>` would refuse. The command redraws the card, so the
220
- // answer to the press is the new state, not a second message about it.
221
- if (data.startsWith('jb:')) {
222
- await clearKeyboard();
223
- await runCommandFromButton(`/jobs ${data.slice(3)}`, { chatId, threadId, key });
224
- return;
225
- }
226
-
227
- // A button on the load card, or on the notice that held a prompt back. Both
228
- // are `/load` verbs, so the tap and the typed command run the same code.
229
- if (data.startsWith('ld:')) {
230
- await handleLoadPress({ data, key, t, lang, answer, clearKeyboard, redeliver, runCommandFromButton, chatId, threadId, log });
231
- return;
232
- }
233
-
234
- // A button on the failover card. Every press becomes the verb of `/fallback`,
235
- // so a tap and a typed line land in the same code — and the command redraws the
236
- // card, which is why the old keyboard is trimmed only when the press leaves it.
237
- if (isFallbackPress(data)) {
238
- const target = pressTarget(data);
239
- const words = { t: 'toggle', u: 'up', d: 'down', x: 'test', e: 'chain', s: 'show' };
240
- // `r` is two verbs on one letter: with a number it removes that route, alone
241
- // it opens the remove list. Anything else is a stale card and does nothing.
242
- const verb = target && (target.verb === 'r' ? (target.n ? 'remove' : 'menu') : words[target.verb]);
243
- if (!verb) {
244
- await answer(t(lang, 'bridge.cb.unknown'));
245
- return;
246
- }
247
- const typed = target.n && verb !== 'menu' ? `/fallback ${verb} ${target.n}` : `/fallback ${verb}`;
248
- await clearKeyboard();
249
- await answer(typed);
250
- log(`fallback press ${typed} for ${key}`);
251
- await runCommandFromButton(typed, { chatId, threadId, key, lang });
252
- return;
253
- }
254
-
255
- if (isMenuPress(data)) {
256
- // The panel is a set of cards: the hub, then one page per section. Moving
257
- // between them edits this message, so browsing costs no new messages. A
258
- // command press is exactly a typed command, so it goes through the same
259
- // `handleControl`; the card is replaced by whatever that command answers.
260
- const target = menuTarget(data);
261
- if (target.kind === 'hub' || target.kind === 'section') {
262
- const card = renderPanel({ t: (k, v) => t(lang, k, v), page: target.page || '' });
263
- await tg('editMessageText', {
264
- chat_id: chatId,
265
- message_id: messageId,
266
- text: card.text,
267
- reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
268
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
269
- }).catch(() => {});
270
- await answer(t(lang, 'bridge.cb.done'));
271
- return;
272
- }
273
- if (target.kind === 'close') {
274
- // The card collapses into one line that can be deleted by hand, and the
275
- // buttons go with it: a panel that stays open is a panel that lies about
276
- // being closed.
277
- await tg('editMessageText', {
278
- chat_id: chatId,
279
- message_id: messageId,
280
- text: t(lang, 'ctrl.menu.closed'),
281
- reply_markup: { inline_keyboard: [] },
282
- ...(threadId > 0 ? { thread_id: threadId, message_thread_id: threadId } : {}),
283
- }).catch(() => {});
284
- await answer(t(lang, 'ctrl.menu.closedToast'));
285
- log(`menu closed for ${key}`);
286
- return;
287
- }
288
- const name = target.kind === 'command' ? target.name : '';
289
- await clearKeyboard();
290
- // `/new` and `/stop` change something when typed alone, and a stray tap on
291
- // them is a command nobody asked for — so they open their explanation.
292
- const typed = runsUnasked(name) && CONTROL_COMMANDS.includes(name)
293
- ? commandForName(name, { t: (k, v) => t(lang, k, v) })
294
- : `/help ${name}`;
295
- await answer(typed || t(lang, 'bridge.cb.unknown'));
296
- if (!typed) return;
297
- log(`menu press /${name} for ${key}`);
298
- await runCommandFromButton(typed, { chatId, threadId, key, lang });
299
- return;
300
- }
301
-
302
- if (data === 'stop') {
303
- const killed = killTurn(key);
304
- await clearKeyboard();
305
- await answer(t(lang, killed ? 'bridge.cb.stopping' : 'bridge.cb.nothingToStop'));
306
- log(`stop via button for ${key}: ${killed ? 'killed' : 'nothing'}`);
307
- if (killed) await send(chatId, t(lang, 'bridge.cb.turnStopped'), threadId);
308
- return;
309
- }
310
-
311
- if (data === 'logs') {
312
- await answer(t(lang, 'bridge.cb.showingLog'));
313
- try {
314
- const lines = readFileSync(LOG, 'utf8').split(/\r?\n/).filter(Boolean).slice(-12);
315
- await send(chatId, lines.join('\n') || t(lang, 'bridge.cb.logEmpty'), threadId);
316
- } catch (error) {
317
- await send(chatId, t(lang, 'bridge.cb.logUnreadable', { err: error.message }), threadId);
318
- }
319
- return;
320
- }
321
-
322
- if (data === 'doctor') {
323
- await answer(t(lang, 'bridge.cb.checking'));
324
- await send(chatId, t(lang, 'bridge.cb.doctorHint'), threadId);
325
- return;
326
- }
327
-
328
- if (data === 'resume') {
329
- // Not a retry: the session already holds everything the turn produced.
330
- // A continuation prompt asks the agent to check the state and go on.
331
- await clearKeyboard();
332
- await answer(t(lang, 'btn.continue'));
333
- log(`resume via button for ${key}`);
334
- const thread = threadId || 0;
335
- enqueue(key, () => handleMessage({
336
- chat: { id: chatId },
337
- from: { id: config.allowedUserIds[0] },
338
- message_id: 0,
339
- message_thread_id: thread || undefined,
340
- is_topic_message: thread > 0,
341
- text: t(lang, 'prompt.continueTurn'),
342
- }));
343
- return;
344
- }
345
-
346
- if (data === 'retry') {
347
- const original = lastPrompt.get(key);
348
- if (!original) {
349
- await answer(t(lang, 'bridge.cb.nothingToRetry'));
350
- await clearKeyboard();
351
- return;
352
- }
353
- await clearKeyboard();
354
- await answer(t(lang, 'bridge.cb.retrying'));
355
- log(`retry via button for ${key}`);
356
- enqueue(key, () => handleMessage({ ...original, message_id: original.message_id }));
357
- return;
358
- }
359
-
360
- // Two card presses, one rule each: what the card said is re-read from the
361
- // thing it described before acting, never trusted from the button. The diff
362
- // checks its hunk hash, the model card checks the route its profile declares.
363
- if (data.startsWith('df:')) {
364
- if (await diffPressRouter({ chatId, threadId, key, lang, config, state, answer, clearKeyboard, log, enqueue, handleMessage })(data)) return;
365
- }
366
- if (data.startsWith(MODEL_PREFIX)) {
367
- if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
368
- }
369
-
370
- if (await handleTourPress({ data, lang, chatId, threadId, messageId, answer })) return;
371
-
372
- if (await handleEditPress({ data, key, lang, chatId, threadId, messageId, answer })) return;
373
-
374
- if (await handleFilePress({ data, key, lang, chatId, threadId, messageId, answer })) return;
375
-
376
- if (data.startsWith('tc:')) {
377
- // The turn card's own switches. Redrawn from state like the task card, so a
378
- // double tap settles on one truth; an id this build does not know answers
379
- // "stale" instead of writing a key nothing reads.
380
- const next = toggleCardBlock(state, key, data.slice(3));
381
- if (!next) {
382
- await answer(t(lang, 'card.stale'));
383
- return;
384
- }
385
- state.cardBlocks = { ...(state.cardBlocks || {}), [key]: next };
386
- saveState();
387
- const blocks = cardBlocks(state, key);
388
- await tg('editMessageText', {
389
- chat_id: chatId,
390
- message_id: messageId,
391
- text: renderCardSettings(blocks, lang),
392
- reply_markup: { inline_keyboard: inlineKeyboard(cardKeyboard(blocks, lang)) },
393
- }).catch(() => {});
394
- await answer(t(lang, next.includes(data.slice(3)) ? 'card.cbOn' : 'card.cbOff'));
395
- log(`card block ${data.slice(3)} toggled for ${key}`);
396
- return;
397
- }
398
-
399
- if (data.startsWith('t:')) {
400
- // A task card. The whole message is redrawn from state, so a double tap or
401
- // two people pressing converge on one truth instead of stacking ✅ marks.
402
- const n = Number(data.slice(2));
403
- const goal = toggleTask(state, key, n);
404
- if (!goal) {
405
- await answer(t(lang, 'bridge.cb.taskStale'));
406
- return;
407
- }
408
- saveState();
409
- const text = renderTaskCard(goal, lang);
410
- await tg('editMessageText', {
411
- chat_id: chatId,
412
- message_id: messageId,
413
- text,
414
- reply_markup: { inline_keyboard: inlineKeyboard(taskRows(goal)) },
415
- }).catch(() => {});
416
- await answer(t(lang, goal.tasks[n - 1]?.done ? 'bridge.cb.taskDone' : 'bridge.cb.taskUndone'));
417
- log(`task ${n} toggled for ${key}`);
418
- return;
419
- }
420
-
421
- if (data.startsWith('ap:')) {
422
- const [, verdict, requestId] = data.split(':');
423
- const pending = approvals.get(requestId);
424
- if (!pending) {
425
- await answer(t(lang, 'bridge.cb.approvalStale'));
426
- await clearKeyboard();
427
- return;
428
- }
429
- clearTimeout(pending.timer);
430
- approvals.delete(requestId);
431
- await clearKeyboard();
432
- const allowed = verdict === 'y' || verdict === 'a';
433
- const remember = verdict === 'a';
434
- pending.resolve({ allowed, remember, expired: false });
435
- await answer(t(lang, allowed ? (remember ? 'bridge.cb.allowedAlways' : 'bridge.cb.allowed') : 'bridge.cb.denied'));
436
- log(`approval ${verdict} for request ${requestId}`);
437
- return;
438
- }
439
-
440
- await answer(t(lang, 'bridge.cb.unknown'));
441
- }
442
-
443
-
444
- /**
445
- * A press that failed before it could answer.
446
- *
447
- * Without this the throw reached the poll loop, which logged it and moved on:
448
- * the log knew, the person did not. The toast is the same shape as every other
449
- * answer, so a broken button and a stale one look different, and both look
450
- * different from a button that never arrived.
451
- */
452
- export async function answerPressFailed(query) {
453
- const chatId = query?.message?.chat?.id;
454
- const threadId = query?.message?.message_thread_id ?? 0;
455
- const lang = resolveLang(state, sessionKey(chatId, threadId), null, config);
456
- await tgFast('answerCallbackQuery', { callback_query_id: query?.id, text: t(lang, 'bridge.cb.failed') }).catch(() => {});
457
- }
458
-
459
- /**
460
- * A task list as one message plus one button per task. The label carries the
461
- * state, the payload carries only the number, so the card survives a relabel and
462
- * stays inside Telegram's 64-byte callback limit.
463
- */
464
- export function renderTaskCard(goal, lang) {
465
- const { done, total } = progressOf(goal);
466
- const lines = [t(lang, 'goal.set', { text: goal.text })];
467
- goal.tasks.forEach((task, i) => lines.push(`${task.done ? '✅' : '⬜'} ${i + 1}. ${task.text}`));
468
- lines.push(t(lang, 'goal.progress', { done, total }), '', t(lang, 'task.tapHint'));
469
- return lines.join('\n');
470
- }
471
-
472
- export function taskRows(goal) {
473
- if (!goal || goal.done) return [];
474
- const rows = [];
475
- for (let i = 0; i < Math.min(goal.tasks.length, 90); i += 3) {
476
- rows.push(goal.tasks.slice(i, i + 3).map((task, k) => ({ text: `${task.done ? '✅' : '⬜'} ${i + k + 1}`, data: `t:${i + k + 1}` })));
477
- }
478
- return rows;
479
- }
1
+ // Every button press: the router, the settings card, the rewind ticket, the
2
+ // task card. One place, because a press may mean a control command, a card
3
+ // update or an approval, and only one handler may claim it.
4
+ import { CONTROL_COMMANDS } from './control.mjs';
5
+ import { isFallbackPress, pressTarget } from '../model/fallback-card.mjs';
6
+ import { progressOf, toggleTask } from '../work/goals.mjs';
7
+ import { handleMessage } from './handle-message.mjs';
8
+ import { resolveLang, t } from '../core/i18n.mjs';
9
+ import { handleLoadPress } from '../work/load-guard.mjs';
10
+ import { sessionKey } from '../core/keys.mjs';
11
+ import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
12
+ import { DSH_HOME, LOG } from '../core/paths.mjs';
13
+ import { approvals, enqueue, lastPrompt, redeliver, rewindUsed } from '../turn/queue.mjs';
14
+ import { answerRewindPress, cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
15
+ import { applyRewind, newestBackup, restoreBackup } from '../work/rewind.mjs';
16
+ import { diffPressRouter } from '../control/cmd-diff.mjs';
17
+ import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/model-card.mjs';
18
+ import { runCommandFromButton } from '../core/run-command.mjs';
19
+ import { handleCardPress } from '../profile/settings-press.mjs';
20
+ import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
21
+ import { handleFilePress } from './file-press.mjs';
22
+ import { handleMcpPress } from './mcp-press.mjs';
23
+ import { handlePlanPress } from './plan-press.mjs';
24
+ import { handlePluginSettingsPress } from './plugin-settings-press.mjs';
25
+ import { handleEditPress } from './edit-press.mjs';
26
+ import { handleTourPress } from './tour-press.mjs';
27
+ import { config, done, log, saveState, state } from '../core/state.mjs';
28
+ import { inlineKeyboard, send, sendFile, tg, tgFast } from './telegram.mjs';
29
+ import { sessionFile } from './thoughts.mjs';
30
+ import { activeTurns, killTurn, profileOf } from '../turn/turn.mjs';
31
+ import { QUIET_MS, quietGuard } from './quiet-guard.mjs';
32
+ import { readFileSync } from 'node:fs';
33
+ import { join } from 'node:path';
34
+
35
+ /** Answer a button press: acknowledge, act, and describe the outcome. */
36
+ export async function handleCallback(query) {
37
+ const data = String(query.data || '');
38
+ const chatId = query.message?.chat?.id;
39
+ const messageId = query.message?.message_id;
40
+ const threadId = query.message?.message_thread_id ?? 0;
41
+ const key = sessionKey(chatId, threadId);
42
+ const lang = resolveLang(state, key, null, config);
43
+ const answerRaw = (text, show = false) =>
44
+ tgFast('answerCallbackQuery', { callback_query_id: query.id, text, show_alert: show }).catch(() => false);
45
+
46
+ // A press must end in something. Silence is the one outcome a person cannot
47
+ // tell from a broken bot, and it was the one outcome the code could produce
48
+ // without a trace: a handler that returned without saying anything left the
49
+ // spinner turning for a few seconds and no line in the log at all. The guard
50
+ // turns that case into one honest line, once, whether the handler is still
51
+ // running or already gone.
52
+ const guard = quietGuard({
53
+ onSlow: () => {
54
+ log(`callback ${data} from ${query.from?.id} in ${chatId}/${threadId}: nothing answered in ${QUIET_MS / 1000}s`);
55
+ void tgFast('answerCallbackQuery', { callback_query_id: query.id, text: t(lang, 'bridge.cb.slow') }).catch(() => {});
56
+ void send(chatId, t(lang, 'bridge.cb.slowLine', { sec: QUIET_MS / 1000 }), threadId).catch(() => {});
57
+ },
58
+ });
59
+ const answer = guard.wrap(answerRaw);
60
+
61
+ // A button is a message without a sender the rest of the code can check, and
62
+ // the chat itself may be a group. Anything that changes configuration must
63
+ // come from an allowed user, exactly like the message path at the top of the
64
+ // poll loop. The refusal is deliberately the same as "unknown button".
65
+ const presser = query.from?.id;
66
+ if (!config.allowedUserIds.includes(presser) && !config.allowedUserIds.includes(chatId)) {
67
+ log(`ignored callback from ${presser} (chat ${chatId})`);
68
+ await answer(t(lang, 'bridge.cb.unknown'));
69
+ return;
70
+ }
71
+ // Every accepted press is named in the log before it is handled: a button that
72
+ // answers nothing was indistinguishable from a button that never arrived.
73
+ log(`callback ${data} from ${presser} in ${chatId}/${threadId}`);
74
+
75
+ // Trim the buttons of the pressed message first: a button that already did
76
+ // its job must not be pressable a second time.
77
+ const clearKeyboard = () => {
78
+ guard.mark();
79
+ return tgFast('editMessageReplyMarkup', { chat_id: chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } }).catch(() => {});
80
+ };
81
+
82
+ if (data.startsWith('m:')) {
83
+ // The settings card. Its own answer path, because a tap that redraws or
84
+ // flips one setting must not go through the defaults below (`clearKeyboard`
85
+ // would strip the tabs it is about to draw again).
86
+ await handleCardPress(query, { chatId, messageId, threadId, key, lang, answer });
87
+ return;
88
+ }
89
+
90
+ // `/dsh`'s own two presses. Each types the command the card advertised, so the
91
+ // install path and the confirmation in front of it exist exactly once — a
92
+ // button that called npm itself would be a second way to replace the harness.
93
+ if (data.startsWith('ds:')) {
94
+ await clearKeyboard();
95
+ await answer(t(lang, 'bridge.cb.done'));
96
+ await runCommandFromButton(`/dsh ${data === 'ds:confirm' ? 'update confirm' : 'update'}`, { chatId, threadId, key, lang });
97
+ return;
98
+ }
99
+
100
+ // `/mcp`'s own presses: open one server, confirm or cancel an add. The press
101
+ // re-reads the profile rather than trusting the card, so a confirmed add can
102
+ // never overwrite an edit made after the preview.
103
+ // The plan card's two presses: Approve replays the request with plan mode off,
104
+ // Keep planning asks for a revision. The id on the card decides whether a press
105
+ // still belongs to the topic's current plan.
106
+ if (data.startsWith('pm:')) {
107
+ guard.mark();
108
+ const claimed = await handlePlanPress({ data, key, lang, chatId, threadId, answer, clearKeyboard, redeliver, log });
109
+ if (claimed) return;
110
+ }
111
+
112
+ if (data.startsWith('mc:')) {
113
+ guard.mark();
114
+ const claimed = await handleMcpPress({ data, key, lang, chatId, threadId, messageId, answer });
115
+ if (claimed) return;
116
+ }
117
+
118
+ // A switch on the plugin settings card. It reads the profile again on every
119
+ // press, writes one key, and redraws the card with the value the file returned.
120
+ if (data.startsWith('ps:')) {
121
+ guard.mark();
122
+ const claimed = await handlePluginSettingsPress({ data, key, lang, chatId, messageId, answer, tg, inlineKeyboard });
123
+ if (claimed) return;
124
+ }
125
+
126
+ // `/compact`'s one press: the card explains where compaction lives and offers
127
+ // the thing that does work here, which is a fresh session. It types the command
128
+ // rather than doing the work, so `/new` keeps exactly one implementation.
129
+ if (data === 'cp:new') {
130
+ await clearKeyboard();
131
+ await answer(t(lang, 'bridge.cb.done'));
132
+ await runCommandFromButton('/new', { chatId, threadId, key, lang });
133
+ return;
134
+ }
135
+
136
+ if (isRewindPress(data)) {
137
+ // A rewind button. What it acts on is read here, not taken from the card:
138
+ // between drawing "go back 2" and the press, the session may have moved on,
139
+ // and the answer says so instead of cutting the wrong turns.
140
+ const sessionId = state.sessions[key] || '';
141
+ const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
142
+ const line = answerRewindPress(data, {
143
+ used: rewindUsed,
144
+ lang,
145
+ // Bound, not the raw `t`: this helper calls `t(key, vars)` with one
146
+ // argument, so the unbound import read the key as a language and returned
147
+ // the string "undefined" — which is what every rewind button answered on
148
+ // 2026-11-01 until the binding was fixed here.
149
+ t: (k, vars) => t(lang, k, vars),
150
+ ctx: {
151
+ sessionId,
152
+ busy: activeTurns.has(key),
153
+ file: sessionPath,
154
+ cut: (steps) => cutSession(sessionPath, steps, applyRewind),
155
+ undo: () => {
156
+ const backup = newestBackup(sessionPath);
157
+ if (!backup) return { error: 'nothing' };
158
+ try {
159
+ restoreBackup(backup, sessionPath);
160
+ return { backup };
161
+ } catch (error) {
162
+ return { error: error.message };
163
+ }
164
+ },
165
+ },
166
+ });
167
+ // The card becomes the one line answering the press, and keeps no buttons.
168
+ await tg('editMessageText', {
169
+ chat_id: chatId,
170
+ message_id: messageId,
171
+ text: line,
172
+ reply_markup: { inline_keyboard: [] },
173
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
174
+ }).catch(() => {});
175
+ await answer(t(lang, 'bridge.cb.done'));
176
+ log(`rewind press ${data} for ${key}`);
177
+ return;
178
+ }
179
+
180
+ // A search result's plus button. The name came from the registry and the
181
+ // command is the one the hint under the list names, so a tap installs exactly
182
+ // what was read — no hidden second path into pnpm.
183
+ if (data.startsWith('pl:i:')) {
184
+ const wanted = data.slice(5);
185
+ if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
186
+ await answer(t(lang, 'bridge.cb.unknown'));
187
+ return;
188
+ }
189
+ await clearKeyboard();
190
+ await answer(`/plugin add ${wanted}`);
191
+ log(`plugin install via button: ${wanted}`);
192
+ await runCommandFromButton(`/plugin add ${wanted}`, { chatId, threadId, key, lang });
193
+ return;
194
+ }
195
+
196
+ // The up arrow on the update card. Same shape as the plus of a search result:
197
+ // the name was printed by the command that read the registry, and the tap runs
198
+ // `/plugin update <name>` — nothing else.
199
+ if (data.startsWith('pl:u:')) {
200
+ const wanted = data.slice(5);
201
+ if (!/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(wanted)) {
202
+ await answer(t(lang, 'bridge.cb.unknown'));
203
+ return;
204
+ }
205
+ await clearKeyboard();
206
+ await answer(`/plugin update ${wanted}`);
207
+ log(`plugin update via button: ${wanted}`);
208
+ await runCommandFromButton(`/plugin update ${wanted}`, { chatId, threadId, key, lang });
209
+ return;
210
+ }
211
+
212
+ if (data.startsWith('fk:')) {
213
+ // A branch button from /branches. It does what `/resume <id>` does, so the
214
+ // topic moves onto that branch and the answer comes from the command
215
+ // itself — one implementation, one sentence.
216
+ const wanted = data.slice(3);
217
+ if (!/^session-[0-9a-f-]{36}$/.test(wanted)) {
218
+ await answer(t(lang, 'bridge.cb.unknown'));
219
+ return;
220
+ }
221
+ await clearKeyboard();
222
+ await runCommandFromButton(`/resume ${wanted.slice(8)}`, { chatId, threadId, key, lang });
223
+ return;
224
+ }
225
+
226
+ // A parallel-slot button from the /jobs card. It runs the command the card
227
+ // advertises, so validation and storage live in one place and a tap cannot
228
+ // write a value `/jobs <n>` would refuse. The command redraws the card, so the
229
+ // answer to the press is the new state, not a second message about it.
230
+ if (data.startsWith('jb:')) {
231
+ await clearKeyboard();
232
+ await runCommandFromButton(`/jobs ${data.slice(3)}`, { chatId, threadId, key });
233
+ return;
234
+ }
235
+
236
+ // A button on the load card, or on the notice that held a prompt back. Both
237
+ // are `/load` verbs, so the tap and the typed command run the same code.
238
+ if (data.startsWith('ld:')) {
239
+ await handleLoadPress({ data, key, t, lang, answer, clearKeyboard, redeliver, runCommandFromButton, chatId, threadId, log });
240
+ return;
241
+ }
242
+
243
+ // A button on the failover card. Every press becomes the verb of `/fallback`,
244
+ // so a tap and a typed line land in the same code — and the command redraws the
245
+ // card, which is why the old keyboard is trimmed only when the press leaves it.
246
+ if (isFallbackPress(data)) {
247
+ const target = pressTarget(data);
248
+ const words = { t: 'toggle', u: 'up', d: 'down', x: 'test', e: 'chain', s: 'show' };
249
+ // `r` is two verbs on one letter: with a number it removes that route, alone
250
+ // it opens the remove list. Anything else is a stale card and does nothing.
251
+ const verb = target && (target.verb === 'r' ? (target.n ? 'remove' : 'menu') : words[target.verb]);
252
+ if (!verb) {
253
+ await answer(t(lang, 'bridge.cb.unknown'));
254
+ return;
255
+ }
256
+ const typed = target.n && verb !== 'menu' ? `/fallback ${verb} ${target.n}` : `/fallback ${verb}`;
257
+ await clearKeyboard();
258
+ await answer(typed);
259
+ log(`fallback press ${typed} for ${key}`);
260
+ await runCommandFromButton(typed, { chatId, threadId, key, lang });
261
+ return;
262
+ }
263
+
264
+ if (isMenuPress(data)) {
265
+ // The panel is a set of cards: the hub, then one page per section. Moving
266
+ // between them edits this message, so browsing costs no new messages. A
267
+ // command press is exactly a typed command, so it goes through the same
268
+ // `handleControl`; the card is replaced by whatever that command answers.
269
+ const target = menuTarget(data);
270
+ if (target.kind === 'hub' || target.kind === 'section') {
271
+ const card = renderPanel({ t: (k, v) => t(lang, k, v), page: target.page || '' });
272
+ await tg('editMessageText', {
273
+ chat_id: chatId,
274
+ message_id: messageId,
275
+ text: card.text,
276
+ reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
277
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
278
+ }).catch(() => {});
279
+ await answer(t(lang, 'bridge.cb.done'));
280
+ return;
281
+ }
282
+ if (target.kind === 'close') {
283
+ // The card collapses into one line that can be deleted by hand, and the
284
+ // buttons go with it: a panel that stays open is a panel that lies about
285
+ // being closed.
286
+ await tg('editMessageText', {
287
+ chat_id: chatId,
288
+ message_id: messageId,
289
+ text: t(lang, 'ctrl.menu.closed'),
290
+ reply_markup: { inline_keyboard: [] },
291
+ ...(threadId > 0 ? { thread_id: threadId, message_thread_id: threadId } : {}),
292
+ }).catch(() => {});
293
+ await answer(t(lang, 'ctrl.menu.closedToast'));
294
+ log(`menu closed for ${key}`);
295
+ return;
296
+ }
297
+ const name = target.kind === 'command' ? target.name : '';
298
+ await clearKeyboard();
299
+ // `/new` and `/stop` change something when typed alone, and a stray tap on
300
+ // them is a command nobody asked for — so they open their explanation.
301
+ const typed = runsUnasked(name) && CONTROL_COMMANDS.includes(name)
302
+ ? commandForName(name, { t: (k, v) => t(lang, k, v) })
303
+ : `/help ${name}`;
304
+ await answer(typed || t(lang, 'bridge.cb.unknown'));
305
+ if (!typed) return;
306
+ log(`menu press /${name} for ${key}`);
307
+ await runCommandFromButton(typed, { chatId, threadId, key, lang });
308
+ return;
309
+ }
310
+
311
+ if (data === 'stop') {
312
+ const killed = killTurn(key);
313
+ await clearKeyboard();
314
+ await answer(t(lang, killed ? 'bridge.cb.stopping' : 'bridge.cb.nothingToStop'));
315
+ log(`stop via button for ${key}: ${killed ? 'killed' : 'nothing'}`);
316
+ if (killed) await send(chatId, t(lang, 'bridge.cb.turnStopped'), threadId);
317
+ return;
318
+ }
319
+
320
+ if (data === 'logs') {
321
+ await answer(t(lang, 'bridge.cb.showingLog'));
322
+ try {
323
+ const lines = readFileSync(LOG, 'utf8').split(/\r?\n/).filter(Boolean).slice(-12);
324
+ await send(chatId, lines.join('\n') || t(lang, 'bridge.cb.logEmpty'), threadId);
325
+ } catch (error) {
326
+ await send(chatId, t(lang, 'bridge.cb.logUnreadable', { err: error.message }), threadId);
327
+ }
328
+ return;
329
+ }
330
+
331
+ if (data === 'doctor') {
332
+ await answer(t(lang, 'bridge.cb.checking'));
333
+ await send(chatId, t(lang, 'bridge.cb.doctorHint'), threadId);
334
+ return;
335
+ }
336
+
337
+ if (data === 'resume') {
338
+ // Not a retry: the session already holds everything the turn produced.
339
+ // A continuation prompt asks the agent to check the state and go on.
340
+ await clearKeyboard();
341
+ await answer(t(lang, 'btn.continue'));
342
+ log(`resume via button for ${key}`);
343
+ const thread = threadId || 0;
344
+ enqueue(key, () => handleMessage({
345
+ chat: { id: chatId },
346
+ from: { id: config.allowedUserIds[0] },
347
+ message_id: 0,
348
+ message_thread_id: thread || undefined,
349
+ is_topic_message: thread > 0,
350
+ text: t(lang, 'prompt.continueTurn'),
351
+ }));
352
+ return;
353
+ }
354
+
355
+ if (data === 'retry') {
356
+ const original = lastPrompt.get(key);
357
+ if (!original) {
358
+ await answer(t(lang, 'bridge.cb.nothingToRetry'));
359
+ await clearKeyboard();
360
+ return;
361
+ }
362
+ await clearKeyboard();
363
+ await answer(t(lang, 'bridge.cb.retrying'));
364
+ log(`retry via button for ${key}`);
365
+ enqueue(key, () => handleMessage({ ...original, message_id: original.message_id }));
366
+ return;
367
+ }
368
+
369
+ // Two card presses, one rule each: what the card said is re-read from the
370
+ // thing it described before acting, never trusted from the button. The diff
371
+ // checks its hunk hash, the model card checks the route its profile declares.
372
+ if (data.startsWith('df:')) {
373
+ if (await diffPressRouter({ chatId, threadId, key, lang, config, state, answer, clearKeyboard, log, enqueue, handleMessage })(data)) return;
374
+ }
375
+ if (data.startsWith(MODEL_PREFIX)) {
376
+ if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
377
+ }
378
+
379
+ if (await handleTourPress({ data, lang, chatId, threadId, messageId, answer })) return;
380
+
381
+ if (await handleEditPress({ data, key, lang, chatId, threadId, messageId, answer })) return;
382
+
383
+ if (await handleFilePress({ data, key, lang, chatId, threadId, messageId, answer })) return;
384
+
385
+ if (data.startsWith('tc:')) {
386
+ // The turn card's own switches. Redrawn from state like the task card, so a
387
+ // double tap settles on one truth; an id this build does not know answers
388
+ // "stale" instead of writing a key nothing reads.
389
+ const next = toggleCardBlock(state, key, data.slice(3));
390
+ if (!next) {
391
+ await answer(t(lang, 'card.stale'));
392
+ return;
393
+ }
394
+ state.cardBlocks = { ...(state.cardBlocks || {}), [key]: next };
395
+ saveState();
396
+ const blocks = cardBlocks(state, key);
397
+ await tg('editMessageText', {
398
+ chat_id: chatId,
399
+ message_id: messageId,
400
+ text: renderCardSettings(blocks, lang),
401
+ reply_markup: { inline_keyboard: inlineKeyboard(cardKeyboard(blocks, lang)) },
402
+ }).catch(() => {});
403
+ await answer(t(lang, next.includes(data.slice(3)) ? 'card.cbOn' : 'card.cbOff'));
404
+ log(`card block ${data.slice(3)} toggled for ${key}`);
405
+ return;
406
+ }
407
+
408
+ if (data.startsWith('t:')) {
409
+ // A task card. The whole message is redrawn from state, so a double tap or
410
+ // two people pressing converge on one truth instead of stacking ✅ marks.
411
+ const n = Number(data.slice(2));
412
+ const goal = toggleTask(state, key, n);
413
+ if (!goal) {
414
+ await answer(t(lang, 'bridge.cb.taskStale'));
415
+ return;
416
+ }
417
+ saveState();
418
+ const text = renderTaskCard(goal, lang);
419
+ await tg('editMessageText', {
420
+ chat_id: chatId,
421
+ message_id: messageId,
422
+ text,
423
+ reply_markup: { inline_keyboard: inlineKeyboard(taskRows(goal)) },
424
+ }).catch(() => {});
425
+ await answer(t(lang, goal.tasks[n - 1]?.done ? 'bridge.cb.taskDone' : 'bridge.cb.taskUndone'));
426
+ log(`task ${n} toggled for ${key}`);
427
+ return;
428
+ }
429
+
430
+ if (data.startsWith('ap:')) {
431
+ const [, verdict, requestId] = data.split(':');
432
+ const pending = approvals.get(requestId);
433
+ if (!pending) {
434
+ await answer(t(lang, 'bridge.cb.approvalStale'));
435
+ await clearKeyboard();
436
+ return;
437
+ }
438
+ clearTimeout(pending.timer);
439
+ approvals.delete(requestId);
440
+ await clearKeyboard();
441
+ const allowed = verdict === 'y' || verdict === 'a';
442
+ const remember = verdict === 'a';
443
+ pending.resolve({ allowed, remember, expired: false });
444
+ await answer(t(lang, allowed ? (remember ? 'bridge.cb.allowedAlways' : 'bridge.cb.allowed') : 'bridge.cb.denied'));
445
+ log(`approval ${verdict} for request ${requestId}`);
446
+ return;
447
+ }
448
+
449
+ await answer(t(lang, 'bridge.cb.unknown'));
450
+ }
451
+
452
+
453
+ /**
454
+ * A press that failed before it could answer.
455
+ *
456
+ * Without this the throw reached the poll loop, which logged it and moved on:
457
+ * the log knew, the person did not. The toast is the same shape as every other
458
+ * answer, so a broken button and a stale one look different, and both look
459
+ * different from a button that never arrived.
460
+ */
461
+ export async function answerPressFailed(query) {
462
+ const chatId = query?.message?.chat?.id;
463
+ const threadId = query?.message?.message_thread_id ?? 0;
464
+ const lang = resolveLang(state, sessionKey(chatId, threadId), null, config);
465
+ await tgFast('answerCallbackQuery', { callback_query_id: query?.id, text: t(lang, 'bridge.cb.failed') }).catch(() => {});
466
+ }
467
+
468
+ /**
469
+ * A task list as one message plus one button per task. The label carries the
470
+ * state, the payload carries only the number, so the card survives a relabel and
471
+ * stays inside Telegram's 64-byte callback limit.
472
+ */
473
+ export function renderTaskCard(goal, lang) {
474
+ const { done, total } = progressOf(goal);
475
+ const lines = [t(lang, 'goal.set', { text: goal.text })];
476
+ goal.tasks.forEach((task, i) => lines.push(`${task.done ? '✅' : '⬜'} ${i + 1}. ${task.text}`));
477
+ lines.push(t(lang, 'goal.progress', { done, total }), '', t(lang, 'task.tapHint'));
478
+ return lines.join('\n');
479
+ }
480
+
481
+ export function taskRows(goal) {
482
+ if (!goal || goal.done) return [];
483
+ const rows = [];
484
+ for (let i = 0; i < Math.min(goal.tasks.length, 90); i += 3) {
485
+ rows.push(goal.tasks.slice(i, i + 3).map((task, k) => ({ text: `${task.done ? '✅' : '⬜'} ${i + k + 1}`, data: `t:${i + k + 1}` })));
486
+ }
487
+ return rows;
488
+ }