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