@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10

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 (170) hide show
  1. package/README.md +52 -22
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
  8. package/build/backend-worker.mjs +69 -122
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +188 -25
  13. package/dist/backend/claude/subagents.js +41 -9
  14. package/dist/backend/claude/todo-list.js +114 -0
  15. package/dist/backend/claude/workflow-parent.js +1 -1
  16. package/dist/backend/diff-excerpt-instructions.js +8 -0
  17. package/dist/backend/fake/index.js +54 -6
  18. package/dist/backend/mcp.js +4 -1
  19. package/dist/backend/pi/agent-permissions.js +1 -1
  20. package/dist/backend/pi/cache-warming.js +8 -0
  21. package/dist/backend/pi/canonical-json.js +120 -0
  22. package/dist/backend/pi/compaction-model.js +3 -2
  23. package/dist/backend/pi/host-auth.js +258 -0
  24. package/dist/backend/pi/import.js +269 -0
  25. package/dist/backend/pi/index.js +118 -20
  26. package/dist/backend/pi/model-auth.js +159 -0
  27. package/dist/backend/pi/model-catalog.js +120 -0
  28. package/dist/backend/pi/model-config.js +5 -0
  29. package/dist/backend/pi/model-selection.js +32 -0
  30. package/dist/backend/pi/plan-limits.js +41 -0
  31. package/dist/backend/pi/state.js +19 -1
  32. package/dist/backend/pi/subagents.js +7 -3
  33. package/dist/backend/pi/todo-list.js +23 -0
  34. package/dist/backend/pi/work.js +9 -1
  35. package/dist/backend/pi/workflow-parent.js +1 -1
  36. package/dist/backend/pi/workflow-subagent.js +4 -3
  37. package/dist/backend/plan-limits.js +17 -0
  38. package/dist/backend/session-tools.js +1 -1
  39. package/dist/backend/worker/claude-state.js +48 -0
  40. package/dist/backend/worker/entry.js +42 -8
  41. package/dist/backend/worker/index.js +131 -15
  42. package/dist/backend/worker/launcher.js +11 -4
  43. package/dist/backend/worker/protocol.js +2 -1
  44. package/dist/backend/worker/rpc.js +13 -0
  45. package/dist/backend/worker/sandbox-mcp.js +18 -7
  46. package/dist/backend/workflow-tools.js +9 -7
  47. package/dist/build-id +1 -1
  48. package/dist/cli/application.js +48 -42
  49. package/dist/cli/bootstrap.js +2 -2
  50. package/dist/cli/host-control.js +1 -1
  51. package/dist/cli/install-guard.js +2 -2
  52. package/dist/cli/main.js +4 -4
  53. package/dist/cli/systemd-update.js +3 -3
  54. package/dist/cli/update.js +6 -6
  55. package/dist/cli/web-update.js +6 -6
  56. package/dist/client/connection.js +46 -0
  57. package/dist/client/context-usage.js +3 -4
  58. package/dist/client/diff.js +40 -0
  59. package/dist/client/enquiry.js +0 -6
  60. package/dist/client/markdown.js +3 -2
  61. package/dist/client/model-choices.js +1 -1
  62. package/dist/client/permission.js +1 -2
  63. package/dist/client/project-name.js +3 -1
  64. package/dist/client/reduce.js +77 -3
  65. package/dist/client/relative-time.js +1 -1
  66. package/dist/client/scope-kind.js +6 -3
  67. package/dist/client/search.js +1 -1
  68. package/dist/client/status.js +1 -1
  69. package/dist/client/subagent-tree.js +49 -0
  70. package/dist/client/tool-chains.js +1 -1
  71. package/dist/client/tool-summary.js +28 -18
  72. package/dist/daemon/changes.js +128 -0
  73. package/dist/daemon/commit.js +84 -0
  74. package/dist/daemon/config-store.js +8 -3
  75. package/dist/daemon/config.js +105 -4
  76. package/dist/daemon/diff-excerpts.js +52 -0
  77. package/dist/daemon/git-state.js +197 -0
  78. package/dist/daemon/git.js +53 -10
  79. package/dist/daemon/github-image.js +18 -0
  80. package/dist/daemon/github.js +54 -0
  81. package/dist/daemon/host-control-routes.js +1 -1
  82. package/dist/daemon/host.js +940 -119
  83. package/dist/daemon/http.js +4 -1
  84. package/dist/daemon/log.js +3 -0
  85. package/dist/daemon/mcp-auth.js +1 -1
  86. package/dist/daemon/models.js +2 -2
  87. package/dist/daemon/pi-model-cache.js +44 -0
  88. package/dist/daemon/pull-request.js +223 -138
  89. package/dist/daemon/push.js +43 -0
  90. package/dist/daemon/repository.js +123 -0
  91. package/dist/daemon/runtime.js +103 -22
  92. package/dist/daemon/secret-store.js +1 -1
  93. package/dist/daemon/server.js +111 -14
  94. package/dist/daemon/skills.js +24 -0
  95. package/dist/daemon/spend-ledger.js +118 -0
  96. package/dist/daemon/stack-metadata.js +12 -5
  97. package/dist/daemon/stack.js +162 -657
  98. package/dist/daemon/store.js +2 -0
  99. package/dist/daemon/summariser.js +30 -12
  100. package/dist/daemon/tour.js +56 -0
  101. package/dist/daemon/whisper.js +144 -0
  102. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  103. package/dist/daemon/workflow-authoring-scope.js +1 -1
  104. package/dist/daemon/workflow-builder-files.js +2 -2
  105. package/dist/daemon/workflow-builder-guidance.js +1 -1
  106. package/dist/daemon/workflow-builder-routes.js +2 -2
  107. package/dist/daemon/workflow-builder.js +44 -17
  108. package/dist/daemon/workflow-environment.js +193 -0
  109. package/dist/daemon/workflow-execution-launch.js +77 -0
  110. package/dist/daemon/workflow-execution-resources.js +76 -0
  111. package/dist/daemon/workflow-execution-routes.js +12 -9
  112. package/dist/daemon/workflow-execution-values.js +128 -0
  113. package/dist/daemon/workflow-executions.js +400 -311
  114. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  115. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  116. package/dist/daemon/workflow-mcp.js +1 -1
  117. package/dist/daemon/workflow-routes.js +60 -2
  118. package/dist/daemon/workflow-schedule-driver.js +251 -0
  119. package/dist/daemon/workflow-schedule-routes.js +137 -0
  120. package/dist/daemon/workflow-schedules.js +342 -0
  121. package/dist/isolation/filesystem.js +6 -2
  122. package/dist/isolation/sandbox.js +61 -18
  123. package/dist/isolation/shared-sandbox.js +3 -3
  124. package/dist/isolation/toolchain-assets.js +1 -1
  125. package/dist/protocol/events.js +3 -0
  126. package/dist/protocol/plan-limits.js +1 -0
  127. package/dist/protocol/settings.js +1 -0
  128. package/dist/protocol/spend.js +2 -0
  129. package/dist/protocol/stack.js +12 -39
  130. package/dist/protocol/workflow-schedules.js +1 -0
  131. package/dist/workflows/calls.js +53 -0
  132. package/dist/workflows/errors.js +2 -0
  133. package/dist/workflows/executors.js +6 -5
  134. package/dist/workflows/graph.js +83 -9
  135. package/dist/workflows/invocations.js +23 -0
  136. package/dist/workflows/mcp.js +1 -1
  137. package/dist/workflows/owner.js +45 -0
  138. package/dist/workflows/records.js +127 -11
  139. package/dist/workflows/recovery.js +38 -2
  140. package/dist/workflows/runtime-settings.js +16 -16
  141. package/dist/workflows/runtime.js +2 -2
  142. package/dist/workflows/schedule-errors.js +2 -0
  143. package/dist/workflows/schedule-store.js +385 -0
  144. package/dist/workflows/scheduler.js +367 -96
  145. package/dist/workflows/schedules.js +130 -0
  146. package/dist/workflows/schema.js +3 -1
  147. package/dist/workflows/store.js +126 -13
  148. package/package.json +10 -6
  149. package/web/dist/assets/index-C76t-z4w.css +2 -0
  150. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  151. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  152. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  153. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  154. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  155. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  156. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  157. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  158. package/web/dist/index.html +6 -5
  159. package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
  160. package/dist/daemon/publish.js +0 -289
  161. package/dist/tui/app.js +0 -612
  162. package/dist/tui/keys.js +0 -90
  163. package/dist/tui/render.js +0 -411
  164. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  165. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  166. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  167. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  168. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  169. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  170. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -0,0 +1,415 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { projectKey } from "../worker/claude-state.js";
6
+ import { TODO_TOOLS, TodoList } from "./todo-list.js";
7
+ /**
8
+ * Reading Claude Code's own conversation records, for Import (ADR 0047).
9
+ *
10
+ * Claude Code writes one JSONL file per conversation under `<config>/projects/<scope key>/`, keyed
11
+ * by the directory it was started in. That key is the same one Flow's Claude records use
12
+ * (`projectKey`), which is what makes a Scope the natural unit to list by: what is listed here is
13
+ * exactly what a Revive in that Scope could continue.
14
+ *
15
+ * The format is Claude Code's, undocumented, and grows a record type most releases. So this reads
16
+ * leniently in the manner of `TranscriptStore.readEntries` — an unparseable line is skipped, an
17
+ * unknown record type is ignored — and only the handful of shapes below are interpreted at all.
18
+ * Everything else in the file (request blobs, file-history snapshots, permission-mode markers) is
19
+ * the CLI's bookkeeping, and the Presentation Transcript is what a human saw rather than that.
20
+ *
21
+ * Records are taken in file order, not by walking `parentUuid` from the leaf. The walk looks like
22
+ * the faithful choice, since it is how the CLI rebuilds a conversation after a rewind — but the
23
+ * results of parallel tool calls hang off sibling branches of that tree, and a walk silently drops
24
+ * them. Showing an abandoned rewind branch is a smaller lie than a tool call with no result.
25
+ */
26
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
27
+ /** The longest title taken from a first prompt, matching the length a rail row can show. */
28
+ const TITLE_LENGTH = 80;
29
+ /** Claude Code's config root, resolved the way the CLI and `migrateLegacyClaudeState` resolve it. */
30
+ export function claudeConfigDir(env, scope) {
31
+ return resolve(scope, env.CLAUDE_CONFIG_DIR || join(env.HOME ?? homedir(), ".claude"));
32
+ }
33
+ /** Where Claude Code keeps the conversations it started in `scope`. */
34
+ export function conversationsDir(env, scope) {
35
+ return join(claudeConfigDir(env, scope), "projects", projectKey(scope));
36
+ }
37
+ /**
38
+ * Every conversation Claude Code recorded in `scope`, newest first. Empty when it recorded none.
39
+ *
40
+ * A conversation with no human prompt in it is left out: Claude Code writes a file for a session
41
+ * that was opened and closed again, and offering an empty transcript to import is offering nothing.
42
+ *
43
+ * Read asynchronously and only skimmed, because this runs on the Session Host's one thread every
44
+ * time the picker opens. A Scope's files run to a hundred megabytes, nearly all of it request
45
+ * blobs, replies and tool output; parsing all that stalled every live Agent Session's stream for
46
+ * over a second. A listing needs only titles, prompts and times, so only those lines are parsed.
47
+ */
48
+ export async function listClaudeCodeConversations(env, scope) {
49
+ const dir = conversationsDir(env, scope);
50
+ let names;
51
+ try {
52
+ names = await readdir(dir);
53
+ }
54
+ catch {
55
+ return [];
56
+ }
57
+ const conversations = [];
58
+ for (const name of names) {
59
+ const id = name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) : "";
60
+ if (!UUID.test(id))
61
+ continue;
62
+ let raw;
63
+ try {
64
+ raw = await readFile(join(dir, name), "utf8");
65
+ }
66
+ catch {
67
+ // Unreadable, or too large to hold as one string: either way not something to offer.
68
+ continue;
69
+ }
70
+ const skimmed = translate(parse(raw, worthListing), mtimeOf(join(dir, name)), () => undefined);
71
+ const prompts = skimmed.events.filter(({ event }) => event.type === "turn_started").length;
72
+ if (prompts === 0)
73
+ continue;
74
+ conversations.push({
75
+ id,
76
+ title: skimmed.title,
77
+ startedAt: skimmed.startedAt,
78
+ // The skim leaves out the replies, so its last time is the last prompt's. The file's own last
79
+ // line says when the conversation actually last moved.
80
+ updatedAt: lastTimestamp(raw) ?? skimmed.updatedAt,
81
+ prompts,
82
+ });
83
+ }
84
+ return conversations.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
85
+ }
86
+ /**
87
+ * Whether a line can change what a listing shows, judged before it is parsed.
88
+ *
89
+ * Claude Code writes compact JSON, so the record type is a plain substring. Titles and human
90
+ * prompts are kept; replies and tool results are not, since neither starts a turn or names one.
91
+ */
92
+ function worthListing(line) {
93
+ if (line.includes('"type":"user"'))
94
+ return !line.includes('"tool_result"');
95
+ return line.includes('"type":"ai-title"') || line.includes('"type":"custom-title"')
96
+ || line.includes('"type":"summary"') || line.includes('"queued_command"');
97
+ }
98
+ function lastTimestamp(raw) {
99
+ const tail = raw.slice(-65_536);
100
+ const stamps = [...tail.matchAll(/"timestamp":"([^"]+)"/g)];
101
+ return stamps.at(-1)?.[1];
102
+ }
103
+ /**
104
+ * One conversation, translated into Agent Events. Throws when there is no such conversation.
105
+ *
106
+ * The id is checked before it is joined into a path: it arrives over the wire, and a `../` in it
107
+ * would otherwise read whatever JSONL the caller could name.
108
+ */
109
+ export function readClaudeCodeConversation(env, scope, conversationId, storeImage) {
110
+ if (!UUID.test(conversationId))
111
+ throw new Error("Invalid Claude Code conversation id");
112
+ const path = join(conversationsDir(env, scope), `${conversationId}.jsonl`);
113
+ let raw;
114
+ try {
115
+ raw = readFileSync(path, "utf8");
116
+ }
117
+ catch {
118
+ throw new Error("Claude Code conversation not found");
119
+ }
120
+ return translate(parse(raw), mtimeOf(path), storeImage);
121
+ }
122
+ function parse(raw, keep = () => true) {
123
+ const records = [];
124
+ for (const line of raw.split("\n")) {
125
+ if (!line.trim() || !keep(line))
126
+ continue;
127
+ try {
128
+ const record = JSON.parse(line);
129
+ if (record && typeof record === "object")
130
+ records.push(record);
131
+ }
132
+ catch {
133
+ // A torn line, most likely the last one of a conversation still being written. Its neighbours
134
+ // are still good, which is the difference from our own append-only transcript.
135
+ }
136
+ }
137
+ return records;
138
+ }
139
+ function spoken(text) {
140
+ const cleaned = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "").trim();
141
+ if (cleaned === "" || cleaned.includes("<local-command-caveat>"))
142
+ return undefined;
143
+ const command = /<command-name>([\s\S]*?)<\/command-name>/.exec(cleaned)?.[1];
144
+ if (command !== undefined) {
145
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(cleaned)?.[1] ?? "";
146
+ return { kind: "prompt", text: `${command.trim()} ${args.trim()}`.trim() };
147
+ }
148
+ const shell = /<bash-input>([\s\S]*?)<\/bash-input>/.exec(cleaned)?.[1];
149
+ if (shell !== undefined)
150
+ return { kind: "prompt", text: `! ${shell.trim()}` };
151
+ const outputs = [...cleaned.matchAll(/<(local-command-stdout|bash-stdout|bash-stderr)>([\s\S]*?)<\/\1>/g)];
152
+ if (outputs.length > 0) {
153
+ const output = outputs.map((match) => match[2].trim()).filter(Boolean).join("\n");
154
+ return output === "" ? undefined : { kind: "output", text: output };
155
+ }
156
+ // Pasted text is kept, but not the frame the CLI draws around it for the model's benefit.
157
+ const unwrapped = cleaned.replace(/<pasted_content\b[^>]*>\n?/g, "").replace(/\n?<\/pasted_content>/g, "").trim();
158
+ return unwrapped === "" ? undefined : { kind: "prompt", text: unwrapped };
159
+ }
160
+ /** How Claude Code records a turn the human stopped, as the text of a user record. */
161
+ const INTERRUPTED = /^\[Request interrupted by user(?: for tool use)?\]\s*/;
162
+ /** The tool whose calls are Subagents, under its current name and the one it had before. */
163
+ const SUBAGENT_TOOLS = new Set(["Agent", "Task"]);
164
+ /** The longest notice taken from something an agent or a background task said. */
165
+ const NOTICE_LENGTH = 500;
166
+ function translate(records, fallbackAt, storeImage) {
167
+ const events = [];
168
+ const seen = new Set();
169
+ const openCalls = new Set();
170
+ /** Subagents still running, by the id of the call that spawned them, with what their card shows. */
171
+ const openSubagents = new Map();
172
+ /** Prompts already shown from a `queued_command`, so the `user` record that delivers one later is not shown twice. */
173
+ const queued = new Set();
174
+ /** The Todo List, rebuilt by the class the live adapter uses, from the todo calls still waiting on a result. */
175
+ const todoList = new TodoList();
176
+ const todoCalls = new Map();
177
+ let turnId;
178
+ let interrupted = false;
179
+ let at = fallbackAt;
180
+ let startedAt;
181
+ let customTitle;
182
+ let titled;
183
+ let firstPrompt;
184
+ const push = (event) => events.push({ at, event });
185
+ const settleSubagent = (callId, state) => {
186
+ const brief = openSubagents.get(callId);
187
+ if (!brief)
188
+ return;
189
+ openSubagents.delete(callId);
190
+ push({ type: "subagent", subagentId: callId, ...brief, state });
191
+ };
192
+ const endTurn = () => {
193
+ if (turnId === undefined)
194
+ return;
195
+ // A call the file never recorded an answer for — the CLI was quit mid-call, most often. Left
196
+ // open, it would spin forever in a transcript nothing can ever finish.
197
+ for (const callId of openCalls) {
198
+ push({ type: "tool_ended", callId, result: "No result was recorded.", isError: true });
199
+ }
200
+ openCalls.clear();
201
+ push({ type: "turn_ended", turnId, reason: interrupted ? "aborted" : "complete" });
202
+ turnId = undefined;
203
+ interrupted = false;
204
+ };
205
+ const beginTurn = (id) => {
206
+ endTurn();
207
+ turnId = id;
208
+ push({ type: "turn_started", turnId: id });
209
+ };
210
+ /** Something a human said: a new turn when none is running, otherwise a steer inside it. */
211
+ const said = (id, text, attachments, steering) => {
212
+ if (!steering || turnId === undefined) {
213
+ firstPrompt ??= text;
214
+ beginTurn(id);
215
+ }
216
+ // After `turn_started`, which is the reverse of what a live turn records. A live prompt is
217
+ // logged by the host before the backend says it began; here both are known at once, and the
218
+ // order the reducer needs is only that the message lands inside the turn it opened.
219
+ push({ type: "user_message", id, text, ...(attachments.length ? { attachments } : {}) });
220
+ };
221
+ for (const record of records) {
222
+ if (record.type === "custom-title" && record.customTitle)
223
+ customTitle = record.customTitle;
224
+ if (record.type === "ai-title" && record.aiTitle)
225
+ titled = record.aiTitle;
226
+ if (record.type === "summary" && record.summary && titled === undefined)
227
+ titled = record.summary;
228
+ const queuedPrompt = record.type === "attachment" && record.attachment?.type === "queued_command"
229
+ // A background task's notification is queued the same way, told apart only by its mode.
230
+ && (record.attachment.commandMode ?? "prompt") === "prompt"
231
+ && (record.attachment.origin?.kind ?? "human") === "human" && typeof record.attachment.prompt === "string"
232
+ ? record.attachment.prompt
233
+ : undefined;
234
+ if (record.type !== "user" && record.type !== "assistant" && record.type !== "system" && queuedPrompt === undefined)
235
+ continue;
236
+ if (record.isSidechain || record.isMeta || !record.uuid || seen.has(record.uuid))
237
+ continue;
238
+ seen.add(record.uuid);
239
+ if (record.timestamp) {
240
+ at = record.timestamp;
241
+ startedAt ??= record.timestamp;
242
+ }
243
+ const id = record.uuid;
244
+ if (queuedPrompt !== undefined) {
245
+ // Typed while a turn ran. Claude Code hands it to the model inside that turn and frequently
246
+ // never writes it as a `user` record, so this is the only place the human's words survive.
247
+ const typed = spoken(queuedPrompt);
248
+ if (typed?.kind !== "prompt")
249
+ continue;
250
+ queued.add(typed.text);
251
+ said(id, typed.text, [], true);
252
+ continue;
253
+ }
254
+ if (record.type === "system") {
255
+ if (record.subtype === "compact_boundary") {
256
+ push({
257
+ type: "compacted",
258
+ trigger: record.compactMetadata?.trigger === "manual" ? "manual" : "auto",
259
+ before: record.compactMetadata?.preTokens ?? 0,
260
+ });
261
+ }
262
+ continue;
263
+ }
264
+ const content = record.message?.content;
265
+ if (record.type === "user") {
266
+ // The summary that stands in for the conversation after a compaction. The `compacted` marker
267
+ // above already says that happened, and the summary was written for the model, not the human.
268
+ if (record.isCompactSummary)
269
+ continue;
270
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content ?? [];
271
+ const answering = blocks.some((block) => block.type === "tool_result");
272
+ for (const block of blocks) {
273
+ if (block.type !== "tool_result" || !block.tool_use_id || !openCalls.has(block.tool_use_id))
274
+ continue;
275
+ openCalls.delete(block.tool_use_id);
276
+ const isError = block.is_error === true;
277
+ push({ type: "tool_ended", callId: block.tool_use_id, result: block.content ?? "", isError });
278
+ const todo = todoCalls.get(block.tool_use_id);
279
+ if (todo) {
280
+ todoCalls.delete(block.tool_use_id);
281
+ const entries = todoList.settle(todo.name, todo.input, record.toolUseResult, isError);
282
+ if (entries)
283
+ push({ type: "plan", entries, callId: block.tool_use_id });
284
+ }
285
+ // A backgrounded Subagent answers at once with a launch receipt; its card stays running
286
+ // until the task notification that reports how it ended.
287
+ if (!isAsyncLaunch(record.toolUseResult))
288
+ settleSubagent(block.tool_use_id, isError ? "error" : "complete");
289
+ }
290
+ const texts = blocks.flatMap((block) => block.type === "text" && block.text ? [block.text] : []);
291
+ // Not every `user` record is the human. A background task finishing, or another agent
292
+ // reporting back, arrives the same way; showing it as typed would put words in their mouth.
293
+ const from = record.origin?.kind ?? "human";
294
+ if (from !== "human") {
295
+ const text = texts.join("\n");
296
+ if (from === "task-notification") {
297
+ const callId = /<tool-use-id>([\s\S]*?)<\/tool-use-id>/.exec(text)?.[1]?.trim();
298
+ const status = /<status>([\s\S]*?)<\/status>/.exec(text)?.[1]?.trim();
299
+ if (callId)
300
+ settleSubagent(callId, status === "completed" ? "complete" : status === "failed" ? "error" : "aborted");
301
+ const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
302
+ push({ type: "notice", level: "info", text: summary || "A background task finished." });
303
+ }
304
+ else {
305
+ const plain = text.replace(/<[^>]+>/g, "").trim();
306
+ if (plain)
307
+ push({ type: "notice", level: "info", text: clip(plain) });
308
+ }
309
+ continue;
310
+ }
311
+ const words = [];
312
+ for (const raw of texts) {
313
+ const marker = INTERRUPTED.exec(raw);
314
+ if (marker)
315
+ interrupted = true;
316
+ const typed = spoken(marker ? raw.slice(marker[0].length) : raw);
317
+ if (typed?.kind === "output")
318
+ push({ type: "notice", level: "info", text: typed.text });
319
+ else if (typed)
320
+ words.push(typed.text);
321
+ }
322
+ const attachments = blocks.flatMap((block) => block.type === "image" && block.source?.type === "base64" && block.source.media_type && block.source.data
323
+ ? [storeImage(block.source.media_type, block.source.data)].filter((stored) => stored !== undefined)
324
+ : []);
325
+ if (words.length === 0 && attachments.length === 0)
326
+ continue;
327
+ const text = words.join("\n\n");
328
+ // Already shown when it was typed. The turn it starts is still a turn, so it is opened.
329
+ if (attachments.length === 0 && queued.delete(text)) {
330
+ if (!answering)
331
+ beginTurn(id);
332
+ continue;
333
+ }
334
+ // Words beside a tool result were sent while the turn was running: a steer, not a new turn.
335
+ said(id, text, attachments, answering);
336
+ continue;
337
+ }
338
+ // An assistant record with no open turn is the model speaking first — a resumed conversation
339
+ // whose prompt lives in an earlier file. It still needs a turn to land in.
340
+ if (turnId === undefined)
341
+ beginTurn(id);
342
+ if (typeof content === "string") {
343
+ if (content.trim())
344
+ push({ type: "message", id, text: content, final: true });
345
+ continue;
346
+ }
347
+ for (const [index, block] of (content ?? []).entries()) {
348
+ const blockId = `${id}:${index}`;
349
+ if (record.isApiErrorMessage && block.type === "text" && block.text) {
350
+ push({ type: "notice", level: "error", text: block.text });
351
+ }
352
+ else if (block.type === "text" && block.text?.trim()) {
353
+ push({ type: "message", id: blockId, text: block.text, final: true });
354
+ }
355
+ else if (block.type === "thinking" && block.thinking?.trim()) {
356
+ // Often empty: the API redacts reasoning to a signature, and an empty block is noise.
357
+ push({ type: "thinking", id: blockId, text: block.thinking, final: true });
358
+ }
359
+ else if (block.type === "tool_use" && block.id && block.name) {
360
+ openCalls.add(block.id);
361
+ push({ type: "tool_started", callId: block.id, name: block.name, input: block.input ?? {} });
362
+ // Sidechain records are skipped above, so every call here is the conversation's own model's.
363
+ if (TODO_TOOLS.has(block.name))
364
+ todoCalls.set(block.id, { name: block.name, input: block.input ?? {} });
365
+ // The card a live Revive would show for the same call, so an imported Subagent does not
366
+ // look different from one spawned after the import.
367
+ if (SUBAGENT_TOOLS.has(block.name)) {
368
+ const brief = briefOf(block.name, block.input);
369
+ openSubagents.set(block.id, brief);
370
+ push({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
371
+ }
372
+ }
373
+ }
374
+ }
375
+ endTurn();
376
+ // Still running when the file stops: whatever became of them was never written down here.
377
+ for (const callId of [...openSubagents.keys()])
378
+ settleSubagent(callId, "aborted");
379
+ const named = customTitle ?? titled;
380
+ return {
381
+ title: named ?? titleFrom(firstPrompt) ?? "Imported Claude Code conversation",
382
+ named: named !== undefined,
383
+ startedAt: startedAt ?? fallbackAt,
384
+ updatedAt: at,
385
+ events,
386
+ };
387
+ }
388
+ /** What a Subagent's card shows, read as the live adapter reads it: its type, then its task. */
389
+ function briefOf(tool, input) {
390
+ const fields = (input ?? {});
391
+ const name = typeof fields.subagent_type === "string" ? fields.subagent_type : tool;
392
+ return typeof fields.description === "string" ? { name, description: fields.description } : { name };
393
+ }
394
+ /** Whether a Subagent's tool result is a launch receipt rather than its answer — see the live adapter's. */
395
+ function isAsyncLaunch(result) {
396
+ const status = result?.status;
397
+ return status === "async_launched" || status === "remote_launched";
398
+ }
399
+ function clip(text) {
400
+ return text.length <= NOTICE_LENGTH ? text : `${text.slice(0, NOTICE_LENGTH - 1)}…`;
401
+ }
402
+ function titleFrom(prompt) {
403
+ const line = prompt?.split("\n").map((part) => part.trim()).find(Boolean);
404
+ if (!line)
405
+ return undefined;
406
+ return line.length <= TITLE_LENGTH ? line : `${line.slice(0, TITLE_LENGTH - 1)}…`;
407
+ }
408
+ function mtimeOf(path) {
409
+ try {
410
+ return statSync(path).mtime.toISOString();
411
+ }
412
+ catch {
413
+ return new Date().toISOString();
414
+ }
415
+ }