dsh-tg-bridge 1.30.0 → 1.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bridge-kick.mjs CHANGED
@@ -6,6 +6,13 @@
6
6
  // otherwise it exits immediately. A live pid that refuses to die (EPERM) counts
7
7
  // as alive: refusing to start a second poller is what prevents 409 conflicts.
8
8
  //
9
+ // It also owns the one failure the bridge cannot report about itself. A release
10
+ // that throws while it loads never runs a turn, so the turn path records nothing
11
+ // and no rollback is ever considered — the tick is the only thing still watching.
12
+ // When the install keeps dying without answering, or the record already says the
13
+ // version on disk is faulted, this puts the last proven release back before it
14
+ // starts the bridge again.
15
+ //
9
16
  // Exit codes: 0 = nothing to do or started, 2 = start failed.
10
17
 
11
18
  import { spawn, spawnSync } from 'node:child_process';
@@ -18,6 +25,12 @@ const DIR = join(DSH_HOME, 'tg-bridge');
18
25
  const BRIDGE = join(DIR, 'bridge.mjs');
19
26
  const PID_FILE = join(DIR, 'bridge.pid');
20
27
  const KICK_LOG = join(DIR, 'kick.log');
28
+ const STATE_FILE = join(DIR, 'state.json');
29
+ const STARTS_FILE = join(DIR, 'kick-starts.json');
30
+
31
+ /** How many dead starts, inside this window, mean "this release does not run". */
32
+ const CRASH_WINDOW_MS = 15 * 60 * 1000;
33
+ const CRASH_STARTS = 2;
21
34
 
22
35
  // Shared with setup.mjs: a restart holds this lock, so a tick that lands in the
23
36
  // middle of one must not start a second poller.
@@ -101,12 +114,86 @@ function bridgePids() {
101
114
  return (r.stdout || '').split(/\r?\n/).map((v) => Number(v.trim())).filter((v) => Number.isInteger(v) && v > 0);
102
115
  }
103
116
 
104
- function main() {
117
+ /** The starts this tick has issued, and when. */
118
+ function readStarts() {
119
+ try {
120
+ const raw = JSON.parse(readFileSync(STARTS_FILE, 'utf8'));
121
+ return Array.isArray(raw) ? raw.filter((v) => Number.isFinite(Number(v))) : [];
122
+ } catch {
123
+ return [];
124
+ }
125
+ }
126
+
127
+ function writeStarts(list) {
128
+ try {
129
+ writeFileSync(STARTS_FILE, JSON.stringify(list), 'utf8');
130
+ } catch {}
131
+ }
132
+
133
+ /**
134
+ * Did the last starts all end without the bridge ever becoming healthy?
135
+ *
136
+ * A start is "dead" when the pid it produced is gone and no bridge is running,
137
+ * which is exactly the situation this tick is in when it decides to start one.
138
+ * The count is reset by a healthy pid, so a laptop that reboots twice in an hour
139
+ * is not mistaken for a broken release.
140
+ */
141
+ function crashLoop(now = Date.now()) {
142
+ const recent = readStarts().filter((at) => now - Number(at) <= CRASH_WINDOW_MS);
143
+ writeStarts(recent);
144
+ return recent.length >= CRASH_STARTS;
145
+ }
146
+
147
+ function readState() {
148
+ try {
149
+ return JSON.parse(readFileSync(STATE_FILE, 'utf8').replace(/^\uFEFF/, ''));
150
+ } catch {
151
+ return {};
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Put the last proven release back when the version on disk cannot run.
157
+ *
158
+ * Loaded lazily and inside a try/catch: this tick must never be the reason a
159
+ * working bridge stays down, and `stability.mjs` imports the release module that
160
+ * shells out to npm. If the import fails, the tick starts the bridge as it is.
161
+ */
162
+ async function maybeRollback(evidence) {
163
+ let target = '';
164
+ try {
165
+ const { startupRollback, applyRollback } = await import('./stability.mjs');
166
+ const state = readState();
167
+ const { bridgeVersion } = await import('./control/release.mjs');
168
+ const installed = bridgeVersion();
169
+ target = startupRollback(state, installed, evidence);
170
+ if (!target) return '';
171
+ log(`release ${installed} has not proven itself (${evidence.crashLoop ? 'crash loop' : 'recorded faults'}): restoring ${target}`);
172
+ const result = await applyRollback(state, { version: target, lang: 'en', t: (_l, key) => key, log });
173
+ // The stamp the next tick reads. It is set even when the restore failed: a
174
+ // supervisor that retries a broken registry every sixty seconds is a log
175
+ // loop, not a recovery.
176
+ const release = state.release && typeof state.release === 'object' ? state.release : (state.release = {});
177
+ release.startupRolledBackAt = Date.now();
178
+ // The state file is the record the next tick reads: write it even when the
179
+ // restore failed, so a repeated failure is visible instead of retried blind.
180
+ try {
181
+ const { writeAtomic } = await import('./state.mjs');
182
+ writeAtomic(STATE_FILE, JSON.stringify(state, null, 2));
183
+ } catch {}
184
+ log(`rollback to ${target}: ${result.ok ? `ok via ${result.via}` : `failed (${(result.problems || []).join(' | ').slice(0, 200)})`}`);
185
+ return result.ok ? target : '';
186
+ } catch (error) {
187
+ log(`rollback skipped: ${String(error?.message ?? error).slice(0, 200)}`);
188
+ return '';
189
+ }
190
+ }
191
+
192
+ async function main() {
105
193
  if (!acquireLock('kick')) {
106
194
  log('restart in progress (setup holds the lock), skipping this tick');
107
195
  return 0;
108
- }
109
- if (!existsSync(BRIDGE)) {
196
+ } if (!existsSync(BRIDGE)) {
110
197
  log('bridge.mjs missing');
111
198
  return 2;
112
199
  }
@@ -120,6 +207,8 @@ function main() {
120
207
  // the minute tick costs one kill(0) instead of a PowerShell process scan.
121
208
  if (filePid && alive(filePid)) {
122
209
  if (restartPending) log(`marker present but pid ${filePid} alive`);
210
+ // A live bridge proves the release can start: forget the crash history.
211
+ writeStarts([]);
123
212
  return 0;
124
213
  }
125
214
  // Only when the pid file is stale or missing: scan for a bridge that started
@@ -130,6 +219,13 @@ function main() {
130
219
  return 0;
131
220
  }
132
221
 
222
+ const loop = crashLoop();
223
+ const restored = await maybeRollback({ crashLoop: loop });
224
+ if (restored) {
225
+ // The restored files are on disk; this start is the test of them, and the
226
+ // crash counter starts from zero so one bad release cannot fail twice.
227
+ writeStarts([]);
228
+ }
133
229
  log(restartPending ? 'marker present and no bridge: starting' : 'no bridge: starting');
134
230
  // spawn(), NOT spawnSync(): spawnSync waits for the child to exit, and this
135
231
  // child is meant to outlive the tick.
@@ -146,8 +242,12 @@ function main() {
146
242
  return 2;
147
243
  }
148
244
  child.unref();
245
+ if (!restored) writeStarts([...readStarts(), Date.now()]);
149
246
  log(`start issued pid=${child.pid ?? '?'}`);
150
247
  return 0;
151
248
  }
152
249
 
153
- process.exit(main());
250
+ main().then((code) => process.exit(code), (error) => {
251
+ log(`tick failed: ${String(error?.message ?? error).slice(0, 200)}`);
252
+ process.exit(2);
253
+ });
@@ -35,6 +35,7 @@ import { agentsOf, fleetOf, patchRows, skillsOf, AGENTS, PERSONA_HEADING, soulOf
35
35
  import { fmt, AGENTSETS, agentset, agentsetOf, profileRowOf, bindAgentset, agentsetCard, agentsetKeyboard } from './agentsets.mjs';
36
36
  import { taskKeyboard, goalView, taskView, filterLogLines } from './tasks.mjs';
37
37
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
38
+ import { applyRollback, releaseFacts } from '../stability.mjs';
38
39
  import { buildReport, tailOf, writeReport } from '../report.mjs';
39
40
  import { effectivePreset } from '../permission-rows.mjs';
40
41
 
@@ -45,7 +46,7 @@ import { effectivePreset } from '../permission-rows.mjs';
45
46
  * It lives in a function because `/update` without an argument now opens with
46
47
  * the same lines: "am I current?" used to be two commands and two messages.
47
48
  */
48
- function versionCard(lang) {
49
+ function versionCard(lang, state = {}) {
49
50
  const installed = bridgeVersion();
50
51
  const latest = npmLatest('dsh-tg-bridge');
51
52
  const where = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
@@ -54,6 +55,14 @@ function versionCard(lang) {
54
55
  lines.push(t(lang, 'ctrl.version.latest', { v: latest || t(lang, 'ctrl.version.offline') }));
55
56
  if (installed && latest && installed !== latest) lines.push(t(lang, 'ctrl.version.update', { v: latest }));
56
57
  lines.push(t(lang, 'ctrl.version.root', { path: where }));
58
+ // What this install has proved about the code it is running. A version that
59
+ // has answered a turn is the one an update may fall back to; one that has
60
+ // only ever thrown is named as such instead of looking equal to a good one.
61
+ const facts = releaseFacts(state, installed);
62
+ lines.push(t(lang, facts.verdict === 'proven' ? 'rel.proven' : facts.verdict === 'faulted' ? 'rel.faulted' : 'rel.unproven', {
63
+ n: facts.verdict === 'proven' ? facts.turns : facts.faults,
64
+ }));
65
+ if (facts.lastGood) lines.push(t(lang, 'rel.lastGood', { v: facts.lastGood }));
57
66
  lines.push(t(lang, 'ctrl.version.hint'));
58
67
  // The number above comes from package.json on disk; the code actually
59
68
  // answering this came from the files as they were at process start. When
@@ -305,7 +314,7 @@ export async function handleBridgeCommands(ctx) {
305
314
  // Kept as the body `/update` uses: the old spelling is rewritten to
306
315
  // `/update` before dispatch, so this only answers if something calls it
307
316
  // directly. One card, one source of the numbers.
308
- say(versionCard(lang));
317
+ say(versionCard(lang, state));
309
318
  return true;
310
319
  }
311
320
  case '/update': {
@@ -328,6 +337,21 @@ export async function handleBridgeCommands(ctx) {
328
337
  say(change.text);
329
338
  return true;
330
339
  }
340
+ if (sub === 'rollback') {
341
+ // The manual way back. It exists because the automatic one needs two
342
+ // faults before it acts: someone who has seen one is allowed to decide
343
+ // sooner than the rule does.
344
+ const facts = releaseFacts(state, installed);
345
+ if (!facts.lastGood) { say(t(lang, 'rel.manualNone')); return true; }
346
+ if (!facts.canRollBack) { say(t(lang, 'rel.manualCurrent', { v: facts.lastGood })); return true; }
347
+ const done = await applyRollback(state, {
348
+ version: facts.lastGood, lang, t, log, chatId, threadId,
349
+ send: (id, text, thread) => send(id, text, thread),
350
+ });
351
+ saveState();
352
+ if (done.ok) say(t(lang, 'rel.manualDone', { v: facts.lastGood }));
353
+ return true;
354
+ }
331
355
  if (sub === 'confirm') {
332
356
  if (!latest) {
333
357
  say(t(lang, 'ctrl.update.offline'));
@@ -352,6 +376,11 @@ export async function handleBridgeCommands(ctx) {
352
376
  say(t(lang, 'ctrl.update.broken', { v: latest }) + `\n\n${result.problems.slice(0, 6).join('\n')}`);
353
377
  return true;
354
378
  }
379
+ // The new files are on disk but the release is unproven until a turn
380
+ // answers on it. A version that is new and unproven must not keep the
381
+ // old proven one's record, or a rollback would return to nothing.
382
+ if (!state.release) state.release = {};
383
+ state.release.unproven = latest;
355
384
  // The files on disk are the new ones now; this process still runs the
356
385
  // old code, so the way back is one folder name.
357
386
  policy.notified = latest;
@@ -363,7 +392,7 @@ export async function handleBridgeCommands(ctx) {
363
392
  // This used to be two commands (`/version` for the numbers, `/update` for
364
393
  // the state), which meant "am I current?" took two messages. One card
365
394
  // answers both, and `/version` still arrives here rewritten.
366
- say(versionCard(lang) + '\n\n' + describeUpdate(updateState({ installed, latest, mode: policy.mode, notified: policy.notified })));
395
+ say(versionCard(lang, state) + '\n\n' + describeUpdate(updateState({ installed, latest, mode: policy.mode, notified: policy.notified })));
367
396
  return true;
368
397
  }
369
398
  case '/report': {
@@ -96,6 +96,40 @@ export function installRelease(version) {
96
96
  }
97
97
  }
98
98
 
99
+ /** The update backups this install keeps, newest first. */
100
+ export function updateBackups(root = bridgeRoot()) {
101
+ try {
102
+ return readdirSync(root)
103
+ .filter((name) => name.startsWith('update-backup-'))
104
+ .sort()
105
+ .reverse();
106
+ } catch {
107
+ return [];
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The newest saved copy of the files an update replaced.
113
+ *
114
+ * The offline way back: an install whose registry is unreachable can still be
115
+ * put back to the release it ran before the update, because `copyRelease` saved
116
+ * it. Restoring is only ever done after the candidate failed its own check, so
117
+ * the files being put back are the ones that were working.
118
+ */
119
+ export function newestUpdateBackup(root = bridgeRoot()) {
120
+ const [newest] = updateBackups(root);
121
+ return newest ? join(root, newest) : '';
122
+ }
123
+
124
+ /** Put the newest saved copy back over this install. Returns the directory used. */
125
+ export function restoreUpdateBackup(dir) {
126
+ if (!dir || !existsSync(dir)) throw new Error('no update backup to restore');
127
+ const root = bridgeRoot();
128
+ if (!safeUpdateRoot(root)) throw new Error(`refusing to write into ${root}`);
129
+ restoreBackup(root, dir);
130
+ return dir;
131
+ }
132
+
99
133
  /** Version of the bridge this process runs, read from its own package.json. */
100
134
  export function bridgeVersion() {
101
135
  const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
@@ -23,13 +23,14 @@ import { renderPrices } from './prices.mjs';
23
23
  import { settingsChipOf, turnPlan } from './profile-view.mjs';
24
24
  import { startProgress } from './progress.mjs';
25
25
  import { reportRefusals } from './sandbox-note.mjs';
26
+ import { noteTurn } from './stability.mjs';
26
27
  import { makeTurnEvents, newTelemetry } from './turn-events.mjs';
27
28
  import { lastPrompt, maxParallel, queues } from './queue.mjs';
28
29
  import { token } from './secrets.mjs';
29
30
  import { config, done, log, saveConfig, saveState, state } from './state.mjs';
30
31
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
31
32
  import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
32
- import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnStartedAt, typingLoop } from './turn.mjs';
33
+ import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnAttempt, turnStartedAt, typingLoop } from './turn.mjs';
33
34
  import { join } from 'node:path';
34
35
  import { existsSync } from 'node:fs';
35
36
 
@@ -377,6 +378,7 @@ ${t(lang, 'help.body')}`,
377
378
  log,
378
379
  onSession: (id) => liveSessions.set(key, id),
379
380
  });
381
+ const attempt = turnAttempt(text, key, { onEvent, onAbort: () => killTurn(key), env: thoughtEnv, profile: turnProfile || profileOf(key), cwd, lang });
380
382
  let result = await attempt(sessionAtStart);
381
383
  if (result.error && /unknown id|not found|не найдена|was recorded in/i.test(result.error) && sessionAtStart) {
382
384
  delete state.sessions[key];
@@ -458,26 +460,23 @@ ${t(lang, 'help.body')}`,
458
460
  return;
459
461
  }
460
462
  if (result.error) {
461
- // The status message already carries the failure (progress.finish turned it
462
- // into the error report), so only the log gets the detail here — a second
463
- // ⚠️ message would just duplicate it.
463
+ // The card already carries the failure, so only the log gets the detail — a
464
+ // second ⚠️ message would duplicate it. The release record decides whether a
465
+ // code fault means the version on disk cannot be trusted, and does the
466
+ // rollback itself: a turn that throws is the only evidence a static check
467
+ // cannot produce.
464
468
  log(`turn failed ${where} ${seconds}s ${summary} :: ${result.error.slice(0, 400)}`);
465
- // Keep the last failure for `/report`: the person who asks for a bug report
466
- // is usually the one who just saw this line, and asking them to reproduce it
467
- // before a report can be written is how a report never gets written.
468
- state.lastFailure = state.lastFailure || {};
469
- state.lastFailure[key] = {
470
- at: new Date().toISOString(),
471
- error: result.error.slice(0, 2000),
472
- model: telemetry.model,
473
- tools: telemetry.toolNames,
474
- cwd,
475
- seconds,
476
- };
469
+ await noteTurn(state, {
470
+ key, error: result.error, model: telemetry.model, tools: telemetry.toolNames, cwd, seconds,
471
+ lang, chatId, threadId, log, t, send,
472
+ });
477
473
  saveState();
478
474
  return;
479
475
  }
480
476
  log(`turn ok ${where} ${seconds}s session=${result.sessionId} ${summary}`);
477
+ // An answered turn proves this release works, and makes it the version a later
478
+ // rollback returns to.
479
+ await noteTurn(state, { saveState });
481
480
  // A turn that ends without an answer hands back its last assistant text —
482
481
  // the reasoning — and sending that looks exactly like the bot answering with
483
482
  // its own notes. Say what happened instead of forwarding the page.
@@ -0,0 +1,18 @@
1
+ // Release trust: which version this install has proved it can run.
2
+ //
3
+ // Kept out of `ctrl.mjs` because it is not about a command: it is what the card,
4
+ // the rollback notice and `/update` all say about the files on disk, and it has
5
+ // to agree with itself in three languages.
6
+ export default {
7
+ 'rel.proven': 'proven: {n} turns answered',
8
+ 'rel.unproven': 'not proven yet — no turn has run on it',
9
+ 'rel.faulted': 'failing: {n} code faults',
10
+ 'rel.lastGood': 'last proven: {v}',
11
+ 'rel.none': 'no proven version on record yet',
12
+ 'rel.rolledBack': 'Version {v} did not run: it threw a code fault, so I went back to {to}. The bridge restarts itself and continues on the proven release.',
13
+ 'rel.rolledBackBackup': 'Version {v} did not run: it threw a code fault. The registry was unreachable, so I restored {to} from the copy the last update saved.',
14
+ 'rel.rollbackFailed': 'Could not go back to {v}: {why}. The files are where they were — nothing was replaced by a guess.',
15
+ 'rel.manualCurrent': 'Already on the proven version {v}.',
16
+ 'rel.manualNone': 'No proven version on record yet: one turn has to answer on the current release first.',
17
+ 'rel.manualDone': 'Restored {v}. Send /restart confirm to load it.',
18
+ };
package/i18n/en.mjs CHANGED
@@ -7,5 +7,5 @@ import ctrl from './en/ctrl.mjs';
7
7
  import sandbox from './en/sandbox.mjs';
8
8
  import core from './en/core.mjs';
9
9
  import fallback from './en/fallback.mjs';
10
-
11
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback };
10
+ import release from './en/release.mjs';
11
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release };
@@ -0,0 +1,17 @@
1
+ // Доверие к версии: что этот экземпляр успел доказать про код, который крутит.
2
+ //
3
+ // Отдельно от `ctrl.mjs`, потому что это не про команду: так карточка, сообщение
4
+ // об откате и `/update` говорят об одном и том же, и в трёх языках одинаково.
5
+ export default {
6
+ 'rel.proven': 'проверена: {n} ход(ов) с ответом',
7
+ 'rel.unproven': 'ещё не проверена — ни один ход на ней не прошёл',
8
+ 'rel.faulted': 'сбоит: {n} кодовых ошибки',
9
+ 'rel.lastGood': 'последняя проверенная: {v}',
10
+ 'rel.none': 'проверенной версии пока нет',
11
+ 'rel.rolledBack': 'Версия {v} не заработала: код упал на первом же ходе, поэтому вернул {to}. Мост перезапустится сам и продолжит на проверенной версии.',
12
+ 'rel.rolledBackBackup': 'Версия {v} не заработала: код упал. Реестр недоступен, поэтому восстановил {to} из копии, которую сохранило прошлое обновление.',
13
+ 'rel.rollbackFailed': 'Вернуться на {v} не вышло: {why}. Файлы остались как были — ничего не заменено догадкой.',
14
+ 'rel.manualCurrent': 'Уже стоит проверенная версия {v}.',
15
+ 'rel.manualNone': 'Проверенной версии пока нет: сначала один ход должен ответить на текущей.',
16
+ 'rel.manualDone': 'Вернул {v}. Напиши /restart confirm, чтобы её загрузить.',
17
+ };
package/i18n/ru.mjs CHANGED
@@ -7,5 +7,5 @@ import ctrl from './ru/ctrl.mjs';
7
7
  import sandbox from './ru/sandbox.mjs';
8
8
  import core from './ru/core.mjs';
9
9
  import fallback from './ru/fallback.mjs';
10
-
11
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback };
10
+ import release from './ru/release.mjs';
11
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release };
@@ -0,0 +1,17 @@
1
+ // 版本可信度:这个安装已经证明它能跑的那份代码。
2
+ //
3
+ // 不放在 `ctrl.mjs` 里,因为它不是某条命令的事:卡片、回退通知和 `/update`
4
+ // 说的都是磁盘上的同一批文件,三种语言必须一致。
5
+ export default {
6
+ 'rel.proven': '已验证:{n} 次回合有回答',
7
+ 'rel.unproven': '尚未验证——还没在上面跑过回合',
8
+ 'rel.faulted': '有故障:{n} 次代码错误',
9
+ 'rel.lastGood': '上一个已验证版本:{v}',
10
+ 'rel.none': '还没有已验证的版本记录',
11
+ 'rel.rolledBack': '版本 {v} 跑不起来:代码在第一个回合就崩了,所以退回 {to}。桥接会自行重启,继续用已验证的版本。',
12
+ 'rel.rolledBackBackup': '版本 {v} 跑不起来:代码崩了。仓库连不上,所以用上次更新保存的副本恢复了 {to}。',
13
+ 'rel.rollbackFailed': '退不回 {v}:{why}。文件保持原样——没有用猜测替换任何东西。',
14
+ 'rel.manualCurrent': '当前已经是已验证版本 {v}。',
15
+ 'rel.manualNone': '还没有已验证的版本:先要让一个回合在当前版本上正常回答。',
16
+ 'rel.manualDone': '已恢复 {v}。发送 /restart confirm 加载它。',
17
+ };
package/i18n/zh.mjs CHANGED
@@ -7,5 +7,5 @@ import ctrl from './zh/ctrl.mjs';
7
7
  import sandbox from './zh/sandbox.mjs';
8
8
  import core from './zh/core.mjs';
9
9
  import fallback from './zh/fallback.mjs';
10
-
11
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback };
10
+ import release from './zh/release.mjs';
11
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release };
package/notes.mjs CHANGED
@@ -16,6 +16,30 @@
16
16
  // is not this turn's progress.
17
17
  import { readFileSync } from 'node:fs';
18
18
 
19
+ /**
20
+ * The longest a single note may be when it reaches the chat.
21
+ *
22
+ * Telegram allows 4096, so this is a readability budget, not an API limit — and
23
+ * a budget applied with `slice` alone is what made the decision trail look
24
+ * broken: the card showed "…при провале — от" and the chat showed "…откатывается
25
+ * на по" in the middle of a word, with nothing saying a cut had happened. A note
26
+ * that is too long is now cut at a word boundary and marked with an ellipsis, so
27
+ * the reader sees a shortened thought rather than a truncated one.
28
+ */
29
+ export const NOTE_MAX = 300;
30
+
31
+ /** Cut `text` at a word boundary at or under `max`, with an honest ellipsis. */
32
+ export function clipNote(text, max = NOTE_MAX) {
33
+ const value = String(text || '').trim();
34
+ if (value.length <= max) return value;
35
+ const head = value.slice(0, max - 1);
36
+ const space = head.search(/\s\S*$/);
37
+ // No space at all (one long token, or a script that does not break on spaces):
38
+ // a hard cut is the only option left, and the ellipsis still says it happened.
39
+ const cut = space > max * 0.5 ? head.slice(0, space) : head;
40
+ return `${cut.trimEnd()}…`;
41
+ }
42
+
19
43
  /** Every note in one file, as `{ at, text }`, oldest first. Missing file = []. */
20
44
  export function readNotes(file) {
21
45
  try {
@@ -26,7 +50,7 @@ export function readNotes(file) {
26
50
  try {
27
51
  const row = JSON.parse(line);
28
52
  const text = String(row.text || '').trim();
29
- return text ? { at: Number(row.at) || 0, text: text.slice(0, 140) } : null;
53
+ return text ? { at: Number(row.at) || 0, text: clipNote(text) } : null;
30
54
  } catch { return null; }
31
55
  })
32
56
  .filter(Boolean);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.30.0",
3
+ "version": "1.30.1",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -61,6 +61,7 @@
61
61
  "context-meter.mjs",
62
62
  "install-check.mjs",
63
63
  "sandbox-note.mjs",
64
+ "stability.mjs",
64
65
  "turn-events.mjs",
65
66
  "cost.mjs",
66
67
  "price-cache.mjs",
package/stability.mjs ADDED
@@ -0,0 +1,341 @@
1
+ // Which release this install may trust, and what to do when it turns out it
2
+ // cannot.
3
+ //
4
+ // 1.30.0 shipped with a call to a function that did not exist. Nothing caught it
5
+ // before the restart: the file parsed, every import resolved, 588 tests passed.
6
+ // It failed on the first real message, and the person was left on a version that
7
+ // answered nothing — the exact outcome an update is supposed to rule out.
8
+ //
9
+ // A static check cannot see a name that is never defined inside a function body.
10
+ // The only honest test is a turn that runs, so this module keeps the result of
11
+ // that test per version:
12
+ //
13
+ // proven this version answered a real turn — the code that matters works
14
+ // faulted it threw a code fault (a name that is not defined, a module that
15
+ // does not export what it promises) and not a provider or network
16
+ // error, which says nothing about the release
17
+ // unknown installed, never ran
18
+ //
19
+ // Two faults on a version that has never answered, while a proven version is
20
+ // still on record, is the condition for going back. One is a fluke; two is the
21
+ // release. And a provider error is never counted: rolling back because a balance
22
+ // ran out would move a working install for a reason that has nothing to do with
23
+ // the code.
24
+ import { writeFileSync } from 'node:fs';
25
+ import { bridgeVersion, installRelease, newestUpdateBackup, restoreUpdateBackup } from './control/release.mjs';
26
+ import { RESTART_MARKER } from './paths.mjs';
27
+
28
+ /** Faults needed before a never-proven version is considered broken. */
29
+ export const FAULT_LIMIT = 2;
30
+
31
+ /**
32
+ * How long after a rollback a second one is refused.
33
+ *
34
+ * The files on disk go back to the proven release, but the process that is
35
+ * running them is still the broken one until it exits — and it can serve several
36
+ * more messages before the queue drains. Without a cooldown each of those would
37
+ * fetch, restore and announce the same rollback again.
38
+ */
39
+ export const ROLLBACK_COOLDOWN_MS = 10 * 60 * 1000;
40
+
41
+ /**
42
+ * Errors that are the release's fault, not the world's.
43
+ *
44
+ * Each of these means the code that shipped is wrong: a name it never defined, a
45
+ * module that does not export what it imports, a file that does not parse. The
46
+ * list is deliberately narrow — a 402, a 429, a timeout and "all providers are
47
+ * busy" all reach a turn as errors too, and none of them is a verdict on 1.30.0.
48
+ */
49
+ const CODE_FAULT = new RegExp([
50
+ 'is not defined',
51
+ 'is not a function',
52
+ 'is not a constructor',
53
+ 'is not iterable',
54
+ 'Cannot read propert',
55
+ 'Cannot find module',
56
+ 'does not provide an export',
57
+ 'ERR_MODULE_NOT_FOUND',
58
+ 'ERR_UNSUPPORTED_DIR_IMPORT',
59
+ 'ERR_INVALID_MODULE_SPECIFIER',
60
+ 'SyntaxError',
61
+ 'Unexpected token',
62
+ 'Unexpected end of input',
63
+ ].join('|'), 'i');
64
+
65
+ /** True when this error text blames the code that is running. */
66
+ export function isCodeFault(text) {
67
+ return CODE_FAULT.test(String(text || ''));
68
+ }
69
+
70
+ /**
71
+ * The release record, created on first use.
72
+ *
73
+ * `state.release` is one install-wide object: a version is proven or broken for
74
+ * the machine, not for a topic, and two topics must not disagree about whether
75
+ * the same files work.
76
+ */
77
+ export function releasesOf(state) {
78
+ if (!state.release || typeof state.release !== 'object') state.release = {};
79
+ const release = state.release;
80
+ if (!release.proven || typeof release.proven !== 'object') release.proven = {};
81
+ if (!release.faults || typeof release.faults !== 'object') release.faults = {};
82
+ if (typeof release.lastGood !== 'string') release.lastGood = '';
83
+ return release;
84
+ }
85
+
86
+ /** What is known about one version: `proven`, `faulted` or `unknown`. */
87
+ export function verdictOf(state, version) {
88
+ if (!version) return 'unknown';
89
+ const release = releasesOf(state);
90
+ if (release.proven[version]) return 'proven';
91
+ if (Number(release.faults[version]) > 0) return 'faulted';
92
+ return 'unknown';
93
+ }
94
+
95
+ /**
96
+ * Record how a finished turn reflects on the running release.
97
+ *
98
+ * Called once per turn, from the two places a turn can end. Returns what the
99
+ * caller should do about it: `rollback` is the version to go back to, or ''.
100
+ *
101
+ * @param {object} state the install's state object (mutated)
102
+ * @param {{version?: string, error?: string, at?: number}} turn
103
+ * @returns {{verdict: 'proven'|'fault'|'neutral', faults: number, rollback: string, from: string}}
104
+ */
105
+ export function noteOutcome(state, turn = {}) {
106
+ const release = releasesOf(state);
107
+ const version = turn.version || bridgeVersion();
108
+ const at = Number(turn.at) || Date.now();
109
+ const from = version;
110
+ if (!version) return { verdict: 'neutral', faults: 0, rollback: '', from };
111
+
112
+ if (!turn.error) {
113
+ // An answered turn is the proof a static check cannot give.
114
+ const before = release.proven[version];
115
+ release.proven[version] = { at, turns: (Number(before?.turns) || 0) + 1 };
116
+ release.lastGood = version;
117
+ // A version that recovered is not faulted any more: one bad turn after a
118
+ // provider hiccup must not leave a permanent mark on a release that works.
119
+ delete release.faults[version];
120
+ return { verdict: 'proven', faults: 0, rollback: '', from };
121
+ }
122
+ if (!isCodeFault(turn.error)) return { verdict: 'neutral', faults: Number(release.faults[version]) || 0, rollback: '', from };
123
+
124
+ const faults = (Number(release.faults[version]) || 0) + 1;
125
+ release.faults[version] = faults;
126
+ release.faultedAt = at;
127
+ release.faultedVersion = version;
128
+ // Never proven, and the previous release is still on record: the install has
129
+ // somewhere better to be. A rollback that just happened is not repeated for a
130
+ // turn that started before it.
131
+ const candidate = release.lastGood && release.lastGood !== version ? release.lastGood : '';
132
+ const cooling = Number(release.rolledBackAt) > 0 && at - Number(release.rolledBackAt) < ROLLBACK_COOLDOWN_MS;
133
+ const rollback = faults >= FAULT_LIMIT && !release.proven[version] && candidate && !cooling ? candidate : '';
134
+ // Remembered here, not only in applyRollback: the process running the broken
135
+ // code keeps serving turns until it exits, and each would ask again.
136
+ if (rollback) release.rolledBackAt = at;
137
+ return { verdict: 'fault', faults, rollback, from };
138
+ }
139
+
140
+ /**
141
+ * Should a start be abandoned in favour of the last proven release?
142
+ *
143
+ * The turn path cannot answer this one: a release that throws while it loads
144
+ * never runs a turn, so nothing is recorded and `noteOutcome` never fires. The
145
+ * supervisor tick is the only thing watching that case, and it needs the same
146
+ * rule rather than a second copy of it — which is why the decision lives here,
147
+ * as a pure function over the state it can read.
148
+ *
149
+ * `crashLoop` is the tick's own evidence: several starts in a row, each followed
150
+ * by a dead process. It counts the same way one recorded fault does, because
151
+ * from the outside "it died three times without answering" and "it threw twice"
152
+ * are the same fact — this install is not working.
153
+ *
154
+ * @param {object} state
155
+ * @param {string} installed version on disk
156
+ * @param {{crashLoop?: boolean, at?: number}} [evidence]
157
+ * @returns {string} the version to go back to, or '' to start as it is
158
+ */
159
+ export function startupRollback(state, installed, evidence = {}) {
160
+ const release = releasesOf(state);
161
+ const at = Number(evidence.at) || Date.now();
162
+ if (!installed || !release.lastGood) return '';
163
+ // The version already on record as good is not a rollback target.
164
+ if (release.lastGood === installed) return '';
165
+ // A version that answered once works; a bad start later is not the release.
166
+ if (release.proven[installed]) return '';
167
+ // The supervisor keeps its own stamp, separate from the turn path's: the two
168
+ // run on different clocks, and a tick that just restored the files must not do
169
+ // it again a minute later while the start it triggered is still failing.
170
+ if (Number(release.startupRolledBackAt) > 0 && at - Number(release.startupRolledBackAt) < ROLLBACK_COOLDOWN_MS) return '';
171
+ const faults = Number(release.faults[installed]) || 0;
172
+ if (faults >= FAULT_LIMIT || evidence.crashLoop) return release.lastGood;
173
+ return '';
174
+ }
175
+
176
+ /**
177
+ * Keep the last failure for `/report`, and the reason a rollback happened.
178
+ *
179
+ * Moved out of `handle-message.mjs` when the release record needed the same
180
+ * information: the person who asks for a bug report is usually the one who just
181
+ * saw the failure, and asking them to reproduce it first is how a report never
182
+ * gets written.
183
+ */
184
+ export function recordFailure(state, key, info = {}) {
185
+ if (!state.lastFailure || typeof state.lastFailure !== 'object') state.lastFailure = {};
186
+ state.lastFailure[key] = {
187
+ at: new Date().toISOString(),
188
+ error: String(info.error || '').slice(0, 2000),
189
+ model: info.model || '',
190
+ tools: Array.isArray(info.tools) ? info.tools : [],
191
+ cwd: info.cwd || '',
192
+ seconds: Number(info.seconds) || 0,
193
+ version: info.version || '',
194
+ };
195
+ return state.lastFailure[key];
196
+ }
197
+
198
+ /**
199
+ * Go back to a proven release: fetch it from npm, or restore the newest copy the
200
+ * last update saved when the registry is not reachable.
201
+ *
202
+ * Returns what happened, in facts the caller turns into one sentence — never a
203
+ * promise that the rollback worked before it did.
204
+ *
205
+ * @param {string} version
206
+ * @param {{install?: Function, backup?: Function}} [deps] for tests
207
+ * @returns {{ok: boolean, version: string, via: 'npm'|'backup'|'', problems: string[]}}
208
+ */
209
+ export function rollbackRelease(version, deps = {}) {
210
+ if (!version) return { ok: false, version: '', via: '', problems: ['no version to go back to'] };
211
+ const install = deps.install || installRelease;
212
+ const problems = [];
213
+ try {
214
+ const result = install(version);
215
+ if (result?.rolledBack) {
216
+ // The release we were going back to would not load either: keep the files
217
+ // where they are and say why, instead of stacking one broken install on
218
+ // another.
219
+ return { ok: false, version, via: 'npm', problems: result.problems || [] };
220
+ }
221
+ return { ok: true, version, via: 'npm', problems: [] };
222
+ } catch (error) {
223
+ problems.push(String(error?.message ?? error).slice(0, 200));
224
+ }
225
+ const backup = deps.backup || newestUpdateBackup;
226
+ const restore = deps.restore || restoreUpdateBackup;
227
+ const dir = backup();
228
+ if (!dir) return { ok: false, version, via: '', problems };
229
+ try {
230
+ restore(dir);
231
+ return { ok: true, version, via: 'backup', problems };
232
+ } catch (error) {
233
+ problems.push(String(error?.message ?? error).slice(0, 200));
234
+ return { ok: false, version, via: 'backup', problems };
235
+ }
236
+ }
237
+
238
+ /**
239
+ * One line of fact about a version, for `/update` and for the rollback notice.
240
+ *
241
+ * Data, not prose: the words live in the three locale tables, and a module that
242
+ * builds sentences is a module that has to be edited three times for one change.
243
+ */
244
+ export function releaseFacts(state, installed = '') {
245
+ const release = releasesOf(state);
246
+ const version = installed || bridgeVersion();
247
+ return {
248
+ version,
249
+ verdict: verdictOf(state, version),
250
+ turns: Number(release.proven[version]?.turns) || 0,
251
+ provenAt: Number(release.proven[version]?.at) || 0,
252
+ faults: Number(release.faults[version]) || 0,
253
+ lastGood: release.lastGood || '',
254
+ canRollBack: Boolean(release.lastGood && release.lastGood !== version),
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Everything a finished turn says about the release it ran on.
260
+ *
261
+ * One call per turn, from the two places a turn can end, so the two branches can
262
+ * never disagree about what "this version works" means. Returns the verdict; a
263
+ * rollback, when it happens, has already been announced in the chat and the
264
+ * restart marker has been written, so the caller only has to save the state.
265
+ *
266
+ * Never throws: the record of a release is not worth losing the answer that is
267
+ * about to be sent.
268
+ */
269
+ export async function noteTurn(state, info = {}) {
270
+ const { key = '', error = '', model = '', tools = [], cwd = '', seconds = 0, saveState } = info;
271
+ // Read once per turn: an update may have replaced the files, and a version
272
+ // that is on disk but not yet loaded must not be credited with this turn.
273
+ const version = info.version || bridgeVersion();
274
+ let outcome = { verdict: 'neutral', faults: 0, rollback: '', from: version };
275
+ try {
276
+ if (error) recordFailure(state, key, { error, model, tools, cwd, seconds, version });
277
+ outcome = noteOutcome(state, { version, error, at: Number(info.at) || Date.now() });
278
+ if (outcome.rollback) await applyRollback(state, { ...info, version: outcome.rollback });
279
+ } catch (failure) {
280
+ if (typeof info.log === 'function') info.log(`release record skipped: ${String(failure?.message ?? failure).slice(0, 200)}`);
281
+ return outcome;
282
+ }
283
+ // Saving is a separate failure mode: a full disk must not lose the verdict, and
284
+ // must not fail the turn either.
285
+ try {
286
+ if (typeof saveState === 'function') saveState();
287
+ } catch (failure) {
288
+ if (typeof info.log === 'function') info.log(`release state not saved: ${String(failure?.message ?? failure).slice(0, 200)}`);
289
+ }
290
+ return outcome;
291
+ }
292
+
293
+ /**
294
+ * Go back to the last proven release and let the supervisor load it.
295
+ *
296
+ * The files are restored on disk, and `restart.pending` is written instead of
297
+ * calling `process.exit`: the bridge exits when its queue is empty, so the turn
298
+ * that discovered the fault still finishes and answers. Nothing is killed
299
+ * mid-sentence, and the person gets a message about it either way.
300
+ *
301
+ * @param {object} state
302
+ * @param {object} deps everything that touches the outside world
303
+ * @returns {Promise<{ok: boolean, to: string, via: string, text: string}>}
304
+ */
305
+ export async function applyRollback(state, deps = {}) {
306
+ const { version = '', lang = 'en', t = (_, key) => key, log = () => {}, chatId = 0, threadId = 0, at = Date.now() } = deps;
307
+ const send = deps.send || (async () => {});
308
+ const release = releasesOf(state);
309
+ const target = version || release.lastGood;
310
+ if (!target) return { ok: false, to: '', via: '', text: '' };
311
+ const result = rollbackRelease(target, deps);
312
+ // Only a rollback that happened starts the cooldown: one that failed (registry
313
+ // down, no backup) is worth retrying on the next turn.
314
+ if (result.ok) release.rolledBackAt = at;
315
+ release.history = [
316
+ ...(Array.isArray(release.history) ? release.history : []),
317
+ { from: release.faultedVersion || '', to: target, at, via: result.via, ok: result.ok },
318
+ ].slice(-5);
319
+ const text = result.ok
320
+ ? t(lang, result.via === 'backup' ? 'rel.rolledBackBackup' : 'rel.rolledBack', { v: release.faultedVersion || '?', to: target })
321
+ : t(lang, 'rel.rollbackFailed', { v: target, why: (result.problems[0] || '').slice(0, 200) });
322
+ if (result.ok) {
323
+ // Ask for the restart, do not perform it: the supervisor starts the restored
324
+ // files only once nothing is in flight, which is what keeps this turn's
325
+ // answer from being the last thing the person ever sees.
326
+ try {
327
+ writeFileSync(RESTART_MARKER, JSON.stringify({ at, from: release.faultedVersion || '', to: target }), 'utf8');
328
+ } catch (error) {
329
+ log(`rollback restart marker not written: ${String(error?.message ?? error).slice(0, 120)}`);
330
+ }
331
+ }
332
+ log(`rollback ${result.ok ? 'done' : 'failed'} to ${target} via ${result.via || 'nothing'}${result.problems.length ? ` :: ${result.problems.join(' | ').slice(0, 300)}` : ''}`);
333
+ if (chatId) {
334
+ try {
335
+ await send(chatId, text, threadId);
336
+ } catch (error) {
337
+ log(`rollback notice not sent: ${String(error?.message ?? error).slice(0, 120)}`);
338
+ }
339
+ }
340
+ return { ok: result.ok, to: target, via: result.via, text, problems: result.problems };
341
+ }
package/turn.mjs CHANGED
@@ -160,6 +160,18 @@ export async function typingLoop(chatId, threadId, stopFlag) {
160
160
  * Returns {sessionId, text, error}: the error carrying "no activity" when the
161
161
  * idle window expires.
162
162
  */
163
+ /**
164
+ * Bind one turn's options to a function of the session id.
165
+ *
166
+ * The retry paths in `handle-message.mjs` need the same turn with another
167
+ * session — a session recorded in a different directory, or one whose write
168
+ * handle was held. Building those options twice is how `attempt` went missing
169
+ * in 1.30.0 and every turn failed with "attempt is not defined".
170
+ */
171
+ export function turnAttempt(task, key, options) {
172
+ return (sessionId) => runTurnLive(task, sessionId, key, options);
173
+ }
174
+
163
175
  export function runTurnLive(task, sessionId, key, options = {}) {
164
176
  const idleMs = Number(options.idleMs ?? config.turnIdleMs ?? 300000);
165
177
  // A tool can legitimately run for many minutes (install, build, test suite)