dsh-tg-bridge 1.9.2 → 1.10.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
@@ -167,7 +167,7 @@ Send the bot:
167
167
  | `/doctor` | report: pid, Telegram, disk, directory, session |
168
168
  | `/version` | bridge version, the latest on npm, bridge directory |
169
169
  | `/update` | says whether a newer release exists (`/update confirm` installs it) |
170
- | `/thoughts` | the last turn's reasoning, deleted after a few minutes |
170
+ | `/thoughts [file\|all\|off]` | the last turn's reasoning as a message; `file`/`all` send the full log as a Markdown document, `off` hides the block |
171
171
  | `/help` | commands grouped by category |
172
172
  | `/cd my-app` | topic bound to the project |
173
173
  | `/prices` | model prices and the cost of the current one |
@@ -264,13 +264,18 @@ Two things land in the same progress message, and neither sends a chat message o
264
264
  **The model's reasoning.** Every `thinking` block the CLI commits is folded into one
265
265
  Telegram `<blockquote expandable>`: collapsed it is a single line, tapped it opens the whole
266
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.
267
+ a reasoning section you can expand. The block is written once, in the final edit of the turn,
268
+ and never touched again: Telegram re-collapses an expanded block on every edit of its message,
269
+ which used to yank the chat away from a half-read paragraph. While the turn runs the message
270
+ only gets a counter (`🧠 Размышления · 4821`) and the last three steps, so the live edits stay
271
+ short. Escaped, and trimmed to its tail when a turn thinks longer than a message can hold; the
272
+ panel never exceeds one message. A cut block says `… · начало скрыто · /thoughts file`, which
273
+ sends the whole log as a document. If the API refuses the markup, the same content is retried
274
+ as plain text.
271
275
 
272
276
  **The steps.** Three calls fit inline. A turn that makes more moves its complete step list into
273
- a second collapsed block, so "what did it actually run" is one tap away instead of a count.
277
+ a second collapsed block, added in that same final edit, so "what did it actually run" is one
278
+ tap away instead of a count.
274
279
 
275
280
  **The agent's own notes.** The agent can add a short decision trail:
276
281
 
@@ -286,9 +291,20 @@ newest turn's thought file, because tool shells do not inherit the bridge enviro
286
291
  `/reasoning` is the switch for the 💭 mechanism. It is on by default: every turn carries a
287
292
  short instruction to leave one line at each decision point (task clear, cause found, risky
288
293
  change, result checked). `/reasoning off` drops the instruction and the `💭` lines for that
289
- topic — useful when the step list is all you want. The reasoning block is model output and is
290
- not switched by it; `/thoughts` copies the last turn's reasoning out as a message. The setting
291
- lives in `state.json` per topic, so a chatty research topic and a terse deploy topic can differ.
294
+ topic — useful when the step list is all you want. The setting lives in `state.json` per topic,
295
+ so a chatty research topic and a terse deploy topic can differ.
296
+
297
+ The reasoning block itself is model output; `/thoughts` is what reads it back:
298
+
299
+ - `/thoughts` — the last turn as a message, in parts, deleted after a few minutes;
300
+ - `/thoughts file` — the **whole** last turn as `reasoning-<date>-file.md`, sent as a document
301
+ (a five-hour turn is tens of thousands of characters, which no chat message can hold);
302
+ - `/thoughts all` — every turn of the session in one file (a long session is a couple of MB);
303
+ - `/thoughts off` / `on` — keep the block out of the turn panel (the panel then shows
304
+ `🧠 Размышления · N · /thoughts file`) or bring it back.
305
+
306
+ The log is built from the session file on demand, so nothing is duplicated while a turn runs.
307
+ Files land in `~/.dsh/tg-bridge/thoughts/` and older ones are pruned after a week.
292
308
 
293
309
  ### Profiles per topic
294
310
 
package/bot-menu.mjs CHANGED
@@ -59,7 +59,7 @@ const COMMANDS = [
59
59
  { command: 'plan', description: 'Режим плана: состояние и как получить план без правок' },
60
60
  { command: 'jobs', description: 'Что мост выполняет сейчас: ходы и очередь' },
61
61
  { command: 'remind', description: 'Напоминание: /remind +15m текст или 09:30 текст' },
62
- { command: 'thoughts', description: 'Рассуждения последнего хода (исчезает)' },
62
+ { command: 'thoughts', description: 'Рассуждения хода: текстом, файлом или выкл' },
63
63
  { command: 'version', description: 'Версия моста и последняя на npm' },
64
64
  { command: 'update', description: 'Обновить мост из npm: /update confirm' },
65
65
  ];
@@ -96,7 +96,7 @@ const COMMANDS_EN = [
96
96
  { command: 'plan', description: 'Plan mode: state and how to ask for a plan without edits' },
97
97
  { command: 'jobs', description: 'What the bridge runs now: turns and queue' },
98
98
  { command: 'remind', description: 'Reminder: /remind +15m text or 09:30 text' },
99
- { command: 'thoughts', description: 'Reasoning of the last turn (self-deleting)' },
99
+ { command: 'thoughts', description: 'Reasoning of the last turn (text, file or off)' },
100
100
  { command: 'version', description: 'Bridge version and the latest on npm' },
101
101
  { command: 'update', description: 'Update the bridge from npm: /update confirm' },
102
102
  ];
@@ -133,7 +133,7 @@ const COMMANDS_ZH = [
133
133
  { command: 'plan', description: '计划模式:状态与如何只要计划不改动' },
134
134
  { command: 'jobs', description: '桥接器当前在跑:轮次与队列' },
135
135
  { command: 'remind', description: '提醒:/remind +15m 文本 或 09:30 文本' },
136
- { command: 'thoughts', description: '上一轮的推理(稍后自动消失)' },
136
+ { command: 'thoughts', description: '本轮推理:文本、文件或关闭' },
137
137
  { command: 'version', description: '桥接版本与 npm 上的最新版本' },
138
138
  { command: 'update', description: '从 npm 更新桥接:/update confirm' },
139
139
  ];
package/bridge.mjs CHANGED
@@ -941,6 +941,7 @@ function killTurn(key) {
941
941
  */
942
942
  async function startProgress(chatId, threadId, lang = 'ru') {
943
943
  const started = Date.now();
944
+ const panelKey = sessionKey(chatId, threadId);
944
945
  const steps = [];
945
946
  const thinkingParts = [];
946
947
  /** Last reported token usage for this turn, for the cache line. */
@@ -993,6 +994,9 @@ async function startProgress(chatId, threadId, lang = 'ru') {
993
994
  steps,
994
995
  thoughts,
995
996
  thinking: thinkingParts.join('\n\n'),
997
+ // `/thoughts off` keeps the block out of the chat and leaves the counter;
998
+ // the log itself is a file the command sends on demand.
999
+ reasoning: state.thinkBlock?.[panelKey] === 'counter' ? 'counter' : 'block',
996
1000
  cache,
997
1001
  });
998
1002
  };
@@ -1026,8 +1030,15 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1026
1030
  log(`progress message failed: ${error.message}`);
1027
1031
  }
1028
1032
 
1033
+ let lastView = '';
1029
1034
  const edit = async (text, keyboard = undefined, view = null) => {
1030
1035
  if (!messageId) return;
1036
+ // Re-sending identical text counts as an edit on the phone (the block
1037
+ // collapses and the list re-lays-out), so a no-op must not reach Telegram.
1038
+ if (view && keyboard === undefined && view.html === lastView) {
1039
+ dirty = false;
1040
+ return;
1041
+ }
1031
1042
  const payload = {
1032
1043
  chat_id: chatId,
1033
1044
  message_id: messageId,
@@ -1042,6 +1053,7 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1042
1053
  if (keyboard !== undefined) body.reply_markup = keyboard ?? { inline_keyboard: [] };
1043
1054
  await tg('editMessageText', body);
1044
1055
  }
1056
+ lastView = view ? view.html : text;
1045
1057
  lastEdit = Date.now();
1046
1058
  } catch (error) {
1047
1059
  // "message is not modified" and rate limits are expected: ignore quietly.
@@ -1057,7 +1069,7 @@ async function startProgress(chatId, threadId, lang = 'ru') {
1057
1069
  if (!dirty) return;
1058
1070
  dirty = false;
1059
1071
  await edit('', undefined, panel());
1060
- }, 3500);
1072
+ }, 5000);
1061
1073
  timer.unref?.();
1062
1074
  }
1063
1075
 
package/control.mjs CHANGED
@@ -11,14 +11,16 @@ import { join, basename } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { t, LANGS, normalizeLang } from './i18n.mjs';
13
13
  import { addTask, clearGoal, doneTask, finishGoal, goalOf, progressOf, removeTask, setGoal } from './goals.mjs';
14
- import { lastTurnReasoning, lastTurnText, sessionFile, sessionStats } from './thoughts.mjs';
14
+ import { lastTurnReasoning, lastTurnReasoningSteps, lastTurnText, reasoningMarkdown, sessionFile, sessionReasoningSteps, sessionStats } from './thoughts.mjs';
15
15
  import { parseAgentPresets, parseModelSelection, parsePermissionPresets, parseReasoningEfforts, parseSubagentFleet, parseSubagentRows } from './agents.mjs';
16
16
  import { setRowConfig, unsetRowConfig } from './profile-edit.mjs';
17
17
  import { parseReminder, stampAt, upcoming } from './reminders.mjs';
18
18
 
19
19
  const HOME = homedir();
20
20
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
21
- const PROFILES = join(DSH_HOME, 'profiles');
21
+ const PROFILES = join(DSH_HOME, 'profiles');
22
+ /** Where a reasoning log is written before it is sent as a document. */
23
+ const THOUGHT_DIR = join(DSH_HOME, 'tg-bridge', 'thoughts');
22
24
  const APP = join(process.env.LOCALAPPDATA || '', 'Programs', 'DeepSeek Harness');
23
25
  const EXE = join(APP, 'DeepSeek Harness.exe');
24
26
  const DSH_CMD = join(APP, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd');
@@ -1682,40 +1684,98 @@ export async function handleControl(ctx) {
1682
1684
  return true;
1683
1685
  }
1684
1686
 
1685
- case '/thoughts': {
1686
- // The reasoning of the last turn, pulled from the session log itself. It
1687
- // is ephemeral: the reply lives a few minutes and then deletes itself, so
1688
- // a long plan never turns into chat clutter.
1689
- const sessionId = ctx.state.sessions?.[key];
1690
- if (!sessionId) {
1691
- say(t(lang, 'ctrl.thoughts.noSession'));
1692
- return true;
1693
- }
1694
- const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1695
- const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
1696
- if (!text) {
1697
- // Not every turn plans: a one-word answer has no reasoning part at all.
1698
- // Saying "here is what the last turn answered" beats a dead end that
1699
- // looks like a broken command.
1700
- const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
1701
- say(answered
1702
- ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}`
1703
- : t(lang, 'ctrl.thoughts.none'));
1704
- return true;
1705
- }
1706
- // A message caps at 4096 characters; a long plan goes out in parts instead
1707
- // of being cut at the first one with a "…" that hides the rest.
1708
- const title = t(lang, 'ctrl.thoughts.title', { chars: text.length });
1709
- const parts = [];
1710
- for (let at = 0; at < text.length; at += 3600) parts.push(text.slice(at, at + 3600));
1711
- parts.forEach((part, index) => {
1712
- say(parts.length > 1
1713
- ? `${title} (${index + 1}/${parts.length})\n\n${part}`
1714
- : `${title}\n\n${part}`);
1715
- });
1716
- return true;
1717
- }
1718
-
1687
+ case '/thoughts': {
1688
+ // The model's reasoning, read from the session log. Text by default (short,
1689
+ // ephemeral, deletes itself); `file` and `all` write a Markdown log and send
1690
+ // it as a document, because a five-hour turn is megabytes of text that no
1691
+ // chat message can hold; `off` keeps the block out of the panel entirely.
1692
+ const mode = String(arg || '').trim().toLowerCase();
1693
+
1694
+ if (mode === 'off' || mode === 'on') {
1695
+ state.thinkBlock = state.thinkBlock || {};
1696
+ if (mode === 'off') state.thinkBlock[key] = 'counter';
1697
+ else delete state.thinkBlock[key];
1698
+ ctx.saveState?.();
1699
+ say(t(lang, mode === 'off' ? 'ctrl.thoughts.off' : 'ctrl.thoughts.on'));
1700
+ return true;
1701
+ }
1702
+
1703
+ const sessionId = ctx.state.sessions?.[key];
1704
+ if (!sessionId) {
1705
+ say(t(lang, 'ctrl.thoughts.noSession'));
1706
+ return true;
1707
+ }
1708
+ const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1709
+
1710
+ if (mode === 'file' || mode === 'all') {
1711
+ const turns = mode === 'all'
1712
+ ? sessionReasoningSteps(file).map((turn, index) => ({ title: t(lang, 'ctrl.thoughts.turn', { n: index + 1 }), steps: turn.steps }))
1713
+ : [{ steps: lastTurnReasoningSteps(file) }];
1714
+ const steps = turns.reduce((sum, turn) => sum + turn.steps.length, 0);
1715
+ const chars = turns.reduce((sum, turn) => sum + turn.steps.reduce((n, step) => n + step.length, 0), 0);
1716
+ if (!steps) {
1717
+ say(t(lang, 'ctrl.thoughts.none'));
1718
+ return true;
1719
+ }
1720
+ const now = new Date();
1721
+ const pad = (n) => String(n).padStart(2, '0');
1722
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
1723
+ const stamp = date.replace(/[ :]/g, '-');
1724
+ const path = join(THOUGHT_DIR, `reasoning-${stamp}-${mode}.md`);
1725
+ try {
1726
+ mkdirSync(THOUGHT_DIR, { recursive: true });
1727
+ writeFileSync(path, reasoningMarkdown({
1728
+ title: t(lang, mode === 'all' ? 'ctrl.thoughts.fileTitleAll' : 'ctrl.thoughts.fileTitleLast'),
1729
+ meta: [date, t(lang, 'ctrl.thoughts.fileMeta', { steps, chars, turns: turns.length })],
1730
+ stepTitle: t(lang, 'ctrl.thoughts.step'),
1731
+ turns,
1732
+ }), 'utf8');
1733
+ // A log is a keepsake, not an archive: a week is plenty and the dir
1734
+ // does not grow without bound.
1735
+ for (const name of readdirSync(THOUGHT_DIR)) {
1736
+ if (!name.startsWith('reasoning-')) continue;
1737
+ const old = join(THOUGHT_DIR, name);
1738
+ try {
1739
+ if (Date.now() - statSync(old).mtimeMs > 7 * 86400000) rmSync(old, { force: true });
1740
+ } catch {}
1741
+ }
1742
+ if (ctx.sendFile) {
1743
+ await ctx.sendFile(path, t(lang, 'ctrl.thoughts.fileCaption', { chars, steps }));
1744
+ return true;
1745
+ }
1746
+ // No file transport in this context (tests): the log still leaves as text.
1747
+ say(`${t(lang, 'ctrl.thoughts.fileCaption', { chars, steps })}\n\n${readFileSync(path, 'utf8').slice(0, 3200)}`);
1748
+ return true;
1749
+ } catch (error) {
1750
+ say(t(lang, 'ctrl.thoughts.fileError', { error: String(error.message).slice(0, 120) }));
1751
+ return true;
1752
+ }
1753
+ }
1754
+
1755
+ const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
1756
+ if (!text) {
1757
+ // Not every turn plans: a one-word answer has no reasoning part at all.
1758
+ // Saying "here is what the last turn answered" beats a dead end that
1759
+ // looks like a broken command.
1760
+ const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
1761
+ say(answered
1762
+ ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}\n\n${t(lang, 'ctrl.thoughts.hint')}`
1763
+ : `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.hint')}`);
1764
+ return true;
1765
+ }
1766
+ // A message caps at 4096 characters; a long plan goes out in parts instead
1767
+ // of being cut at the first one with a "…" that hides the rest.
1768
+ const title = t(lang, 'ctrl.thoughts.title', { chars: text.length });
1769
+ const parts = [];
1770
+ for (let at = 0; at < text.length; at += 3600) parts.push(text.slice(at, at + 3600));
1771
+ parts.forEach((part, index) => {
1772
+ const last = index === parts.length - 1;
1773
+ const head = parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title;
1774
+ say(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
1775
+ });
1776
+ return true;
1777
+ }
1778
+
1719
1779
  case '/version': {
1720
1780
  // Which bridge is running, which one npm has, and whether this install can
1721
1781
  // update itself. A report, so it answers even in the middle of a turn.
package/i18n.mjs CHANGED
@@ -231,7 +231,17 @@ const DICT = {
231
231
  'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
232
232
  'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
233
233
  'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
234
- 'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
234
+ 'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
235
+ 'ctrl.thoughts.hint': 'Whole log as a file: /thoughts file · whole session: /thoughts all · hide the block: /thoughts off',
236
+ 'ctrl.thoughts.fileCaption': '🧠 Reasoning log · {chars} chars · {steps} steps',
237
+ 'ctrl.thoughts.off': 'The reasoning block is off in this chat. /thoughts file still sends the whole log as a file.',
238
+ 'ctrl.thoughts.on': 'The reasoning block is back in the turn panel.',
239
+ 'ctrl.thoughts.fileError': 'Could not build the log file: {error}',
240
+ 'ctrl.thoughts.fileTitleLast': 'Reasoning of the last turn',
241
+ 'ctrl.thoughts.fileTitleAll': 'Reasoning of the whole session',
242
+ 'ctrl.thoughts.fileMeta': '{steps} steps · {chars} chars · {turns} turns',
243
+ 'ctrl.thoughts.step': 'Step',
244
+ 'ctrl.thoughts.turn': 'Turn {n}',
235
245
  'goal.none': 'No goal in this topic. Set one: /goal <text>',
236
246
  'goal.set': 'Goal: {text}',
237
247
  'goal.default': 'Tasks',
@@ -595,7 +605,17 @@ const DICT = {
595
605
  'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
596
606
  'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
597
607
  'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
598
- 'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
608
+ 'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
609
+ 'ctrl.thoughts.hint': 'Весь лог файлом: /thoughts file · вся сессия: /thoughts all · убрать блок: /thoughts off',
610
+ 'ctrl.thoughts.fileCaption': '🧠 Лог рассуждений · {chars} символов · шагов {steps}',
611
+ 'ctrl.thoughts.off': 'Блок рассуждений в этом чате выключен. Полный лог по-прежнему отдаёт /thoughts file.',
612
+ 'ctrl.thoughts.on': 'Блок рассуждений снова в панели хода.',
613
+ 'ctrl.thoughts.fileError': 'Не смог собрать файл лога: {error}',
614
+ 'ctrl.thoughts.fileTitleLast': 'Размышления последнего хода',
615
+ 'ctrl.thoughts.fileTitleAll': 'Размышления всей сессии',
616
+ 'ctrl.thoughts.fileMeta': 'шагов {steps} · {chars} символов · ходов {turns}',
617
+ 'ctrl.thoughts.step': 'Шаг',
618
+ 'ctrl.thoughts.turn': 'Ход {n}',
599
619
  'goal.none': 'В этой теме нет цели. Задать: /goal <текст>',
600
620
  'goal.set': 'Цель: {text}',
601
621
  'goal.default': 'Задачи',
@@ -959,7 +979,17 @@ const DICT = {
959
979
  'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
960
980
  'ctrl.thoughts.none': '上一轮没有保存推理过程。',
961
981
  'ctrl.thoughts.lastAnswer': '上一轮的回答:',
962
- 'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
982
+ 'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
983
+ 'ctrl.thoughts.hint': '完整日志文件:/thoughts file · 整个会话:/thoughts all · 隐藏区块:/thoughts off',
984
+ 'ctrl.thoughts.fileCaption': '🧠 推理日志 · {chars} 字符 · {steps} 步',
985
+ 'ctrl.thoughts.off': '本聊天的推理区块已关闭。完整日志仍可用 /thoughts file 获取。',
986
+ 'ctrl.thoughts.on': '推理区块已回到进度面板。',
987
+ 'ctrl.thoughts.fileError': '无法生成日志文件:{error}',
988
+ 'ctrl.thoughts.fileTitleLast': '上一轮的推理',
989
+ 'ctrl.thoughts.fileTitleAll': '整个会话的推理',
990
+ 'ctrl.thoughts.fileMeta': '{steps} 步 · {chars} 字符 · {turns} 轮',
991
+ 'ctrl.thoughts.step': '步骤',
992
+ 'ctrl.thoughts.turn': '第 {n} 轮',
963
993
  'goal.none': '本话题还没有目标。设置:/goal <文本>',
964
994
  'goal.set': '目标:{text}',
965
995
  'goal.default': '任务',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.9.2",
3
+ "version": "1.10.0",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/panel.mjs CHANGED
@@ -79,12 +79,17 @@ export function addStep(steps, line) {
79
79
  * Long content lives in Telegram's native `<blockquote expandable>`: collapsed it
80
80
  * is one line, tapped it shows the whole trail, and it never floods the chat. Two
81
81
  * blocks at most — the model's reasoning and, when a turn makes more than three
82
- * tool calls, the full step list — so the chat still reads as one message per
83
- * turn. `plain` is the same content without markup, for the fallback path when
82
+ * tool calls, the full step list. They appear only in the final edit (`final`):
83
+ * Telegram re-collapses an expanded block on every edit of its message, so a live
84
+ * edit that carried blocks would yank the chat away from whoever is reading one.
85
+ * `plain` is the same content without markup, for the fallback path when
84
86
  * the parser refuses a message and for `plainText` installs.
85
87
  */
86
88
  export function progressPanel({
87
89
  lang = 'ru', seconds = 0, final = false, steps = [], thoughts = [], thinking = '', cache = '',
90
+ // `counter` keeps the reasoning out of the chat: a number in the panel, the
91
+ // log itself in the file that `/thoughts file` sends.
92
+ reasoning = 'block',
88
93
  } = {}) {
89
94
  const head = final
90
95
  ? `✅ ${t(lang, 'status.done')} · ${seconds} ${secondsUnit(lang)}`
@@ -92,38 +97,55 @@ export function progressPanel({
92
97
  const mind = thoughts.map((line) => `💭 ${line}`);
93
98
  const base = [head, ...mind, cache].filter(Boolean).join('\n').length;
94
99
 
95
- // Up to three steps fit inline and read better there; a longer turn would turn
96
- // the panel into a wall of shell commands, so its steps move into a block.
100
+ // While the turn runs this message is rewritten every few seconds, and
101
+ // Telegram drops an expanded block on every edit — which is what yanks the
102
+ // chat away from someone mid-sentence. So a live edit stays short: the last
103
+ // steps inline, a counter instead of the reasoning, no collapsible content at
104
+ // all. The two blocks arrive once, in the final edit, which nothing touches
105
+ // again, so a block can be opened and read in peace.
97
106
  const many = steps.length > 3;
98
- const inline = many ? [] : steps.map((line) => `• ${line}`);
107
+ const inline = many
108
+ ? (final ? [] : steps.slice(-3).map((line) => `• ${line}`))
109
+ : steps.map((line) => `• ${line}`);
110
+ const more = !final && many ? t(lang, 'status.more', { n: steps.length - 3 }) : '';
111
+ const text = String(thinking || '').trim();
112
+ const live = (reasoning === 'counter' && final)
113
+ ? (text ? `🧠 ${t(lang, 'status.thinkTitle')} · ${text.length} · /thoughts file` : '')
114
+ : (!final && text ? `🧠 ${t(lang, 'status.thinkTitle')} · ${text.length}` : '');
99
115
  const stepsRoom = Math.max(0, Math.min(STEPS_MAX, PANEL_MAX - base - 1200));
100
- const all = many
116
+ const all = many && final
101
117
  ? tailOf(steps.map((line) => `• ${line}`).join('\n'), stepsRoom)
102
118
  : { text: '', cut: false };
103
119
  const stepsLabel = `🛠 ${t(lang, 'status.stepsTitle')} · ${steps.length}`
104
120
  + `${all.cut ? ` · ${t(lang, 'status.thinkCut')}` : ''}`;
105
121
 
106
- const fixed = base + inline.join('\n').length + all.text.length + 120;
122
+ // The block's own label can carry the cut suffix, so it has to be budgeted too.
123
+ const labelRoom = `🧠 ${t(lang, 'status.thinkTitle')} · ${t(lang, 'status.thinkCut')} · /thoughts file\n`.length;
124
+ const fixed = base + inline.join('\n').length + all.text.length + more.length + live.length + labelRoom + 120;
107
125
  const room = Math.max(400, Math.min(THINKING_MAX, PANEL_MAX - fixed));
108
- const body = tailOf(String(thinking || '').trim(), room);
126
+ const body = final && reasoning === 'block' ? tailOf(text, room) : { text: '', cut: false };
109
127
  // A cut block starts mid-sentence; say so and point at the one command that
110
128
  // still has the whole text, otherwise the reasoning reads as broken.
111
129
  const thinkLabel = `🧠 ${t(lang, 'status.thinkTitle')}`
112
- + `${body.cut ? ` · ${t(lang, 'status.thinkCut')} · /thoughts` : ''}`;
130
+ + `${body.cut ? ` · ${t(lang, 'status.thinkCut')} · /thoughts file` : ''}`;
113
131
 
114
132
  const html = [
115
133
  head,
116
134
  ...mind.map((line) => escapeHtml(line)),
135
+ escapeHtml(live),
117
136
  body.text ? `<blockquote expandable>${escapeHtml(thinkLabel)}\n${escapeHtml(body.text)}</blockquote>` : '',
118
137
  ...inline.map((line) => escapeHtml(line)),
138
+ escapeHtml(more),
119
139
  all.text ? `<blockquote expandable>${escapeHtml(stepsLabel)}\n${escapeHtml(all.text)}</blockquote>` : '',
120
140
  escapeHtml(cache),
121
141
  ].filter(Boolean).join('\n');
122
142
  const plain = [
123
143
  head,
124
144
  ...mind,
145
+ live,
125
146
  body.text ? `${thinkLabel}\n${body.text}` : '',
126
147
  ...inline,
148
+ more,
127
149
  all.text ? `${stepsLabel}\n${all.text}` : '',
128
150
  cache,
129
151
  ].filter(Boolean).join('\n');
package/thoughts.mjs CHANGED
@@ -98,9 +98,84 @@ function lastTurnBlocks(file) {
98
98
  return out;
99
99
  }
100
100
 
101
+ /**
102
+ * The last turn's reasoning, complete, one entry per committed assistant step.
103
+ * Chat text is capped (a five-hour turn would not fit any message); a file has
104
+ * no such problem, so this keeps everything.
105
+ */
106
+ export function lastTurnReasoningSteps(file) {
107
+ return lastTurnBlocks(file)
108
+ .filter((part) => part.type === 'reasoning' && part.text && part.text.trim())
109
+ .map((part) => part.text.trim());
110
+ }
111
+
112
+ /** Reasoning of every turn of the session, oldest first: `[{ steps: [...] }]`. */
113
+ export function sessionReasoningSteps(file) {
114
+ if (!file || !existsSync(file)) return [];
115
+ let buf;
116
+ try {
117
+ buf = readFileSync(file);
118
+ } catch {
119
+ return [];
120
+ }
121
+ const starts = frameStarts(buf);
122
+ const turns = [];
123
+ let current = null;
124
+ for (let i = 0; i < starts.length - 1; i++) {
125
+ let text = '';
126
+ try {
127
+ text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
128
+ } catch {
129
+ continue;
130
+ }
131
+ for (const line of text.split('\n')) {
132
+ if (!line) continue;
133
+ let record;
134
+ try {
135
+ record = JSON.parse(line);
136
+ } catch {
137
+ continue;
138
+ }
139
+ if (record.type === 'turn/start') {
140
+ current = { steps: [] };
141
+ turns.push(current);
142
+ continue;
143
+ }
144
+ if (record.type !== 'assistant/message') continue;
145
+ if (!current) {
146
+ current = { steps: [] };
147
+ turns.push(current);
148
+ }
149
+ for (const part of record.data?.message?.content ?? []) {
150
+ if (part.type === 'reasoning' && part.text && part.text.trim()) current.steps.push(part.text.trim());
151
+ }
152
+ }
153
+ }
154
+ return turns;
155
+ }
156
+
157
+ /**
158
+ * A reasoning log as a file someone can open in an editor: a header with the
159
+ * facts, then one section per step. Plain Markdown, because every editor and
160
+ * Telegram's own preview render it.
161
+ */
162
+ export function reasoningMarkdown({ title, meta = [], stepTitle = 'Step', turns = [] }) {
163
+ const lines = [`# ${title}`, ''];
164
+ for (const line of meta) lines.push(`- ${line}`);
165
+ lines.push('');
166
+ const manyTurns = turns.length > 1;
167
+ turns.forEach((turn, turnIndex) => {
168
+ if (!turn.steps.length) return;
169
+ if (manyTurns) lines.push(`## ${turn.title || `${stepTitle} ${turnIndex + 1}`}`, '');
170
+ turn.steps.forEach((step, index) => {
171
+ lines.push(`### ${stepTitle} ${index + 1}`, '', step, '');
172
+ });
173
+ });
174
+ return `${lines.join('\n').trim()}\n`;
175
+ }
176
+
101
177
  /** The last turn's own answer text — the fallback when it planned nothing. */
102
- export function lastTurnText(file, { maxChars = 1500 } = {}) {
103
- const text = lastTurnBlocks(file)
178
+ export function lastTurnText(file, { maxChars = 1500 } = {}) { const text = lastTurnBlocks(file)
104
179
  .filter((part) => part.type === 'text' && part.text)
105
180
  .map((part) => part.text.trim())
106
181
  .join('\n\n')