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