@spunto/build 0.31.0 → 0.33.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.
@@ -1,623 +0,0 @@
1
- /**
2
- * Claude's dialect, read into our vocabulary — the SDK's messages, which are exactly the CLI's
3
- * `--output-format stream-json --verbose` shapes.
4
- *
5
- * Lives with the Claude runner (RFC 0048 § 9): the runner bundles it and prints the contract
6
- * (`claudeContractLines`): the platform reads no Claude line, ever.
7
- *
8
- * Written against output measured in a real worker, not against a spec: the shapes below are what
9
- * the CLI emitted, and the tests replay recorded samples so a change in that output shows up as a
10
- * failing test rather than as an empty timeline.
11
- */
12
-
13
- import { SUBAGENT_STATUSES, cleanTitle, clip, type NormalizedEvent } from "../../agent-contract/vocabulary"
14
-
15
- export { cleanTitle }
16
- import { contextWindowOf } from "./model-window"
17
- import { claudeTurnLimit, resetFromText, type TurnLimit } from "./turn-limit"
18
-
19
- /** Marks the `control_request`s that ask the CLI for a title, and so the `control_response`s that answer. */
20
- export const TITLE_REQUEST_PREFIX = "spunto-title-"
21
-
22
- export function adaptClaudeJson(obj: Record<string, unknown>): NormalizedEvent[] {
23
- const type = obj.type
24
-
25
- if (type === "system" && obj.subtype === "init") {
26
- const model = typeof obj.model === "string" ? obj.model : null
27
- return [
28
- {
29
- type: "session.started",
30
- payload: {
31
- harness: "claude-code",
32
- model,
33
- // Read here and nowhere else: this is the only line that spells the model the way the
34
- // *session* was opened (`claude-opus-5[1m]`), suffix included — the assistant messages
35
- // that follow carry the plain API id. From the catalogue only, so this stays a pure
36
- // function; the runner replaces it with the model's own answer when it has a key to ask
37
- // with (`resolveContextWindow`).
38
- contextWindow: contextWindowOf(model),
39
- cwd: typeof obj.cwd === "string" ? obj.cwd : null,
40
- sessionId: typeof obj.session_id === "string" ? obj.session_id : null,
41
- tools: Array.isArray(obj.tools) ? obj.tools.filter((t) => typeof t === "string") : [],
42
- },
43
- },
44
- ]
45
- }
46
-
47
- // The set of background tasks (a `run_in_background` shell, a backgrounded subagent) still
48
- // alive, restated whole on every change. Why it has to be read: a `result` ends the *turn*, not
49
- // the work — measured, a turn that leaves a background task running emits its `result`, and
50
- // when that task finishes the harness wakes itself up for another turn and another `result`,
51
- // nobody having said anything. So a `result` is a hand-back only if nothing was left running
52
- // behind it, and this line is the only place that says so.
53
- if (type === "system" && obj.subtype === "background_tasks_changed") {
54
- const tasks = (Array.isArray(obj.tasks) ? obj.tasks : [])
55
- .filter((t): t is Record<string, unknown> => !!t && typeof t === "object")
56
- .map((t) => ({
57
- id: typeof t.task_id === "string" ? t.task_id : null,
58
- kind: typeof t.task_type === "string" ? t.task_type : null,
59
- description: typeof t.description === "string" ? t.description : null,
60
- }))
61
- return [{ type: "session.background", payload: { tasks } }]
62
- }
63
-
64
- if (type === "assistant" || type === "user") {
65
- const message = obj.message as Record<string, unknown> | undefined
66
- const content = Array.isArray(message?.content) ? message!.content : []
67
- const role = type === "assistant" ? "assistant" : "user"
68
- // Set on every message a subagent produced: the `Agent` call that started it. What it does is
69
- // nested under that call rather than told as the session's own thread.
70
- const parentCallId = typeof obj.parent_tool_use_id === "string" && obj.parent_tool_use_id ? obj.parent_tool_use_id : null
71
- const events: NormalizedEvent[] = []
72
- for (const rawBlock of content) {
73
- if (!rawBlock || typeof rawBlock !== "object") continue
74
- const block = rawBlock as Record<string, unknown>
75
- switch (block.type) {
76
- case "text": {
77
- // A subagent's `user` text is the prompt it was given — already the input of the call
78
- // that started it. Told again as a `user` message, it would read as a human's turn
79
- // to everything that looks for one (the hand-back, the shared thread, the cockpit).
80
- if (parentCallId && role === "user") break
81
- const { text, truncated } = clip(block.text)
82
- if (text) events.push({ type: "message", payload: { role, text, truncated } })
83
- break
84
- }
85
- case "thinking": {
86
- const { text, truncated } = clip(block.thinking)
87
- if (text) events.push({ type: "thinking", payload: { text, truncated } })
88
- break
89
- }
90
- case "tool_use": {
91
- const name = typeof block.name === "string" ? block.name : "tool"
92
- const { text: input, truncated } = clip(block.input)
93
- events.push({
94
- type: "tool.call",
95
- payload: { callId: typeof block.id === "string" ? block.id : null, name, input, truncated },
96
- })
97
- // A todo list is a plan, and a plan is the single most useful thing to show while a
98
- // session runs. Emitted *alongside* the tool call rather than instead of it: the call
99
- // is what happened, the plan is what it means.
100
- const plan = todoPlan(block.input)
101
- if (plan) events.push(plan)
102
- break
103
- }
104
- case "tool_result": {
105
- const { text: output, truncated } = clip(
106
- typeof block.content === "string" ? block.content : block.content ?? "",
107
- )
108
- events.push({
109
- type: "tool.result",
110
- payload: {
111
- callId: typeof block.tool_use_id === "string" ? block.tool_use_id : null,
112
- isError: block.is_error === true,
113
- output,
114
- truncated,
115
- },
116
- })
117
- break
118
- }
119
- }
120
- }
121
- // The synthetic message Claude Code writes when the API refused the call carries the one
122
- // structured reset time of a usage limit; the `result` that follows does not. Kept on the
123
- // message so ingestion can carry it over to the turn's end (`stampLimitReset`).
124
- if (type === "assistant") {
125
- const limit = claudeTurnLimit(obj)
126
- if (limit) for (const e of events) if (e.type === "message") e.payload.limit = limit
127
- }
128
- // What the call that produced this message cost, and how full the context was when it ran.
129
- // Only assistant messages carry it — a `user` line is tool results being handed back.
130
- if (type === "assistant") {
131
- const measured = callUsage(message)
132
- if (measured) events.push(measured)
133
- }
134
- if (parentCallId) for (const e of events) e.payload.parentCallId = parentCallId
135
- return events
136
- }
137
-
138
- if (type === "result") {
139
- const usage = (obj.usage ?? {}) as Record<string, unknown>
140
- const limit = claudeTurnLimit(obj)
141
- return [
142
- {
143
- type: "usage",
144
- payload: {
145
- // The harness's own running total, **cumulative over the whole process** — with an
146
- // interactive session a `result` lands at the end of every turn and each one restates
147
- // the session so far. Summing them would bill the first turn once per turn that
148
- // followed; the latest one is the answer. (Claude Code's own SDK reader does the same:
149
- // it overwrites `total_cost_usd`/`num_turns` on each result rather than adding.)
150
- scope: "session",
151
- inputTokens: num(usage.input_tokens),
152
- outputTokens: num(usage.output_tokens),
153
- cacheReadTokens: num(usage.cache_read_input_tokens),
154
- cacheCreationTokens: num(usage.cache_creation_input_tokens),
155
- costUsd: num(obj.total_cost_usd),
156
- turns: num(obj.num_turns),
157
- durationMs: num(obj.duration_ms),
158
- },
159
- },
160
- {
161
- type: "session.ended",
162
- payload: {
163
- // `is_error` too: a turn the API refused (a usage limit, measured) still says
164
- // `subtype: "success"` — it is the *harness* that ended cleanly, not the turn.
165
- status: obj.subtype === "success" && obj.is_error !== true ? "succeeded" : "failed",
166
- stopReason: typeof obj.stop_reason === "string" ? obj.stop_reason : null,
167
- summary: clip(obj.result).text,
168
- ...(limit ? { limit } : {}),
169
- },
170
- },
171
- ]
172
- }
173
-
174
- // The CLI's answer to a `generate_session_title` request. Only ours, recognised by request id:
175
- // a `control_response` is also how an interrupt is acknowledged, and that one is no name.
176
- if (type === "control_response") {
177
- const response = (obj.response ?? {}) as Record<string, unknown>
178
- const inner = (response.response ?? {}) as Record<string, unknown>
179
- const requestId = typeof response.request_id === "string" ? response.request_id : ""
180
- const title = response.subtype === "success" && requestId.startsWith(TITLE_REQUEST_PREFIX) ? cleanTitle(inner.title) : null
181
- if (title) return [{ type: "session.title", payload: { title } }]
182
- }
183
-
184
- // Tokens of a message still being written (`includePartialMessages`). Not events: the finished
185
- // `assistant` line repeats them whole, and one row per token would bury the session. They fold
186
- // into the transient draft instead (`claudeDelta` below, `draft.ts` for the old dialects).
187
- if (type === "stream_event") return []
188
-
189
- // Known-but-uninteresting (`rate_limit_event`, `system/thinking_tokens`) and anything the CLI
190
- // grows next land here rather than being dropped: an unknown event is information about the
191
- // harness, and the UI keeps it behind a toggle.
192
- return [{ type: "raw", payload: { json: obj } }]
193
- }
194
-
195
- function num(value: unknown): number | null {
196
- return typeof value === "number" && Number.isFinite(value) ? value : null
197
- }
198
-
199
- /**
200
- * What **one model call** consumed, read off an assistant message.
201
- *
202
- * Two different questions are answered by these numbers, and only the first is obvious:
203
- *
204
- * - added up over the session, they are what it has spent in tokens — and unlike the `result`
205
- * line, they exist *during* a turn, which is when someone is watching;
206
- * - the latest one alone is the **context**: `input + cache_read + cache_creation` is the prompt
207
- * the harness just sent, so it is how full the window is right now. Same formula Claude Code
208
- * uses for its own context meter.
209
- *
210
- * Skipped when every counter is zero: an API error makes the CLI emit a synthetic assistant
211
- * message with an all-zero usage, and drawing a context that just fell to zero would be a lie
212
- * about the session rather than a fact about the error.
213
- */
214
- function callUsage(message: Record<string, unknown> | undefined): NormalizedEvent | null {
215
- const usage = message?.usage
216
- if (!usage || typeof usage !== "object") return null
217
- const u = usage as Record<string, unknown>
218
- const inputTokens = num(u.input_tokens) ?? 0
219
- const outputTokens = num(u.output_tokens) ?? 0
220
- const cacheReadTokens = num(u.cache_read_input_tokens) ?? 0
221
- const cacheCreationTokens = num(u.cache_creation_input_tokens) ?? 0
222
- if (inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens === 0) return null
223
- // `<synthetic>` is what the CLI puts there when no model ran at all.
224
- const model = typeof message?.model === "string" && !message.model.startsWith("<") ? message.model : null
225
- return {
226
- type: "usage",
227
- payload: {
228
- scope: "call",
229
- model,
230
- inputTokens,
231
- outputTokens,
232
- cacheReadTokens,
233
- cacheCreationTokens,
234
- contextTokens: inputTokens + cacheReadTokens + cacheCreationTokens,
235
- },
236
- }
237
- }
238
-
239
- /** Claude Code's TodoWrite input, as a `plan` — `{ todos: [{ content, status }] }`. */
240
- function todoPlan(input: unknown): NormalizedEvent | null {
241
- if (!input || typeof input !== "object") return null
242
- const todos = (input as Record<string, unknown>).todos
243
- if (!Array.isArray(todos) || todos.length === 0) return null
244
- const steps = todos
245
- .filter((t): t is Record<string, unknown> => !!t && typeof t === "object")
246
- .map((t) => ({
247
- text: clip(t.content ?? t.activeForm ?? "").text,
248
- status: typeof t.status === "string" ? t.status : "pending",
249
- }))
250
- .filter((s) => s.text)
251
- return steps.length > 0 ? { type: "plan", payload: { steps } } : null
252
- }
253
-
254
- // ── The contract, as the runner prints it ────────────────────────────────────
255
-
256
- /**
257
- * A partial message (`stream_event`, `includePartialMessages`) as the contract's transient
258
- * `message.delta`: a text block starting opens a fresh draft, a `text_delta` grows it. A subagent's
259
- * partials (`parent_tool_use_id` set) are skipped — what it writes is not what the session says to
260
- * the reader, and interleaving it would garble the draft of the main thread.
261
- */
262
- export function claudeDelta(obj: Record<string, unknown>): Record<string, unknown>[] {
263
- if (obj.type !== "stream_event" || obj.parent_tool_use_id) return []
264
- const event = (obj.event ?? {}) as Record<string, unknown>
265
- if (event.type === "content_block_start") {
266
- const block = (event.content_block ?? {}) as Record<string, unknown>
267
- if (block.type === "text") return [{ type: "message.delta", start: true, text: typeof block.text === "string" ? block.text : "" }]
268
- } else if (event.type === "content_block_delta") {
269
- const delta = (event.delta ?? {}) as Record<string, unknown>
270
- if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text) return [{ type: "message.delta", text: delta.text }]
271
- }
272
- return []
273
- }
274
-
275
- /** How deep `withoutFileBytes` looks. A content block sits two or three levels down; this is a loop guard. */
276
- const MAX_DEPTH = 8
277
-
278
- /**
279
- * The message with every base64 file block reduced to what it is (`{type, media_type}`).
280
- *
281
- * What the *events* are read from, not what is printed as `source`: a screenshot a tool hands back
282
- * is megabytes of base64 on one line, and read as text it would fill a `tool.result` with 8 KB of
283
- * noise. The bytes stay whole in `source`, where the platform takes them out and stores them as a
284
- * file of the task (RFC 0022) — so the event only needs to say that a file was there.
285
- */
286
- export function withoutFileBytes(value: unknown, depth = 0): unknown {
287
- if (depth > MAX_DEPTH || !value || typeof value !== "object") return value
288
- if (Array.isArray(value)) return value.map((v) => withoutFileBytes(v, depth + 1))
289
- const obj = value as Record<string, unknown>
290
- const src = obj.source as Record<string, unknown> | undefined
291
- if ((obj.type === "image" || obj.type === "document") && src && typeof src === "object" && src.type === "base64") {
292
- const { source: _s, ...rest } = obj
293
- return { ...rest, media_type: src.media_type }
294
- }
295
- return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, withoutFileBytes(v, depth + 1)]))
296
- }
297
-
298
- /**
299
- * The Claude runner's reading of a session: SDK messages in, lines of the contract out — each event
300
- * a message reads into, with the message itself as `source`. Every line of one message carries the
301
- * same `source`, so the platform can tell they belong together (and stores a file they carry once).
302
- *
303
- * Stateful for one reason: **when a limit lifts**. Claude Code puts `resetsAt` on the synthetic
304
- * assistant message it writes in place of the refused answer, one line *before* the `result` that
305
- * ends the turn — which only says it in prose (« resets 9pm (UTC) »), measured on 2026-10-17. The
306
- * contract says it where the platform waits for it, on `session.ended`: carried over from that
307
- * message, else read from the prose against the clock (`now`, a parameter for the tests).
308
- */
309
- export function claudeTranslator(now: () => Date = () => new Date()): (message: Record<string, unknown>) => Record<string, unknown>[] {
310
- let carried: string | null = null
311
- const compaction = compactionReader()
312
- const skills = skillReader()
313
- const subagents = subagentTracker()
314
- return (message) => {
315
- if (message.type === "stream_event") return claudeDelta(message)
316
- // The runner answers the `title` verb itself; a control response is never a title here.
317
- if (message.type === "control_response") return []
318
- const compacted = compaction(message)
319
- if (compacted.handled) return compacted.lines
320
- const subagent = subagents(message)
321
- if (subagent) return [...compacted.lines, ...subagent.map((line) => ({ ...line, source: message }))]
322
- const skill = skills(message)
323
- if (skill) return [...compacted.lines, skill]
324
- const events = adaptClaudeJson(withoutFileBytes(message) as Record<string, unknown>)
325
- for (const e of events) {
326
- const limit = e.payload.limit as TurnLimit | undefined
327
- if (e.type === "message" && limit?.resetsAt) carried = limit.resetsAt
328
- if (e.type !== "session.ended") continue
329
- if (limit && !limit.resetsAt) {
330
- const resetsAt = carried ?? resetFromText(limit.message, now())
331
- if (resetsAt) e.payload.limit = { ...limit, resetsAt }
332
- }
333
- carried = null
334
- }
335
- return [...compacted.lines, ...events.map((e) => ({ type: e.type, ...e.payload, source: message }))]
336
- }
337
- }
338
-
339
- // ── Skills ────────────────────────────────────────────────────────────────────
340
-
341
- /** How Claude Code opens the turn that carries a skill's instructions. Measured on 2.1.310, 2026-11-24. */
342
- const SKILL_PREFIX = /^Base directory for this skill: ([^\n]*)\n*/
343
-
344
- /** How many asked-for skills are remembered while their body has not come: a loop guard, not a limit anyone reaches. */
345
- const MAX_PENDING_SKILLS = 16
346
-
347
- /**
348
- * A skill being loaded, read as one `skill.loaded` rather than as something the member wrote.
349
- *
350
- * When the model calls the `Skill` tool, Claude Code answers the call with one line (« Launching
351
- * skill: e2e-proof ») and then hands the model the skill's whole SKILL.md as a **user** turn,
352
- * `isSynthetic`, opening with « Base directory for this skill: <path> ». Read naively that is
353
- * kilobytes of instructions in the member's name. So the calls are remembered as they go by, and
354
- * the synthetic turn that follows is tied back to the call that asked for it — by the skill's
355
- * name, else the oldest call still waiting. A body no call explains (a slash command typed in a
356
- * terminal session) still comes out as `skill.loaded`, named after its directory.
357
- */
358
- function skillReader(): (message: Record<string, unknown>) => Record<string, unknown> | null {
359
- const pending: { callId: string; name: string }[] = []
360
- return (message) => {
361
- if (message.type === "assistant") {
362
- const content = (message.message as Record<string, unknown> | undefined)?.content
363
- for (const block of Array.isArray(content) ? content : []) {
364
- if (!block || typeof block !== "object" || block.type !== "tool_use" || block.name !== "Skill") continue
365
- const skill = (block.input as Record<string, unknown> | undefined)?.skill
366
- if (typeof block.id === "string" && typeof skill === "string") pending.push({ callId: block.id, name: skill })
367
- if (pending.length > MAX_PENDING_SKILLS) pending.shift()
368
- }
369
- return null
370
- }
371
- if (message.type !== "user" || message.isSynthetic !== true) return null
372
- const full = userText(message)
373
- const header = SKILL_PREFIX.exec(full)
374
- if (!header) return null
375
- const path = header[1]!.trim() || null
376
- const dir = path?.split("/").filter(Boolean).pop() ?? ""
377
- // `plugin:skill` is called by its full name and lives in a directory named after the skill.
378
- const at = pending.findIndex((p) => p.name === dir || p.name.split(":").pop() === dir)
379
- const call = at >= 0 ? pending.splice(at, 1)[0]! : pending.shift()
380
- const { text, truncated } = clip(full.slice(header[0].length))
381
- const parentCallId = typeof message.parent_tool_use_id === "string" && message.parent_tool_use_id ? message.parent_tool_use_id : null
382
- return {
383
- type: "skill.loaded",
384
- callId: call?.callId ?? null,
385
- name: call?.name ?? (dir || "skill"),
386
- path,
387
- text,
388
- truncated,
389
- ...(parentCallId ? { parentCallId } : {}),
390
- source: message,
391
- }
392
- }
393
- }
394
-
395
- // ── Compaction ────────────────────────────────────────────────────────────────
396
-
397
- /**
398
- * How Claude Code's summary turn begins — only for a summary nothing else marks (a subagent's has
399
- * no boundary before it). Measured on Claude Code 2.1.310, 2026-11-24.
400
- */
401
- const SUMMARY_PREFIX = "This session is being continued from a previous conversation"
402
-
403
- type Compaction = { lines: Record<string, unknown>[]; handled: boolean }
404
-
405
- /**
406
- * A compaction, read as **one** `context.compacted`. What Claude Code prints, measured on
407
- * 2026-11-24 (a session that compacted twelve times):
408
- *
409
- * 1. `system/status` `compacting`, restated as the summary is written (`compact_output_chars`);
410
- * 2. `system/status` `null`, `compact_result: "success"`;
411
- * 3. `system/compact_boundary` — the numbers (`compact_metadata`: trigger, tokens before and
412
- * after, duration), and `preserved_segment.anchor_uuid`, the uuid of…
413
- * 4. …a **user** turn, `isSynthetic`, whose text is the summary the session carries on with.
414
- *
415
- * Read naively, (1)–(3) are `raw` and (4) is 8 KB the member seems to have written. So (1) and (2)
416
- * are absorbed, (3) is held, and (4) closes it — recognised by the anchor first, then by what
417
- * Claude Code marks (`isCompactSummary`, `isVisibleInTranscriptOnly`), then as the synthetic turn
418
- * right after a boundary, and by its first words only when nothing else says so. A boundary that
419
- * no summary follows still comes out, without one, before the next line.
420
- *
421
- * A failed compaction (`compact_result: "failed"`) is left to the generic reader: it is information
422
- * about the harness, and rare enough not to need a type.
423
- */
424
- function compactionReader(): (message: Record<string, unknown>) => Compaction {
425
- let boundary: Record<string, unknown> | null = null
426
- const flush = (): Record<string, unknown>[] => {
427
- if (!boundary) return []
428
- const line = compactedLine(boundary, null)
429
- boundary = null
430
- return [line]
431
- }
432
- return (message) => {
433
- if (message.type === "system" && message.subtype === "status") {
434
- const absorbed = message.status === "compacting" || (message.status === null && message.compact_result === "success")
435
- return { lines: absorbed ? [] : flush(), handled: absorbed }
436
- }
437
- if (message.type === "system" && message.subtype === "compact_boundary") {
438
- const lines = flush()
439
- boundary = message
440
- return { lines, handled: true }
441
- }
442
- if (message.type === "user" && isSummaryTurn(message, boundary)) {
443
- const line = compactedLine(boundary, message)
444
- boundary = null
445
- return { lines: [line], handled: true }
446
- }
447
- return { lines: flush(), handled: false }
448
- }
449
- }
450
-
451
- function isSummaryTurn(message: Record<string, unknown>, boundary: Record<string, unknown> | null): boolean {
452
- if (message.isCompactSummary === true) return true
453
- if (boundary) {
454
- const anchor = anchorOf(boundary)
455
- if (anchor && message.uuid === anchor) return true
456
- if (message.isVisibleInTranscriptOnly === true) return true
457
- if (!anchor && message.isSynthetic === true && !message.parent_tool_use_id) return true
458
- }
459
- return message.isSynthetic === true && userText(message).startsWith(SUMMARY_PREFIX)
460
- }
461
-
462
- function anchorOf(boundary: Record<string, unknown>): string | null {
463
- const meta = (boundary.compact_metadata ?? {}) as Record<string, unknown>
464
- for (const key of ["preserved_messages", "preserved_segment"]) {
465
- const anchor = (meta[key] as Record<string, unknown> | undefined)?.anchor_uuid
466
- if (typeof anchor === "string") return anchor
467
- }
468
- return null
469
- }
470
-
471
- function userText(message: Record<string, unknown>): string {
472
- const content = (message.message as Record<string, unknown> | undefined)?.content
473
- if (typeof content === "string") return content
474
- if (!Array.isArray(content)) return ""
475
- return content
476
- .filter((b): b is Record<string, unknown> => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string")
477
- .map((b) => b.text as string)
478
- .join("\n\n")
479
- }
480
-
481
- /** The event, with both harness lines as its source when there are two — the projection stays replayable. */
482
- function compactedLine(boundary: Record<string, unknown> | null, summary: Record<string, unknown> | null): Record<string, unknown> {
483
- const meta = (boundary?.compact_metadata ?? {}) as Record<string, unknown>
484
- const { text, truncated } = clip(summary ? userText(summary) : "")
485
- const parentCallId = typeof summary?.parent_tool_use_id === "string" && summary.parent_tool_use_id ? summary.parent_tool_use_id : null
486
- return {
487
- type: "context.compacted",
488
- trigger: typeof meta.trigger === "string" ? meta.trigger : null,
489
- preTokens: num(meta.pre_tokens),
490
- postTokens: num(meta.post_tokens),
491
- durationMs: num(meta.duration_ms),
492
- ...(summary ? { summary: text, truncated } : {}),
493
- ...(parentCallId ? { parentCallId } : {}),
494
- source: boundary && summary ? [boundary, summary] : (boundary ?? summary),
495
- }
496
- }
497
-
498
- /** A subagent as the contract states it: one `subagent` line, restated whole on every change. */
499
- type Subagent = {
500
- callId: string
501
- status: (typeof SUBAGENT_STATUSES)[number]
502
- description: string | null
503
- kind: string | null
504
- background: boolean
505
- activity: string | null
506
- lastTool: string | null
507
- toolUses: number | null
508
- tokens: number | null
509
- durationMs: number | null
510
- summary?: string
511
- }
512
-
513
- /**
514
- * The subagents of a session, read off Claude Code's task lines — `null` for a line that is not
515
- * about one, `[]` for one that is but changes nothing worth a row.
516
- *
517
- * Measured with the SDK 0.3.310 (2026-11-24), for a subagent in the foreground and two in the
518
- * background: `system/task_started` (with the `tool_use_id` of the `Agent` call, its description,
519
- * `subagent_type`, `is_backgrounded`), a `system/task_progress` per tool it uses (`description`
520
- * is then what it is doing — « Reading /etc/hostname » —, `last_tool_name`, running totals),
521
- * `system/task_updated` (a patch: `status`, `is_backgrounded`), and `system/task_notification`
522
- * when it ends, with its report as `summary`. The same lines exist for a backgrounded shell
523
- * (`task_type: "local_bash"`), which is not a subagent: only the tasks that started as an agent
524
- * are followed, and a line about a task never seen starting (a session resumed mid-way) is one
525
- * only if it names a `subagent_type`.
526
- *
527
- * Stateful because only `task_started` says what the agent was asked: every later line is the
528
- * whole state again, so a reader keeps the latest line of a `callId` and needs nothing else.
529
- */
530
- export function subagentTracker(): (message: Record<string, unknown>) => Record<string, unknown>[] | null {
531
- const byTask = new Map<string, Subagent>()
532
- const line = (sub: Subagent): Record<string, unknown>[] => [{ type: "subagent", ...sub }]
533
- const text = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.replace(/\s+/g, " ").trim() : null)
534
- const totals = (sub: Subagent, usage: unknown) => {
535
- if (!usage || typeof usage !== "object") return
536
- const u = usage as Record<string, unknown>
537
- sub.toolUses = num(u.tool_uses) ?? sub.toolUses
538
- sub.tokens = num(u.total_tokens) ?? sub.tokens
539
- sub.durationMs = num(u.duration_ms) ?? sub.durationMs
540
- }
541
-
542
- return (message) => {
543
- if (message.type !== "system" || typeof message.subtype !== "string") return null
544
- const taskId = typeof message.task_id === "string" ? message.task_id : null
545
- if (!taskId) return null
546
- const known = byTask.get(taskId)
547
- const callId = typeof message.tool_use_id === "string" && message.tool_use_id ? message.tool_use_id : null
548
- const isAgent = message.task_type === "local_agent" || typeof message.subagent_type === "string"
549
-
550
- // Met for the first time: a start, or a later line of a subagent whose start this process
551
- // never saw. Anything that is not an agent — or that names no call to hang it under — is not ours.
552
- const meet = (): Subagent | null => {
553
- if (known) return known
554
- if (!isAgent || !callId) return null
555
- const sub: Subagent = {
556
- callId,
557
- status: "running",
558
- description: text(message.description),
559
- kind: text(message.subagent_type),
560
- background: message.is_backgrounded === true,
561
- activity: null,
562
- lastTool: null,
563
- toolUses: null,
564
- tokens: null,
565
- durationMs: null,
566
- }
567
- byTask.set(taskId, sub)
568
- return sub
569
- }
570
-
571
- switch (message.subtype) {
572
- case "task_started": {
573
- const sub = meet()
574
- return sub ? line(sub) : null
575
- }
576
- case "task_progress": {
577
- const sub = meet()
578
- if (!sub) return null
579
- // With `agentProgressSummaries`, a model-written line every ~30 s; else the harness's own
580
- // (« Running List first three entries in /etc »). Either is what it is doing now.
581
- sub.activity = text(message.summary) ?? text(message.description) ?? sub.activity
582
- sub.lastTool = text(message.last_tool_name) ?? sub.lastTool
583
- totals(sub, message.usage)
584
- return line(sub)
585
- }
586
- case "task_updated": {
587
- if (!known) return null
588
- const patch = (message.patch ?? {}) as Record<string, unknown>
589
- let changed = false
590
- if (patch.is_backgrounded === true && !known.background) {
591
- known.background = true
592
- changed = true
593
- }
594
- // `completed` is said again, with the report, by the notification right behind it.
595
- const ended = endStatus(patch.status)
596
- if (ended && ended !== "completed" && known.status === "running") {
597
- known.status = ended
598
- changed = true
599
- }
600
- return changed ? line(known) : []
601
- }
602
- case "task_notification": {
603
- const sub = meet()
604
- if (!sub) return null
605
- sub.status = endStatus(message.status) ?? "completed"
606
- sub.activity = null
607
- const summary = text(message.summary) === null ? null : String(message.summary).trim()
608
- if (summary) sub.summary = summary
609
- totals(sub, message.usage)
610
- return line(sub)
611
- }
612
- default:
613
- return null
614
- }
615
- }
616
- }
617
-
618
- function endStatus(value: unknown): Subagent["status"] | null {
619
- if (value === "completed") return "completed"
620
- if (value === "failed") return "failed"
621
- if (value === "stopped" || value === "killed") return "stopped"
622
- return null
623
- }