dsh-tg-bridge 1.19.3 → 1.19.5

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
@@ -32,7 +32,7 @@ a bot that answers, one step at a time.
32
32
 
33
33
  ## Requirements
34
34
 
35
- - Node.js ≥ 20
35
+ - Node.js ≥ 24 (the version DeepSeek Harness ships; sessions are zstd-compressed)
36
36
  - DeepSeek Harness `0.2.1-rc.2` or newer in the `0.2.x` line (`>=0.2.1-rc.2 <0.3.0`)
37
37
  - DeepSeek Harness installed (`~/.dsh/profiles/headless`)
38
38
  - A Telegram bot token from [@BotFather](https://t.me/BotFather)
@@ -69,7 +69,7 @@ can be listed next to them:
69
69
 
70
70
  One command: your bot token and your numeric id. Nothing to edit by hand.
71
71
 
72
- **Any platform with Node.js ≥ 20**
72
+ **Any platform with Node.js ≥ 24**
73
73
 
74
74
  ```bash
75
75
  npx dsh-tg-bridge@latest init --token 123456789:AA... --user 123456789
@@ -370,7 +370,7 @@ so a chatty research topic and a terse deploy topic can differ.
370
370
 
371
371
  The reasoning block itself is model output; `/thoughts` is what reads it back:
372
372
 
373
- - `/thoughts` — the last turn as a message, in parts, deleted after a few minutes;
373
+ - `/thoughts` — the last turn as a message, in parts, deleted after three minutes;
374
374
  - `/thoughts file` — the **whole** last turn as `reasoning-<date>-file.md`, sent as a document
375
375
  (a five-hour turn is tens of thousands of characters, which no chat message can hold);
376
376
  - `/thoughts all` — every turn of the session in one file (a long session is a couple of MB);
package/bridge.mjs CHANGED
@@ -865,6 +865,10 @@ async function runCommandFromButton(typed, { chatId, threadId, key }) {
865
865
  }),
866
866
  api: tg,
867
867
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
868
+ // A report meant to be read once (/thoughts) can ask for a message that
869
+ // removes itself. Without this the chat is told it will disappear while the
870
+ // message is a normal one — a promise nothing was keeping.
871
+ ephemeral: (out) => sendEphemeral(chatId, out, threadId),
868
872
  seedTopic: ensureTopicSeed,
869
873
  profile: profileOf(key),
870
874
  reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
package/control.mjs CHANGED
@@ -2297,13 +2297,14 @@ export async function handleControl(ctx) {
2297
2297
  }
2298
2298
  }
2299
2299
 
2300
+ const brief = ctx.ephemeral || ((out) => say(out));
2300
2301
  const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
2301
2302
  if (!text) {
2302
2303
  // Not every turn plans: a one-word answer has no reasoning part at all.
2303
2304
  // Saying "here is what the last turn answered" beats a dead end that
2304
2305
  // looks like a broken command.
2305
2306
  const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
2306
- say(answered
2307
+ brief(answered
2307
2308
  ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}\n\n${t(lang, 'ctrl.thoughts.hint')}`
2308
2309
  : `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.hint')}`);
2309
2310
  return true;
@@ -2316,7 +2317,7 @@ export async function handleControl(ctx) {
2316
2317
  parts.forEach((part, index) => {
2317
2318
  const last = index === parts.length - 1;
2318
2319
  const head = parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title;
2319
- say(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
2320
+ brief(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
2320
2321
  });
2321
2322
  return true;
2322
2323
  }
package/i18n.mjs CHANGED
@@ -447,7 +447,7 @@ const DICT = {
447
447
  'ctrl.logs.title': 'Log ({shown} of {total})',
448
448
  'ctrl.logs.fileCaption': 'bridge.log, {mb} MB — the whole file',
449
449
  'ctrl.logs.noFileChannel': 'This bridge build cannot send files; use /logs 200.',
450
- 'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
450
+ 'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, this message disappears in 3 minutes):',
451
451
  'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
452
452
  'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
453
453
  'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
@@ -1086,7 +1086,7 @@ const DICT = {
1086
1086
  'ctrl.logs.title': 'Лог ({shown} из {total})',
1087
1087
  'ctrl.logs.fileCaption': 'bridge.log, {mb} МБ — файл целиком',
1088
1088
  'ctrl.logs.noFileChannel': 'Эта сборка моста не умеет отправлять файлы; используй /logs 200.',
1089
- 'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
1089
+ 'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, сообщение исчезнет через 3 минуты):',
1090
1090
  'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
1091
1091
  'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
1092
1092
  'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
@@ -1725,7 +1725,7 @@ const DICT = {
1725
1725
  'ctrl.logs.title': '日志({shown}/{total})',
1726
1726
  'ctrl.logs.fileCaption': 'bridge.log,{mb} MB —— 完整文件',
1727
1727
  'ctrl.logs.noFileChannel': '这个桥接版本无法发送文件;请用 /logs 200。',
1728
- 'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
1728
+ 'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,本消息 3 分钟后自动消失):',
1729
1729
  'ctrl.thoughts.none': '上一轮没有保存推理过程。',
1730
1730
  'ctrl.thoughts.lastAnswer': '上一轮的回答:',
1731
1731
  'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.19.3",
3
+ "version": "1.19.5",
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",
@@ -18,7 +18,7 @@
18
18
  "hooks": "node install-hooks.mjs"
19
19
  },
20
20
  "engines": {
21
- "node": ">=20",
21
+ "node": ">=24",
22
22
  "dsh": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0"
23
23
  },
24
24
  "dsh": {
package/rewind.mjs CHANGED
@@ -18,7 +18,14 @@
18
18
  import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { dirname, join } from 'node:path';
21
- import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
21
+ import * as zlib from 'node:zlib';
22
+
23
+ // Session files are zstd frames. Node24 has the codec; anything older would fail
24
+ // here with a module error nobody can act on, so the failure names the fix.
25
+ const { zstdCompressSync, zstdDecompressSync } = zlib;
26
+ if (typeof zstdCompressSync !== 'function') {
27
+ throw new Error('dsh-tg-bridge needs Node 24 or newer: session files are zstd-compressed');
28
+ }
22
29
 
23
30
  const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
24
31
 
package/thoughts.mjs CHANGED
@@ -1,237 +1,244 @@
1
- // "What was the model thinking in the last turn?" — read straight from the
2
- // session log instead of keeping a copy in memory.
3
- //
4
- // A session is `<sessions>/<cwd>/<id>/session.v4.jsonl.zstd`: one zstd frame per
5
- // appended batch of records, and a `turn/start` record marks the beginning of a
6
- // turn. Walking the file backwards from the newest frame is enough to reach the
7
- // current turn, which keeps the command cheap on a 13 MB log with 16k frames.
8
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
9
- import { join } from 'node:path';
10
- import { zstdDecompressSync } from 'node:zlib';
11
-
12
- const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
13
-
14
- /** Every zstd frame start in `buf`, ascending. */
15
- function frameStarts(buf) {
16
- const starts = [];
17
- let at = 0;
18
- for (;;) {
19
- const found = buf.indexOf(MAGIC, at);
20
- if (found < 0) break;
21
- starts.push(found);
22
- at = found + MAGIC.length;
23
- }
24
- starts.push(buf.length);
25
- return starts;
26
- }
27
-
28
- /** Path of a session file, or '' when the id is unknown. */
29
- export function sessionFile(sessionsRoot, sessionId) {
30
- if (!sessionId) return '';
31
- let dirs = [];
32
- try {
33
- dirs = readdirSync(sessionsRoot, { withFileTypes: true }).filter((e) => e.isDirectory());
34
- } catch {
35
- return '';
36
- }
37
- for (const dir of dirs) {
38
- const direct = join(sessionsRoot, dir.name, sessionId, 'session.v4.jsonl.zstd');
39
- if (existsSync(direct)) return direct;
40
- }
41
- return '';
42
- }
43
-
44
- /**
45
- * Reasoning blocks of the last turn, oldest first. `maxChars` keeps the head of
46
- * the stream: that is where the plan and the first diagnosis are.
47
- *
48
- * Not every turn has reasoning to show: a one-word answer ("ok") carries a text
49
- * part and nothing else, and some models are not given a reasoning budget at all.
50
- * The caller distinguishes "no plan in this turn" from "no such session".
51
- */
52
- export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
53
- const blocks = lastTurnBlocks(file).filter((part) => part.type === 'reasoning' && part.text);
54
- const text = blocks.map((part) => part.text.trim()).join('\n\n').trim();
55
- return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
56
- }
57
-
58
- /** Every part of every assistant message of the last turn, in order. */
59
- function lastTurnBlocks(file) {
60
- if (!file || !existsSync(file)) return [];
61
- let buf;
62
- try {
63
- buf = readFileSync(file);
64
- } catch {
65
- return [];
66
- }
67
- const starts = frameStarts(buf);
68
- const lines = [];
69
- let reachedTurnStart = false;
70
- for (let i = starts.length - 2; i >= 0 && !reachedTurnStart; i--) {
71
- let text = '';
72
- try {
73
- text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
74
- } catch {
75
- continue;
76
- }
77
- const parts = text.split('\n').filter(Boolean);
78
- for (let j = parts.length - 1; j >= 0; j--) {
79
- lines.push(parts[j]);
80
- if (parts[j].includes('"type":"turn/start"')) {
81
- reachedTurnStart = true;
82
- break;
83
- }
84
- }
85
- }
86
- lines.reverse();
87
- const out = [];
88
- for (const line of lines) {
89
- let record;
90
- try {
91
- record = JSON.parse(line);
92
- } catch {
93
- continue;
94
- }
95
- if (record?.type !== 'assistant/message') continue;
96
- for (const part of record.data?.message?.content ?? []) out.push(part);
97
- }
98
- return out;
99
- }
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
-
177
- /** The last turn's own answer text — the fallback when it planned nothing. */
178
- export function lastTurnText(file, { maxChars = 1500 } = {}) { const text = lastTurnBlocks(file)
179
- .filter((part) => part.type === 'text' && part.text)
180
- .map((part) => part.text.trim())
181
- .join('\n\n')
182
- .trim();
183
- return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
184
- }
185
-
186
- /**
187
- * What a `/status` card wants to know about a session: when it started, when it
188
- * last did anything, which model answered, how big the context is now, and how
189
- * many tokens were billed over the session's whole life.
190
- *
191
- * `totalTokens` on an assistant message is the size of the prompt that turn sent
192
- * (input + cache read), i.e. the current context — not the lifetime total, which
193
- * is the sum over every call.
194
- */
195
- export function sessionStats(file) {
196
- const empty = { createdAt: 0, lastActivity: 0, model: '', contextTokens: 0, lifetimeTokens: 0, turns: 0 };
197
- if (!file || !existsSync(file)) return empty;
198
- let buf;
199
- try {
200
- buf = readFileSync(file);
201
- } catch {
202
- return empty;
203
- }
204
- const stats = { ...empty };
205
- const starts = frameStarts(buf);
206
- for (let i = 0; i < starts.length - 1; i++) {
207
- let text = '';
208
- try {
209
- text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
210
- } catch {
211
- continue;
212
- }
213
- for (const line of text.split('\n')) {
214
- if (!line) continue;
215
- let record;
216
- try {
217
- record = JSON.parse(line);
218
- } catch {
219
- continue;
220
- }
221
- if (record.type === 'session' && record.createdAt) stats.createdAt = record.createdAt;
222
- if (record.type === 'turn/start') stats.turns += 1;
223
- if (record.time) stats.lastActivity = Math.max(stats.lastActivity, record.time);
224
- if (record.type !== 'assistant/message') continue;
225
- const usage = record.data?.usage;
226
- if (usage) {
227
- if (Number.isFinite(usage.totalTokens)) stats.contextTokens = usage.totalTokens;
228
- const billed = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) + (usage.cacheReadTokens ?? 0);
229
- stats.lifetimeTokens += billed;
230
- }
231
- if (!stats.model && record.data?.message?.model) stats.model = record.data.message.model;
232
- }
233
- }
234
- return stats;
235
- }
236
-
237
- export { frameStarts };
1
+ // "What was the model thinking in the last turn?" — read straight from the
2
+ // session log instead of keeping a copy in memory.
3
+ //
4
+ // A session is `<sessions>/<cwd>/<id>/session.v4.jsonl.zstd`: one zstd frame per
5
+ // appended batch of records, and a `turn/start` record marks the beginning of a
6
+ // turn. Walking the file backwards from the newest frame is enough to reach the
7
+ // current turn, which keeps the command cheap on a 13 MB log with 16k frames.
8
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import * as zlib from 'node:zlib';
11
+
12
+ // Session files are zstd frames. Node24 has the codec; anything older would fail
13
+ // here with a module error nobody can act on, so the failure names the fix.
14
+ const { zstdDecompressSync } = zlib;
15
+ if (typeof zstdDecompressSync !== 'function') {
16
+ throw new Error('dsh-tg-bridge needs Node 24 or newer: session files are zstd-compressed');
17
+ }
18
+
19
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
20
+
21
+ /** Every zstd frame start in `buf`, ascending. */
22
+ function frameStarts(buf) {
23
+ const starts = [];
24
+ let at = 0;
25
+ for (;;) {
26
+ const found = buf.indexOf(MAGIC, at);
27
+ if (found < 0) break;
28
+ starts.push(found);
29
+ at = found + MAGIC.length;
30
+ }
31
+ starts.push(buf.length);
32
+ return starts;
33
+ }
34
+
35
+ /** Path of a session file, or '' when the id is unknown. */
36
+ export function sessionFile(sessionsRoot, sessionId) {
37
+ if (!sessionId) return '';
38
+ let dirs = [];
39
+ try {
40
+ dirs = readdirSync(sessionsRoot, { withFileTypes: true }).filter((e) => e.isDirectory());
41
+ } catch {
42
+ return '';
43
+ }
44
+ for (const dir of dirs) {
45
+ const direct = join(sessionsRoot, dir.name, sessionId, 'session.v4.jsonl.zstd');
46
+ if (existsSync(direct)) return direct;
47
+ }
48
+ return '';
49
+ }
50
+
51
+ /**
52
+ * Reasoning blocks of the last turn, oldest first. `maxChars` keeps the head of
53
+ * the stream: that is where the plan and the first diagnosis are.
54
+ *
55
+ * Not every turn has reasoning to show: a one-word answer ("ok") carries a text
56
+ * part and nothing else, and some models are not given a reasoning budget at all.
57
+ * The caller distinguishes "no plan in this turn" from "no such session".
58
+ */
59
+ export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
60
+ const blocks = lastTurnBlocks(file).filter((part) => part.type === 'reasoning' && part.text);
61
+ const text = blocks.map((part) => part.text.trim()).join('\n\n').trim();
62
+ return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
63
+ }
64
+
65
+ /** Every part of every assistant message of the last turn, in order. */
66
+ function lastTurnBlocks(file) {
67
+ if (!file || !existsSync(file)) return [];
68
+ let buf;
69
+ try {
70
+ buf = readFileSync(file);
71
+ } catch {
72
+ return [];
73
+ }
74
+ const starts = frameStarts(buf);
75
+ const lines = [];
76
+ let reachedTurnStart = false;
77
+ for (let i = starts.length - 2; i >= 0 && !reachedTurnStart; i--) {
78
+ let text = '';
79
+ try {
80
+ text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
81
+ } catch {
82
+ continue;
83
+ }
84
+ const parts = text.split('\n').filter(Boolean);
85
+ for (let j = parts.length - 1; j >= 0; j--) {
86
+ lines.push(parts[j]);
87
+ if (parts[j].includes('"type":"turn/start"')) {
88
+ reachedTurnStart = true;
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ lines.reverse();
94
+ const out = [];
95
+ for (const line of lines) {
96
+ let record;
97
+ try {
98
+ record = JSON.parse(line);
99
+ } catch {
100
+ continue;
101
+ }
102
+ if (record?.type !== 'assistant/message') continue;
103
+ for (const part of record.data?.message?.content ?? []) out.push(part);
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * The last turn's reasoning, complete, one entry per committed assistant step.
110
+ * Chat text is capped (a five-hour turn would not fit any message); a file has
111
+ * no such problem, so this keeps everything.
112
+ */
113
+ export function lastTurnReasoningSteps(file) {
114
+ return lastTurnBlocks(file)
115
+ .filter((part) => part.type === 'reasoning' && part.text && part.text.trim())
116
+ .map((part) => part.text.trim());
117
+ }
118
+
119
+ /** Reasoning of every turn of the session, oldest first: `[{ steps: [...] }]`. */
120
+ export function sessionReasoningSteps(file) {
121
+ if (!file || !existsSync(file)) return [];
122
+ let buf;
123
+ try {
124
+ buf = readFileSync(file);
125
+ } catch {
126
+ return [];
127
+ }
128
+ const starts = frameStarts(buf);
129
+ const turns = [];
130
+ let current = null;
131
+ for (let i = 0; i < starts.length - 1; i++) {
132
+ let text = '';
133
+ try {
134
+ text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
135
+ } catch {
136
+ continue;
137
+ }
138
+ for (const line of text.split('\n')) {
139
+ if (!line) continue;
140
+ let record;
141
+ try {
142
+ record = JSON.parse(line);
143
+ } catch {
144
+ continue;
145
+ }
146
+ if (record.type === 'turn/start') {
147
+ current = { steps: [] };
148
+ turns.push(current);
149
+ continue;
150
+ }
151
+ if (record.type !== 'assistant/message') continue;
152
+ if (!current) {
153
+ current = { steps: [] };
154
+ turns.push(current);
155
+ }
156
+ for (const part of record.data?.message?.content ?? []) {
157
+ if (part.type === 'reasoning' && part.text && part.text.trim()) current.steps.push(part.text.trim());
158
+ }
159
+ }
160
+ }
161
+ return turns;
162
+ }
163
+
164
+ /**
165
+ * A reasoning log as a file someone can open in an editor: a header with the
166
+ * facts, then one section per step. Plain Markdown, because every editor and
167
+ * Telegram's own preview render it.
168
+ */
169
+ export function reasoningMarkdown({ title, meta = [], stepTitle = 'Step', turns = [] }) {
170
+ const lines = [`# ${title}`, ''];
171
+ for (const line of meta) lines.push(`- ${line}`);
172
+ lines.push('');
173
+ const manyTurns = turns.length > 1;
174
+ turns.forEach((turn, turnIndex) => {
175
+ if (!turn.steps.length) return;
176
+ if (manyTurns) lines.push(`## ${turn.title || `${stepTitle} ${turnIndex + 1}`}`, '');
177
+ turn.steps.forEach((step, index) => {
178
+ lines.push(`### ${stepTitle} ${index + 1}`, '', step, '');
179
+ });
180
+ });
181
+ return `${lines.join('\n').trim()}\n`;
182
+ }
183
+
184
+ /** The last turn's own answer text — the fallback when it planned nothing. */
185
+ export function lastTurnText(file, { maxChars = 1500 } = {}) { const text = lastTurnBlocks(file)
186
+ .filter((part) => part.type === 'text' && part.text)
187
+ .map((part) => part.text.trim())
188
+ .join('\n\n')
189
+ .trim();
190
+ return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
191
+ }
192
+
193
+ /**
194
+ * What a `/status` card wants to know about a session: when it started, when it
195
+ * last did anything, which model answered, how big the context is now, and how
196
+ * many tokens were billed over the session's whole life.
197
+ *
198
+ * `totalTokens` on an assistant message is the size of the prompt that turn sent
199
+ * (input + cache read), i.e. the current context — not the lifetime total, which
200
+ * is the sum over every call.
201
+ */
202
+ export function sessionStats(file) {
203
+ const empty = { createdAt: 0, lastActivity: 0, model: '', contextTokens: 0, lifetimeTokens: 0, turns: 0 };
204
+ if (!file || !existsSync(file)) return empty;
205
+ let buf;
206
+ try {
207
+ buf = readFileSync(file);
208
+ } catch {
209
+ return empty;
210
+ }
211
+ const stats = { ...empty };
212
+ const starts = frameStarts(buf);
213
+ for (let i = 0; i < starts.length - 1; i++) {
214
+ let text = '';
215
+ try {
216
+ text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
217
+ } catch {
218
+ continue;
219
+ }
220
+ for (const line of text.split('\n')) {
221
+ if (!line) continue;
222
+ let record;
223
+ try {
224
+ record = JSON.parse(line);
225
+ } catch {
226
+ continue;
227
+ }
228
+ if (record.type === 'session' && record.createdAt) stats.createdAt = record.createdAt;
229
+ if (record.type === 'turn/start') stats.turns += 1;
230
+ if (record.time) stats.lastActivity = Math.max(stats.lastActivity, record.time);
231
+ if (record.type !== 'assistant/message') continue;
232
+ const usage = record.data?.usage;
233
+ if (usage) {
234
+ if (Number.isFinite(usage.totalTokens)) stats.contextTokens = usage.totalTokens;
235
+ const billed = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) + (usage.cacheReadTokens ?? 0);
236
+ stats.lifetimeTokens += billed;
237
+ }
238
+ if (!stats.model && record.data?.message?.model) stats.model = record.data.message.model;
239
+ }
240
+ }
241
+ return stats;
242
+ }
243
+
244
+ export { frameStarts };