dsh-tg-bridge 1.7.6 → 1.8.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/README.md CHANGED
@@ -15,7 +15,9 @@ blocks.
15
15
  included; no second model is needed (a vision overlay stays opt-in).
16
16
  - **Project per topic**: `/cd my-app`, and all turns run from that directory.
17
17
  - **Goal and checklist per topic**: `/goal`, `/task`; both survive restarts and are prepended to every turn.
18
- - **Live progress**: "⏳ Working..." with steps, a timer and the cache hit rate at the end.
18
+ - **Live progress**: one edited message per turn — steps, a timer and the cache hit rate, plus
19
+ the model's reasoning in a collapsed block you can tap open (no extra messages, the whole
20
+ trail stays with the turn).
19
21
  - **No lost messages**: a journal with acknowledgement and replay.
20
22
  - **Fail-fast**: when the quota runs out it switches to a free model right away.
21
23
  - **`dsh-tg check`**: diagnostics in one command, no changes to the system.
@@ -176,7 +178,9 @@ Send the bot:
176
178
  Work: /cd · /new · /stop · /send · /seed
177
179
  Goals: /goal · /task
178
180
  Sessions: /status · /sessions · /resume
181
+ Agents: /agents · /agents <id> · /agents set model|depth|filter
179
182
  Models: /model · /model <id> · /prices
183
+ Tuning: /effort · /permissions · /preset · /plan · /jobs · /remind
180
184
  Profiles: /profile · /profile <name> · /profile new <name> from <template>
181
185
  Extensions: /skills · /plugins · /soul
182
186
  Diagnostics: /doctor · /logs [errors|N|text]
@@ -253,10 +257,19 @@ and a line in `~/.dsh/profiles/headless/cordis.patch.yml`:
253
257
  The bridge checks the profile itself: if the line is missing, it does not write the task
254
258
  (it would just expire) and behaves as before, queueing the message.
255
259
 
256
- ### Live thoughts
260
+ ### Live thoughts and reasoning
257
261
 
258
- The agent can leave a short decision trail inside the progress message instead of sending
259
- extra chat messages:
262
+ Two things land in the same progress message, and neither sends a chat message of its own.
263
+
264
+ **The model's reasoning.** Every `thinking` block the CLI commits is folded into one
265
+ Telegram `<blockquote expandable>`: collapsed it is a single line, tapped it opens the whole
266
+ trail of the turn, and it stays there after the turn ends — the same way the desktop app shows
267
+ a reasoning section you can expand. The block is edited in place every few seconds (Telegram
268
+ rate-limits edits), escaped, and trimmed to its tail when a turn thinks longer than a message
269
+ can hold; the panel never exceeds one message. If the API refuses the markup, the same content
270
+ is retried as plain text.
271
+
272
+ **The agent's own notes.** The agent can add a short decision trail:
260
273
 
261
274
  ```bash
262
275
  node ~/.dsh/tg-bridge/say.mjs --thought "checking why the watchdog fired twice"
@@ -267,11 +280,12 @@ message shows the last two as `💭` lines. The command needs no ids: it falls b
267
280
  newest turn's thought file, because tool shells do not inherit the bridge environment.
268
281
  `--thought` never sends a Telegram message on its own.
269
282
 
270
- `/reasoning` is the switch for the whole mechanism. It is on by default: every turn carries a
283
+ `/reasoning` is the switch for the 💭 mechanism. It is on by default: every turn carries a
271
284
  short instruction to leave one line at each decision point (task clear, cause found, risky
272
285
  change, result checked). `/reasoning off` drops the instruction and the `💭` lines for that
273
- topic — useful when the step list is all you want. The setting lives in `state.json` per topic,
274
- so a chatty research topic and a terse deploy topic can differ.
286
+ topic — useful when the step list is all you want. The reasoning block is model output and is
287
+ not switched by it; `/thoughts` copies the last turn's reasoning out as a message. The setting
288
+ lives in `state.json` per topic, so a chatty research topic and a terse deploy topic can differ.
275
289
 
276
290
  ### Profiles per topic
277
291
 
package/agents.mjs ADDED
@@ -0,0 +1,302 @@
1
+ // Reading a profile's delegation setup out of its Cordis patch.
2
+ //
3
+ // A profile patch is YAML, and this module deliberately does not parse YAML: it
4
+ // reads the few keys the bridge reports on, from the rows that declare them.
5
+ // A row is `- id: <row>` with `name:` and `config:` beside it, so the row ends
6
+ // where the indent drops back to the dash, and the config's own keys are the
7
+ // shallowest lines inside it.
8
+ //
9
+ // This is its own module with tests because a wrong indent assumption turns
10
+ // "the subagent model is X" into a confident lie, and a person setting a cost
11
+ // budget has to be able to trust that line.
12
+
13
+ /** Indent width of a line (tabs count as one column, as YAML forbids them). */
14
+ const indentOf = (line) => /^\s*/.exec(line)[0].length;
15
+
16
+ /** Strip one layer of matching quotes. */
17
+ const unquote = (value) => value.replace(/^['"]|['"]$/g, '');
18
+
19
+ /**
20
+ * The row that owns the `name:` line at `at`: its dash line indent and the
21
+ * lines below it, up to the next row.
22
+ * @param {string[]} lines patch lines
23
+ * @param {number} at index of the `name:` line
24
+ * @returns {{ indent: number, body: string[] }}
25
+ */
26
+ function rowAt(lines, at) {
27
+ let indent = Math.max(0, indentOf(lines[at]) - 2);
28
+ for (let i = at - 1; i >= 0 && i >= at - 3; i -= 1) {
29
+ if (/^\s*-\s*(id|name):/.test(lines[i])) {
30
+ indent = indentOf(lines[i]);
31
+ break;
32
+ }
33
+ }
34
+ const body = [];
35
+ for (let i = at + 1; i < lines.length; i += 1) {
36
+ const line = lines[i];
37
+ if (!line.trim()) continue;
38
+ if (indentOf(line) <= indent) break;
39
+ body.push(line);
40
+ }
41
+ return { indent, body };
42
+ }
43
+
44
+ /**
45
+ * The keys of a nested block (`config:`, `agentOptions:`), read as a flat map of
46
+ * its shallowest keys. Deeper values belong to the nested maps this module reads
47
+ * separately, so they never override a top-level key.
48
+ * @param {string[]} body lines below the block's key
49
+ * @param {number} base indent of the block's key line
50
+ */
51
+ function blockKeys(body, base) {
52
+ const rows = body.filter((line) => indentOf(line) > base && !/^\s*-\s/.test(line));
53
+ if (rows.length === 0) return {};
54
+ const depth = Math.min(...rows.map(indentOf));
55
+ const out = {};
56
+ for (const line of rows) {
57
+ if (indentOf(line) !== depth) continue;
58
+ const match = /^\s*([A-Za-z][\w-]*):\s*(.*?)\s*$/.exec(line);
59
+ if (!match) continue;
60
+ if (match[2]) out[match[1]] = unquote(match[2]);
61
+ else out[match[1]] = true;
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /** Index of the last `key:` line at a depth shallower than `body`'s keys. */
67
+ function blockStart(body, key) {
68
+ for (let i = body.length - 1; i >= 0; i -= 1) {
69
+ if (new RegExp(`^\\s*${key}:\\s*$`).test(body[i])) return i;
70
+ }
71
+ return -1;
72
+ }
73
+
74
+ /** A `toolFilter:` allow/deny list, counted rather than enumerated. */
75
+ function toolFilterOf(body) {
76
+ const at = blockStart(body, 'toolFilter');
77
+ if (at < 0) return { allow: 0, deny: 0 };
78
+ const base = indentOf(body[at]);
79
+ const out = { allow: 0, deny: 0 };
80
+ let list = '';
81
+ for (let i = at + 1; i < body.length; i += 1) {
82
+ const line = body[i];
83
+ if (!line.trim()) continue;
84
+ if (indentOf(line) <= base) break;
85
+ const key = /^\s*(allow|deny):\s*$/.exec(line);
86
+ if (key) {
87
+ list = key[1];
88
+ continue;
89
+ }
90
+ if (list && /^\s*-\s*\S/.test(line)) out[list] += 1;
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * Every `dsh-tool-subagent` row of a patch: one per delegation tool the model
97
+ * can actually see (`subagent`, `subagent_fork`, …).
98
+ * @param {string} text profile patch
99
+ */
100
+ export function parseSubagentRows(text) {
101
+ const lines = String(text || '').split(/\r?\n/);
102
+ const rows = [];
103
+ for (let i = 0; i < lines.length; i += 1) {
104
+ if (!/^\s*name:\s*['"]?@deepseek-ai\/dsh-tool-subagent['"]?\s*$/.test(lines[i])) continue;
105
+ const { body } = rowAt(lines, i);
106
+ const configAt = blockStart(body, 'config');
107
+ const config = configAt >= 0 ? blockKeys(body.slice(configAt + 1), indentOf(body[configAt])) : {};
108
+ const optionsAt = blockStart(body, 'agentOptions');
109
+ const options = optionsAt >= 0 ? blockKeys(body.slice(optionsAt + 1), indentOf(body[optionsAt])) : {};
110
+ const filter = toolFilterOf(body);
111
+ // The row id sits on the line above `name:`; a patch can also declare the
112
+ // pair inline, and then there is nothing to name the row by.
113
+ const idLine = i > 0 ? /^\s*-\s*id:\s*(\S+)\s*$/.exec(lines[i - 1]) : null;
114
+ rows.push({
115
+ id: idLine ? idLine[1] : '',
116
+ toolName: config.toolName || 'subagent',
117
+ provider: config.provider || 'spawn',
118
+ model: options.model || '',
119
+ modelProvider: options.provider || '',
120
+ reasoningEffort: options.reasoningEffort || '',
121
+ maxTokens: options.maxTokens || '',
122
+ maxDepth: /^\d+$/.test(config.maxDepth || '') ? Number(config.maxDepth) : (config.maxDepth || ''),
123
+ backgroundMode: config.backgroundMode || 'one-shot',
124
+ background: config.enableRunInBackground !== 'false',
125
+ persona: body.some((line) => /^\s*persona:\s*\S/.test(line)),
126
+ toolAllow: filter.allow,
127
+ toolDeny: filter.deny,
128
+ });
129
+ }
130
+ return rows;
131
+ }
132
+
133
+ /**
134
+ * The `model-selection-settings` row: which routes a delegated turn may pick.
135
+ * Absent means the child simply inherits the tool's own `agentOptions`.
136
+ * @param {string} text profile patch
137
+ */
138
+ export function parseModelSelection(text) {
139
+ const lines = String(text || '').split(/\r?\n/);
140
+ const at = lines.findIndex((line) => /^\s*name:\s*['"]?@deepseek-ai\/dsh-tool-subagent\/model-selection-settings['"]?\s*$/.test(line));
141
+ if (at < 0) return null;
142
+ const { body } = rowAt(lines, at);
143
+ const configAt = blockStart(body, 'config');
144
+ const config = configAt >= 0 ? blockKeys(body.slice(configAt + 1), indentOf(body[configAt])) : {};
145
+ const allowed = [];
146
+ const base = blockStart(body, 'allowedModels');
147
+ if (base >= 0) {
148
+ const indent = indentOf(body[base]);
149
+ let current = null;
150
+ for (let i = base + 1; i < body.length; i += 1) {
151
+ const line = body[i];
152
+ if (!line.trim()) continue;
153
+ if (indentOf(line) <= indent && !/^\s*-/.test(line)) break;
154
+ const start = /^\s*-\s*(.*)$/.exec(line);
155
+ if (start) {
156
+ current = {};
157
+ allowed.push(current);
158
+ const inline = /^(provider|model):\s*(\S+)/.exec(start[1]);
159
+ if (inline) current[inline[1]] = unquote(inline[2]);
160
+ continue;
161
+ }
162
+ const pair = /^\s*([a-z]+):\s*(\S+)/.exec(line);
163
+ if (pair && current) current[pair[1]] = unquote(pair[2]);
164
+ }
165
+ }
166
+ return { enabled: config.enabled !== 'false', allowed };
167
+ }
168
+
169
+ /**
170
+ * Child sessions this session started, newest first, from DSH's projection
171
+ * cache. The catalog row is what the delegation tools themselves publish, so
172
+ * the list is the same one the desktop sidebar shows.
173
+ * @param {unknown} cache parsed `session-*.json`
174
+ */
175
+ export function parseSubagentFleet(cache) {
176
+ const rows = cache?.record?.rows ?? cache?.rows ?? {};
177
+ const head = rows.subagentCatalog?.val?.head?.values;
178
+ const list = Array.isArray(head)
179
+ ? head
180
+ .filter((row) => row && typeof row.childId === 'string')
181
+ .map((row) => ({
182
+ id: row.childId,
183
+ label: typeof row.label === 'string' ? row.label : '',
184
+ mode: typeof row.mode === 'string' ? row.mode : '',
185
+ at: Number(row.childCreatedAt) || 0,
186
+ }))
187
+ .sort((a, b) => b.at - a.at)
188
+ : [];
189
+ const policy = rows.subagentModelSelectionPolicy?.val;
190
+ const plan = rows.plan?.val;
191
+ return {
192
+ children: list,
193
+ policy: policy && typeof policy === 'object' ? policy : null,
194
+ plan: plan && typeof plan === 'object' ? { active: plan.active === true, pending: plan.pending === true } : null,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Reasoning efforts a provider declares for one model, in declaration order.
200
+ * The ids are provider-owned (`off`, `minimal` … `max`), so the list has to come
201
+ * from the route's own catalog: writing an effort the route never declared would
202
+ * only fail on the next turn.
203
+ * @param {string} text profile patch
204
+ * @param {string} modelId model the profile currently runs
205
+ */
206
+ export function parseReasoningEfforts(text, modelId) {
207
+ const lines = String(text || '').split(/\r?\n/);
208
+ const start = lines.findIndex((line) => new RegExp(`^\\s*-\\s*id:\\s*${modelId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`).test(line));
209
+ if (start < 0) return [];
210
+ const indent = indentOf(lines[start]);
211
+ let end = lines.length;
212
+ for (let i = start + 1; i < lines.length; i += 1) {
213
+ if (!lines[i].trim()) continue;
214
+ if (indentOf(lines[i]) <= indent) { end = i; break; }
215
+ }
216
+ let effortAt = -1;
217
+ for (let i = start + 1; i < end; i += 1) {
218
+ if (/^\s*reasoningEfforts:\s*$/.test(lines[i])) { effortAt = i; break; }
219
+ }
220
+ if (effortAt < 0) return [];
221
+ const effortIndent = indentOf(lines[effortAt]);
222
+ const out = [];
223
+ for (let i = effortAt + 1; i < end; i += 1) {
224
+ const line = lines[i];
225
+ if (!line.trim()) continue;
226
+ if (indentOf(line) <= effortIndent) break;
227
+ const key = /^\s*([a-z]+):/.exec(line);
228
+ if (key) out.push(key[1]);
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * The permission table of a profile: the presets it declares and the one it
235
+ * starts in. The bridge runs unattended, so this is the knob that decides
236
+ * whether a turn may write outside its workspace.
237
+ * @param {string} text profile patch
238
+ */
239
+ export function parsePermissionPresets(text) {
240
+ const lines = String(text || '').split(/\r?\n/);
241
+ const at = lines.findIndex((line) => /^\s*name:\s*['"]?@deepseek-ai\/dsh-permission-presets['"]?\s*$/.test(line));
242
+ if (at < 0) return null;
243
+ const { body } = rowAt(lines, at);
244
+ const configAt = blockStart(body, 'config');
245
+ if (configAt < 0) return null;
246
+ const config = blockKeys(body.slice(configAt + 1), indentOf(body[configAt]));
247
+ const presets = [];
248
+ const tableAt = blockStart(body, 'presets');
249
+ if (tableAt >= 0) {
250
+ const indent = indentOf(body[tableAt]);
251
+ let current = null;
252
+ for (let i = tableAt + 1; i < body.length; i += 1) {
253
+ const line = body[i];
254
+ if (!line.trim()) continue;
255
+ if (indentOf(line) <= indent) break;
256
+ if (indentOf(line) === indent + 2) {
257
+ const key = /^\s*([\w-]+):\s*$/.exec(line);
258
+ if (key) {
259
+ current = { id: key[1], sandbox: '', approval: '' };
260
+ presets.push(current);
261
+ }
262
+ continue;
263
+ }
264
+ const pair = /^\s*([a-z]+):\s*(\S+)/.exec(line);
265
+ if (pair && current) current[pair[1]] = unquote(pair[2]);
266
+ }
267
+ }
268
+ return { presets, current: unquote(config.defaultPreset || '') };
269
+ }
270
+
271
+ /**
272
+ * Agent presets a profile declares, plus the one the registry starts in.
273
+ * Presets are compositions of persona, instructions and tools; only a profile
274
+ * that mounts them can switch roles at all.
275
+ * @param {string} text profile patch
276
+ */
277
+ export function parseAgentPresets(text) {
278
+ const lines = String(text || '').split(/\r?\n/);
279
+ const presets = [];
280
+ // The row's own `config:` sits directly under it. `blockStart` picks the LAST
281
+ // match, which inside a preset row is the config of the last nested plugin —
282
+ // so this reads the first block at the row's own depth instead.
283
+ const configAtRow = (body, indent) => {
284
+ const at = body.findIndex((line) => indentOf(line) === indent + 2 && /^\s*config:\s*$/.test(line));
285
+ return at >= 0 ? blockKeys(body.slice(at + 1), indent + 2) : {};
286
+ };
287
+ for (let i = 0; i < lines.length; i += 1) {
288
+ if (!/^\s*name:\s*['"]?@deepseek-ai\/dsh-agent-preset['"]?\s*$/.test(lines[i])) continue;
289
+ const { indent, body } = rowAt(lines, i);
290
+ const config = configAtRow(body, indent);
291
+ const idLine = /^\s*-\s*id:\s*(\S+)\s*$/.exec(lines[i - 1] || '');
292
+ presets.push({ row: idLine ? idLine[1] : '', id: unquote(config.id || ''), order: Number(unquote(config.order || '0')) || 0 });
293
+ }
294
+ let selected = '';
295
+ for (let i = 0; i < lines.length; i += 1) {
296
+ if (!/^\s*name:\s*['"]?@deepseek-ai\/dsh-agent-preset-registry['"]?\s*$/.test(lines[i])) continue;
297
+ const { indent, body } = rowAt(lines, i);
298
+ const config = configAtRow(body, indent);
299
+ selected = unquote(config.selectedDefault || '') || unquote(config.default || '');
300
+ }
301
+ return { presets: presets.filter((preset) => preset.id).sort((a, b) => a.order - b.order), selected };
302
+ }
package/bot-menu.mjs CHANGED
@@ -52,6 +52,13 @@ const COMMANDS = [
52
52
  { command: 'lang', description: 'Язык интерфейса: en, ru, zh' },
53
53
  { command: 'reasoning', description: 'Заметки по ходу: /reasoning on|off' },
54
54
  { command: 'profile', description: 'Профиль темы: /profile <имя>, /profile new' },
55
+ { command: 'agents', description: 'Агенты и субагенты: кто, на какой модели, кого запускали' },
56
+ { command: 'effort', description: 'Усилие рассуждения модели: /effort high' },
57
+ { command: 'permissions', description: 'Права профиля: пресет песочницы и подтверждений' },
58
+ { command: 'preset', description: 'Пресет агента (персона и инструменты): /preset <id>' },
59
+ { command: 'plan', description: 'Режим плана: состояние и как получить план без правок' },
60
+ { command: 'jobs', description: 'Что мост выполняет сейчас: ходы и очередь' },
61
+ { command: 'remind', description: 'Напоминание: /remind +15m текст или 09:30 текст' },
55
62
  { command: 'thoughts', description: 'Рассуждения последнего хода (исчезает)' },
56
63
  { command: 'version', description: 'Версия моста и последняя на npm' },
57
64
  { command: 'update', description: 'Обновить мост из npm: /update confirm' },
@@ -82,6 +89,13 @@ const COMMANDS_EN = [
82
89
  { command: 'lang', description: 'Interface language: en, ru, zh' },
83
90
  { command: 'reasoning', description: 'Working notes: /reasoning on|off' },
84
91
  { command: 'profile', description: 'Topic profile: /profile <name>, /profile new' },
92
+ { command: 'agents', description: 'Agents and subagents: who runs, on which model, who was spawned' },
93
+ { command: 'effort', description: 'Reasoning effort: /effort high' },
94
+ { command: 'permissions', description: 'Profile permissions: sandbox and approval preset' },
95
+ { command: 'preset', description: 'Agent preset (persona and tools): /preset <id>' },
96
+ { command: 'plan', description: 'Plan mode: state and how to ask for a plan without edits' },
97
+ { command: 'jobs', description: 'What the bridge runs now: turns and queue' },
98
+ { command: 'remind', description: 'Reminder: /remind +15m text or 09:30 text' },
85
99
  { command: 'thoughts', description: 'Reasoning of the last turn (self-deleting)' },
86
100
  { command: 'version', description: 'Bridge version and the latest on npm' },
87
101
  { command: 'update', description: 'Update the bridge from npm: /update confirm' },
@@ -112,6 +126,13 @@ const COMMANDS_ZH = [
112
126
  { command: 'lang', description: '界面语言:en、ru、zh' },
113
127
  { command: 'reasoning', description: '工作记录:/reasoning on|off' },
114
128
  { command: 'profile', description: '话题配置档:/profile <名称>,/profile new' },
129
+ { command: 'agents', description: '智能体与子智能体:谁在运行、用什么模型、启动过谁' },
130
+ { command: 'effort', description: '推理力度:/effort high' },
131
+ { command: 'permissions', description: '配置档权限:沙箱与确认预设' },
132
+ { command: 'preset', description: '智能体预设(人格与工具):/preset <id>' },
133
+ { command: 'plan', description: '计划模式:状态与如何只要计划不改动' },
134
+ { command: 'jobs', description: '桥接器当前在跑:轮次与队列' },
135
+ { command: 'remind', description: '提醒:/remind +15m 文本 或 09:30 文本' },
115
136
  { command: 'thoughts', description: '上一轮的推理(稍后自动消失)' },
116
137
  { command: 'version', description: '桥接版本与 npm 上的最新版本' },
117
138
  { command: 'update', description: '从 npm 更新桥接:/update confirm' },
package/bridge.mjs CHANGED
@@ -33,6 +33,7 @@ import { handleControl, CONTROL_COMMANDS, modelOf, reasoningOf } from './control
33
33
  import { drainGoalJobs, goalOf, renderPromptBlock } from './goals.mjs';
34
34
  import { renderPrices } from './prices.mjs';
35
35
  import { t, resolveLang } from './i18n.mjs';
36
+ import { progressPanel } from './panel.mjs';
36
37
 
37
38
  const HOME = homedir();
38
39
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -170,6 +171,29 @@ setInterval(() => {
170
171
  }
171
172
  }, 2000).unref();
172
173
 
174
+ // Reminders: a turn is one short-lived process, so the only clock that can
175
+ // outlive a message is this one. A reminder that came due while the bridge was
176
+ // down fires on the first tick after it starts; one created for a topic that
177
+ // has since been deleted still tries, and the delivery error is logged.
178
+ setInterval(() => {
179
+ try {
180
+ const now = Date.now();
181
+ const rows = Array.isArray(state.reminders) ? state.reminders : [];
182
+ const ready = rows.filter((row) => row && Number(row.at) <= now);
183
+ if (ready.length === 0) return;
184
+ const ids = new Set(ready.map((row) => row.id));
185
+ state.reminders = rows.filter((row) => !ids.has(row.id));
186
+ saveState();
187
+ for (const row of ready) {
188
+ Promise.resolve(send(String(row.chatId), t(row.lang || 'ru', 'ctrl.remind.due', { text: row.text }), Number(row.threadId) || 0))
189
+ .then(() => log(`reminder ${row.id} delivered`))
190
+ .catch((error) => log(`reminder ${row.id} delivery failed: ${error.message}`));
191
+ }
192
+ } catch (error) {
193
+ log(`reminder loop failed: ${error.message}`);
194
+ }
195
+ }, 20_000).unref();
196
+
173
197
  function log(line) {
174
198
  const text = `${new Date().toISOString()} ${line}\n`;
175
199
  try { appendFileSync(LOG, text, 'utf8'); } catch {}
@@ -926,10 +950,15 @@ function toolLine(event) {
926
950
  * seconds — Telegram rate-limits edits) with the latest step and a counter, and
927
951
  * finally turned into a short summary. Errors are edited into the same message
928
952
  * so the person always sees one continuous trace instead of scattered notes.
953
+ *
954
+ * Reasoning is folded into the same message as a collapsed block, so a turn that
955
+ * thinks for ten minutes still leaves one line in the chat — and the whole trail
956
+ * one tap away.
929
957
  */
930
958
  async function startProgress(chatId, threadId, lang = 'ru') {
931
959
  const started = Date.now();
932
960
  const steps = [];
961
+ const thinkingParts = [];
933
962
  /** Last reported token usage for this turn, for the cache line. */
934
963
  const usage = { inputTokens: 0, cacheReadTokens: 0 };
935
964
  let messageId = 0;
@@ -965,51 +994,67 @@ async function startProgress(chatId, threadId, lang = 'ru') {
965
994
  }, 3000);
966
995
  thoughtTimer.unref?.();
967
996
 
968
- const body = (final = false) => {
969
- const seconds = Math.round((Date.now() - started) / 1000);
970
- const head = final
971
- ? `✅ ${t(lang, 'status.done')} · ${seconds} ${lang === 'en' ? 's' : lang === 'zh' ? '秒' : 'с'}`
972
- : `⏳ ${t(lang, 'status.working')}… ${seconds} ${lang === 'en' ? 's' : lang === 'zh' ? '秒' : 'с'}`;
973
- // Three recent steps is enough to see the shape of the work; six lines of
974
- // shell commands read as noise on a phone.
975
- const tail = steps.slice(-3).map((line) => `• ${line}`).join('\n');
976
- const more = steps.length > 3 ? `\n${t(lang, 'status.more', { n: steps.length - 3 })}` : '';
977
- const mind = thoughts.length ? `\n${thoughts.map((line) => `💭 ${line}`).join('\n')}` : '';
997
+ const panel = (final = false) => {
978
998
  // The cache line belongs to the outcome, not to every intermediate edit.
979
999
  const cache = final && usage.cacheReadTokens
980
- ? `\n${t(lang, 'status.cacheLine', {
1000
+ ? t(lang, 'status.cacheLine', {
981
1001
  pct: Math.round((usage.cacheReadTokens / Math.max(1, usage.cacheReadTokens + (usage.inputTokens ?? 0))) * 100),
982
1002
  k: Math.round(usage.cacheReadTokens / 1000),
983
- })}`
1003
+ })
984
1004
  : '';
985
- return (tail ? `${head}${mind}\n${tail}${more}${cache}` : `${head}${mind}${cache}`);
1005
+ return progressPanel({
1006
+ lang,
1007
+ seconds: Math.round((Date.now() - started) / 1000),
1008
+ final,
1009
+ steps,
1010
+ thoughts,
1011
+ thinking: thinkingParts.join('\n\n'),
1012
+ cache,
1013
+ });
1014
+ };
1015
+
1016
+ /** Send or edit the panel; a rejected parse falls back to the plain twin. */
1017
+ const post = async (method, payload, view, keyboard = undefined) => {
1018
+ const body = { ...payload, text: view.html, parse_mode: 'HTML' };
1019
+ if (keyboard !== undefined) body.reply_markup = keyboard ?? { inline_keyboard: [] };
1020
+ try {
1021
+ return await tg(method, body);
1022
+ } catch (error) {
1023
+ log(`${method} html failed (${String(error.message).slice(0, 100)}); retrying as plain text`);
1024
+ const plain = { ...payload, text: view.plain };
1025
+ delete plain.parse_mode;
1026
+ if (keyboard !== undefined) plain.reply_markup = keyboard ?? { inline_keyboard: [] };
1027
+ return tg(method, plain);
1028
+ }
986
1029
  };
987
1030
 
988
1031
  try {
989
- const res = await tg('sendMessage', {
1032
+ const res = await post('sendMessage', {
990
1033
  chat_id: chatId,
991
- text: body(),
992
1034
  disable_web_page_preview: true,
993
1035
  ...(threadId > 0 ? { message_thread_id: threadId } : {}),
994
- });
1036
+ }, panel());
995
1037
  messageId = res.message_id;
996
1038
  } catch (error) {
997
1039
  log(`progress message failed: ${error.message}`);
998
1040
  }
999
1041
 
1000
- const edit = async (text, keyboard = undefined) => {
1042
+ const edit = async (text, keyboard = undefined, view = null) => {
1001
1043
  if (!messageId) return;
1044
+ const payload = {
1045
+ chat_id: chatId,
1046
+ message_id: messageId,
1047
+ disable_web_page_preview: true,
1048
+ };
1002
1049
  try {
1003
- const payload = {
1004
- chat_id: chatId,
1005
- message_id: messageId,
1006
- text,
1007
- disable_web_page_preview: true,
1008
- };
1009
- // `null` means "remove the buttons"; an object replaces them; `undefined`
1010
- // leaves the current keyboard alone (intermediate status edits).
1011
- if (keyboard !== undefined) payload.reply_markup = keyboard ?? { inline_keyboard: [] };
1012
- await tg('editMessageText', payload);
1050
+ if (view) await post('editMessageText', payload, view, keyboard);
1051
+ else {
1052
+ // Plain text (errors, notes): whatever the caller passes is literal, so
1053
+ // it must not be run through the HTML parser.
1054
+ const body = { ...payload, text };
1055
+ if (keyboard !== undefined) body.reply_markup = keyboard ?? { inline_keyboard: [] };
1056
+ await tg('editMessageText', body);
1057
+ }
1013
1058
  lastEdit = Date.now();
1014
1059
  } catch (error) {
1015
1060
  // "message is not modified" and rate limits are expected: ignore quietly.
@@ -1024,7 +1069,7 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1024
1069
  timer = null;
1025
1070
  if (!dirty) return;
1026
1071
  dirty = false;
1027
- await edit(body());
1072
+ await edit('', undefined, panel());
1028
1073
  }, 3500);
1029
1074
  timer.unref?.();
1030
1075
  }
@@ -1042,6 +1087,21 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1042
1087
  schedule();
1043
1088
  return;
1044
1089
  }
1090
+ // The CLI emits one `thinking` event per committed assistant step, so the
1091
+ // panel grows a paragraph at a time — visible while the turn runs, and
1092
+ // still there, collapsed, when it ends.
1093
+ if (event.type === 'thinking' && event.text) {
1094
+ thinkingParts.push(String(event.text));
1095
+ // A turn can think for a long time; only the tail of the stream is ever
1096
+ // shown, so the head is dropped before it becomes a memory leak.
1097
+ if (thinkingParts.join('\n\n').length > 24000) {
1098
+ const kept = thinkingParts.join('\n\n').slice(-24000);
1099
+ thinkingParts.length = 0;
1100
+ thinkingParts.push(kept);
1101
+ }
1102
+ schedule();
1103
+ return;
1104
+ }
1045
1105
  // Usage rides on the status events; keep the latest numbers so the final
1046
1106
  // line can show the cache hit rate of this very turn.
1047
1107
  if (event.type === 'status' && event.usage) {
@@ -1080,7 +1140,7 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1080
1140
  await edit(text, timedOut ? continueKeyboard(sessionKey(chatId, threadId), lang) : errorKeyboard(sessionKey(chatId, threadId), lang));
1081
1141
  return true;
1082
1142
  }
1083
- await edit(body(true), null);
1143
+ await edit('', null, panel(true));
1084
1144
  return false;
1085
1145
  },
1086
1146
  };
@@ -1386,6 +1446,14 @@ ${t(lang, 'help.body')}`,
1386
1446
  saveState,
1387
1447
  log,
1388
1448
  send,
1449
+ // What `/jobs` shows: the turns that hold a slot right now and how many
1450
+ // wait behind them. `queues` counts a topic that is running too, so the
1451
+ // waiters are the keys without an active turn.
1452
+ jobs: () => ({
1453
+ active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
1454
+ queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
1455
+ max: MAX_PARALLEL,
1456
+ }),
1389
1457
  api: tg,
1390
1458
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
1391
1459
  seedTopic: ensureTopicSeed,