telecoder 0.0.0-stage → 1.3.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.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,1067 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as os from 'os';
4
+ import * as crypto from 'crypto';
5
+ import { tablesToLists } from '../telegram/table-lists.js';
6
+ /** True if this record is the synthetic "API Error" stop record Claude Code writes when an in-flight request dies. */
7
+ function isApiErrorRecord(rec) {
8
+ return rec.isApiErrorMessage === true;
9
+ }
10
+ /**
11
+ * True if a user-role record carrying prose was injected by Claude Code rather
12
+ * than sent by the user — so it must not be treated as a turn boundary.
13
+ *
14
+ * The one that actually bites is `<task-notification>`: a background task
15
+ * (Bash `run_in_background`, a Task/Agent subagent, the post-push security
16
+ * review) finishing mid-turn writes a *user*-role record with real text in it.
17
+ * Boundary logic that only asks "is this a user record with prose?" then slices
18
+ * the turn at the notification and hands back nothing but the tail the model
19
+ * wrote after it — the whole answer above it is silently dropped. That is the
20
+ * "reply arrives truncated, /history shows the rest" bug, and it lands exactly
21
+ * where the user least wants it: long turns that ran background work.
22
+ *
23
+ * Denylist rather than `origin.kind === 'human'` allowlist on purpose. Records
24
+ * written by older Claude Code versions carry none of these fields, and an
25
+ * allowlist would classify every one of them as synthetic — leaving no
26
+ * boundary at all and degrading a working read into a screen-scrape fallback.
27
+ * Unknown shapes keep the old behaviour; only the known-synthetic ones move.
28
+ */
29
+ export function isSyntheticUserRecord(rec) {
30
+ return rec.origin?.kind === 'task-notification'
31
+ || rec.promptSource === 'system'
32
+ || rec.isMeta === true
33
+ || rec.isCompactSummary === true;
34
+ }
35
+ /**
36
+ * Whether a user-role record that isSyntheticUserRecord lets through holds a
37
+ * prompt, a slash command, or a note. Claude Code writes its record of a slash
38
+ * command, what one printed, and notes in the user's place like [Request
39
+ * interrupted by user] as plain user records, with none of the fields that
40
+ * flag the others, so the text is all there is to tell them by.
41
+ *
42
+ * Not folded into isSyntheticUserRecord: the end-of-turn read uses that to find
43
+ * the turn's prompt, and for a turn that ran /compact the command's records are
44
+ * that prompt — without them it would find the prompt before and hand back its
45
+ * reply again.
46
+ */
47
+ export function userTextKind(text) {
48
+ const t = text.trim();
49
+ // What a slash command printed, and a note written in the user's place.
50
+ if (/^<local-command-/.test(t) || /^\[[^\]]*\]$/.test(t))
51
+ return 'note';
52
+ // Claude Code's record of a slash command, and a command sent as the prompt:
53
+ // /compact, /model opus. A path is not one.
54
+ if (/^<(command-name|command-message)/.test(t) || /^\/[a-z][\w:-]*(\s|$)/i.test(t))
55
+ return 'command';
56
+ return 'prompt';
57
+ }
58
+ /** Build the path Claude Code uses to store a session's JSONL log. */
59
+ export function sessionJsonlPath(workingDirectory, sessionId) {
60
+ const encoded = workingDirectory.replace(/\//g, '-');
61
+ return path.join(os.homedir(), '.claude', 'projects', encoded, `${sessionId}.jsonl`);
62
+ }
63
+ /** True if Claude Code has an on-disk session log for `id` under `cwd`. */
64
+ export function claudeSessionFileExists(workingDirectory, sessionId) {
65
+ return fs.existsSync(sessionJsonlPath(workingDirectory, sessionId));
66
+ }
67
+ /**
68
+ * Mtime (ms since epoch) of the session's JSONL log, or 0 if it doesn't exist
69
+ * yet. Used by the pty provider as an end-of-turn signal — claude flushes a fresh
70
+ * record to the log for every assistant message, tool call, system event,
71
+ * compaction boundary, etc., so a moving mtime is reliable evidence that
72
+ * claude actually did work for the current prompt (the prior bullet-count
73
+ * heuristic broke on slash commands like /compact that don't emit a `●`).
74
+ */
75
+ export function sessionJsonlMtimeMs(workingDirectory, sessionId) {
76
+ try {
77
+ return fs.statSync(sessionJsonlPath(workingDirectory, sessionId)).mtimeMs;
78
+ }
79
+ catch {
80
+ return 0;
81
+ }
82
+ }
83
+ /** Size in bytes of the session's JSONL log, or 0 if it doesn't exist yet. */
84
+ export function sessionJsonlSize(workingDirectory, sessionId) {
85
+ try {
86
+ return fs.statSync(sessionJsonlPath(workingDirectory, sessionId)).size;
87
+ }
88
+ catch {
89
+ return 0;
90
+ }
91
+ }
92
+ /** What a slash command printed, as its records carry it. */
93
+ const LOCAL_COMMAND_OUTPUT = /<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>/g;
94
+ /** The colour codes a command's printed output can keep. */
95
+ const ANSI_SGR = /\x1b\[[0-9;]*m/g;
96
+ /** A markdown copy of a command's report opens with a heading: `## Context Usage`. */
97
+ const MARKDOWN_COPY = /^\s*#{1,6} /;
98
+ /**
99
+ * What a slash command answered with, from the records it appended to the log
100
+ * after `fromByte`, or undefined when it wrote nothing worth showing.
101
+ *
102
+ * A command that prompts the model (a custom command, a skill) is answered as
103
+ * a prompt is, and the model's prose is the reply. Most never reach the model.
104
+ * `/mcp` and the other menus print a line as they close — `Reconnected to
105
+ * sjs-dev.`, `MCP dialog dismissed` — and log it as `<local-command-stdout>`,
106
+ * on a user record or a system one depending on the line. Only the turn's own
107
+ * records are read, because the latest reply in the log is, for a command
108
+ * like that, the reply to whatever came before it.
109
+ *
110
+ * `/context` prints a drawing: a grid of ⛁ and ⛶ beside the legend, laid out
111
+ * for a terminal's fixed-width columns. Claude Code also logs the same report
112
+ * as markdown for the model, on a meta user record, and that copy is the
113
+ * answer instead, its tables as lists (see tablesToLists).
114
+ */
115
+ export function readCommandReply(workingDirectory, sessionId, fromByte) {
116
+ let log;
117
+ try {
118
+ log = fs.readFileSync(sessionJsonlPath(workingDirectory, sessionId));
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ // A log shorter than it was at submit was rewritten, and none of it is the turn's.
124
+ if (log.length < fromByte)
125
+ return undefined;
126
+ return commandReplyIn(log.subarray(fromByte).toString('utf-8'));
127
+ }
128
+ /** {@link readCommandReply} over a turn's records already in hand. */
129
+ export function commandReplyIn(raw) {
130
+ const prose = [];
131
+ const printed = [];
132
+ const markdownCopies = [];
133
+ for (const line of raw.split('\n')) {
134
+ if (!line.trim())
135
+ continue;
136
+ let rec;
137
+ try {
138
+ rec = JSON.parse(line);
139
+ }
140
+ catch {
141
+ continue;
142
+ }
143
+ if (rec.type === 'assistant') {
144
+ if (isApiErrorRecord(rec))
145
+ continue;
146
+ const text = extractText(rec.message?.content);
147
+ if (text)
148
+ prose.push(text);
149
+ }
150
+ else if (rec.type === 'user' || rec.type === 'system') {
151
+ const text = typeof rec.content === 'string' ? rec.content : extractText(rec.message?.content);
152
+ if (rec.type === 'user' && rec.isMeta === true && MARKDOWN_COPY.test(text)) {
153
+ markdownCopies.push(text.trim());
154
+ continue;
155
+ }
156
+ for (const match of text.matchAll(LOCAL_COMMAND_OUTPUT)) {
157
+ const out = match[2].replace(ANSI_SGR, '').trim();
158
+ if (out)
159
+ printed.push(out);
160
+ }
161
+ }
162
+ }
163
+ if (prose.length > 0)
164
+ return prose.join('\n\n');
165
+ // Only beside printed output: a custom command's expanded prompt is a meta
166
+ // record too, and can open with a heading, but prints nothing.
167
+ if (printed.length > 0 && markdownCopies.length > 0)
168
+ return markdownCopies.map(tablesToLists).join('\n\n');
169
+ return printed.length > 0 ? printed.join('\n') : undefined;
170
+ }
171
+ /**
172
+ * Read the most recent assistant-message usage block from a Claude Code session
173
+ * log. Returns undefined if the log doesn't exist or has no usage records.
174
+ *
175
+ * Claude writes the JSONL append-only with usage attached to each assistant
176
+ * message (`message.usage = {input_tokens, cache_read_input_tokens, ...}`).
177
+ * We scan newest-first to find the last usage block — that represents the
178
+ * cumulative token state after the last turn.
179
+ *
180
+ * A compaction after that block outdates it. `/compact` writes its boundary
181
+ * and summary with no usage on either, so the last block still sizes the
182
+ * conversation the summary replaced: the footer under "Context compacted —
183
+ * 536.4k → 13.7k tokens" read 54%, until the next reply put it right. The
184
+ * boundary's `postTokens` is the size of what's left, so it stands as the
185
+ * context until a reply reports one.
186
+ */
187
+ export function readLastUsageFromJsonl(workingDirectory, sessionId) {
188
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
189
+ if (!fs.existsSync(filePath))
190
+ return undefined;
191
+ const raw = fs.readFileSync(filePath, 'utf-8');
192
+ const lines = raw.split('\n');
193
+ let numTurns = 0;
194
+ let lastUsage;
195
+ // From the `api-request` record the CLI writes before each call: the effort
196
+ // and model that request went out with. /info shows the pair as what
197
+ // actually served the reply, with the reply's own model taking precedence.
198
+ let lastEffort = '';
199
+ let lastRequestModel = '';
200
+ for (const line of lines) {
201
+ if (!line)
202
+ continue;
203
+ let rec;
204
+ try {
205
+ rec = JSON.parse(line);
206
+ }
207
+ catch {
208
+ continue;
209
+ }
210
+ if (rec.type === 'user')
211
+ numTurns++;
212
+ if (rec.type === 'api-request') {
213
+ const params = rec.params;
214
+ const outputConfig = params?.output_config;
215
+ const effort = outputConfig?.effort ?? params?.effort;
216
+ if (typeof effort === 'string')
217
+ lastEffort = effort;
218
+ if (typeof params?.model === 'string')
219
+ lastRequestModel = params.model;
220
+ continue;
221
+ }
222
+ // Skip the synthetic API-error record: its usage is all zeros and would
223
+ // wipe out the legitimate cumulative totals from the real assistant turn
224
+ // that ran just before it.
225
+ if (isApiErrorRecord(rec))
226
+ continue;
227
+ const compaction = compactionInfo(rec);
228
+ if (compaction) {
229
+ // Older builds record no postTokens; the last block is all there is then.
230
+ if (compaction.postTokens > 0) {
231
+ lastUsage = {
232
+ // None of the summary is cached yet, so all of it counts as input.
233
+ inputTokens: compaction.postTokens,
234
+ outputTokens: 0,
235
+ cacheReadTokens: 0,
236
+ cacheWriteTokens: 0,
237
+ model: lastUsage?.model ?? '',
238
+ effort: '',
239
+ numTurns: 0,
240
+ };
241
+ }
242
+ continue;
243
+ }
244
+ const msg = rec.message;
245
+ const usage = msg?.usage;
246
+ if (!usage)
247
+ continue;
248
+ lastUsage = {
249
+ inputTokens: typeof usage.input_tokens === 'number' ? usage.input_tokens : 0,
250
+ outputTokens: typeof usage.output_tokens === 'number' ? usage.output_tokens : 0,
251
+ cacheReadTokens: typeof usage.cache_read_input_tokens === 'number' ? usage.cache_read_input_tokens : 0,
252
+ cacheWriteTokens: typeof usage.cache_creation_input_tokens === 'number' ? usage.cache_creation_input_tokens : 0,
253
+ model: typeof msg?.model === 'string' ? msg.model : '',
254
+ effort: '',
255
+ numTurns: 0, // filled in after the loop
256
+ };
257
+ }
258
+ if (!lastUsage)
259
+ return undefined;
260
+ lastUsage.numTurns = numTurns;
261
+ lastUsage.effort = lastEffort;
262
+ if (!lastUsage.model)
263
+ lastUsage.model = lastRequestModel;
264
+ return lastUsage;
265
+ }
266
+ /** First numeric value among `keys` on `obj`, or 0. Tolerates snake/camel drift. */
267
+ function numField(obj, ...keys) {
268
+ if (!obj)
269
+ return 0;
270
+ for (const k of keys) {
271
+ const v = obj[k];
272
+ if (typeof v === 'number')
273
+ return v;
274
+ }
275
+ return 0;
276
+ }
277
+ /** The compaction a `compact_boundary` record describes, or undefined for any other record. */
278
+ function compactionInfo(rec) {
279
+ if (rec.type !== 'system' || rec.subtype !== 'compact_boundary')
280
+ return undefined;
281
+ const meta = (rec.compactMetadata ?? rec.compact_metadata);
282
+ const ts = typeof rec.timestamp === 'string' ? Date.parse(rec.timestamp) : NaN;
283
+ return {
284
+ trigger: meta?.trigger === 'auto' ? 'auto' : 'manual',
285
+ preTokens: numField(meta, 'preTokens', 'pre_tokens'),
286
+ postTokens: numField(meta, 'postTokens', 'post_tokens'),
287
+ timestampMs: Number.isNaN(ts) ? 0 : ts,
288
+ };
289
+ }
290
+ /**
291
+ * Return the most recent `compact_boundary` record from a session log, or
292
+ * undefined if the log has none. Claude Code appends one of these whenever the
293
+ * context is compacted — manually (`/compact`) or automatically near the limit
294
+ * — but renders no `●` glyph for it, so screen scraping can't see that a
295
+ * compaction happened. Reading it back from the JSONL is how the provider
296
+ * knows to send the "Context Compacted" notice.
297
+ *
298
+ * On-disk shape (Claude Code 2.1.x):
299
+ * {"type":"system","subtype":"compact_boundary",
300
+ * "compactMetadata":{"trigger":"manual","preTokens":445116,"postTokens":15617,...},
301
+ * "timestamp":"2026-07-22T07:09:43.860Z"}
302
+ * Older builds used snake_case `compact_metadata`/`pre_tokens`; both are handled.
303
+ */
304
+ export function readLastCompactionFromJsonl(workingDirectory, sessionId) {
305
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
306
+ if (!fs.existsSync(filePath))
307
+ return undefined;
308
+ let raw;
309
+ try {
310
+ raw = fs.readFileSync(filePath, 'utf-8');
311
+ }
312
+ catch {
313
+ return undefined;
314
+ }
315
+ let last;
316
+ for (const line of raw.split('\n')) {
317
+ // Cheap pre-filter — these records are rare, skip the JSON.parse otherwise.
318
+ if (!line.includes('compact_boundary'))
319
+ continue;
320
+ let rec;
321
+ try {
322
+ rec = JSON.parse(line);
323
+ }
324
+ catch {
325
+ continue;
326
+ }
327
+ last = compactionInfo(rec) ?? last;
328
+ }
329
+ return last;
330
+ }
331
+ /** Pull joined text from a record's content blocks, ignoring tool/thinking blocks. */
332
+ export function extractText(content) {
333
+ if (typeof content === 'string')
334
+ return content.trim();
335
+ if (!Array.isArray(content))
336
+ return '';
337
+ return content
338
+ .filter((c) => c && c.type === 'text' && typeof c.text === 'string')
339
+ .map((c) => c.text.trim())
340
+ .filter((t) => t.length > 0)
341
+ .join('\n\n');
342
+ }
343
+ /**
344
+ * Return the joined text of every assistant content block emitted since the
345
+ * most recent `type:'user'` record. End-of-turn extraction uses this
346
+ * instead of scraping the xterm buffer because a single turn can produce
347
+ * multiple `●` text blocks interleaved with tool calls — screen-scrape only
348
+ * picks the last `●`, silently dropping the earlier blocks. Returns undefined
349
+ * if the log isn't on disk yet or has no assistant text since the last user
350
+ * record (caller should fall back to whatever signal it has).
351
+ */
352
+ export function readLastAssistantTurnText(workingDirectory, sessionId) {
353
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
354
+ if (!fs.existsSync(filePath))
355
+ return undefined;
356
+ return lastAssistantTurnText(fs.readFileSync(filePath, 'utf-8'));
357
+ }
358
+ /**
359
+ * {@link readLastAssistantTurnText} over a transcript already in hand rather
360
+ * than on disk — a branch's cut of one, which has no file until it is loaded.
361
+ */
362
+ export function lastAssistantTurnText(raw) {
363
+ // Walk forward; every real user prompt starts the collection over, so what
364
+ // is left at the end is the text of every assistant record after the last
365
+ // one. turnRecordIn decides which records count as which.
366
+ let texts;
367
+ for (const line of raw.split('\n')) {
368
+ const rec = turnRecordIn(line);
369
+ if (rec?.kind === 'prompt')
370
+ texts = [];
371
+ else if (rec?.kind === 'text')
372
+ texts?.push(rec.text);
373
+ }
374
+ if (!texts || texts.length === 0)
375
+ return undefined;
376
+ return texts.join('\n\n');
377
+ }
378
+ /**
379
+ * Classify one line of the log for {@link lastAssistantTurnText}: a real user
380
+ * prompt, which starts a turn, an assistant record carrying prose, or neither.
381
+ * Exported so the PTY stream (pty-stream.ts) reads a turn's records as they
382
+ * land by exactly the rules the end-of-turn read uses — the live message then
383
+ * converges on the final one rather than disagreeing with it.
384
+ *
385
+ * Crucial subtlety: `type:'user'` records aren't only user prompts — every
386
+ * tool_result is also delivered as a user-role record. If we treated each
387
+ * user record as a turn boundary we'd slice from the LAST tool_result,
388
+ * dropping all assistant text emitted earlier in the same turn. Requiring
389
+ * prose (extractText returns '' for tool_result-only records) isolates real
390
+ * prompts.
391
+ *
392
+ * Prose alone isn't enough to prove a record is a prompt, though: a
393
+ * background task reporting in writes a user-role record full of text.
394
+ * isSyntheticUserRecord keeps those from stealing the boundary.
395
+ *
396
+ * Synthetic API-error records carry the "API Error: ..." string as a plain
397
+ * text block — they are neither, so the error doesn't get joined into the
398
+ * assistant response shown to the user. The caller surfaces the error
399
+ * separately via readLastApiErrorFromJsonl.
400
+ */
401
+ export function turnRecordIn(line) {
402
+ if (!line.trim())
403
+ return undefined;
404
+ let rec;
405
+ try {
406
+ rec = JSON.parse(line);
407
+ }
408
+ catch {
409
+ return undefined;
410
+ }
411
+ if (rec.type !== 'user' && rec.type !== 'assistant')
412
+ return undefined;
413
+ if (isApiErrorRecord(rec))
414
+ return undefined;
415
+ // extractText filters out tool_use / tool_result / thinking blocks.
416
+ const text = extractText(rec.message?.content);
417
+ if (!text)
418
+ return undefined;
419
+ if (rec.type === 'assistant')
420
+ return { kind: 'text', text };
421
+ return isSyntheticUserRecord(rec) ? undefined : { kind: 'prompt' };
422
+ }
423
+ /**
424
+ * The shape of the last `count` conversation records, one line each, for a log
425
+ * line. Holds record and block types and never their text, because this ends up
426
+ * in the bot's logs and the text is the user's conversation.
427
+ */
428
+ export function describeLogTail(workingDirectory, sessionId, count) {
429
+ let raw;
430
+ try {
431
+ raw = fs.readFileSync(sessionJsonlPath(workingDirectory, sessionId), 'utf-8');
432
+ }
433
+ catch {
434
+ return [];
435
+ }
436
+ const described = [];
437
+ for (const line of raw.split('\n')) {
438
+ if (!line.trim())
439
+ continue;
440
+ let rec;
441
+ try {
442
+ rec = JSON.parse(line);
443
+ }
444
+ catch {
445
+ continue;
446
+ }
447
+ if (rec.type !== 'user' && rec.type !== 'assistant')
448
+ continue;
449
+ const content = rec.message?.content;
450
+ const blocks = Array.isArray(content)
451
+ ? content.map((block) => block?.type ?? 'unknown').join(',')
452
+ : 'string';
453
+ const flags = [
454
+ isSyntheticUserRecord(rec) ? 'synthetic' : '',
455
+ rec.origin?.kind ? `origin=${rec.origin.kind}` : '',
456
+ rec.isApiErrorMessage ? 'api-error' : '',
457
+ ].filter(Boolean).join(' ');
458
+ described.push(`${rec.timestamp ?? 'no-time'} ${rec.type} ${blocks}${flags ? ` ${flags}` : ''}`);
459
+ }
460
+ return described.slice(-count);
461
+ }
462
+ /**
463
+ * Identity of the last real user prompt in the log — the same turn boundary
464
+ * readLastAssistantTurnText slices from. Snapshotted just before a prompt is
465
+ * submitted so end-of-turn can tell "claude answered us" apart from "claude
466
+ * never received the prompt and the log still ends on the previous turn".
467
+ *
468
+ * That second case is not hypothetical: a pty respawned against a large session
469
+ * replays the whole transcript, and while it renders, the editor can swallow
470
+ * the Enter that submits our prompt. The log then still holds the *previous*
471
+ * turn, and reading assistant text out of it hands the user a stale answer as
472
+ * if it were a fresh one.
473
+ *
474
+ * tool_result records are user-role too, so real prompts are isolated the same
475
+ * way as above: by requiring non-empty prose after tool blocks are filtered,
476
+ * and by skipping the injected records isSyntheticUserRecord names. Without
477
+ * that second filter a background task finishing between submit and end-of-turn
478
+ * moves the marker on its own, and a prompt the editor swallowed reads as
479
+ * delivered.
480
+ */
481
+ export function readLastUserPromptMarker(workingDirectory, sessionId) {
482
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
483
+ if (!fs.existsSync(filePath))
484
+ return undefined;
485
+ let raw;
486
+ try {
487
+ raw = fs.readFileSync(filePath, 'utf-8');
488
+ }
489
+ catch {
490
+ return undefined;
491
+ }
492
+ let last;
493
+ for (const line of raw.split('\n')) {
494
+ if (!line.trim())
495
+ continue;
496
+ let rec;
497
+ try {
498
+ rec = JSON.parse(line);
499
+ }
500
+ catch {
501
+ continue;
502
+ }
503
+ if (rec.type !== 'user')
504
+ continue;
505
+ if (isSyntheticUserRecord(rec))
506
+ continue;
507
+ const text = extractText(rec.message?.content);
508
+ if (!text)
509
+ continue;
510
+ last = { id: rec.uuid ?? `${rec.timestamp ?? ''}|${text.slice(0, 120)}`, text };
511
+ }
512
+ return last;
513
+ }
514
+ /**
515
+ * If the most recent assistant record after the last user prompt is the
516
+ * synthetic API-error record (Claude Code's stop marker when its in-flight
517
+ * request died), return its text. Otherwise undefined.
518
+ *
519
+ * Used by the PTY provider to detect that the turn we just resolved actually
520
+ * ended in an API failure and to throw rather than silently returning whatever
521
+ * partial assistant text was streamed before the socket dropped.
522
+ */
523
+ export function readLastApiErrorFromJsonl(workingDirectory, sessionId) {
524
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
525
+ if (!fs.existsSync(filePath))
526
+ return undefined;
527
+ const raw = fs.readFileSync(filePath, 'utf-8');
528
+ const lines = raw.split('\n');
529
+ let lastPromptIdx = -1;
530
+ const records = [];
531
+ for (const line of lines) {
532
+ if (!line.trim())
533
+ continue;
534
+ let rec;
535
+ try {
536
+ rec = JSON.parse(line);
537
+ }
538
+ catch {
539
+ continue;
540
+ }
541
+ const role = rec.type === 'user' ? 'user' : rec.type === 'assistant' ? 'assistant' : null;
542
+ if (!role)
543
+ continue;
544
+ const text = extractText(rec.message?.content);
545
+ records.push({ role, apiError: isApiErrorRecord(rec), text });
546
+ if (role === 'user' && text.length > 0 && !isApiErrorRecord(rec) && !isSyntheticUserRecord(rec)) {
547
+ lastPromptIdx = records.length - 1;
548
+ }
549
+ }
550
+ if (lastPromptIdx === -1)
551
+ return undefined;
552
+ // Walk the post-prompt window newest-first: the FIRST assistant record we
553
+ // see going backwards is the "most recent assistant record". If that record
554
+ // is the API-error one, the turn ended with a failure.
555
+ for (let i = records.length - 1; i > lastPromptIdx; i--) {
556
+ if (records[i].role !== 'assistant')
557
+ continue;
558
+ if (records[i].apiError)
559
+ return records[i].text || 'API Error';
560
+ return undefined; // most recent assistant record is a real reply — no error
561
+ }
562
+ return undefined;
563
+ }
564
+ /**
565
+ * Read the most recent `type:'ai-title'` record's `aiTitle` field from the
566
+ * session log. Claude Code writes this as a session-level label (visible in
567
+ * its resume picker); empirically it locks in early and doesn't track topic
568
+ * shifts, so treat it as a session label, not a live focus tracker. Useful
569
+ * as a seed when our own topic state is empty (resume path, or Haiku failure
570
+ * with no prior topic).
571
+ */
572
+ export function readLastAiTitle(workingDirectory, sessionId) {
573
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
574
+ if (!fs.existsSync(filePath))
575
+ return undefined;
576
+ const raw = fs.readFileSync(filePath, 'utf-8');
577
+ const lines = raw.split('\n');
578
+ let lastTitle;
579
+ for (const line of lines) {
580
+ if (!line.trim())
581
+ continue;
582
+ // Cheap pre-filter — these records are dense, no point parsing every line.
583
+ if (!line.includes('"ai-title"'))
584
+ continue;
585
+ let rec;
586
+ try {
587
+ rec = JSON.parse(line);
588
+ }
589
+ catch {
590
+ continue;
591
+ }
592
+ if (rec.type !== 'ai-title')
593
+ continue;
594
+ const title = rec.aiTitle;
595
+ if (typeof title === 'string' && title.trim().length > 0) {
596
+ lastTitle = title.trim();
597
+ }
598
+ }
599
+ return lastTitle;
600
+ }
601
+ /**
602
+ * Rebuild the conversation as an alternating list of turns. Multiple
603
+ * consecutive records of the same role (e.g. assistant emits thinking + text in
604
+ * separate records) collapse into a single turn, so every user turn is followed
605
+ * by at most one assistant turn.
606
+ */
607
+ function readTurns(workingDirectory, sessionId) {
608
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
609
+ if (!fs.existsSync(filePath))
610
+ return [];
611
+ return turnsIn(fs.readFileSync(filePath, 'utf-8'));
612
+ }
613
+ /** {@link readTurns} over a transcript already in hand rather than on disk. */
614
+ function turnsIn(raw) {
615
+ const { records } = proseRecordsIn(raw);
616
+ const turns = [];
617
+ records.forEach((record, i) => {
618
+ // A command nothing answered — a /compact, a /login — isn't a turn of the
619
+ // conversation. Merged in, it would open the next prompt's turn. One that
620
+ // was answered, like a skill, stays: it's what the reply answers.
621
+ if (record.role === 'user' && userTextKind(record.text) === 'command' && records[i + 1]?.role !== 'assistant') {
622
+ return;
623
+ }
624
+ const last = turns[turns.length - 1];
625
+ if (last && last.role === record.role) {
626
+ last.text += '\n\n' + record.text;
627
+ }
628
+ else {
629
+ turns.push({ role: record.role, text: record.text, timestamp: record.timestamp });
630
+ }
631
+ });
632
+ return turns;
633
+ }
634
+ /** What a record that follows nothing is filed under, among the ids of the records others follow. */
635
+ const NO_PARENT = '';
636
+ /**
637
+ * Every record in a transcript that carries prose, each as a turn of its own:
638
+ * what the user sent and what the assistant wrote back, in order. With them,
639
+ * the line of the file's last record that has an id: where its conversation
640
+ * stands.
641
+ *
642
+ * Turns a `/rewind` took back are left out. Claude Code doesn't delete them:
643
+ * the log is append-only, so they stay in the file and the next prompt is
644
+ * written after them, following the record the rewound prompt followed. Two
645
+ * things the user sent that follow the same record are therefore one that
646
+ * replaced the other, and everything from the first up to the second is no
647
+ * longer the conversation. Read in file order, /history and /prompts showed
648
+ * turns Claude no longer has. A prompt stopped before it got any reply is
649
+ * replaced the same way, and for the same reason: Claude Code takes it back
650
+ * out of the conversation and hands it to the input box.
651
+ */
652
+ function proseRecordsIn(raw) {
653
+ const records = [];
654
+ let lastRecordLine = 0;
655
+ const lines = raw.split('\n');
656
+ for (let i = 0; i < lines.length; i++) {
657
+ const line = lines[i];
658
+ if (!line.trim())
659
+ continue;
660
+ let rec;
661
+ try {
662
+ rec = JSON.parse(line);
663
+ }
664
+ catch {
665
+ continue;
666
+ }
667
+ const cutBefore = lastRecordLine;
668
+ const uuid = typeof rec.uuid === 'string' ? rec.uuid : undefined;
669
+ if (uuid)
670
+ lastRecordLine = i + 1;
671
+ const role = rec.type === 'user' ? 'user' : rec.type === 'assistant' ? 'assistant' : null;
672
+ if (!role)
673
+ continue;
674
+ if (isApiErrorRecord(rec))
675
+ continue;
676
+ // Injected user-role records (a background task reporting in, a slash
677
+ // command's caveat wrapper) are not something the user said. Left in, they
678
+ // read as the user pasting XML and they split one reply into two
679
+ // exchanges, so the recap shows half an answer per entry.
680
+ if (role === 'user' && isSyntheticUserRecord(rec))
681
+ continue;
682
+ const text = extractText(rec.message?.content);
683
+ if (!text)
684
+ continue; // pure tool_result / tool_use / thinking — skip
685
+ // What a command printed, or a note written in the user's place, isn't
686
+ // something the user said either.
687
+ if (role === 'user' && userTextKind(text) === 'note')
688
+ continue;
689
+ // A conversation's first prompt follows nothing, and says so with a null.
690
+ // One sent after a rewind to before it follows nothing either.
691
+ const parentUuid = role !== 'user' ? undefined
692
+ : typeof rec.parentUuid === 'string' ? rec.parentUuid
693
+ : rec.parentUuid === null ? NO_PARENT : undefined;
694
+ const replaced = parentUuid === undefined ? -1 : records.findIndex((r) => r.parentUuid === parentUuid);
695
+ if (replaced === -1) {
696
+ records.push({ role, text, timestamp: rec.timestamp, uuid, parentUuid, line: i + 1, cutBefore });
697
+ continue;
698
+ }
699
+ // The exchange before the rewound stretch ends where that stretch began,
700
+ // not at the record above this one, which is the last of what was taken
701
+ // back. A branch cut there would end on it, and carry on from it.
702
+ const endsBefore = records[replaced].cutBefore;
703
+ records.length = replaced;
704
+ records.push({ role, text, timestamp: rec.timestamp, uuid, parentUuid, line: i + 1, cutBefore: endsBefore });
705
+ }
706
+ return { records, lastRecordLine };
707
+ }
708
+ /**
709
+ * Read the JSONL log for a session and return the last `n` user/assistant
710
+ * exchanges. Tool calls, tool results, and thinking blocks are skipped so the
711
+ * recap reads like a conversation transcript.
712
+ */
713
+ export function readRecentExchanges(workingDirectory, sessionId, n) {
714
+ return pairExchanges(readTurns(workingDirectory, sessionId)).slice(-n);
715
+ }
716
+ /**
717
+ * The last exchange of a transcript already in hand — a branch's, say — paired
718
+ * the way /history pairs them, so the two show the same thing.
719
+ */
720
+ export function lastExchangeIn(raw) {
721
+ return pairExchanges(turnsIn(raw)).at(-1);
722
+ }
723
+ function pairExchanges(turns) {
724
+ // Pair user → assistant exchanges. Skip an unpaired trailing user turn
725
+ // (in-flight question with no response yet).
726
+ const exchanges = [];
727
+ for (let i = 0; i < turns.length; i++) {
728
+ if (turns[i].role !== 'user')
729
+ continue;
730
+ const next = turns[i + 1];
731
+ if (!next || next.role !== 'assistant')
732
+ continue;
733
+ exchanges.push({ user: turns[i].text, assistant: next.text });
734
+ i++;
735
+ }
736
+ return exchanges;
737
+ }
738
+ /**
739
+ * Every prompt the user typed, oldest first.
740
+ *
741
+ * Unlike readRecentExchanges this keeps a trailing prompt that has no reply yet
742
+ * and flags it `pending`. "What did I just ask?" while a long turn is still
743
+ * running is the case /prompts exists for, so dropping the unanswered tail
744
+ * would answer every question but that one.
745
+ *
746
+ * Each record is a prompt of its own, not merged into a turn the way
747
+ * readRecentExchanges merges them: a prompt interrupted before any reply stays
748
+ * apart from the one after it, and stays pending. Commands are returned with
749
+ * the rest, even the ones nothing answered, like a /compact; which of them to
750
+ * show is for the caller to decide.
751
+ *
752
+ * A prompt's exchange ends where the next thing the user sent begins — a
753
+ * command as much as a prompt — so a branch cut after it leaves a /compact
754
+ * that came later out.
755
+ */
756
+ export function readUserPrompts(workingDirectory, sessionId) {
757
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
758
+ if (!fs.existsSync(filePath))
759
+ return [];
760
+ return userPromptsIn(fs.readFileSync(filePath, 'utf-8'));
761
+ }
762
+ /** {@link readUserPrompts} over a transcript already in hand rather than on disk. */
763
+ export function userPromptsIn(raw) {
764
+ const { records, lastRecordLine } = proseRecordsIn(raw);
765
+ const prompts = [];
766
+ // Walked from the end, so each prompt knows where the one after it begins.
767
+ let endLine = lastRecordLine;
768
+ for (let i = records.length - 1; i >= 0; i--) {
769
+ const record = records[i];
770
+ if (record.role !== 'user')
771
+ continue;
772
+ prompts.push({
773
+ text: record.text,
774
+ timestamp: record.timestamp,
775
+ pending: records[i + 1]?.role !== 'assistant',
776
+ uuid: record.uuid,
777
+ line: record.line,
778
+ endLine,
779
+ });
780
+ endLine = record.cutBefore;
781
+ }
782
+ return prompts.reverse();
783
+ }
784
+ /**
785
+ * True if the session log contains a thinking block whose `signature` looks
786
+ * fabricated rather than a genuine Anthropic signature. CCR mints placeholder
787
+ * signatures for DeepSeek's reasoning — a Unix-ms timestamp (e.g.
788
+ * "1780826242641") or an empty string — because DeepSeek has no signature
789
+ * concept. Genuine Anthropic signatures are long base64 blobs (60+ chars,
790
+ * mixed case with +//=). Replaying a fabricated one against the real Anthropic
791
+ * API trips `400 Invalid signature in thinking block`, so the agent uses this
792
+ * to fork a poisoned session instead of resuming it.
793
+ *
794
+ * Heuristic and cheap (a single regex sweep). Used only as a last-resort guard
795
+ * for sessions with no recorded owner provider (e.g. created before ownership
796
+ * tracking existed, or after a restart dropped the in-memory owner).
797
+ */
798
+ /**
799
+ * Classify a thinking-block `signature` value as fabricated (not from the real
800
+ * Anthropic API). CCR uses an empty string or a Unix-ms timestamp as a
801
+ * placeholder for DeepSeek's reasoning; genuine Anthropic signatures are long
802
+ * base64 blobs containing non-digit characters.
803
+ */
804
+ export function isForeignThinkingSignature(sig) {
805
+ return sig.length === 0 || /^\d+$/.test(sig);
806
+ }
807
+ export function hasForeignThinkingSignatures(workingDirectory, sessionId) {
808
+ const filePath = sessionJsonlPath(workingDirectory, sessionId);
809
+ if (!fs.existsSync(filePath))
810
+ return false;
811
+ let raw;
812
+ try {
813
+ raw = fs.readFileSync(filePath, 'utf-8');
814
+ }
815
+ catch {
816
+ return false;
817
+ }
818
+ const sigRe = /"signature"\s*:\s*"([^"]*)"/g;
819
+ let m;
820
+ while ((m = sigRe.exec(raw)) !== null) {
821
+ if (isForeignThinkingSignature(m[1]))
822
+ return true;
823
+ }
824
+ return false;
825
+ }
826
+ /**
827
+ * Which backend wrote a session, read off its transcript: 'ccr' when a reply
828
+ * came from a model that isn't Claude (CCR passes through DeepSeek's own name,
829
+ * `deepseek-flash`, whatever its router config calls the route) or carries a
830
+ * fabricated thinking signature; 'claude' when every reply is Claude's;
831
+ * undefined when there is no reply to tell by.
832
+ *
833
+ * For sessions TeleCoder didn't start, which have no recorded owner — one
834
+ * from a terminal, or from a bot that predates ownership tracking.
835
+ */
836
+ export function detectOwnerProvider(file) {
837
+ let raw;
838
+ try {
839
+ raw = fs.readFileSync(file, 'utf-8');
840
+ }
841
+ catch {
842
+ return undefined;
843
+ }
844
+ // Only replies count: a tool result can carry a `model` field of its own,
845
+ // naming whatever model the tool was asked about.
846
+ let sawClaude = false;
847
+ for (const line of raw.split('\n')) {
848
+ if (!line.includes('"assistant"'))
849
+ continue;
850
+ let rec;
851
+ try {
852
+ rec = JSON.parse(line);
853
+ }
854
+ catch {
855
+ continue;
856
+ }
857
+ if (rec.type !== 'assistant')
858
+ continue;
859
+ const model = rec.message?.model;
860
+ if (typeof model === 'string' && model !== '<synthetic>') {
861
+ if (!model.startsWith('claude-'))
862
+ return 'ccr';
863
+ sawClaude = true;
864
+ }
865
+ const content = rec.message?.content;
866
+ if (Array.isArray(content)) {
867
+ for (const block of content) {
868
+ if (block?.type === 'thinking' && typeof block.signature === 'string' && isForeignThinkingSignature(block.signature)) {
869
+ return 'ccr';
870
+ }
871
+ }
872
+ }
873
+ }
874
+ return sawClaude ? 'claude' : undefined;
875
+ }
876
+ /**
877
+ * A transcript with every record's `sessionId` set to `newSessionId`. Claude
878
+ * Code stamps the session's id into each record, and a resume can get
879
+ * confused when a copy's filename and contents disagree.
880
+ *
881
+ * A plain text replace of the one id the records carry, read from the first
882
+ * record that has one: parsing and re-serializing every record took half a
883
+ * second of the event loop on a 54 MB transcript, during which no chat on the
884
+ * bot got a reply, where this takes a few milliseconds and leaves every other
885
+ * byte as it was. The id is replaced wherever that exact field text occurs, so
886
+ * a tool result that quoted a record of the transcript changes too, which is
887
+ * harmless. A transcript whose records carry more than one id — none Claude
888
+ * Code writes, but a hand-merged file could — takes the record-by-record path.
889
+ */
890
+ export function rewriteJsonlSessionId(jsonl, newSessionId) {
891
+ if (!jsonl.trim())
892
+ return jsonl;
893
+ const oldSessionId = firstSessionId(jsonl);
894
+ if (oldSessionId !== undefined) {
895
+ const rewritten = oldSessionId === newSessionId
896
+ ? jsonl
897
+ : jsonl.split(`"sessionId":"${oldSessionId}"`).join(`"sessionId":"${newSessionId}"`);
898
+ const leftover = new RegExp(`"sessionId"\\s*:\\s*"(?!${escapeRegExp(newSessionId)}")`);
899
+ if (!leftover.test(rewritten))
900
+ return rewritten;
901
+ }
902
+ return rewriteJsonlSessionIdPerRecord(jsonl, newSessionId);
903
+ }
904
+ /** The `sessionId` of the first record that has one, or undefined. */
905
+ function firstSessionId(jsonl) {
906
+ let start = 0;
907
+ while (start < jsonl.length) {
908
+ let end = jsonl.indexOf('\n', start);
909
+ if (end === -1)
910
+ end = jsonl.length;
911
+ const line = jsonl.slice(start, end);
912
+ start = end + 1;
913
+ if (!line.includes('"sessionId"'))
914
+ continue;
915
+ try {
916
+ const rec = JSON.parse(line);
917
+ if (typeof rec.sessionId === 'string')
918
+ return rec.sessionId;
919
+ }
920
+ catch {
921
+ // Not a record; keep looking.
922
+ }
923
+ }
924
+ return undefined;
925
+ }
926
+ function escapeRegExp(s) {
927
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
928
+ }
929
+ /** rewriteJsonlSessionId, one record at a time: exact, and slow on a large transcript. */
930
+ function rewriteJsonlSessionIdPerRecord(jsonl, newSessionId) {
931
+ const lines = jsonl.split('\n');
932
+ const out = [];
933
+ for (const line of lines) {
934
+ if (!line) {
935
+ out.push(line);
936
+ continue;
937
+ }
938
+ try {
939
+ const rec = JSON.parse(line);
940
+ if (typeof rec.sessionId === 'string')
941
+ rec.sessionId = newSessionId;
942
+ out.push(JSON.stringify(rec));
943
+ }
944
+ catch {
945
+ // Pass through anything we can't parse — better than corrupting the file.
946
+ out.push(line);
947
+ }
948
+ }
949
+ return out.join('\n');
950
+ }
951
+ /**
952
+ * Whether a record closes a turn: the reply's last record, which Claude Code
953
+ * stamps `end_turn`, the error record a turn that died on its API call ends
954
+ * with, or the note an interrupted one leaves in the user's place.
955
+ */
956
+ function endsTurn(rec) {
957
+ if (rec.type === 'assistant') {
958
+ return rec.message?.stop_reason === 'end_turn' || isApiErrorRecord(rec);
959
+ }
960
+ return rec.type === 'user' && /^\[Request interrupted/.test(extractText(rec.message?.content).trim());
961
+ }
962
+ /**
963
+ * Whether the log has the end of the turn running in it: its last
964
+ * conversation record closes a turn (see endsTurn). Claude Code writes an
965
+ * assistant message's records only once the whole message is in, so while a
966
+ * reply is still being written the log ends on the prompt, or on the turn's
967
+ * last tool result. A log that can't be read answers true, since there is
968
+ * nothing in it to wait for.
969
+ */
970
+ export function readTurnEnded(workingDirectory, sessionId) {
971
+ let raw;
972
+ try {
973
+ raw = fs.readFileSync(sessionJsonlPath(workingDirectory, sessionId), 'utf-8');
974
+ }
975
+ catch {
976
+ return true;
977
+ }
978
+ return turnEndedIn(raw);
979
+ }
980
+ /** {@link readTurnEnded} over a transcript already in hand. */
981
+ export function turnEndedIn(raw) {
982
+ const lines = raw.split('\n');
983
+ for (let i = lines.length - 1; i >= 0; i--) {
984
+ if (!lines[i].trim())
985
+ continue;
986
+ let rec;
987
+ try {
988
+ rec = JSON.parse(lines[i]);
989
+ }
990
+ catch {
991
+ continue;
992
+ }
993
+ if (rec.type === 'user' || rec.type === 'assistant')
994
+ return endsTurn(rec);
995
+ }
996
+ return true;
997
+ }
998
+ /**
999
+ * A transcript whose last turn is still running, as a branch that leaves that
1000
+ * turn out but knows it's under way: everything up to the last turn that
1001
+ * ended, then what opened the running one (the prompt, or a background task
1002
+ * reporting back), then `note` as the reply to it.
1003
+ *
1004
+ * The running turn's own records stay out because half a turn doesn't resume:
1005
+ * a tool call with no result is one the API turns down. The prompt goes in as
1006
+ * its own record, copied whole, rather than quoted in the next message, so
1007
+ * however long it is nothing blurs it into what's sent next, and the branch
1008
+ * remembers it through a resume. The reply has no thinking block, since one
1009
+ * needs a signature only the API can make.
1010
+ *
1011
+ * Without anything on disk yet for the running turn, there's nothing to answer
1012
+ * with the note, and the branch is the transcript up to the last turn that ended.
1013
+ */
1014
+ export function branchPastRunningTurn(raw, note) {
1015
+ const lines = raw.split('\n').filter((line) => line.trim());
1016
+ const records = lines.map((line) => {
1017
+ try {
1018
+ return JSON.parse(line);
1019
+ }
1020
+ catch {
1021
+ return undefined;
1022
+ }
1023
+ });
1024
+ let cut = 0;
1025
+ records.forEach((rec, i) => { if (rec && endsTurn(rec))
1026
+ cut = i + 1; });
1027
+ // What opened the running turn: everything after the cut up to its first reply.
1028
+ let opened = records.findIndex((rec, i) => i >= cut && rec?.type === 'assistant');
1029
+ if (opened === -1)
1030
+ opened = records.length;
1031
+ const settled = lines.slice(0, cut);
1032
+ const opening = records.slice(cut, opened);
1033
+ const parent = [...opening].reverse().find((rec) => rec?.type === 'user' && typeof rec.uuid === 'string');
1034
+ if (!parent)
1035
+ return { jsonl: joinLines(settled), noted: false };
1036
+ // Shaped like a reply Claude Code wrote, from the last real one there is.
1037
+ const template = records.slice(0, cut).reverse().find((rec) => rec?.type === 'assistant' && !isApiErrorRecord(rec));
1038
+ const reply = {
1039
+ parentUuid: parent.uuid,
1040
+ isSidechain: false,
1041
+ userType: parent.userType ?? 'external',
1042
+ cwd: parent.cwd,
1043
+ sessionId: parent.sessionId,
1044
+ version: parent.version,
1045
+ gitBranch: parent.gitBranch,
1046
+ message: {
1047
+ id: `msg_${crypto.randomUUID().replace(/-/g, '')}`,
1048
+ type: 'message',
1049
+ role: 'assistant',
1050
+ model: template?.message?.model ?? 'claude',
1051
+ content: [{ type: 'text', text: note }],
1052
+ stop_reason: 'end_turn',
1053
+ stop_sequence: null,
1054
+ // The context as it stood before the running prompt, near enough for the
1055
+ // status line until the branch's first turn reports its own.
1056
+ usage: template?.message?.usage ?? { input_tokens: 0, output_tokens: 0 },
1057
+ },
1058
+ type: 'assistant',
1059
+ uuid: crypto.randomUUID(),
1060
+ timestamp: new Date().toISOString(),
1061
+ };
1062
+ return { jsonl: joinLines([...settled, ...lines.slice(cut, opened), JSON.stringify(reply)]), noted: true };
1063
+ }
1064
+ function joinLines(lines) {
1065
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
1066
+ }
1067
+ //# sourceMappingURL=session-jsonl.js.map