dsh-tg-bridge 1.43.1 → 1.45.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.
package/bridge-kick.mjs CHANGED
@@ -16,7 +16,7 @@
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
22
 
@@ -43,6 +43,8 @@ const CRASH_STARTS = 2;
43
43
  // LOCK_MAX_AGE_MS here so even a genuinely wedged holder cannot wedge the guard.
44
44
  const LOCK = join(DIR, 'restart.lock');
45
45
  const LOCK_MAX_AGE_MS = 180_000;
46
+ // A restart marker older than this is a leftover, not a restart in progress.
47
+ const MARKER_MAX_AGE_MS = 600_000;
46
48
 
47
49
  function acquireLock(owner) {
48
50
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -88,6 +90,32 @@ function log(line) {
88
90
  } catch {}
89
91
  }
90
92
 
93
+ /**
94
+ * Forget a restart marker that outlived its restart.
95
+ *
96
+ * The bridge reads the marker on start to tell other topics their turn was cut,
97
+ * then clears it. If it is still there with a live bridge, the process that
98
+ * should have cleared it did not run — and every later start would read this
99
+ * stale marker as "the previous process died mid-turn". Ten minutes is well past
100
+ * any start, so the marker is a leftover, not news.
101
+ */
102
+ function clearStaleMarker(marker) {
103
+ let age = Number.POSITIVE_INFINITY;
104
+ try {
105
+ age = Date.now() - statSync(marker).mtimeMs;
106
+ } catch {}
107
+ if (age < MARKER_MAX_AGE_MS) {
108
+ log('marker present and bridge alive, restart still in progress');
109
+ return;
110
+ }
111
+ try {
112
+ unlinkSync(marker);
113
+ log(`cleared stale restart marker (${Math.round(age / 1000)}s old, bridge alive)`);
114
+ } catch (error) {
115
+ log(`could not clear the restart marker: ${String(error?.message ?? error).slice(0, 120)}`);
116
+ }
117
+ }
118
+
91
119
  function pidFromFile() {
92
120
  try {
93
121
  const pid = Number(readFileSync(PID_FILE, 'utf8').trim());
@@ -193,7 +221,8 @@ async function main() {
193
221
  if (!acquireLock('kick')) {
194
222
  log('restart in progress (setup holds the lock), skipping this tick');
195
223
  return 0;
196
- } if (!existsSync(BRIDGE)) {
224
+ }
225
+ if (!existsSync(BRIDGE)) {
197
226
  log('bridge.mjs missing');
198
227
  return 2;
199
228
  }
@@ -206,7 +235,7 @@ async function main() {
206
235
  // Cheap path first: a live pid file is authoritative for a healthy bridge, so
207
236
  // the minute tick costs one kill(0) instead of a PowerShell process scan.
208
237
  if (filePid && alive(filePid)) {
209
- if (restartPending) log(`marker present but pid ${filePid} alive`);
238
+ if (restartPending) clearStaleMarker(marker);
210
239
  // A live bridge proves the release can start: forget the crash history.
211
240
  writeStarts([]);
212
241
  return 0;
package/bridge.mjs CHANGED
@@ -111,7 +111,12 @@ process.on('uncaughtException', (error) => {
111
111
  process.exit(1);
112
112
  });
113
113
  process.on('unhandledRejection', (reason) => {
114
+ // Logging alone left the process running in a state nobody had designed: the
115
+ // turn that rejected is gone, the loop keeps polling, and the next /doctor
116
+ // shows a healthy bridge. Exit instead — the minute tick starts a clean one,
117
+ // and the interruption notice tells the topics what happened.
114
118
  log(`FATAL unhandled rejection: ${reason && reason.stack ? reason.stack : reason}`);
119
+ process.exit(1);
115
120
  });
116
121
  process.on('exit', (code) => {
117
122
  log(`bridge exiting code=${code}`);
@@ -18,7 +18,8 @@ import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/mod
18
18
  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
- import { handleFilePress } from './file-press.mjs';
21
+ import { handleFilePress } from './file-press.mjs';
22
+ import { handleEditPress } from './edit-press.mjs';
22
23
  import { handleTourPress } from './tour-press.mjs';
23
24
  import { config, done, log, saveState, state } from '../core/state.mjs';
24
25
  import { inlineKeyboard, send, sendFile, tg, tgFast } from './telegram.mjs';
@@ -346,10 +347,12 @@ export async function handleCallback(query) {
346
347
  if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
347
348
  }
348
349
 
349
- if (await handleTourPress({ data, lang, chatId, threadId, messageId, answer })) return;
350
-
351
- if (await handleFilePress({ data, key, lang, chatId, threadId, messageId, answer })) return;
352
-
350
+ if (await handleTourPress({ data, lang, chatId, threadId, messageId, answer })) return;
351
+
352
+ if (await handleEditPress({ data, key, lang, chatId, threadId, messageId, answer })) return;
353
+
354
+ if (await handleFilePress({ data, key, lang, chatId, threadId, messageId, answer })) return;
355
+
353
356
  if (data.startsWith('tc:')) {
354
357
  // The turn card's own switches. Redrawn from state like the task card, so a
355
358
  // double tap settles on one truth; an id this build does not know answers
@@ -13,7 +13,7 @@ export const CONTROL_COMMANDS = [
13
13
  'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
14
14
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
15
  'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
16
- 'ls', 'view',
16
+ 'ls', 'view', 'edit',
17
17
  ];
18
18
 
19
19
  /**
package/chat/control.mjs CHANGED
@@ -42,6 +42,7 @@ import { handleViewCommands } from '../control/cmd-views.mjs';
42
42
  import { handleEndpointCommands } from '../control/cmd-endpoint.mjs';
43
43
  import { handleEveryCommands } from '../control/cmd-every.mjs';
44
44
  import { handleFileCommands } from '../control/cmd-files.mjs';
45
+ import { handleEditCommands } from '../control/cmd-edit.mjs';
45
46
  import { handleFindCommands } from '../control/cmd-find.mjs';
46
47
  import { handleDshCommands } from '../control/cmd-dsh.mjs';
47
48
  import { handleCompactCommands } from '../control/cmd-compact.mjs';
@@ -116,7 +117,7 @@ export async function handleControl(ctx) {
116
117
  // that is not its job. The order is alphabetical, not meaningful: no two
117
118
  // groups claim the same command, so a miss falls through to `default` below.
118
119
  const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
119
- for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleFileCommands, handleFindCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleStartCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
120
+ for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEditCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleFileCommands, handleFindCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleStartCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
120
121
  if (await handler(child)) return true;
121
122
  }
122
123
  // Nothing claimed it: the bridge answers an unknown `/` command itself, with
@@ -0,0 +1,35 @@
1
+ // A press on the `/edit` diff card: apply or cancel.
2
+ //
3
+ // The card is redrawn into the outcome, so the chat keeps one record of what
4
+ // happened to those lines instead of a dead card with two live-looking buttons.
5
+ // The press re-reads the file — see `applyEdit` — because a button carries a
6
+ // decision, not a copy of the file.
7
+ import { applyEdit, cancelEdit } from '../control/cmd-edit.mjs';
8
+ import { inlineKeyboard, tg } from './telegram.mjs';
9
+ import { t } from '../core/i18n.mjs';
10
+
11
+ /**
12
+ * Handle one `ed:` press.
13
+ *
14
+ * @returns {Promise<boolean>} true when the press was this module's to answer.
15
+ */
16
+ export async function handleEditPress({ data, key, lang, chatId, threadId, messageId, answer }) {
17
+ if (!String(data || '').startsWith('ed:')) return false;
18
+ const what = String(data).slice(3);
19
+ // The outcome replaces the diff: the buttons are gone, so a second press has
20
+ // nothing to hit, and the transcript shows the result where the question was.
21
+ const settle = async (text) => {
22
+ await tg('editMessageText', {
23
+ chat_id: chatId,
24
+ message_id: messageId,
25
+ text,
26
+ reply_markup: { inline_keyboard: inlineKeyboard([]) },
27
+ }).catch(() => {});
28
+ await answer(text.split('\n')[0].slice(0, 180));
29
+ };
30
+ const ctx = { key, lang, chatId, threadId, answer, settle, reply: settle };
31
+ if (what === 'a') return applyEdit(ctx);
32
+ if (what === 'c') return cancelEdit(ctx);
33
+ await answer(t(lang, 'ctrl.edit.stale'));
34
+ return true;
35
+ }
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { commandParts, GENERAL_SAFE } from './commands.mjs';
9
9
  import { CONTROL_COMMANDS, handleControl, modelOf } from './control.mjs';
10
+ import { takeEditText } from '../control/cmd-edit.mjs';
10
11
  import { reasoningMode } from './notes.mjs';
11
12
  import { explainFailure } from '../turn/failures.mjs';
12
13
  import { runFallbackChain } from '../model/fallback.mjs';
@@ -193,6 +194,11 @@ export async function handleMessage(msg, album = null) {
193
194
  return;
194
195
  }
195
196
 
197
+ // An edit waiting for its replacement owns the next message: it is the new
198
+ // text for those lines, not a task. Before the unknown-command answer, so a
199
+ // replacement starting with `/` still reaches the file. Seam: `edit-press`.
200
+ if (!effective && await takeEditText({ text, key, lang, state, saveState, reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra) })) return;
201
+
196
202
  // An unknown slash command must never become an AI turn: it burns money and
197
203
  // answers something the person did not ask. Answer with the menu instead.
198
204
  if (command && !effective) {
@@ -10,7 +10,7 @@ import { t } from '../core/i18n.mjs';
10
10
  /** The /help group each command is listed under. */
11
11
  const SECTION = {
12
12
  start: 'Other', cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work', diff: 'Work', find: 'Work',
13
- ls: 'Work', view: 'Work',
13
+ ls: 'Work', view: 'Work', edit: 'Work',
14
14
  goal: 'Goals', task: 'Goals', tasks: 'Goals',
15
15
  status: 'Sessions', sessions: 'Sessions', rewind: 'Sessions', profile: 'Sessions',
16
16
  agents: 'Agents', model: 'Models', prices: 'Models', cost: 'Models', thoughts: 'Models', fallback: 'Models', endpoint: 'Models',
@@ -15,7 +15,7 @@ import { CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './commands-registry.mjs';
15
15
  * a panel that hides half the bot sends people back to typing.
16
16
  */
17
17
  const SECTIONS = {
18
- work: ['cd', 'ls', 'view', 'seed', 'send', 'diff'],
18
+ work: ['cd', 'ls', 'view', 'edit', 'seed', 'send', 'diff'],
19
19
  session: ['sessions', 'rewind', 'profile', 'agents'],
20
20
  goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
21
  talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'lang', 'endpoint', 'fallback'],
@@ -15,6 +15,7 @@ import { setRowConfig, unsetRowConfig } from '../profile/profile-edit.mjs';
15
15
  import { parseReminder, stampAt, upcoming } from '../work/reminders.mjs';
16
16
  import { AgentsetStore, emptySet, slugId } from '../profile/agentsets.mjs';
17
17
  import { SETTINGS_PAGES, renderSettingsCard, settingsCurrent } from '../profile/settings-card.mjs';
18
+ import { supervisionRows } from './doctor-rows.mjs';
18
19
  import { applyFork, planFork, planRewind } from '../work/rewind.mjs';
19
20
  import { cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
20
21
  import { renderRewindCard, renderRewindUsage } from '../work/rewind-card.mjs';
@@ -246,6 +247,10 @@ export async function handleBridgeCommands(ctx) {
246
247
  add(t(lang, 'ctrl.doctor.logLines'), String(lines.length - start));
247
248
  } catch {}
248
249
 
250
+ // Is anything still watching? A dead supervisor looks exactly like an idle
251
+ // bot until the next crash, which then becomes permanent.
252
+ rows.push(...supervisionRows(lang, DSH_HOME));
253
+
249
254
  // Disk space: the silent killer of model downloads and OCR. This used to
250
255
  // shell out to `powershell (Get-PSDrive C)`, so on macOS and Linux the row
251
256
  // simply vanished — a diagnostic that is silent on the platform you are
@@ -0,0 +1,198 @@
1
+ // `/edit`: change lines in a file from the chat, with a diff and a button.
2
+ //
3
+ // Three steps, each one visible, because a write is the one thing here that
4
+ // cannot be taken back by reading the chat:
5
+ //
6
+ // 1. `/edit app.mjs:12-14` reads those lines and asks for the replacement.
7
+ // 2. The next plain message in that topic is the replacement text.
8
+ // 3. A diff appears with «Применить» and «Отмена». Nothing on disk changes
9
+ // until the first is pressed — and when it is, the lines are re-read and
10
+ // compared with what the diff showed, so an edit made by the agent between
11
+ // the two messages answers "the file moved" instead of overwriting work.
12
+ //
13
+ // A dash (`-`) as the replacement text deletes the lines. That is the only way
14
+ // to say "nothing" in a chat that never sends an empty message.
15
+ import { readTextFile, resolveInRoot, writeTextFile } from '../lib/file-fence.mjs';
16
+ import { t } from '../core/i18n.mjs';
17
+ import { saveState as saveStateNow, state as liveState } from '../core/state.mjs';
18
+ import { ownRoot } from './cmd-files.mjs';
19
+
20
+ /** How many context lines the diff shows around the changed block. */
21
+ export const CONTEXT = 3;
22
+
23
+ /** `/edit app.mjs`, `app.mjs:12`, `app.mjs:12-14`, `app.mjs 12-14`. */
24
+ export function parseTarget(arg) {
25
+ const raw = String(arg || '').trim();
26
+ if (!raw) return { error: 'usage' };
27
+ const m = /^(.*?)(?::(\d+)(?:\s*-\s*(\d+))?|\s+(\d+)(?:\s*-\s*(\d+))?)$/.exec(raw);
28
+ if (!m) return { file: raw, error: 'lines' };
29
+ const file = m[1].trim();
30
+ if (!file) return { error: 'usage' };
31
+ const from = Number(m[2] || m[4]);
32
+ const to = Number(m[3] || m[5] || from);
33
+ if (!from || to < from) return { file, error: 'range' };
34
+ return { file, from, to };
35
+ }
36
+
37
+ /**
38
+ * Split a file into editable lines, keeping the trailing-newline fact.
39
+ *
40
+ * `"a\nb\n"` is two lines, not three: the last empty element is the newline
41
+ * itself, and counting it made `the file has 3 lines` for a two-line file.
42
+ */
43
+ export function splitLines(text) {
44
+ const norm = String(text).replace(/\r\n/g, '\n');
45
+ const trailing = norm.endsWith('\n');
46
+ const lines = (trailing ? norm.slice(0, -1) : norm).split('\n');
47
+ return { lines, trailing };
48
+ }
49
+
50
+ /** The numbered block the person asked to edit, as one message. */
51
+ function blockCard(rel, from, lines, lang) {
52
+ const rows = lines.map((line, n) => `${String(from + n).padStart(4)} ${line}`);
53
+ return [
54
+ t(lang, 'ctrl.edit.head', { path: rel, from, to: from + lines.length - 1 }),
55
+ '```',
56
+ ...rows,
57
+ '```',
58
+ '',
59
+ t(lang, 'ctrl.edit.ask'),
60
+ ].join('\n');
61
+ }
62
+
63
+ /** The diff, as a card: what the lines were, what they become. */
64
+ export function diffCard(rel, from, before, after, lang) {
65
+ const rows = [
66
+ ...before.map((line) => `- ${line}`),
67
+ ...after.map((line) => `+ ${line}`),
68
+ ];
69
+ const head = t(lang, 'ctrl.edit.preview', { path: rel, from, to: from + before.length - 1, remove: before.length, add: after.length });
70
+ return {
71
+ text: [head, '```diff', ...rows, '```'].join('\n'),
72
+ keyboard: [[
73
+ { text: t(lang, 'ctrl.edit.apply'), data: 'ed:a' },
74
+ { text: t(lang, 'ctrl.edit.cancel'), data: 'ed:c' },
75
+ ]],
76
+ next: { kind: 'rows', rows },
77
+ };
78
+ }
79
+
80
+ /** `/edit <file>:<from>[-<to>]` — show the lines and wait for the replacement. */
81
+ export async function handleEditCommands(ctx) {
82
+ if (ctx.command !== '/edit') return false;
83
+ const { key, lang, reply } = ctx;
84
+ const st = ctx.state || liveState;
85
+ const parsed = parseTarget(ctx.arg);
86
+ if (parsed.error) {
87
+ await reply(t(lang, `ctrl.edit.${parsed.error}`));
88
+ return true;
89
+ }
90
+ const root = ownRoot(st, key);
91
+ if (!root) {
92
+ await reply(t(lang, 'ctrl.find.empty'));
93
+ return true;
94
+ }
95
+ const fenced = resolveInRoot(root, parsed.file);
96
+ if (fenced.refusal) {
97
+ await reply(t(lang, `ctrl.find.${fenced.refusal}`, { root }));
98
+ return true;
99
+ }
100
+ if (fenced.dir) {
101
+ await reply(t(lang, 'ctrl.find.file.dir'));
102
+ return true;
103
+ }
104
+ const read = readTextFile(fenced.path);
105
+ if (read.refusal) {
106
+ await reply(t(lang, `ctrl.find.file.${read.refusal}`));
107
+ return true;
108
+ }
109
+ const { lines } = splitLines(read.text);
110
+ if (parsed.to > lines.length) {
111
+ await reply(t(lang, 'ctrl.edit.range', { lines: lines.length }));
112
+ return true;
113
+ }
114
+ st.edit = st.edit || {};
115
+ st.edit[key] = { root, file: parsed.file, from: parsed.from, to: parsed.to, before: lines.slice(parsed.from - 1, parsed.to), step: 'text', at: Date.now() };
116
+ (ctx.saveState || saveStateNow)();
117
+ await reply(blockCard(parsed.file, parsed.from, st.edit[key].before, lang));
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * The replacement text, if this topic is in the middle of an edit.
123
+ *
124
+ * Called from the message handler before the text becomes a turn: during an
125
+ * edit the next message is the new content, not a prompt for the agent. It
126
+ * answers "was this mine" so the caller knows whether to start a turn.
127
+ */
128
+ export async function takeEditText(ctx) {
129
+ const { key, lang, reply } = ctx;
130
+ const st = ctx.state || liveState;
131
+ const cur = st.edit?.[key];
132
+ if (!cur || cur.step !== 'text') return false;
133
+ const text = String(ctx.text || '').replace(/\r\n/g, '\n');
134
+ // A dash is the only way to send "no lines at all" through a chat.
135
+ const after = text.trim() === '-' ? [] : text.replace(/\n$/, '').split('\n');
136
+ const card = diffCard(cur.file, cur.from, cur.before, after, lang);
137
+ st.edit[key] = { ...cur, step: 'confirm', after, at: Date.now() };
138
+ (ctx.saveState || saveStateNow)();
139
+ await reply(card.text, { keyboard: card.keyboard });
140
+ return true;
141
+ }
142
+
143
+ /**
144
+ * Pressed «Применить»: write the lines the diff showed, if the file still has
145
+ * the lines the diff showed.
146
+ */
147
+ export async function applyEdit(ctx) {
148
+ const { key, lang } = ctx;
149
+ const st = ctx.state || liveState;
150
+ const cur = st.edit?.[key];
151
+ if (!cur || cur.step !== 'confirm') {
152
+ await ctx.answer(t(lang, 'ctrl.edit.stale'));
153
+ return true;
154
+ }
155
+ const fenced = resolveInRoot(cur.root, cur.file);
156
+ if (fenced.refusal) {
157
+ await ctx.answer(t(lang, `ctrl.find.${fenced.refusal}`, { root: cur.root }));
158
+ return true;
159
+ }
160
+ const read = readTextFile(fenced.path);
161
+ if (read.refusal) {
162
+ await ctx.answer(t(lang, `ctrl.find.file.${read.refusal}`));
163
+ return true;
164
+ }
165
+ const { lines, trailing } = splitLines(read.text);
166
+ const now = lines.slice(cur.from - 1, cur.to);
167
+ // The file moved on since the diff: the agent may have edited it, or a turn
168
+ // is running. Overwriting that would lose work the person never saw.
169
+ if (now.join('\n') !== cur.before.join('\n')) {
170
+ delete st.edit[key];
171
+ (ctx.saveState || saveStateNow)();
172
+ await ctx.answer(t(lang, 'ctrl.edit.changed'));
173
+ return true;
174
+ }
175
+ const next = [...lines.slice(0, cur.from - 1), ...cur.after, ...lines.slice(cur.to)];
176
+ // Keep the file ending the way it ended: a missing final newline is how the
177
+ // project's own linters mark a file as unedited, and adding one would show up
178
+ // as a change the person never asked for.
179
+ const body = trailing && next.length ? `${next.join('\n')}\n` : next.join('\n');
180
+ const written = writeTextFile(fenced.path, body);
181
+ if (written.refusal) {
182
+ await ctx.answer(t(lang, `ctrl.edit.write.${written.refusal}`));
183
+ return true;
184
+ }
185
+ delete st.edit[key];
186
+ (ctx.saveState || saveStateNow)();
187
+ await ctx.reply(t(lang, 'ctrl.edit.applied', { path: cur.file, from: cur.from, to: cur.to }));
188
+ return true;
189
+ }
190
+
191
+ /** Pressed «Отмена»: forget the pending edit, touch nothing. */
192
+ export async function cancelEdit(ctx) {
193
+ const st = ctx.state || liveState;
194
+ delete st.edit?.[ctx.key];
195
+ (ctx.saveState || saveStateNow)();
196
+ await ctx.reply(t(ctx.lang, 'ctrl.edit.canceled'));
197
+ return true;
198
+ }
@@ -12,7 +12,7 @@ import { listDir, listingCard } from '../chat/file-listing.mjs';
12
12
  import { saveState as saveStateNow, state as liveState } from '../core/state.mjs';
13
13
 
14
14
  /** The folder this topic itself is bound to — no install-wide fallback. */
15
- function ownRoot(st, key) {
15
+ export function ownRoot(st, key) {
16
16
  return (st?.cwd && st.cwd[key]) || '';
17
17
  }
18
18
 
@@ -116,7 +116,7 @@ export async function handleViewCommands(ctx) {
116
116
  lines.push(t(lang, 'ctrl.status.skills', { n: skillsOf().length }));
117
117
  // This line used to print the desktop profile's route and bundle count.
118
118
  // Both facts were true and both were about the install, printed inside a
119
- // card about one topic: the card said "Профиль: headless (unorouter/...)"
119
+ // card about one topic: the card said "Профиль: headless (acme/...)"
120
120
  // four lines up and then named a wikivibe desktop route, which reads as if
121
121
  // the topic answered there. Nothing about the desktop app belongs in a
122
122
  // per-topic card; the count is the one this topic's own profile has.
@@ -0,0 +1,58 @@
1
+ // The two /doctor rows that answer "is anything still watching?".
2
+ //
3
+ // The bridge cannot report its own death, and it cannot report that the minute
4
+ // supervisor stopped either: a dead supervisor looks exactly like a healthy
5
+ // idle bot until the next crash, which then becomes permanent. These rows are
6
+ // read from files on disk (the restart marker and the supervisor's log), so they
7
+ // stay honest even when the process asking is the one that was just restarted.
8
+ //
9
+ // Kept out of `cmd-bridge.mjs`, which is already close to the 500-line ceiling.
10
+ import { existsSync, statSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { t } from '../core/i18n.mjs';
13
+
14
+ /**
15
+ * An age short enough for a diagnostic row: `0s`, `45s`, `12m`, `5h`, `3d`.
16
+ *
17
+ * Deliberately unit-suffixed ASCII rather than a sentence: the row is read in
18
+ * three languages, and "12m" survives all of them where a translated word would
19
+ * need three more keys for no extra meaning.
20
+ */
21
+ export function describeAge(ms) {
22
+ const secs = Math.max(0, Math.round(Number(ms) / 1000) || 0);
23
+ if (secs < 90) return `${secs}s`;
24
+ const mins = Math.round(secs / 60);
25
+ // Rounding 50 minutes up to "1h" would overstate the age of a supervisor that
26
+ // is merely a little behind; the unit changes only when the value does.
27
+ if (mins < 60) return `${mins}m`;
28
+ const hours = Math.round(mins / 60);
29
+ if (hours < 36) return `${hours}h`;
30
+ return `${Math.round(hours / 24)}d`;
31
+ }
32
+
33
+ /** The supervision rows, in the order a person would ask about them. */
34
+ export function supervisionRows(lang, dshHome) {
35
+ const dir = join(dshHome, 'tg-bridge');
36
+ const rows = [];
37
+
38
+ // A marker that outlives its restart means the next start will announce an
39
+ // interrupted turn that is not news. The kick clears it after ten minutes;
40
+ // seeing one older than that here means the supervisor is not running.
41
+ try {
42
+ const marker = join(dir, 'restart.pending');
43
+ rows.push(`${t(lang, 'ctrl.doctor.restartMarker')}: ${existsSync(marker)
44
+ ? t(lang, 'ctrl.doctor.restartMarkerSet', { age: describeAge(Date.now() - statSync(marker).mtimeMs) })
45
+ : t(lang, 'ctrl.doctor.restartMarkerClear')}`);
46
+ } catch {}
47
+
48
+ try {
49
+ const kick = join(dir, 'kick.log');
50
+ rows.push(`${t(lang, 'ctrl.doctor.kickAge')}: ${t(lang, 'ctrl.doctor.kickAgo', {
51
+ age: describeAge(Date.now() - statSync(kick).mtimeMs),
52
+ })}`);
53
+ } catch {
54
+ rows.push(`${t(lang, 'ctrl.doctor.kickAge')}: ${t(lang, 'ctrl.doctor.kickMissing')}`);
55
+ }
56
+
57
+ return rows;
58
+ }
@@ -3,12 +3,12 @@
3
3
  // The flat list this replaces was one tap shorter and two problems worse. A
4
4
  // profile with seventeen routes does not fit on a phone, and two endpoints that
5
5
  // both serve `deepseek-v4.1-flash` made two buttons with the same name — the
6
- // person looking for "the unorouter one" had nothing to tell them apart, and
6
+ // person looking for "the acme one" had nothing to tell them apart, and
7
7
  // `/model deepseek-v4.1-flash` silently kept whichever provider the patch
8
8
  // already had. A model and the endpoint that serves it are one choice, so the
9
9
  // choice is made in two steps and the second screen cannot repeat the first.
10
10
  //
11
- // A press names its subject in full (`md:!p:unorouter`, `md:unorouter:model`),
11
+ // A press names its subject in full (`md:!p:acme`, `md:acme:model`),
12
12
  // never an index: an index would mean "the fourth model" and would switch to the
13
13
  // wrong route the moment the profile gained or lost one between drawing the card
14
14
  // and the tap. Telegram caps callback data at 64 bytes, so a name too long to
@@ -62,7 +62,7 @@ export function modelOf(profile) {
62
62
  *
63
63
  * `modelsOf` answers "which model ids exist", and that is the wrong question to
64
64
  * put on a screen: the same id is declared by several providers — `deepseek-v4.1-flash`
65
- * exists on wikivibe and on unorouter — so a list of ids shows the same name
65
+ * exists on wikivibe and on acme — so a list of ids shows the same name
66
66
  * twice and neither row says where the answers would come from. Picking a model
67
67
  * and picking a route is one decision, so the list is made of routes.
68
68
  *
package/core/state.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // message was mid-flight: `offset` advanced before the turn ran, so nothing ever
6
6
  // replayed it. An update is written here BEFORE the offset moves and deleted
7
7
  // only after the answer reached Telegram — the one order that survives a crash.
8
- import { appendFileSync, existsSync, mkdirSync, openSync, fsyncSync, closeSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync as writeFd } from 'node:fs';
8
+ import { appendFileSync, existsSync, mkdirSync, openSync, fsyncSync, closeSync, copyFileSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync as writeFd } from 'node:fs';
9
9
  import { join, isAbsolute } from 'node:path';
10
10
  import { DONE_FILE, DONE_TTL_MS, DIR, HOME, LOG, PENDING_DIR, STATE } from './paths.mjs';
11
11
 
@@ -29,7 +29,14 @@ export const state = (() => {
29
29
  try {
30
30
  // Strip a UTF-8 BOM: PowerShell's Set-Content adds one and JSON.parse rejects it.
31
31
  return JSON.parse(readFileSync(STATE, 'utf8').replace(/^\uFEFF/, ''));
32
- } catch {
32
+ } catch (error) {
33
+ // Unreadable state used to become an empty one in silence: goals, schedules
34
+ // and sessions were gone and the only trace was that they stopped working.
35
+ // Keep the file that caused it, say why, and start empty.
36
+ try {
37
+ if (!existsSync(`${STATE}.bad`)) copyFileSync(STATE, `${STATE}.bad`);
38
+ } catch {}
39
+ log(`state unreadable: ${String(error?.message ?? error).slice(0, 160)} — kept as state.json.bad, starting empty`);
33
40
  return { offset: 0, sessions: {} };
34
41
  }
35
42
  })();
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.45.0
4
+
5
+ - **A restart marker no longer outlives its restart.** The minute supervisor
6
+ clears `restart.pending` when the bridge is alive and the marker is more than
7
+ ten minutes old. Left behind, it made a much later start announce an interrupted
8
+ turn that had ended weeks earlier.
9
+ - **`/doctor` says whether anything is still watching.** Two new rows: the restart
10
+ marker with its age, and how long ago the supervisor last ticked. A supervisor
11
+ that stopped is invisible otherwise — the bot looks idle until the next crash,
12
+ which then becomes permanent.
13
+ - **A corrupt `state.json` is kept, not silently dropped.** Goals, schedules and
14
+ sessions used to vanish with no trace; the file is now copied to
15
+ `state.json.bad`, the parse error goes to the log, and the bridge starts empty.
16
+ The limit: only the first corrupt copy is kept, so a second corruption is
17
+ logged but not saved.
18
+ - **An unhandled rejection ends the bridge instead of being logged.** It used to
19
+ keep running in a state nobody designed for, with `/doctor` reporting a healthy
20
+ process. The tick starts a clean one; a running turn is announced as
21
+ interrupted, as with any restart.
22
+ - **`/every` help states its limit** in all three languages: a schedule fires only
23
+ while the bridge runs, and a missed time fires once on the next start, not once
24
+ per missed day.
25
+ - **No provider name in the public tree.** The routing service this bridge was
26
+ developed against was named in 81 places — comments, fixtures, specs. Replaced
27
+ with a deliberately fake name; the pre-release scan is clean again.
28
+
29
+ ## 1.44.0
30
+
31
+ - **Change a file from the chat: `/edit`.** `/edit app.mjs:12` shows line 12 and
32
+ asks for the replacement; `/edit app.mjs:12-14` takes a range. The next plain
33
+ message in the topic is the new text — it is not a turn, so a typo fix costs
34
+ one message instead of a provider round trip. A diff appears with «Применить»
35
+ and «Отмена», and nothing on disk changes until the first is pressed. A single
36
+ dash as the replacement deletes the lines, because a chat never sends an empty
37
+ message.
38
+ - **Lines, not a text match.** The first design was "send the old text, send the
39
+ new text, refuse an ambiguous match". That asks the person to solve a problem
40
+ the command created: a string that appears three times needs a fourth message
41
+ of context to disambiguate. Naming the lines has no such state — the file
42
+ position is the answer — and the spec now says so instead of describing the
43
+ version that was not built.
44
+ - **The write re-reads the file.** The button carries a decision, not a copy of
45
+ the file: on the press, the lines are read again and compared with what the
46
+ diff showed. If a turn changed them in between, the answer is "the file
47
+ changed, run /edit again" and nothing is written. That is the difference
48
+ between an undoable edit and a silently overwritten turn.
49
+ - **The fence covers writing.** `writeTextFile` sits next to `readTextFile` in
50
+ `lib/file-fence.mjs`, with the same refusals: nothing outside the topic folder,
51
+ never a directory, nothing that would grow past 512 KB, and never a new file —
52
+ editing a file that disappeared is a refusal, not a creation.
53
+ - The file keeps the trailing newline it had. Adding one would show up as a
54
+ change nobody asked for, and some of this repo's own checks read that byte.
55
+ - `/edit` is in `/help` (work), `/menu`, the registry, and all three locales.
56
+ Fifteen tests cover the parse, the preview, apply, cancel, delete, a multi-line
57
+ range, a stale press, a file changed under the preview, the fence, and the
58
+ no-folder answer. The full suite is 935 passing.
59
+
3
60
  ## 1.43.1
4
61
 
5
62
  - **A state file that cannot be written no longer fails the command.** 1.43.0
package/i18n/en/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'on',
15
15
  'settings.state.off': 'off',
16
16
  'settings.state.auto': 'auto',
17
- 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /ls [folder] · /view \u003cfile\u003e[:line] · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat] · /find \u003ctext\u003e\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /start · /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
17
+ 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /ls [folder] · /view \u003cfile\u003e[:line] · /edit \u003cfile\u003e:\u003clines\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat] · /find \u003ctext\u003e\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /start · /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
18
18
  'settings.reply.title': 'What the bot says',
19
19
  'settings.agent.title': 'Who answers, and how hard it works',
20
20
  'settings.updates.title': 'New releases (this install, not this topic)',
@@ -327,7 +327,23 @@ export default {
327
327
  'ctrl.ls.stale': "That listing is from an older card — run /ls again",
328
328
  'ctrl.view.usage': "Usage: /view <file>[:line] — the file with line numbers, forty lines at a time.",
329
329
  'ctrl.help.about.ls': "/ls [folder] — lists this topic's folder as buttons, folders first. Press a folder to walk into it, a file to read it. `/ls <file>` opens the file instead.",
330
- 'ctrl.help.about.view': "/view <file>[:line] — shows a file with line numbers, forty lines at a time, «More» for the next page. `file:412` opens at line 412. Reading only: changing a file is a turn, and /diff can revert one hunk of what it changed.",
330
+ 'ctrl.help.about.view': "/view <file>[:line] — shows a file with line numbers, forty lines at a time, «More» for the next page. `file:412` opens at line 412. Reading only: use /edit to change a file, and /diff to revert one hunk of what a turn changed.",
331
+ 'ctrl.edit.usage': "Usage: /edit <file>:<line> or <file>:<from>-<to> — then send the replacement text as the next message.",
332
+ 'ctrl.edit.lines': "Name the lines to change: `/edit app.mjs:12` or `/edit app.mjs:12-14`.",
333
+ 'ctrl.edit.range': "That range is past the end: the file has {lines} lines.",
334
+ 'ctrl.edit.head': "{path} · lines {from}–{to} — send the replacement as your next message. One dash «-» deletes them.",
335
+ 'ctrl.edit.ask': "Send the new text for these lines as the next message.",
336
+ 'ctrl.edit.preview': "{path} · lines {from}–{to} — {remove} removed, {add} added. Nothing is written yet.",
337
+ 'ctrl.edit.apply': "Apply",
338
+ 'ctrl.edit.cancel': "Cancel",
339
+ 'ctrl.edit.applied': "Written: {path}, lines {from}–{to}. /diff can revert this hunk.",
340
+ 'ctrl.edit.canceled': "Canceled — the file is unchanged.",
341
+ 'ctrl.edit.stale': "That edit is no longer waiting — run /edit again.",
342
+ 'ctrl.edit.changed': "The file changed since the preview, so nothing was written. Run /edit again to see the current lines.",
343
+ 'ctrl.edit.write.dir': "That is a folder, not a file.",
344
+ 'ctrl.edit.write.large': "The result would be larger than 512 KB, which this chat will not write.",
345
+ 'ctrl.edit.write.missing': "That file is gone — nothing was written.",
346
+ 'ctrl.help.about.edit': "/edit <file>:<line> — change lines in a file from the chat. You name the lines, send the replacement as the next message, and a diff appears with «Apply» and «Cancel»; the file is written only when you press Apply, and only if its lines still match what the diff showed.",
331
347
  'ctrl.help.about.find': "/find <text> [path] — searches this topic's folder for a literal string and shows every match as a button; pressing one opens the file at that line. Binary files and files over 512 KB are skipped and counted.",
332
348
  'start.body': "This bot is DeepSeek Harness in Telegram. Every topic is its own session, with its own folder, model and history.\n\nThree commands make it usable:\n/cd <project> — bind this topic to a folder\n/model — pick the model (buttons, endpoint first)\n/menu — every command as buttons; /help groups them\n\nAnything else you type is a turn: the agent works in the folder of this topic and answers here.",
333
349
 
package/i18n/en/every.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // agree in three languages. It also keeps `ctrl.mjs` under the 500-line
6
6
  // ceiling, which adding thirteen strings to it would have broken.
7
7
  export default {
8
- 'ctrl.help.about.every': 'One repeating schedule: /every 09:00 text runs that text as a normal turn every day at that time. /every list shows this chat\'s schedules, /every rm 2 removes one.',
8
+ 'ctrl.help.about.every': 'One repeating schedule: /every 09:00 text runs that text as a normal turn every day at that time. /every list shows this chat\'s schedules, /every rm 2 removes one. It fires only while the bridge is running; a time that passed while it was down fires once on the next start, not once per missed day.',
9
9
  'ctrl.every.usage': 'Usage: /every 09:00 text — repeats every day at that time · /every list · /every rm 1.',
10
10
  'ctrl.every.title': '🔁 Every day',
11
11
  'ctrl.every.empty': 'No schedules in this chat yet.',
@@ -0,0 +1,13 @@
1
+ // The `/doctor` rows that answer "is anything still watching?".
2
+ //
3
+ // Its own table because `ctrl.mjs` sits at the 500-line ceiling and these six
4
+ // keys belong to one row group: the restart marker and the age of the last
5
+ // supervisor tick. Age is formatted elsewhere and only interpolated here.
6
+ export default {
7
+ 'ctrl.doctor.restartMarker': 'Restart marker',
8
+ 'ctrl.doctor.restartMarkerSet': 'set {age} ago',
9
+ 'ctrl.doctor.restartMarkerClear': 'none',
10
+ 'ctrl.doctor.kickAge': 'Supervisor',
11
+ 'ctrl.doctor.kickAgo': 'last tick {age} ago',
12
+ 'ctrl.doctor.kickMissing': 'no tick yet',
13
+ };
package/i18n/en.mjs CHANGED
@@ -13,4 +13,5 @@ import model from './en/model.mjs';
13
13
  import endpoint from './en/endpoint.mjs';
14
14
  import every from './en/every.mjs';
15
15
  import dsh from './en/dsh.mjs';
16
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh };
16
+ import supervision from './en/supervision.mjs';
17
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh, ...supervision };
package/i18n/ru/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'вкл',
15
15
  'settings.state.off': 'выкл',
16
16
  'settings.state.auto': 'авто',
17
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /ls [папка] · /view \u003cфайл\u003e[:строка] · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat] · /find \u003ctext\u003e\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
17
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /ls [папка] · /view \u003cфайл\u003e[:строка] · /edit \u003cфайл\u003e:\u003cстроки\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat] · /find \u003ctext\u003e\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
18
18
  'settings.reply.title': 'Что бот говорит',
19
19
  'settings.agent.title': 'Кто отвечает и как старается',
20
20
  'settings.updates.title': 'Новые версии (эта установка, не тема)',
@@ -327,7 +327,23 @@ export default {
327
327
  'ctrl.ls.stale': "Этот список с прошлой карточки — запусти /ls снова",
328
328
  'ctrl.view.usage': "Как это работает: /view <файл>[:строка] — файл с номерами строк, по сорок строк.",
329
329
  'ctrl.help.about.ls': "/ls [папка] — папка темы кнопками, папки сверху. Нажатие на папку заходит внутрь, на файл — открывает. `/ls <файл>` открывает файл сразу.",
330
- 'ctrl.help.about.view': "/view <файл>[:строка] — файл с номерами строк, по сорок строк, кнопка «Дальше» листает. `файл:412` открывает на строке 412. Только чтение: менять файл — это ход, а /diff откатывает один кусок того, что ход изменил.",
330
+ 'ctrl.help.about.view': "/view <файл>[:строка] — файл с номерами строк, по сорок строк, кнопка «Дальше» листает. `файл:412` открывает на строке 412. Только чтение: менять файл — это /edit, а /diff откатывает один кусок того, что изменил ход.",
331
+ 'ctrl.edit.usage': "Как это работает: /edit <файл>:<строка> или <файл>:<с>-<по>, а следующим сообщением — новый текст.",
332
+ 'ctrl.edit.lines': "Назови строки: «/edit app.mjs:12» или «/edit app.mjs:12-14».",
333
+ 'ctrl.edit.range': "Такого диапазона нет: в файле строк — {lines}.",
334
+ 'ctrl.edit.head': "{path} · строки {from}–{to} — пришли новый текст следующим сообщением. Один прочерк «-» удалит эти строки.",
335
+ 'ctrl.edit.ask': "Пришли новый текст для этих строк следующим сообщением.",
336
+ 'ctrl.edit.preview': "{path} · строки {from}–{to} — убрано {remove}, добавлено {add}. На диске пока ничего не изменилось.",
337
+ 'ctrl.edit.apply': "Применить",
338
+ 'ctrl.edit.cancel': "Отмена",
339
+ 'ctrl.edit.applied': "Записано: {path}, строки {from}–{to}. /diff откатывает этот кусок.",
340
+ 'ctrl.edit.canceled': "Отменил — файл не тронут.",
341
+ 'ctrl.edit.stale': "Эта правка уже не ждёт — запусти /edit заново.",
342
+ 'ctrl.edit.changed': "Файл изменился после показа, поэтому ничего не записал. Запусти /edit заново, чтобы увидеть текущие строки.",
343
+ 'ctrl.edit.write.dir': "Это папка, а не файл.",
344
+ 'ctrl.edit.write.large': "Получилось бы больше 512 КБ — столько чат не пишет.",
345
+ 'ctrl.edit.write.missing': "Файла уже нет — ничего не записал.",
346
+ 'ctrl.help.about.edit': "/edit <файл>:<строка> — править строки файла прямо из чата. Ты называешь строки, следующим сообщением присылаешь новый текст, появляется дифф с кнопками «Применить» и «Отмена». Файл пишется только по нажатию и только если строки всё ещё те же, что были в диффе.",
331
347
  'ctrl.help.about.find': "/find <текст> [путь] — ищет в папке темы буквальную строку и показывает совпадения кнопками: нажатие открывает файл на этой строке. Двоичные и слишком большие файлы пропускаются со счётчиком.",
332
348
  'start.body': "Этот бот — DeepSeek Harness в Telegram. Каждая тема — своя сессия со своей папкой, моделью и историей.\n\nТри команды, без которых не обойтись:\n/cd <проект> — привязать тему к папке\n/model — выбрать модель (кнопками, сначала эндпоинт)\n/menu — все команды кнопками; /help — по группам\n\nЛюбое другое сообщение — это ход: агент работает в папке темы и отвечает здесь.",
333
349
 
package/i18n/ru/every.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // трёх языках. Заодно `ctrl.mjs` остаётся под потолком в 500 строк, который
6
6
  // тринадцать новых строк бы пробили.
7
7
  export default {
8
- 'ctrl.help.about.every': 'Одно повторяющееся расписание: /every 09:00 текст каждый день в это время запускает текст как обычный ход. /every list показывает расписания этого чата, /every rm 2 убирает одно.',
8
+ 'ctrl.help.about.every': 'Одно повторяющееся расписание: /every 09:00 текст каждый день в это время запускает текст как обычный ход. /every list показывает расписания этого чата, /every rm 2 убирает одно. Срабатывает, только пока мост запущен; время, пропущенное при выключенном мосте, сработает один раз при следующем запуске, а не по разу за каждый пропущенный день.',
9
9
  'ctrl.every.usage': 'Как пользоваться: /every 09:00 текст — повтор каждый день в это время · /every list · /every rm 1.',
10
10
  'ctrl.every.title': '🔁 Каждый день',
11
11
  'ctrl.every.empty': 'В этом чате пока нет расписаний.',
@@ -0,0 +1,13 @@
1
+ // Строки `/doctor`, отвечающие на вопрос «за процессом ещё кто-то смотрит?».
2
+ //
3
+ // Отдельная таблица, потому что `ctrl.mjs` стоит у потолка в 500 строк, а эти
4
+ // шесть ключей — одна группа строк: метка рестарта и возраст последнего тика
5
+ // супервизора. Возраст считается в коде и здесь только подставляется.
6
+ export default {
7
+ 'ctrl.doctor.restartMarker': 'Метка рестарта',
8
+ 'ctrl.doctor.restartMarkerSet': 'висит {age}',
9
+ 'ctrl.doctor.restartMarkerClear': 'нет',
10
+ 'ctrl.doctor.kickAge': 'Супервизор',
11
+ 'ctrl.doctor.kickAgo': 'последний тик {age} назад',
12
+ 'ctrl.doctor.kickMissing': 'тиков ещё не было',
13
+ };
package/i18n/ru.mjs CHANGED
@@ -13,4 +13,5 @@ import model from './ru/model.mjs';
13
13
  import endpoint from './ru/endpoint.mjs';
14
14
  import every from './ru/every.mjs';
15
15
  import dsh from './ru/dsh.mjs';
16
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh };
16
+ import supervision from './ru/supervision.mjs';
17
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh, ...supervision };
package/i18n/zh/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': '开',
15
15
  'settings.state.off': '关',
16
16
  'settings.state.auto': '自动',
17
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /ls [目录] · /view \u003c文件\u003e[:行号] · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat] · /find \u003ctext\u003e\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
17
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /ls [目录] · /view \u003c文件\u003e[:行号] · /edit \u003c文件\u003e:\u003c行\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat] · /find \u003ctext\u003e\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
18
18
  'settings.reply.title': '机器人怎么说',
19
19
  'settings.agent.title': '谁来回答、投入多少',
20
20
  'settings.updates.title': '新版本(针对本次安装,而非话题)',
@@ -327,7 +327,23 @@ export default {
327
327
  'ctrl.ls.stale': "这是旧卡片的列表 —— 重新运行 /ls",
328
328
  'ctrl.view.usage': "用法:/view <文件>[:行号] —— 带行号显示文件,每次四十行。",
329
329
  'ctrl.help.about.ls': "/ls [目录] —— 以按钮列出本话题的目录,目录在前。点目录进入,点文件查看。`/ls <文件>` 直接打开文件。",
330
- 'ctrl.help.about.view': "/view <文件>[:行号] —— 带行号显示文件,每次四十行,「更多」翻页。`文件:412` 直接跳到第 412 行。只读:改文件要发一次回合,/diff 可以只回退其中一段。",
330
+ 'ctrl.help.about.view': "/view <文件>[:行号] —— 带行号显示文件,每次四十行,「更多」翻页。`文件:412` 直接跳到第 412 行。只读:改文件用 /edit,/diff 可以只回退某一回合改过的其中一段。",
331
+ 'ctrl.edit.usage': "用法:/edit <文件>:<行号> 或 <文件>:<起>-<止>,下一条消息就是新内容。",
332
+ 'ctrl.edit.lines': "请指明行:`/edit app.mjs:12` 或 `/edit app.mjs:12-14`。",
333
+ 'ctrl.edit.range': "超出范围:文件只有 {lines} 行。",
334
+ 'ctrl.edit.head': "{path} · 第 {from}–{to} 行 —— 请把新内容作为下一条消息发来。只发一个「-」表示删除这些行。",
335
+ 'ctrl.edit.ask': "请把这几行的新内容作为下一条消息发来。",
336
+ 'ctrl.edit.preview': "{path} · 第 {from}–{to} 行 —— 删除 {remove} 行,新增 {add} 行。磁盘上还没有改动。",
337
+ 'ctrl.edit.apply': "应用",
338
+ 'ctrl.edit.cancel': "取消",
339
+ 'ctrl.edit.applied': "已写入:{path},第 {from}–{to} 行。/diff 可以回退这一段。",
340
+ 'ctrl.edit.canceled': "已取消,文件未改动。",
341
+ 'ctrl.edit.stale': "这个修改已不在等待中 —— 请重新 /edit。",
342
+ 'ctrl.edit.changed': "文件在预览之后变了,所以什么都没写。重新 /edit 看当前的行。",
343
+ 'ctrl.edit.write.dir': "那是目录,不是文件。",
344
+ 'ctrl.edit.write.large': "结果会超过 512 KB,聊天不写这么大的文件。",
345
+ 'ctrl.edit.write.missing': "文件已不存在 —— 什么都没写。",
346
+ 'ctrl.help.about.edit': "/edit <文件>:<行号> —— 直接在聊天里改文件的行。你指定行,下一条消息发新内容,随后出现带「应用」和「取消」的差异;只有按下「应用」才会写入,而且只有这些行仍与差异中显示的一致时才会写。",
331
347
  'ctrl.help.about.find': "/find <文字> [路径] —— 在话题目录里按字面查找,结果以按钮显示,点开即跳到该行。二进制或过大的文件会被跳过并计数。",
332
348
  'start.body': "这个机器人是 Telegram 里的 DeepSeek Harness。每个话题都是独立会话,有自己的目录、模型和历史。\n\n三条必备命令:\n/cd <项目> —— 把话题绑定到目录\n/model —— 选择模型(按钮,先选端点)\n/menu —— 所有命令都以按钮呈现;/help 按组说明\n\n其他任何消息都是一次回合:代理在话题目录里工作并在这里回答。",
333
349
 
package/i18n/zh/every.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // (四个动词和五种拒绝),它的句子要在三种语言里保持一致。这也让 `ctrl.mjs`
5
5
  // 保持在 500 行上限之下 —— 再加十三行就会超过。
6
6
  export default {
7
- 'ctrl.help.about.every': '一个重复的定时任务:/every 09:00 文本 每天这个时间把文本当成普通轮次执行。/every list 显示这个聊天里的定时任务,/every rm 2 删除一个。',
7
+ 'ctrl.help.about.every': '一个重复的定时任务:/every 09:00 文本 每天这个时间把文本当成普通轮次执行。/every list 显示这个聊天里的定时任务,/every rm 2 删除一个。只在桥接运行时触发;停机期间错过的时间会在下次启动时补触发一次,而不是每错过一天补一次。',
8
8
  'ctrl.every.usage': '用法:/every 09:00 文本 —— 每天这个时间重复 · /every list · /every rm 1。',
9
9
  'ctrl.every.title': '🔁 每天',
10
10
  'ctrl.every.empty': '这个聊天还没有定时任务。',
@@ -0,0 +1,12 @@
1
+ // `/doctor` 里回答「还有没有东西在看守」的那两行。
2
+ //
3
+ // 单独一张表,因为 `ctrl.mjs` 已经贴着 500 行上限,而这六个键属于同一组行:
4
+ // 重启标记和上次守护检查的时间。时间在代码里算好,这里只做插值。
5
+ export default {
6
+ 'ctrl.doctor.restartMarker': '重启标记',
7
+ 'ctrl.doctor.restartMarkerSet': '{age} 前留下',
8
+ 'ctrl.doctor.restartMarkerClear': '无',
9
+ 'ctrl.doctor.kickAge': '守护进程',
10
+ 'ctrl.doctor.kickAgo': '上次检查 {age} 前',
11
+ 'ctrl.doctor.kickMissing': '还没有检查记录',
12
+ };
package/i18n/zh.mjs CHANGED
@@ -13,4 +13,5 @@ import model from './zh/model.mjs';
13
13
  import endpoint from './zh/endpoint.mjs';
14
14
  import every from './zh/every.mjs';
15
15
  import dsh from './zh/dsh.mjs';
16
- export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh };
16
+ import supervision from './zh/supervision.mjs';
17
+ export default { ...core, ...ctrl, ...cost, ...sandbox, ...fallback, ...release, ...diff, ...model, ...endpoint, ...every, ...dsh, ...supervision };
@@ -6,7 +6,7 @@
6
6
  // opened only when it is plausibly text and plausibly small: a 400 MB log would
7
7
  // freeze the turn that asked for one line of it, and a binary would put noise in
8
8
  // the chat. A refusal is a sentence with a reason, never a stack trace.
9
- import { readdirSync, readFileSync, statSync } from 'node:fs';
9
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
10
10
  import { isAbsolute, relative, resolve, sep } from 'node:path';
11
11
 
12
12
  /** A text file bigger than this is refused rather than read. */
@@ -73,6 +73,31 @@ export function readTextFile(path) {
73
73
  }
74
74
  }
75
75
 
76
+ /**
77
+ * Write one file through the fence.
78
+ *
79
+ * Only `/edit` calls this, and only after the person pressed the button on a
80
+ * diff they were shown. The same refusals as reading apply: a directory is not
81
+ * a file, and a file that grew past the cap is not something the chat should be
82
+ * asked to rewrite in one message.
83
+ *
84
+ * @returns {{ ok: true, bytes: number } | { refusal: 'dir' | 'large' | 'missing' }}
85
+ */
86
+ export function writeTextFile(path, text) {
87
+ try {
88
+ const info = statSync(path);
89
+ if (info.isDirectory()) return { refusal: 'dir' };
90
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) return { refusal: 'large' };
91
+ writeFileSync(path, text, 'utf8');
92
+ return { ok: true, bytes: Buffer.byteLength(text, 'utf8') };
93
+ } catch (error) {
94
+ // A file removed between the preview and the press is the common case, and
95
+ // it is a refusal rather than a new file: `/edit` never creates one.
96
+ if (error?.code === 'ENOENT') return { refusal: 'missing' };
97
+ throw error;
98
+ }
99
+ }
100
+
76
101
  /**
77
102
  * Walk a folder, bounded by files, milliseconds and depth.
78
103
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.43.1",
3
+ "version": "1.45.0",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/turn/progress.mjs CHANGED
@@ -291,7 +291,10 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
291
291
  lastView = view ? view.html : text;
292
292
  lastEdit = Date.now();
293
293
  } catch (error) {
294
- // "message is not modified" and rate limits are expected: ignore quietly.
294
+ // "message is not modified" and rate limits are expected, so the edit is
295
+ // skipped — but a silent catch is how a panel that never updates hides for
296
+ // weeks. One line names the reason; the turn itself is never failed by it.
297
+ log(`panel edit skipped [${error?.error_code || error?.code || 'error'}]`);
295
298
  dirty = false;
296
299
  }
297
300
  };