dsh-tg-bridge 1.9.3 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 |
@@ -269,8 +269,9 @@ and never touched again: Telegram re-collapses an expanded block on every edit o
269
269
  which used to yank the chat away from a half-read paragraph. While the turn runs the message
270
270
  only gets a counter (`🧠 Размышления · 4821`) and the last three steps, so the live edits stay
271
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`, which returns the whole
273
- text. If the API refuses the markup, the same content is retried as plain text.
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.
274
275
 
275
276
  **The steps.** Three calls fit inline. A turn that makes more moves its complete step list into
276
277
  a second collapsed block, added in that same final edit, so "what did it actually run" is one
@@ -290,9 +291,20 @@ newest turn's thought file, because tool shells do not inherit the bridge enviro
290
291
  `/reasoning` is the switch for the 💭 mechanism. It is on by default: every turn carries a
291
292
  short instruction to leave one line at each decision point (task clear, cause found, risky
292
293
  change, result checked). `/reasoning off` drops the instruction and the `💭` lines for that
293
- topic — useful when the step list is all you want. The reasoning block is model output and is
294
- not switched by it; `/thoughts` copies the last turn's reasoning out as a message. The setting
295
- 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.
296
308
 
297
309
  ### Profiles per topic
298
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
@@ -28,6 +28,7 @@ import { writeSteerJob } from './steer-queue.mjs';
28
28
  import { inlineText } from './media-text.mjs';
29
29
  import { createAlbumBuffer } from './albums.mjs';
30
30
  import { turnArgs } from './cli-args.mjs';
31
+ import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
31
32
  import { ensureProfile } from './profiles.mjs';
32
33
  import { handleControl, CONTROL_COMMANDS, modelOf, reasoningOf } from './control.mjs';
33
34
  import { drainGoalJobs, goalOf, renderPromptBlock } from './goals.mjs';
@@ -379,24 +380,6 @@ async function tg(method, body, timeoutMs = 60000, attempts = 3) {
379
380
  throw lastError;
380
381
  }
381
382
 
382
- function chunk(text, size = 4000) {
383
- const out = [];
384
- let rest = text;
385
- while (rest.length > size) {
386
- let cut = rest.lastIndexOf('\n', size);
387
- if (cut < size * 0.5) cut = size;
388
- out.push(rest.slice(0, cut));
389
- rest = rest.slice(cut).replace(/^\n+/, '');
390
- }
391
- if (rest.length) out.push(rest);
392
- return out;
393
- }
394
-
395
- /**
396
- * Forum topic id of a message, or 0 for the General topic and for private chats.
397
- * Telegram omits `message_thread_id` for the General topic of a forum, so 0 is
398
- * the "no topic" marker and must never be sent back as a thread id.
399
- */
400
383
  function threadOf(msg) {
401
384
  const id = msg.message_thread_id ?? msg.reply_to_message?.message_thread_id;
402
385
  return Number.isInteger(id) && id > 0 ? id : 0;
@@ -591,126 +574,18 @@ function immediateCommandOf(text) {
591
574
  return immediateKind(collapsed, rest);
592
575
  }
593
576
 
594
- /**
595
- * Turn model markdown into plain readable text.
596
- *
597
- * The bridge sends without `parse_mode`, so every `**bold**`, `### heading` and
598
- * `` `code` `` reached the person as literal punctuation — the chat looked
599
- * "filled with junk". Telegram formatting is opt-in per message and a bad
600
- * entity rejects the whole send, so the safe direction is to strip the markers
601
- * and keep the words.
602
- */
603
- export function toPlainText(input) {
604
- let text = String(input ?? '');
605
- // Fenced code blocks: keep the body, drop the fence and language tag.
606
- text = text.replace(/```[a-zA-Z0-9]*\n?/g, '').replace(/```/g, '');
607
- // Inline code and bold/italic/strike markers.
608
- text = text.replace(/`([^`]*)`/g, '$1');
609
- text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
610
- text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
611
- text = text.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1$2');
612
- text = text.replace(/__([^_]+)__/g, '$1');
613
- text = text.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1$2');
614
- text = text.replace(/~~([^~]+)~~/g, '$1');
615
- // Headings: "### Title" -> "Title".
616
- text = text.replace(/^\s{0,3}#{1,6}\s+/gm, '');
617
- // Links: [label](url) -> label (url); bare <url> stays as is.
618
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)');
619
- // Blockquote markers at line start.
620
- text = text.replace(/^\s{0,3}>\s?/gm, '');
621
- // Bullets keep a dash, but " - x" indentation is dropped to one level.
622
- text = text.replace(/^\s*[-*+]\s+/gm, '— ');
623
- // Tables: drop the separator row first (it is pure punctuation), then turn
624
- // the remaining rows into one line each with " · " between cells. The
625
- // separator pattern uses [ \t] rather than \s so it cannot eat the newline
626
- // and glue neighbouring rows together.
627
- text = text.replace(/^[ \t]*\|?[ \t:|-]*-[ \t:|-]*\|?[ \t]*$/gm, '');
628
- text = text.replace(/^[ \t]*\|(.+)\|[ \t]*$/gm, (_match, row) => row.split('|').map((cell) => cell.trim()).filter((cell) => cell !== '').join(' · '));
629
- // Collapse the blank runs the removals leave behind.
630
- text = text.replace(/\n{3,}/g, '\n\n').trim();
631
- return text;
632
- }
633
-
634
- /** Escape the four characters Telegram's HTML parser treats as markup. */
635
- function escapeHtml(value) {
636
- return String(value ?? '')
637
- .replace(/&/g, '&amp;')
638
- .replace(/</g, '&lt;')
639
- .replace(/>/g, '&gt;');
640
- }
641
-
642
- /** Inline markdown inside one non-code segment -> Telegram HTML. */
643
- function inlineHtml(segment) {
644
- let text = escapeHtml(segment);
645
- // Inline code first: its body must not be touched by the emphasis rules.
646
- text = text.replace(/`([^`\n]+)`/g, '<code>$1</code>');
647
- text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '<b><i>$1</i></b>');
648
- text = text.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>');
649
- text = text.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>');
650
- text = text.replace(/__([^_\n]+)__/g, '<b>$1</b>');
651
- text = text.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>');
652
- text = text.replace(/~~([^~\n]+)~~/g, '<s>$1</s>');
653
- // Headings become bold lines.
654
- text = text.replace(/^[ \t]{0,3}#{1,6}[ \t]+(.+)$/gm, '<b>$1</b>');
655
- // Links: [label](url) -> label (url), both already escaped.
656
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)');
657
- // Blockquote markers.
658
- text = text.replace(/^[ \t]{0,3}&gt;[ \t]?/gm, '');
659
- // Bullets.
660
- text = text.replace(/^[ \t]*[-*+][ \t]+/gm, '— ');
661
- // Tables: drop the separator row, then join cells with a middle dot.
662
- text = text.replace(/^[ \t]*\|?[ \t:|-]*-[ \t:|-]*\|?[ \t]*$/gm, '');
663
- text = text.replace(/^[ \t]*\|(.+)\|[ \t]*$/gm, (_m, row) => row.split('|').map((cell) => cell.trim()).filter(Boolean).join(' · '));
664
- return text;
665
- }
666
-
667
- /**
668
- * Markdown -> Telegram HTML with real <pre><code> blocks.
669
- *
670
- * A fenced block is what gives the person a tap-to-copy button in Telegram,
671
- * which is the whole point for shell commands. Everything else stays plain so
672
- * a malformed entity cannot reject the message: `send` falls back to stripped
673
- * text when Telegram refuses to parse.
674
- */
675
- export function toTelegramHtml(input) {
676
- const source = String(input ?? '');
677
- const parts = source.split(/```/);
678
- let out = '';
679
- parts.forEach((segment, index) => {
680
- if (index % 2 === 1) {
681
- // Odd indexes are fenced code. The first line may be a language tag.
682
- const newline = segment.indexOf('\n');
683
- const firstLine = newline === -1 ? '' : segment.slice(0, newline).trim();
684
- const isLanguage = /^[a-zA-Z0-9+#.-]{1,20}$/.test(firstLine);
685
- const body = isLanguage ? segment.slice(newline + 1) : segment;
686
- const language = isLanguage ? firstLine.toLowerCase() : '';
687
- const cls = language ? ` class="language-${language}"` : '';
688
- out += `<pre><code${cls}>${escapeHtml(body.replace(/\n+$/, ''))}</code></pre>`;
689
- } else {
690
- out += inlineHtml(segment);
691
- }
692
- });
693
- return out.replace(/\n{3,}/g, '\n\n').trim();
694
- }
695
-
696
- /**
697
- * Language of a (chat, topic) pair, for the few helpers that have no message to
698
- * read it from: `send` falls back to this for its empty-text placeholder, and
699
- * the callback handler uses it for button answers.
700
- */
701
- function langFor(chatId, threadId = 0) {
702
- return resolveLang(state, sessionKey(chatId, threadId), null, config);
703
- }
704
-
705
577
  async function send(chatId, text, threadId = 0, replyTo = 0) {
706
578
  // Who is reading: the topic's language decides even the fallback line, so an
707
579
  // English or Chinese topic never sees a Russian placeholder.
708
580
  const lang = langFor(chatId, threadId);
709
- const html = config.plainText === true ? '' : toTelegramHtml(text);
710
- const parts = html ? chunk(html, 3800) : chunk(toPlainText(text) || t(lang, 'bridge.progress.empty'));
581
+ const plain = config.plainText === true;
582
+ const parts = plain
583
+ ? chunk(toPlainText(text) || t(lang, 'bridge.progress.empty'), 3800)
584
+ : markdownParts(text);
711
585
  let lastId = 0;
712
586
  for (const part of parts) {
713
- const body = { chat_id: chatId, text: part, disable_web_page_preview: true };
587
+ const html = plain ? '' : toTelegramHtml(part);
588
+ const body = { chat_id: chatId, text: html || part, disable_web_page_preview: true };
714
589
  if (html) body.parse_mode = 'HTML';
715
590
  // Without message_thread_id every reply lands in the General topic, which is
716
591
  // the whole point of carrying the thread through.
@@ -720,15 +595,18 @@ async function send(chatId, text, threadId = 0, replyTo = 0) {
720
595
  try {
721
596
  res = await tg('sendMessage', body);
722
597
  } catch (error) {
723
- // Bad HTML (a stray < or an unsupported tag) must not swallow the reply:
724
- // resend the same part as plain text.
598
+ // The fallback must start from the markdown, not from the HTML: resending
599
+ // the markup as plain text is exactly how the person ends up reading
600
+ // `<b>` and `<code>` instead of a sentence.
725
601
  if (!html) throw error;
726
602
  log(`html send failed (${String(error.message).slice(0, 120)}); resending as plain text`);
727
603
  delete body.parse_mode;
728
- body.text = toPlainText(part) || t(lang, 'bridge.progress.empty');
729
- res = await tg('sendMessage', body);
604
+ for (const piece of chunk(toPlainText(part) || t(lang, 'bridge.progress.empty'), 3800)) {
605
+ body.text = piece;
606
+ res = await tg('sendMessage', body);
607
+ }
730
608
  }
731
- log(`sent chat=${chatId}${threadId ? ` topic=${threadId}` : ''} msg=${res.message_id} len=${part.length}${html ? ' html' : ''}`);
609
+ log(`sent chat=${chatId}${threadId ? ` topic=${threadId}` : ''} msg=${res.message_id} len=${body.text.length}${html ? ' html' : ''}`);
732
610
  lastId = res.message_id;
733
611
  }
734
612
  return lastId;
@@ -941,6 +819,7 @@ function killTurn(key) {
941
819
  */
942
820
  async function startProgress(chatId, threadId, lang = 'ru') {
943
821
  const started = Date.now();
822
+ const panelKey = sessionKey(chatId, threadId);
944
823
  const steps = [];
945
824
  const thinkingParts = [];
946
825
  /** Last reported token usage for this turn, for the cache line. */
@@ -993,6 +872,9 @@ async function startProgress(chatId, threadId, lang = 'ru') {
993
872
  steps,
994
873
  thoughts,
995
874
  thinking: thinkingParts.join('\n\n'),
875
+ // `/thoughts off` keeps the block out of the chat and leaves the counter;
876
+ // the log itself is a file the command sends on demand.
877
+ reasoning: state.thinkBlock?.[panelKey] === 'counter' ? 'counter' : 'block',
996
878
  cache,
997
879
  });
998
880
  };
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.3",
3
+ "version": "1.10.1",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/panel.mjs CHANGED
@@ -87,6 +87,9 @@ export function addStep(steps, line) {
87
87
  */
88
88
  export function progressPanel({
89
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',
90
93
  } = {}) {
91
94
  const head = final
92
95
  ? `✅ ${t(lang, 'status.done')} · ${seconds} ${secondsUnit(lang)}`
@@ -106,7 +109,9 @@ export function progressPanel({
106
109
  : steps.map((line) => `• ${line}`);
107
110
  const more = !final && many ? t(lang, 'status.more', { n: steps.length - 3 }) : '';
108
111
  const text = String(thinking || '').trim();
109
- const live = !final && text ? `🧠 ${t(lang, 'status.thinkTitle')} · ${text.length}` : '';
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}` : '');
110
115
  const stepsRoom = Math.max(0, Math.min(STEPS_MAX, PANEL_MAX - base - 1200));
111
116
  const all = many && final
112
117
  ? tailOf(steps.map((line) => `• ${line}`).join('\n'), stepsRoom)
@@ -114,13 +119,15 @@ export function progressPanel({
114
119
  const stepsLabel = `🛠 ${t(lang, 'status.stepsTitle')} · ${steps.length}`
115
120
  + `${all.cut ? ` · ${t(lang, 'status.thinkCut')}` : ''}`;
116
121
 
117
- const fixed = base + inline.join('\n').length + all.text.length + more.length + live.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;
118
125
  const room = Math.max(400, Math.min(THINKING_MAX, PANEL_MAX - fixed));
119
- const body = final ? tailOf(text, room) : { text: '', cut: false };
126
+ const body = final && reasoning === 'block' ? tailOf(text, room) : { text: '', cut: false };
120
127
  // A cut block starts mid-sentence; say so and point at the one command that
121
128
  // still has the whole text, otherwise the reasoning reads as broken.
122
129
  const thinkLabel = `🧠 ${t(lang, 'status.thinkTitle')}`
123
- + `${body.cut ? ` · ${t(lang, 'status.thinkCut')} · /thoughts` : ''}`;
130
+ + `${body.cut ? ` · ${t(lang, 'status.thinkCut')} · /thoughts file` : ''}`;
124
131
 
125
132
  const html = [
126
133
  head,
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')