dsh-tg-bridge 1.44.0 → 1.46.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 (67) hide show
  1. package/README.md +10 -1
  2. package/bridge-kick.mjs +51 -4
  3. package/bridge.mjs +18 -1
  4. package/chat/answer-shape.mjs +168 -0
  5. package/chat/callbacks.mjs +20 -0
  6. package/chat/commands-registry.mjs +73 -66
  7. package/chat/control.mjs +136 -134
  8. package/chat/handle-message.mjs +19 -16
  9. package/chat/help-explain.mjs +34 -43
  10. package/chat/help-sections.mjs +84 -0
  11. package/chat/inline.mjs +80 -0
  12. package/chat/mcp-press.mjs +144 -0
  13. package/chat/menu-card.mjs +3 -2
  14. package/chat/panel.mjs +14 -0
  15. package/chat/plan-press.mjs +65 -0
  16. package/chat/reply-guard.mjs +34 -3
  17. package/control/cmd-agents.mjs +2 -18
  18. package/control/cmd-bridge.mjs +6 -1
  19. package/control/cmd-dsh.mjs +109 -17
  20. package/control/cmd-mcp.mjs +123 -0
  21. package/control/cmd-plan.mjs +46 -0
  22. package/control/cmd-views.mjs +3 -2
  23. package/control/doctor-rows.mjs +58 -0
  24. package/control/mcp-config.mjs +193 -0
  25. package/control/mcp-write.mjs +97 -0
  26. package/control/model-card.mjs +2 -2
  27. package/control/models.mjs +1 -1
  28. package/control/plan-mode.mjs +92 -0
  29. package/core/app-feed.mjs +84 -0
  30. package/core/app-install.mjs +72 -0
  31. package/core/dsh-version.mjs +67 -1
  32. package/core/start-guard.mjs +44 -0
  33. package/core/state.mjs +9 -2
  34. package/docs/CHANGELOG.md +140 -0
  35. package/docs/COMMANDS.md +300 -0
  36. package/docs/TELEGRAM-SETUP.md +1 -0
  37. package/i18n/en/core.mjs +376 -368
  38. package/i18n/en/ctrl.mjs +480 -496
  39. package/i18n/en/dsh.mjs +15 -3
  40. package/i18n/en/every.mjs +1 -1
  41. package/i18n/en/mcp.mjs +46 -0
  42. package/i18n/en/model.mjs +0 -1
  43. package/i18n/en/plan.mjs +20 -0
  44. package/i18n/en/supervision.mjs +13 -0
  45. package/i18n/en.mjs +19 -16
  46. package/i18n/ru/core.mjs +376 -368
  47. package/i18n/ru/ctrl.mjs +480 -496
  48. package/i18n/ru/dsh.mjs +15 -3
  49. package/i18n/ru/every.mjs +1 -1
  50. package/i18n/ru/mcp.mjs +46 -0
  51. package/i18n/ru/model.mjs +0 -1
  52. package/i18n/ru/plan.mjs +20 -0
  53. package/i18n/ru/supervision.mjs +13 -0
  54. package/i18n/ru.mjs +19 -16
  55. package/i18n/zh/core.mjs +376 -368
  56. package/i18n/zh/ctrl.mjs +480 -496
  57. package/i18n/zh/dsh.mjs +15 -3
  58. package/i18n/zh/every.mjs +1 -1
  59. package/i18n/zh/mcp.mjs +45 -0
  60. package/i18n/zh/model.mjs +0 -1
  61. package/i18n/zh/plan.mjs +20 -0
  62. package/i18n/zh/supervision.mjs +12 -0
  63. package/i18n/zh.mjs +19 -16
  64. package/package.json +1 -1
  65. package/profile/settings-card.mjs +7 -1
  66. package/turn/progress.mjs +4 -1
  67. package/work/goals.mjs +12 -6
package/README.md CHANGED
@@ -696,12 +696,21 @@ no lock race and no lost update.
696
696
 
697
697
  ## Documentation
698
698
 
699
+ - [docs/COMMANDS.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/COMMANDS.md): every command with what it does, in English, Russian and Chinese — the page `/help` links to
699
700
  - [docs/LAYOUT.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/LAYOUT.md): which folder answers which question, and why the entry points stay at the root
700
701
  - [docs/TELEGRAM-SETUP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/TELEGRAM-SETUP.md): BotFather settings, group and bot permissions
701
702
  - [docs/SUPPORT.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/SUPPORT.md): what to send with a bug report, what never to send, and the one-line answer for "the bot went silent"
703
+ - [docs/VOICE.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/VOICE.md): any speech engine as input — a local script, a command with placeholders, an [OI]-compatible API
704
+ - [docs/MOBILE-FIRST.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/MOBILE-FIRST.md): working from a phone: what the chat shows, what it answers first, what it never makes you type
705
+ - [docs/COST.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/COST.md): what one turn costs and how to reduce it
706
+ - [docs/INJECTION-AND-REPLIES.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/INJECTION-AND-REPLIES.md): sending text into a turn that is still running, and how a reply is composed from its parts
707
+ - [docs/DEV-LOOP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/DEV-LOOP.md): how work continues without a person at the keyboard — schedules, the queue, what a turn does when nobody watches
708
+ - [docs/REFACTORING.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/REFACTORING.md): moving code without ever shipping a broken version
702
709
  - [docs/ROADMAP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/ROADMAP.md): what comes next
710
+ - [docs/ONBOARDING-PLAN.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/ONBOARDING-PLAN.md): how a newcomer gets from "I found this repo" to a working bot
703
711
  - [docs/UX-ANALYSIS.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/UX-ANALYSIS.md): interactive UX review
704
- - [docs/COST.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/COST.md): what one turn costs and how to reduce it
712
+ - [docs/HERMES-PARITY.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/HERMES-PARITY.md): DSH against the Hermes agent — what parity would take
713
+ - [docs/MARKETPLACE.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/MARKETPLACE.md): publishing in the DSH marketplace
705
714
  - [docs/CHANGELOG.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/CHANGELOG.md): change history
706
715
  - [docs/RELEASE-CRITERIA.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/RELEASE-CRITERIA.md): release readiness criteria
707
716
 
package/bridge-kick.mjs CHANGED
@@ -16,9 +16,10 @@
16
16
  // Exit codes: 0 = nothing to do or started, 2 = start failed.
17
17
 
18
18
  import { spawn, spawnSync } from 'node:child_process';
19
- import { appendFileSync, existsSync, readFileSync, openSync, closeSync, unlinkSync, writeFileSync } from 'node:fs';
19
+ import { appendFileSync, existsSync, readFileSync, openSync, closeSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
20
20
  import { homedir } from 'node:os';
21
21
  import { join } from 'node:path';
22
+ import { awaitPid } from './core/start-guard.mjs';
22
23
 
23
24
  const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
24
25
  const DIR = join(DSH_HOME, 'tg-bridge');
@@ -43,6 +44,12 @@ const CRASH_STARTS = 2;
43
44
  // LOCK_MAX_AGE_MS here so even a genuinely wedged holder cannot wedge the guard.
44
45
  const LOCK = join(DIR, 'restart.lock');
45
46
  const LOCK_MAX_AGE_MS = 180_000;
47
+ // A restart marker older than this is a leftover, not a restart in progress.
48
+ const MARKER_MAX_AGE_MS = 600_000;
49
+ // How long a tick keeps the lock after spawning, waiting for the child's pid
50
+ // file. Long enough for a cold start to get there, short enough that a wedged
51
+ // child cannot hold the supervisor's lock.
52
+ const START_WAIT_MS = 8_000;
46
53
 
47
54
  function acquireLock(owner) {
48
55
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -88,6 +95,32 @@ function log(line) {
88
95
  } catch {}
89
96
  }
90
97
 
98
+ /**
99
+ * Forget a restart marker that outlived its restart.
100
+ *
101
+ * The bridge reads the marker on start to tell other topics their turn was cut,
102
+ * then clears it. If it is still there with a live bridge, the process that
103
+ * should have cleared it did not run — and every later start would read this
104
+ * stale marker as "the previous process died mid-turn". Ten minutes is well past
105
+ * any start, so the marker is a leftover, not news.
106
+ */
107
+ function clearStaleMarker(marker) {
108
+ let age = Number.POSITIVE_INFINITY;
109
+ try {
110
+ age = Date.now() - statSync(marker).mtimeMs;
111
+ } catch {}
112
+ if (age < MARKER_MAX_AGE_MS) {
113
+ log('marker present and bridge alive, restart still in progress');
114
+ return;
115
+ }
116
+ try {
117
+ unlinkSync(marker);
118
+ log(`cleared stale restart marker (${Math.round(age / 1000)}s old, bridge alive)`);
119
+ } catch (error) {
120
+ log(`could not clear the restart marker: ${String(error?.message ?? error).slice(0, 120)}`);
121
+ }
122
+ }
123
+
91
124
  function pidFromFile() {
92
125
  try {
93
126
  const pid = Number(readFileSync(PID_FILE, 'utf8').trim());
@@ -108,8 +141,15 @@ function alive(pid) {
108
141
  }
109
142
 
110
143
  function bridgePids() {
144
+ // PowerShell is a Windows tool: on macOS and Linux this scan has never found
145
+ // anything, so say so instead of spawning a missing binary and timing out.
146
+ if (process.platform !== 'win32') return [];
147
+ // Match THIS install's bridge, not any bridge on the machine: a second profile
148
+ // under another DSH_HOME would otherwise make a stale pid file here look
149
+ // healthy, and the tick would refuse to start the bridge that is actually gone.
150
+ const literal = BRIDGE.replace(/'/g, "''");
111
151
  const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
112
- "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object { $_.CommandLine -match 'bridge\\.mjs' } | Select-Object -ExpandProperty ProcessId"],
152
+ `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains('${literal}') } | Select-Object -ExpandProperty ProcessId`],
113
153
  { encoding: 'utf8', windowsHide: true, timeout: 20000 });
114
154
  return (r.stdout || '').split(/\r?\n/).map((v) => Number(v.trim())).filter((v) => Number.isInteger(v) && v > 0);
115
155
  }
@@ -193,7 +233,8 @@ async function main() {
193
233
  if (!acquireLock('kick')) {
194
234
  log('restart in progress (setup holds the lock), skipping this tick');
195
235
  return 0;
196
- } if (!existsSync(BRIDGE)) {
236
+ }
237
+ if (!existsSync(BRIDGE)) {
197
238
  log('bridge.mjs missing');
198
239
  return 2;
199
240
  }
@@ -206,7 +247,7 @@ async function main() {
206
247
  // Cheap path first: a live pid file is authoritative for a healthy bridge, so
207
248
  // the minute tick costs one kill(0) instead of a PowerShell process scan.
208
249
  if (filePid && alive(filePid)) {
209
- if (restartPending) log(`marker present but pid ${filePid} alive`);
250
+ if (restartPending) clearStaleMarker(marker);
210
251
  // A live bridge proves the release can start: forget the crash history.
211
252
  writeStarts([]);
212
253
  return 0;
@@ -244,6 +285,12 @@ async function main() {
244
285
  child.unref();
245
286
  if (!restored) writeStarts([...readStarts(), Date.now()]);
246
287
  log(`start issued pid=${child.pid ?? '?'}`);
288
+ // Hold the lock until the child has written its pid file, or for a few
289
+ // seconds at most. Without this the tick exits — and releases the lock —
290
+ // before the bridge is visible, and a tick that lands in that gap starts a
291
+ // second poller. Two bridges on one token is the 409 storm this lock exists
292
+ // to prevent.
293
+ await awaitPid({ readPid: pidFromFile, isAlive: alive, childPid: child.pid, limit: START_WAIT_MS });
247
294
  return 0;
248
295
  }
249
296
 
package/bridge.mjs CHANGED
@@ -77,6 +77,7 @@ import { activeTurns, killTurn, liveSessions, profileOf, runTurn, runTurnLive, t
77
77
  import { approvalKeyboard, continueKeyboard, errorKeyboard } from './chat/keyboards.mjs';
78
78
  import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, noteSeed, topicName, topicSeeded, topicSeededRecently, touchTopic } from './chat/topics.mjs';
79
79
  import { downloadFile, send, sendEphemeral, sendFile, sendWithMarkup, tg } from './chat/telegram.mjs';
80
+ import { sentThroughUs, takeInlineQuery } from './chat/inline.mjs';
80
81
 
81
82
  setMessageHandler(handleMessage);
82
83
 
@@ -111,7 +112,12 @@ process.on('uncaughtException', (error) => {
111
112
  process.exit(1);
112
113
  });
113
114
  process.on('unhandledRejection', (reason) => {
115
+ // Logging alone left the process running in a state nobody had designed: the
116
+ // turn that rejected is gone, the loop keeps polling, and the next /doctor
117
+ // shows a healthy bridge. Exit instead — the minute tick starts a clean one,
118
+ // and the interruption notice tells the topics what happened.
114
119
  log(`FATAL unhandled rejection: ${reason && reason.stack ? reason.stack : reason}`);
120
+ process.exit(1);
115
121
  });
116
122
  process.on('exit', (code) => {
117
123
  log(`bridge exiting code=${code}`);
@@ -221,6 +227,12 @@ async function main() {
221
227
  ack(update.update_id);
222
228
  return;
223
229
  }
230
+ // A hint picked from our own inline results is documentation, not a task.
231
+ if (sentThroughUs(msg)) {
232
+ log(`ignored inline hint in chat ${msg.chat?.id}`);
233
+ ack(update.update_id);
234
+ return;
235
+ }
224
236
  const queueKey = sessionKey(msg.chat.id, threadOf(msg));
225
237
  const thread = threadOf(msg);
226
238
  // `/stop` behind the turn it should kill is a no-op; run the few commands
@@ -442,9 +454,14 @@ async function main() {
442
454
  try {
443
455
  // `callback_query` is required for inline buttons: without it Telegram
444
456
  // never delivers button presses, so «Стоп» would draw but do nothing.
445
- const updates = await tg('getUpdates', { offset: state.offset, timeout: 50, allowed_updates: ['message', 'callback_query'] }, 120000);
457
+ // `inline_query` is what `@bot rew` sends.
458
+ const updates = await tg('getUpdates', { offset: state.offset, timeout: 50, allowed_updates: ['message', 'callback_query', 'inline_query'] }, 120000);
446
459
  if (pollFailures > 0) { log(`poll recovered after ${pollFailures} failure(s)`); pollFailures = 0; }
447
460
  for (const update of updates) {
461
+ if (update.inline_query) {
462
+ await takeInlineQuery({ update, tg, state, config, log, save: saveState });
463
+ continue;
464
+ }
448
465
  if (update.callback_query) {
449
466
  // Buttons are handled inline and immediately: they are neither
450
467
  // journaled nor queued, because a stale button must answer at once.
@@ -0,0 +1,168 @@
1
+ // What the chat refuses to forward from a finished answer.
2
+ //
3
+ // The reasoning guard answers "the model sent its notes and nothing else". This
4
+ // one answers a different, more embarrassing shape: notes wrapped around a real
5
+ // answer. A turn that ends with an English plan — "Live page confirmed…", "Should
6
+ // I update the goal task list?", "Keep ~5 lines." — in front of a Russian reply is
7
+ // still an answer, so the reasoning guard stays silent, and the person reads the
8
+ // model thinking out loud in a language they did not ask for.
9
+ //
10
+ // The repair is deterministic and narrow: a paragraph that is not in the
11
+ // conversation's language and reads like planning is dropped when a real answer
12
+ // follows. Nothing is guessed, nothing is rewritten, and a reply that would come
13
+ // out empty is returned untouched — a wrong paragraph is a bruise, a swallowed
14
+ // answer is a wound.
15
+ import { normalizeLang } from '../core/i18n.mjs';
16
+
17
+ const FENCE = /^\s*(?:```|~~~)/;
18
+
19
+ /** Letters of each script in a run of text, so "which language" is a count. */
20
+ export function scriptProfile(text) {
21
+ const value = String(text ?? '');
22
+ const count = (re) => (value.match(re) || []).length;
23
+ return {
24
+ latin: count(/[A-Za-z]/g),
25
+ cyrillic: count(/[\u0400-\u04FF]/g),
26
+ cjk: count(/[\u4E00-\u9FFF]/g),
27
+ length: value.trim().length,
28
+ };
29
+ }
30
+
31
+ /**
32
+ * Does this text speak the conversation's language?
33
+ *
34
+ * `en` is counted as "not Russian and not Chinese": the answer may quote code,
35
+ * identifiers and file names, so the question is which script dominates.
36
+ */
37
+ export function speaksLang(text, lang) {
38
+ const p = scriptProfile(text);
39
+ const letters = p.latin + p.cyrillic + p.cjk;
40
+ if (!letters) return true;
41
+ if (lang === 'ru') return p.cyrillic / letters >= 0.3;
42
+ if (lang === 'zh') return p.cjk / letters >= 0.3;
43
+ return p.latin / letters >= 0.5;
44
+ }
45
+
46
+ /**
47
+ * A line that announces what the model is about to do, rather than doing it.
48
+ *
49
+ * These are narrow on purpose. The first version of this file also caught every
50
+ * line starting with "now", "so", "also" or "next", which in a Russian
51
+ * conversation is how a quoted English sentence, a book title or a list entry
52
+ * begins — the scrub became a language filter, and a language filter is not what
53
+ * the person asked for. Each cue below needs the planning *shape*: a first
54
+ * person, a label, or a sentence talking about the answer itself.
55
+ */
56
+ const PLAN_CUES = [
57
+ /^(?:should i|let me|let's|i'll|i will|i need to|i should|i could|i'm going to|i am going to)\b/i,
58
+ /^(?:final answer|keep ~?\d+ lines?|todo|next step|checklist)\b/i,
59
+ /^(?:now i|next i|then i|now the answer|now the reply)\b/i,
60
+ /^(?:live page|page confirmed|checked|verified|confirmed:)\b/i,
61
+ /\b(?:the answer|my reply|the reply)\b[^.]{0,40}\b(?:russian|english|chinese|language)\b/i,
62
+ ];
63
+
64
+ /** Anything a line of real content can carry: quoting it makes it content. */
65
+ const CONTENT = /[`"«»„“”]|https?:\/\/|\/\/|^\s*(?:[-*•]|\d+[.)])\s/;
66
+
67
+ /** Planning prefixes that a real sentence can follow: drop the label, keep the text. */
68
+ const PLAN_LABEL = /^(?:mention|note|final answer|answer|reply|next step|todo)\s*:\s*/i;
69
+
70
+ /** The share of a line written in the conversation's own script. */
71
+ function ownShare(text, lang) {
72
+ const p = scriptProfile(text);
73
+ const letters = p.latin + p.cyrillic + p.cjk;
74
+ if (!letters) return 1;
75
+ if (lang === 'ru') return p.cyrillic / letters;
76
+ if (lang === 'zh') return p.cjk / letters;
77
+ return p.latin / letters;
78
+ }
79
+
80
+ /** Is this one line nothing but the model talking to itself? */
81
+ function isPlanLine(line, lang) {
82
+ const text = line.trim();
83
+ if (!text || FENCE.test(text)) return false;
84
+ if (text.length < 12) return false;
85
+ // A quoted line, a link, a bullet or a numbered item is content the person may
86
+ // have asked for, however English it looks.
87
+ if (CONTENT.test(text)) return false;
88
+ // A line mostly in the conversation's language is content, whatever it opens with.
89
+ if (ownShare(text, lang) >= 0.4) return false;
90
+ return PLAN_CUES.some((re) => re.test(text));
91
+ }
92
+
93
+ /**
94
+ * A language the person asked to be answered in, when the sentence says so.
95
+ *
96
+ * "Ответь по-английски", "in Chinese, please", "用英语" — a request that beat the
97
+ * topic's language deliberately. The reply must then be allowed to be foreign,
98
+ * or the scrub would fight the person's own instruction.
99
+ */
100
+ export function languageRequest(text) {
101
+ const body = String(text ?? '');
102
+ if (!body.trim()) return '';
103
+ // No `\b` around the Cyrillic and Han alternatives: `\b` is defined on ASCII
104
+ // word characters, so it never matches before "по-английски".
105
+ const named = [
106
+ { code: 'en', re: /по-английски|на английском|in english|use english|write english|用英语|英语回答/i },
107
+ { code: 'ru', re: /по-русски|на русском|in russian|use russian|write russian|用俄语|俄语回答/i },
108
+ { code: 'zh', re: /по-китайски|на китайском|in chinese|use chinese|write chinese|用中文|中文回答|汉语/i },
109
+ ];
110
+ const hit = named.find((one) => one.re.test(body));
111
+ return hit ? hit.code : '';
112
+ }
113
+
114
+ /** `Keep ~5 lines.Но, страница…` — a plan and an answer glued at a full stop. */
115
+ const glued = (line) => line.replace(/(?<=[.!?])(?=[\u0400-\u04FF\u4E00-\u9FFF])/g, '\n');
116
+
117
+ /**
118
+ * The reply as the chat should read it.
119
+ *
120
+ * @param {string} text the finished turn's text
121
+ * @param {string} lang the conversation language (`ru`, `en`, `zh`)
122
+ * @param {object} [opts]
123
+ * @param {boolean} [opts.allowForeign] the person asked for another language, so
124
+ * neither stripping nor the wrong-language report applies
125
+ * @returns {{ text: string, dropped: number, foreign: boolean }}
126
+ * `dropped` is how many lines were removed; `foreign` means what is left still
127
+ * is not in the conversation's language, which the caller may log.
128
+ */
129
+ export function scrubReply(text, lang, opts = {}) {
130
+ const source = String(text ?? '');
131
+ if (opts.allowForeign) return { text: source, dropped: 0, foreign: false };
132
+ if (!source.trim()) return { text: source, dropped: 0, foreign: false };
133
+ const want = normalizeLang(lang) || 'en';
134
+ // An English conversation has nothing to strip: the cues are English, and the
135
+ // same words are how an English answer legitimately begins.
136
+ if (want === 'en') return { text: source, dropped: 0, foreign: !speaksLang(source, want) };
137
+
138
+ const kept = [];
139
+ let dropped = 0;
140
+ let fenced = false;
141
+ for (const raw of source.split(/\r?\n/)) {
142
+ for (const line of raw.split('\n').flatMap((one) => glued(one).split('\n'))) {
143
+ if (FENCE.test(line)) {
144
+ fenced = !fenced;
145
+ kept.push(line);
146
+ continue;
147
+ }
148
+ if (!fenced && isPlanLine(line, want)) {
149
+ dropped += 1;
150
+ continue;
151
+ }
152
+ // `Mention: /help отвечает на языке темы` — the label is plan, the sentence
153
+ // after it is the answer. Drop the label, keep the sentence.
154
+ if (!fenced && PLAN_LABEL.test(line) && ownShare(line.replace(PLAN_LABEL, ''), want) >= 0.4) {
155
+ kept.push(line.replace(PLAN_LABEL, ''));
156
+ continue;
157
+ }
158
+ kept.push(line);
159
+ }
160
+ }
161
+ const cleaned = kept.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '').trimEnd();
162
+ // Never trade an answer for tidiness: if stripping left nothing worth reading
163
+ // (or nothing in the right language), the original goes out.
164
+ if (!cleaned.trim() || !speaksLang(cleaned, want)) {
165
+ return { text: source, dropped: 0, foreign: !speaksLang(source, want) };
166
+ }
167
+ return { text: cleaned, dropped, foreign: false };
168
+ }
@@ -19,6 +19,8 @@ import { runCommandFromButton } from '../core/run-command.mjs';
19
19
  import { handleCardPress } from '../profile/settings-press.mjs';
20
20
  import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
21
21
  import { handleFilePress } from './file-press.mjs';
22
+ import { handleMcpPress } from './mcp-press.mjs';
23
+ import { handlePlanPress } from './plan-press.mjs';
22
24
  import { handleEditPress } from './edit-press.mjs';
23
25
  import { handleTourPress } from './tour-press.mjs';
24
26
  import { config, done, log, saveState, state } from '../core/state.mjs';
@@ -94,6 +96,24 @@ export async function handleCallback(query) {
94
96
  return;
95
97
  }
96
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
+
97
117
  // `/compact`'s one press: the card explains where compaction lives and offers
98
118
  // the thing that does work here, which is a fresh session. It types the command
99
119
  // rather than doing the work, so `/new` keeps exactly one implementation.
@@ -1,66 +1,73 @@
1
- // The command registry: what exists, what is an alias, what may be advertised.
2
- //
3
- // A module of its own because both directions of the old cycle needed it:
4
- // `control.mjs` dispatches on this list, and `menu-card.mjs` plus
5
- // `help-explain.mjs` render it. Importing it from `control.mjs` made the
6
- // renderers import the dispatcher that imports them, which Node reports as
7
- // `undefined is not a function` three frames away instead of as a cycle. This
8
- // file imports nothing, so it can never be part of one.
9
- export const CONTROL_COMMANDS = [
10
- 'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
11
- 'jobs', 'remind', 'every', 'sessions', 'resume', 'plugins', 'plugin',
12
- 'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
13
- 'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
14
- 'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
- 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
16
- 'ls', 'view', 'edit',
17
- ];
18
-
19
- /**
20
- * Old spellings that no longer have a job of their own. A phone keyboard turns
21
- * `task` into `tasks` and `model` into `models` without the person noticing, so
22
- * each pair is ONE command: one name in `/help` and the panel, and the other
23
- * spelling quietly routed to it. A name that is documented is a name a person
24
- * can mistype; a name that is not documented is a name nobody has to remember.
25
- */
26
- export const COMMAND_ALIASES = {
27
- models: 'model',
28
- plugin: 'plugins',
29
- agentset: 'crew',
30
- task: 'tasks',
31
- // One verb per job: going back is `/rewind` with a word (`fork`, `branches`),
32
- // switching a session is `/sessions <id>`, and "am I current?" is `/update`.
33
- // The old names still work — `control.mjs` rewrites them into the verb and its
34
- // argument — and none of them is advertised, so `/help` stops teaching four
35
- // commands where two do the work.
36
- fork: 'rewind',
37
- branches: 'rewind',
38
- resume: 'sessions',
39
- version: 'update',
40
- };
41
-
42
- /**
43
- * What `/help`, the panel and the Telegram menu are allowed to say. Aliases are
44
- * deliberately absent: they work, and they are never advertised.
45
- */
46
- export const DOCUMENTED_COMMANDS = CONTROL_COMMANDS.filter((name) => !COMMAND_ALIASES[name]);
47
-
48
- /**
49
- * What the Telegram menu shows — and it is deliberately shorter than what
50
- * exists.
51
- *
52
- * Thirty-six rows is not a menu, it is a wall a phone keyboard scrolls through,
53
- * and a wall cannot answer "which of these do I press". These are the thirteen
54
- * things a person does from a chat; `/help` still explains every command, and
55
- * `/menu` still draws every section as buttons. Hiding a name here costs
56
- * nothing: nothing was removed, only unadvertised.
57
- *
58
- * Two rules for adding a row: it must be a documented name (an alias here would
59
- * teach the duplication back through the menu), and it must not be one letter
60
- * away from another row — `sessions` and `resume`, `task` and `tasks` is exactly
61
- * the pair of names this list exists to avoid.
62
- */
63
- export const MENU_COMMANDS = [
64
- 'new', 'status', 'diff', 'sessions', 'goal', 'tasks', 'model', 'plugins',
65
- 'settings', 'menu', 'rewind', 'stop', 'help', 'update',
66
- ];
1
+ // The command registry: what exists, what is an alias, what may be advertised.
2
+ //
3
+ // A module of its own because both directions of the old cycle needed it:
4
+ // `control.mjs` dispatches on this list, and `menu-card.mjs` plus
5
+ // `help-explain.mjs` render it. Importing it from `control.mjs` made the
6
+ // renderers import the dispatcher that imports them, which Node reports as
7
+ // `undefined is not a function` three frames away instead of as a cycle. This
8
+ // file imports nothing, so it can never be part of one.
9
+ /**
10
+ * Names that look like commands but belong to Telegram, not to the bridge:
11
+ * `/setinline` is typed at @BotFather. `/help` tells people to do it, so the
12
+ * guards against "a promise the bot cannot keep" must not read it as one.
13
+ */
14
+ export const EXTERNAL_COMMANDS = ['setinline'];
15
+
16
+ export const CONTROL_COMMANDS = [
17
+ 'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
18
+ 'jobs', 'remind', 'every', 'sessions', 'resume', 'plugins', 'plugin', 'mcp',
19
+ 'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
20
+ 'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
21
+ 'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
22
+ 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
23
+ 'ls', 'view', 'edit',
24
+ ];
25
+
26
+ /**
27
+ * Old spellings that no longer have a job of their own. A phone keyboard turns
28
+ * `task` into `tasks` and `model` into `models` without the person noticing, so
29
+ * each pair is ONE command: one name in `/help` and the panel, and the other
30
+ * spelling quietly routed to it. A name that is documented is a name a person
31
+ * can mistype; a name that is not documented is a name nobody has to remember.
32
+ */
33
+ export const COMMAND_ALIASES = {
34
+ models: 'model',
35
+ plugin: 'plugins',
36
+ agentset: 'crew',
37
+ task: 'tasks',
38
+ // One verb per job: going back is `/rewind` with a word (`fork`, `branches`),
39
+ // switching a session is `/sessions <id>`, and "am I current?" is `/update`.
40
+ // The old names still work — `control.mjs` rewrites them into the verb and its
41
+ // argument — and none of them is advertised, so `/help` stops teaching four
42
+ // commands where two do the work.
43
+ fork: 'rewind',
44
+ branches: 'rewind',
45
+ resume: 'sessions',
46
+ version: 'update',
47
+ };
48
+
49
+ /**
50
+ * What `/help`, the panel and the Telegram menu are allowed to say. Aliases are
51
+ * deliberately absent: they work, and they are never advertised.
52
+ */
53
+ export const DOCUMENTED_COMMANDS = CONTROL_COMMANDS.filter((name) => !COMMAND_ALIASES[name]);
54
+
55
+ /**
56
+ * What the Telegram menu shows — and it is deliberately shorter than what
57
+ * exists.
58
+ *
59
+ * Thirty-six rows is not a menu, it is a wall a phone keyboard scrolls through,
60
+ * and a wall cannot answer "which of these do I press". These are the thirteen
61
+ * things a person does from a chat; `/help` still explains every command, and
62
+ * `/menu` still draws every section as buttons. Hiding a name here costs
63
+ * nothing: nothing was removed, only unadvertised.
64
+ *
65
+ * Two rules for adding a row: it must be a documented name (an alias here would
66
+ * teach the duplication back through the menu), and it must not be one letter
67
+ * away from another row — `sessions` and `resume`, `task` and `tasks` is exactly
68
+ * the pair of names this list exists to avoid.
69
+ */
70
+ export const MENU_COMMANDS = [
71
+ 'new', 'status', 'diff', 'sessions', 'goal', 'tasks', 'model', 'plugins',
72
+ 'settings', 'menu', 'rewind', 'stop', 'help', 'update',
73
+ ];