dsh-tg-bridge 1.45.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.
Files changed (59) hide show
  1. package/README.md +10 -1
  2. package/bridge-kick.mjs +19 -1
  3. package/bridge.mjs +13 -1
  4. package/chat/answer-shape.mjs +168 -0
  5. package/chat/callbacks.mjs +488 -459
  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/plugin-settings-press.mjs +189 -0
  17. package/chat/reply-guard.mjs +34 -3
  18. package/control/cmd-agents.mjs +2 -18
  19. package/control/cmd-bridge.mjs +1 -1
  20. package/control/cmd-dsh.mjs +109 -17
  21. package/control/cmd-mcp.mjs +123 -0
  22. package/control/cmd-plan.mjs +46 -0
  23. package/control/cmd-plugin.mjs +294 -281
  24. package/control/cmd-views.mjs +2 -1
  25. package/control/mcp-config.mjs +193 -0
  26. package/control/mcp-write.mjs +97 -0
  27. package/control/plan-mode.mjs +92 -0
  28. package/control/plugin-settings.mjs +197 -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/docs/CHANGELOG.md +125 -0
  34. package/docs/COMMANDS.md +300 -0
  35. package/docs/TELEGRAM-SETUP.md +1 -0
  36. package/i18n/en/core.mjs +378 -368
  37. package/i18n/en/ctrl.mjs +31 -29
  38. package/i18n/en/dsh.mjs +15 -3
  39. package/i18n/en/mcp.mjs +46 -0
  40. package/i18n/en/model.mjs +0 -1
  41. package/i18n/en/plan.mjs +20 -0
  42. package/i18n/en.mjs +19 -17
  43. package/i18n/ru/core.mjs +378 -368
  44. package/i18n/ru/ctrl.mjs +31 -29
  45. package/i18n/ru/dsh.mjs +15 -3
  46. package/i18n/ru/mcp.mjs +46 -0
  47. package/i18n/ru/model.mjs +0 -1
  48. package/i18n/ru/plan.mjs +20 -0
  49. package/i18n/ru.mjs +19 -17
  50. package/i18n/zh/core.mjs +378 -368
  51. package/i18n/zh/ctrl.mjs +31 -29
  52. package/i18n/zh/dsh.mjs +15 -3
  53. package/i18n/zh/mcp.mjs +45 -0
  54. package/i18n/zh/model.mjs +0 -1
  55. package/i18n/zh/plan.mjs +20 -0
  56. package/i18n/zh.mjs +19 -17
  57. package/package.json +1 -1
  58. package/profile/settings-card.mjs +335 -326
  59. 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
@@ -19,6 +19,7 @@ import { spawn, spawnSync } from 'node:child_process';
19
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');
@@ -45,6 +46,10 @@ const LOCK = join(DIR, 'restart.lock');
45
46
  const LOCK_MAX_AGE_MS = 180_000;
46
47
  // A restart marker older than this is a leftover, not a restart in progress.
47
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;
48
53
 
49
54
  function acquireLock(owner) {
50
55
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -136,8 +141,15 @@ function alive(pid) {
136
141
  }
137
142
 
138
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, "''");
139
151
  const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
140
- "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`],
141
153
  { encoding: 'utf8', windowsHide: true, timeout: 20000 });
142
154
  return (r.stdout || '').split(/\r?\n/).map((v) => Number(v.trim())).filter((v) => Number.isInteger(v) && v > 0);
143
155
  }
@@ -273,6 +285,12 @@ async function main() {
273
285
  child.unref();
274
286
  if (!restored) writeStarts([...readStarts(), Date.now()]);
275
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 });
276
294
  return 0;
277
295
  }
278
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
 
@@ -226,6 +227,12 @@ async function main() {
226
227
  ack(update.update_id);
227
228
  return;
228
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
+ }
229
236
  const queueKey = sessionKey(msg.chat.id, threadOf(msg));
230
237
  const thread = threadOf(msg);
231
238
  // `/stop` behind the turn it should kill is a no-op; run the few commands
@@ -447,9 +454,14 @@ async function main() {
447
454
  try {
448
455
  // `callback_query` is required for inline buttons: without it Telegram
449
456
  // never delivers button presses, so «Стоп» would draw but do nothing.
450
- 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);
451
459
  if (pollFailures > 0) { log(`poll recovered after ${pollFailures} failure(s)`); pollFailures = 0; }
452
460
  for (const update of updates) {
461
+ if (update.inline_query) {
462
+ await takeInlineQuery({ update, tg, state, config, log, save: saveState });
463
+ continue;
464
+ }
453
465
  if (update.callback_query) {
454
466
  // Buttons are handled inline and immediately: they are neither
455
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
+ }