dsh-tg-bridge 1.43.0 → 1.44.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.
@@ -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'],
@@ -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
 
package/core/state.mjs CHANGED
@@ -47,8 +47,23 @@ export function writeAtomic(path, text) {
47
47
  renameSync(tmp, path);
48
48
  }
49
49
 
50
+ /**
51
+ * Persist `state`. Best effort on purpose.
52
+ *
53
+ * Remembering a card's rows is a convenience: the card already reached the
54
+ * person, and a missing or unwritable state file must not turn a finished
55
+ * command into an error. Every command used to decide this for itself, so a
56
+ * fresh machine without `~/.dsh/tg-bridge` made `/ls` die in CI while the same
57
+ * code passed on a machine that had the folder.
58
+ */
50
59
  export function saveState() {
51
- writeAtomic(STATE, JSON.stringify(state, null, 2));
60
+ try {
61
+ writeAtomic(STATE, JSON.stringify(state, null, 2));
62
+ return true;
63
+ } catch (error) {
64
+ log(`state save failed [STATE]: ${error?.code || error?.message || 'unknown'}`);
65
+ return false;
66
+ }
52
67
  }
53
68
 
54
69
  export function log(line) {
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.44.0
4
+
5
+ - **Change a file from the chat: `/edit`.** `/edit app.mjs:12` shows line 12 and
6
+ asks for the replacement; `/edit app.mjs:12-14` takes a range. The next plain
7
+ message in the topic is the new text — it is not a turn, so a typo fix costs
8
+ one message instead of a provider round trip. A diff appears with «Применить»
9
+ and «Отмена», and nothing on disk changes until the first is pressed. A single
10
+ dash as the replacement deletes the lines, because a chat never sends an empty
11
+ message.
12
+ - **Lines, not a text match.** The first design was "send the old text, send the
13
+ new text, refuse an ambiguous match". That asks the person to solve a problem
14
+ the command created: a string that appears three times needs a fourth message
15
+ of context to disambiguate. Naming the lines has no such state — the file
16
+ position is the answer — and the spec now says so instead of describing the
17
+ version that was not built.
18
+ - **The write re-reads the file.** The button carries a decision, not a copy of
19
+ the file: on the press, the lines are read again and compared with what the
20
+ diff showed. If a turn changed them in between, the answer is "the file
21
+ changed, run /edit again" and nothing is written. That is the difference
22
+ between an undoable edit and a silently overwritten turn.
23
+ - **The fence covers writing.** `writeTextFile` sits next to `readTextFile` in
24
+ `lib/file-fence.mjs`, with the same refusals: nothing outside the topic folder,
25
+ never a directory, nothing that would grow past 512 KB, and never a new file —
26
+ editing a file that disappeared is a refusal, not a creation.
27
+ - The file keeps the trailing newline it had. Adding one would show up as a
28
+ change nobody asked for, and some of this repo's own checks read that byte.
29
+ - `/edit` is in `/help` (work), `/menu`, the registry, and all three locales.
30
+ Fifteen tests cover the parse, the preview, apply, cancel, delete, a multi-line
31
+ range, a stale press, a file changed under the preview, the fence, and the
32
+ no-folder answer. The full suite is 935 passing.
33
+
34
+ ## 1.43.1
35
+
36
+ - **A state file that cannot be written no longer fails the command.** 1.43.0
37
+ shipped `/ls` and `/view` calling `saveState()` directly, and on a machine
38
+ that has never run the bridge — CI's clean home, or a fresh install — the
39
+ atomic write throws before the card can be drawn. Remembering a card's rows is
40
+ a convenience: the card already reached the person, so the save now logs
41
+ `state save failed [STATE]` and lets the command finish. This was invisible
42
+ locally because the developer machine has that folder.
43
+ - The bug is covered by a test that points `DSH_HOME` at an empty directory, so
44
+ the clean-machine answer is checked instead of assumed.
45
+ - Nothing else changed: same commands, same behaviour on a machine that works.
46
+
3
47
  ## 1.43.0
4
48
 
5
49
  - **Read the folder from the chat: `/ls` and `/view`.** Until now the only way
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/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/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
 
@@ -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.0",
3
+ "version": "1.44.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",