@silverprotocol/claude-agent-sdk 0.6.7 → 0.7.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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
1
+ import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, withAtomicPush, } from "@silverprotocol/core";
2
2
  // ─── stop_reason → AgFinishReason (spec §4) ───────────────────────────────────
3
3
  // Anthropic BetaStopReason superset → the neutral finish-reason superset.
4
4
  function mapStopReason(stop) {
@@ -26,13 +26,23 @@ function mapStopReason(stop) {
26
26
  return "unknown";
27
27
  }
28
28
  }
29
- // ─── derive stable ids ────────────────────────────────────────────────────────
30
- // A stable per-message turn id: the assistant message is the model's turn, so
31
- // the SDK session id names the turn (a top-level turn shares the session). When
32
- // absent, fall back to the message id.
33
- function turnIdFor(sessionId, messageId) {
34
- return sessionId && sessionId.length > 0 ? `turn_${sessionId}` : `turn_${messageId}`;
29
+ // draft.4 (§8.0 graceful degradation / §10 item 23): when `mapStopReason` had to
30
+ // FALL BACK (a stop_reason this facet has no mapping for, e.g. one a newer
31
+ // Messages API ships), `turn.done.finishReasonRaw` carries the native value
32
+ // verbatim beside finishReason "unknown", so nothing about why the turn ended
33
+ // is lost. Set ONLY on the fallback: a mapped reason, and `null` (a real
34
+ // "stop"), carry no raw companion, so ordinary turns stay byte-identical.
35
+ function stopReasonRaw(stop) {
36
+ return typeof stop === "string" && mapStopReason(stop) === "unknown" ? stop : undefined;
35
37
  }
38
+ // ─── derive stable ids ────────────────────────────────────────────────────────
39
+ // Turn ids are minted per TURN inside `createClaudeNormalizer()` (see
40
+ // `topTurnId` / `nestedTurnId`), never per session: through 0.6.4 the facet
41
+ // keyed every top-level turn on `turn_${session_id}`, so in a multi-turn
42
+ // invoke the second turn's message.start and content landed on T AFTER
43
+ // turn.done(T) (the assembler's seen-turn set suppressed a second
44
+ // turn.start), breaking INV-TURN (SPEC:743), and reduce() merged every turn
45
+ // of a session into one AgTurnRecord (sp-protocol, 2026-09-23).
36
46
  // ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
37
47
  function imageSource(source) {
38
48
  if (source.type === "base64") {
@@ -90,6 +100,23 @@ function mapModelUsage(mu) {
90
100
  cumulative: true,
91
101
  };
92
102
  }
103
+ // `server_tool_use` is typed `{web_search_requests, web_fetch_requests} | null`,
104
+ // but a result frame is discriminant-validated only, so a leaner producer (a
105
+ // proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
106
+ // member passed the `!== null` check and threw a TypeError out of push()
107
+ // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found by sp-protocol writing §10.23),
108
+ // and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
109
+ // anything else ⇒ absent.
110
+ function serverToolRequestCount(usage) {
111
+ if (!isJsonObject(usage))
112
+ return undefined;
113
+ const stu = usage["server_tool_use"];
114
+ if (!isJsonObject(stu))
115
+ return undefined;
116
+ const search = stu["web_search_requests"];
117
+ const fetch = stu["web_fetch_requests"];
118
+ return typeof search === "number" && typeof fetch === "number" ? search + fetch : undefined;
119
+ }
93
120
  function mapTurnUsage(usage, totalCostUsd, modelUsage) {
94
121
  const byModel = {};
95
122
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -102,9 +129,7 @@ function mapTurnUsage(usage, totalCostUsd, modelUsage) {
102
129
  cacheReadTokens: usage.cache_read_input_tokens,
103
130
  cacheWriteTokens: usage.cache_creation_input_tokens,
104
131
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
105
- serverToolRequests: usage.server_tool_use !== null
106
- ? usage.server_tool_use.web_search_requests + usage.server_tool_use.web_fetch_requests
107
- : undefined,
132
+ serverToolRequests: serverToolRequestCount(usage),
108
133
  costUsd: totalCostUsd,
109
134
  cumulative: true,
110
135
  ...(Object.keys(byModel).length > 0 ? { byModel } : {}),
@@ -190,7 +215,7 @@ function assistantContentBlockToAgBlock(block) {
190
215
  return {
191
216
  type: "provider-raw",
192
217
  vendor: "anthropic",
193
- raw: JsonValue.parse(block),
218
+ raw: carryVerbatim(block),
194
219
  };
195
220
  }
196
221
  // ─── user/tool_result content fan-out (spec §2 — tool.done content blocks) ────
@@ -211,7 +236,7 @@ function toolResultContentToAgBlocks(content) {
211
236
  out.push({ type: "image", source: imageSource(part.source) });
212
237
  }
213
238
  else {
214
- out.push({ type: "provider-raw", vendor: "anthropic", raw: JsonValue.parse(part) });
239
+ out.push({ type: "provider-raw", vendor: "anthropic", raw: carryVerbatim(part) });
215
240
  }
216
241
  }
217
242
  return out;
@@ -234,19 +259,64 @@ function mcpToolResultContentToAgBlocks(content) {
234
259
  out.push({ type: "text", text: tb.text });
235
260
  return out;
236
261
  }
237
- // ─── assistant content block fan-out (spec §4 mapping table) ──────────────────
238
- // Per content[] block, drive the engine to emit its lifecycle events under the
239
- // open message named by `messageId`. `blockProviderMetadata` is the refusal-
240
- // fallback `supersedes` carrier (playbook 2026-07-03 SDK-bump adaptation,
241
- // Finding #1 / §8 item 19): the caller passes it ONLY for blockIndex 0 of a
242
- // superseding message, mirroring the established "signature on first block"
243
- // precedent (§8 item 8, Gemini thoughtSignature). `text`/`thinking`/
244
- // `redacted_thinking`/`tool_use` family all have a providerMetadata slot on
245
- // their *.start event and land it there; the remaining rarer block-0 shapes
246
- // (image/resource/mcp_tool_result/compaction) have no providerMetadata slot on
247
- // `content.block` and drop the annotation (NOT the retraction itself, which
248
- // already executed via `message.remove` regardless — see `drive()`).
249
- function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetadata) {
262
+ // `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on sp-probe's
263
+ // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
264
+ // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
265
+ // not carry the tool's own execution output (user-rejected / permission-rule /
266
+ // automode-* / interrupted / cancelled); absent means the tool ran to
267
+ // completion" (the CLI's own schema doc). Read through the JSON boundary; a
268
+ // malformed entry is skipped. The entry itself is NOT carried here (that carry
269
+ // is package 15's); only the kind decides the outcome below.
270
+ function readNonExecutionKinds(frame) {
271
+ const out = new Map();
272
+ if (!isJsonObject(frame))
273
+ return out;
274
+ const list = frame["tool_result_meta"];
275
+ if (!Array.isArray(list))
276
+ return out;
277
+ for (const entry of list) {
278
+ if (isJsonObject(entry) && typeof entry["id"] === "string" && typeof entry["non_execution_kind"] === "string") {
279
+ out.set(entry["id"], entry["non_execution_kind"]);
280
+ }
281
+ }
282
+ return out;
283
+ }
284
+ // The non_execution_kinds that mean the call was NOT PERMITTED to run →
285
+ // `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
286
+ // item 15 routes Claude's permission denials to it; sp-protocol, 2026-09-23).
287
+ // `interrupted`, `cancelled`, absent and any unknown value are not denials and
288
+ // keep "error" (no guessing).
289
+ function isDenialKind(kind) {
290
+ return kind === "user-rejected" || kind === "permission-rule" || (kind !== undefined && kind.startsWith("automode-"));
291
+ }
292
+ // Which assistant `error` codes are transient (retriable). CL-09's stashed
293
+ // top-level close and a nested frame's non-terminal `error` share it.
294
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
295
+ // cousin of rate_limit/server_error) joins the retriable set.
296
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
297
+ // decommissioned model id) is deliberately EXCLUDED: explicit
298
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
299
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
300
+ // deliberate non-retriable: a billing-class code (the account is on
301
+ // hold — a first cousin of `billing_error`, cleared by the account
302
+ // holder, never by re-sending the turn).
303
+ //
304
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
305
+ // deliberate non-retriables recorded here for the same reason — an
306
+ // omission must never read as an oversight:
307
+ // - `verification_required`: the request is gated on an out-of-band
308
+ // human step (identity/org verification). Nothing about the turn
309
+ // changes by re-sending it; the block clears only when a person
310
+ // completes the verification.
311
+ // - `cloud_credential_error`: a credential/billing-class failure on
312
+ // the cloud-provider leg (a first cousin of `billing_error` and
313
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
314
+ // unauthorized credential is exactly as bad on the next attempt.
315
+ function assistantErrorRetriable(errCode) {
316
+ return errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded";
317
+ }
318
+ const NOTHING_ANCHORED = { replay: false, host: false };
319
+ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetadata, blockMeta, phase) {
250
320
  switch (block.type) {
251
321
  case "text": {
252
322
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
@@ -255,23 +325,42 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
255
325
  // a duplicate id-less supplement block.
256
326
  const id = `${messageId}:text:${blockIndex}`;
257
327
  const citations = block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
258
- a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
328
+ if (blockMeta !== undefined) {
329
+ // textStart's sugar has no `_meta` field; `a.emit()` is the base primitive.
330
+ a.emit({
331
+ type: "text.start",
332
+ id,
333
+ messageId,
334
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
335
+ _meta: blockMeta,
336
+ });
337
+ }
338
+ else {
339
+ a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
340
+ }
259
341
  a.textDelta(id, messageId, block.text);
260
342
  a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
261
- return;
343
+ return { replay: true, host: blockMeta !== undefined };
262
344
  }
263
345
  case "thinking": {
264
346
  const id = `${messageId}:reasoning:${blockIndex}`;
265
- if (blockProviderMetadata !== undefined) {
266
- // reasoningStart's sugar signature has no providerMetadata parameter
267
- // (only textStart's does) — `a.emit()` is the documented base
268
- // primitive for exactly this case (schema DOES support it on
269
- // reasoning.start; StreamAssembler docstring: "guarantees no
270
- // AgClosedEventType is ever unreachable").
271
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
347
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
348
+ // reasoningStart's sugar signature has no providerMetadata or `_meta`
349
+ // parameter — `a.emit()` is the documented base primitive for exactly
350
+ // this case (schema DOES support both on reasoning.start;
351
+ // StreamAssembler docstring: "guarantees no AgClosedEventType is ever
352
+ // unreachable").
353
+ a.emit({
354
+ type: "reasoning.start",
355
+ id,
356
+ messageId,
357
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
358
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
359
+ ...(phase !== undefined ? { phase } : {}),
360
+ });
272
361
  }
273
362
  else {
274
- a.reasoningStart(id, messageId);
363
+ a.reasoningStart(id, messageId, phase !== undefined ? { phase } : undefined);
275
364
  }
276
365
  a.reasoningDelta(id, messageId, block.thinking);
277
366
  a.reasoningEnd(id, messageId);
@@ -285,13 +374,19 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
285
374
  provider: "anthropic",
286
375
  });
287
376
  }
288
- return;
377
+ return { replay: true, host: blockMeta !== undefined };
289
378
  }
290
379
  case "redacted_thinking": {
291
380
  // No visible text; the redacted blob is the replay-load-bearing opaque part.
292
381
  const id = `${messageId}:reasoning:${blockIndex}`;
293
- if (blockProviderMetadata !== undefined) {
294
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
382
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
383
+ a.emit({
384
+ type: "reasoning.start",
385
+ id,
386
+ messageId,
387
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
388
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
389
+ });
295
390
  }
296
391
  else {
297
392
  a.reasoningStart(id, messageId);
@@ -302,7 +397,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
302
397
  value: block.data,
303
398
  provider: "anthropic",
304
399
  });
305
- return;
400
+ return { replay: true, host: blockMeta !== undefined };
306
401
  }
307
402
  case "tool_use":
308
403
  case "server_tool_use":
@@ -334,7 +429,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
334
429
  });
335
430
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
336
431
  a.toolArgsAssembled(toolCallId, input);
337
- return;
432
+ return { replay: true, host: false };
338
433
  }
339
434
  case "mcp_tool_result": {
340
435
  // MCP tool results from the assistant side: map to tool.done with content + outcome.
@@ -347,7 +442,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
347
442
  isError: block.is_error,
348
443
  messageId,
349
444
  });
350
- return;
445
+ return NOTHING_ANCHORED;
351
446
  }
352
447
  case "compaction": {
353
448
  // Compaction blocks carry a provider-produced context summary (spec §4).
@@ -360,12 +455,12 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
360
455
  : undefined,
361
456
  provider: "anthropic",
362
457
  });
363
- return;
458
+ return NOTHING_ANCHORED;
364
459
  }
365
460
  default: {
366
461
  // image / resource / other rich content blocks ride content.block (spec §4).
367
462
  a.contentBlock(messageId, assistantContentBlockToAgBlock(block));
368
- return;
463
+ return NOTHING_ANCHORED;
369
464
  }
370
465
  }
371
466
  }
@@ -510,6 +605,30 @@ const CARRIED_STANDALONE_TYPES = new Set([
510
605
  // thread-rotation mapping is a future spec decision, not a mechanical carry.
511
606
  "conversation_reset",
512
607
  ]);
608
+ // The top-level `type` literals the SDKMessage union declares (0.3.280: 39
609
+ // members over these 11 types). A frame whose `type` is NOT among them is
610
+ // RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
611
+ // frame type). The first one observed: `command_lifecycle`
612
+ // ({command_uuid, state: "queued"|"started"|"completed"}, three per prompt,
613
+ // streaming-input mode; live on corpus/multi-result-sonnet5), the host
614
+ // prompt's queue lifecycle keyed by the caller's message uuid. Through the
615
+ // 0.7.0 stack it fell through `drive()` to the no-op, a silent drop against
616
+ // SPEC §8.0 graceful degradation. An unknown top-level type now rides the
617
+ // uniform carry, `ext.anthropic.frame{kind: <type>, frame}`, verbatim (§8 item
618
+ // 22), so the next runtime-only frame type is carried the day it ships.
619
+ const KNOWN_TOP_LEVEL_TYPES = new Set([
620
+ "assistant",
621
+ "user",
622
+ "result",
623
+ "system",
624
+ "stream_event",
625
+ "tool_progress",
626
+ "auth_status",
627
+ "tool_use_summary",
628
+ "rate_limit_event",
629
+ "prompt_suggestion",
630
+ "conversation_reset",
631
+ ]);
513
632
  // Returns the uniform-carry `kind` string for `msg` if it is one of the arms
514
633
  // disposed `carried` in sdk-surface.json, else undefined (leaves router-plane
515
634
  // / dedicated-branch arms — including SDKPermissionDeniedMessage — untouched).
@@ -525,23 +644,97 @@ function anthropicFrameKind(msg) {
525
644
  // runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
526
645
  // carry it verbatim. A malformed list is ignored, never thrown on (Tenet 6);
527
646
  // `string[]` is itself a JsonValue, so no cast is needed downstream.
647
+ // A COPY, never the frame's own array: the value is emitted unparsed
648
+ // (result-meta, message.metadata), core's StreamAssembler does not copy, and
649
+ // push() hands a JSON frame through by reference, so returning `v` would let an
650
+ // emitted event share the host's live array (cto's aliasing audit).
528
651
  function readUserMessageUuids(v) {
529
- return Array.isArray(v) && v.every((s) => typeof s === "string") ? v : undefined;
652
+ return Array.isArray(v) && v.every((s) => typeof s === "string") ? [...v] : undefined;
530
653
  }
654
+ // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
655
+ // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
656
+ // are CLI-wrapper facts the Messages API never consumes. See the split in
657
+ // drive()'s assistant branch.
658
+ const HOST_ONLY_WRAPPER_KEYS = new Set([
659
+ "narration_block_indexes",
660
+ "diagnostics",
661
+ "api_error",
662
+ "api_error_params",
663
+ "api_error_code",
664
+ // rd-15 (founder: defer the field, fix the carries): three more @internal
665
+ // CLI assistant-wrapper strings, carried where the host can read them.
666
+ "error_details",
667
+ "advisor_model",
668
+ "attribution_agent",
669
+ ]);
531
670
  // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
532
671
  // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
533
672
  // 0.3.272 (a pass-through of the Messages API field that rides the assistant
534
673
  // wrapper), so it is read through the JSON boundary and shape-guarded here, never
535
- // cast. Integer indexes into `message.content`; an out-of-range or non-integer
536
- // member means the producer changed shape, so the whole array is refused rather
537
- // than half-carried.
674
+ // cast. Integer indexes into `message.content`; a non-integer or negative member
675
+ // means the producer changed shape, so the whole array is refused rather than
676
+ // half-carried. The upper bound is not checked here: an out-of-range index
677
+ // simply names no block where it is used (the draft.4 `phase` mapping).
678
+ // A copy for the same reason as readUserMessageUuids: the block-less wrapper
679
+ // path emits it in message.metadata unparsed.
538
680
  function readNarrationBlockIndexes(v) {
539
681
  return Array.isArray(v) &&
540
682
  v.length > 0 &&
541
683
  v.every((n) => typeof n === "number" && Number.isInteger(n) && n >= 0)
542
- ? v
684
+ ? [...v]
543
685
  : undefined;
544
686
  }
687
+ // A provider- or harness-originated native subtree forwarded WHOLE: JSON-
688
+ // validated (a copy) and with every `fallback_credit_token` deleted at any
689
+ // depth (withoutCreditTokens). Every verbatim carrier of this facet goes
690
+ // through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
691
+ // carries, provider-raw blocks, and the CLI/API wrapper subtrees
692
+ // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats).
693
+ // Model- or tool-authored payloads (tool input, a deferred tool call, MCP
694
+ // structuredContent / _meta / resourceLinks, structured_output) are NOT
695
+ // stripped: a key there is user content, and the wire already carries the same
696
+ // data as the tool call or result.
697
+ function carryVerbatim(v) {
698
+ return withoutCreditTokens(JsonValue.parse(v));
699
+ }
700
+ // rd-15 / SPEC §13.7 (queued): a provider credit or bearer token is never
701
+ // emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
702
+ // (top level and per fallback), so every key of that name is deleted at any
703
+ // depth; everything else is kept verbatim.
704
+ function withoutCreditTokens(v) {
705
+ if (Array.isArray(v))
706
+ return v.map(withoutCreditTokens);
707
+ if (typeof v === "object" && v !== null) {
708
+ const out = {};
709
+ for (const [k, x] of Object.entries(v))
710
+ if (k !== "fallback_credit_token")
711
+ out[k] = withoutCreditTokens(x);
712
+ return out;
713
+ }
714
+ return v;
715
+ }
716
+ // A tool_result's text, for a failed Task's nested turn.error message: the
717
+ // string content, or its text blocks joined; undefined when there is none.
718
+ function toolResultText(content) {
719
+ if (typeof content === "string")
720
+ return content !== "" ? content : undefined;
721
+ if (!Array.isArray(content))
722
+ return undefined;
723
+ const texts = [];
724
+ for (const b of content)
725
+ if (isJsonObject(b) && b["type"] === "text" && typeof b["text"] === "string")
726
+ texts.push(b["text"]);
727
+ const joined = texts.join("\n");
728
+ return joined !== "" ? joined : undefined;
729
+ }
730
+ // A result's `terminal_reason` when it names why the turn ended other than a
731
+ // normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
732
+ // live API error's own value is "api_error", which is also the generic code, so
733
+ // that close is unchanged. Typed as the SDK's TerminalReason union, but a newer
734
+ // CLI may send an undeclared value, so only a non-empty string is taken.
735
+ function closeCauseTerminalReason(v) {
736
+ return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
737
+ }
545
738
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
546
739
  // on both frames that carry it (the API-error assistant frame and the
547
740
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -713,7 +906,7 @@ function apiErrorStatusRetriable(status) {
713
906
  // value verbatim; it also drives `turn.error.retriable` (see
714
907
  // `startupFailureRetriable`). Read through the JSON boundary because it is
715
908
  // declared on that one arm only.
716
- function resultMetaPayload(msg) {
909
+ function resultMetaPayload(msg, closesAsError) {
717
910
  const byModel = {};
718
911
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
719
912
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -730,7 +923,7 @@ function resultMetaPayload(msg) {
730
923
  // Undeclared siblings are only reachable through the JSON boundary: widen to
731
924
  // `unknown` (no cast) and let the isJsonObject guard narrow.
732
925
  const raw = msg;
733
- const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
926
+ const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? carryVerbatim(raw["subagent_stats"]) : undefined;
734
927
  const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
735
928
  // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
736
929
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
@@ -739,6 +932,26 @@ function resultMetaPayload(msg) {
739
932
  // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
740
933
  const apiErrorCode = readApiErrorCode(msg);
741
934
  const startupFailureReason = readStartupFailureReason(msg);
935
+ // `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
936
+ // input}`): the tool call a host's PreToolUse `defer` decision parked, which
937
+ // the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
938
+ // the host needs it to act on the parked call. Through 0.6.4 the facet never
939
+ // read it (a silent drop). Carried WHOLE and verbatim (the `subagent_stats`
940
+ // precedent); whether it should instead map onto `turn.done.outcome.paused`
941
+ // (asks) is a question routed to sp-protocol / sp-rnd. Fixture-only: no
942
+ // capture sets a defer hook.
943
+ const deferredToolUse = isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
944
+ // `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
945
+ // API error that ended the turn. It already decides `retriable` on an
946
+ // is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
947
+ // the census allowlist's "carry candidate the first time an error seed
948
+ // surfaces it" (sp-probe's api-error-auth seed: 401). Absent or null ⇒ no key.
949
+ const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
950
+ // `stop_reason` on a result that closes as turn.error: turn.error has no
951
+ // finishReason slot (and finishReasonRaw is turn.done-only), so the native
952
+ // value would otherwise be dropped. Carried verbatim ONLY on an error close;
953
+ // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
954
+ const stopReason = closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
742
955
  const payload = {
743
956
  ...(typeof msg.fast_mode_disabled_reason === "string"
744
957
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -753,17 +966,55 @@ function resultMetaPayload(msg) {
753
966
  ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
754
967
  ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
755
968
  ...(subagentStats !== undefined ? { subagentStats } : {}),
969
+ ...(deferredToolUse !== undefined ? { deferredToolUse } : {}),
970
+ ...(apiErrorStatus !== undefined ? { apiErrorStatus } : {}),
971
+ ...(stopReason !== undefined ? { stopReason } : {}),
756
972
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
757
973
  };
758
974
  return Object.keys(payload).length > 0 ? payload : undefined;
759
975
  }
976
+ // A result frame's turn usage, or undefined when the frame's usage trio is not
977
+ // the shape `mapTurnUsage` dereferences. Both result arms are
978
+ // discriminant-validated only, so every call goes through this guard (Tenet 6:
979
+ // a malformed frame must not throw out of push()); absent ⇒ no usage key.
980
+ // The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
981
+ // object and its minimal real shape (numeric input/output token counts, so an
982
+ // empty `usage: {}` stays "no usage" as before), the `modelUsage` object and
983
+ // each of its entries (`mapModelUsage`), and `total_cost_usd`.
984
+ // `server_tool_use` is NOT required: `serverToolRequestCount` reads it totally,
985
+ // so a leaner producer that omits it keeps the rest of its usage.
986
+ function guardedTurnUsage(msg) {
987
+ const raw = msg;
988
+ if (!isJsonObject(raw))
989
+ return undefined;
990
+ const rawUsage = raw["usage"];
991
+ const rawModelUsage = raw["modelUsage"];
992
+ return isJsonObject(rawUsage) &&
993
+ typeof rawUsage["input_tokens"] === "number" &&
994
+ typeof rawUsage["output_tokens"] === "number" &&
995
+ isJsonObject(rawModelUsage) &&
996
+ Object.values(rawModelUsage).every(isJsonObject) &&
997
+ typeof raw["total_cost_usd"] === "number"
998
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
999
+ : undefined;
1000
+ }
1001
+ /** 64 random bits as 16 hex chars: the default per-invoke fallback id stem
1002
+ * (vercel-ai's mintInvokeNonce). */
1003
+ function mintInvokeNonce() {
1004
+ const bytes = new Uint8Array(8);
1005
+ globalThis.crypto.getRandomValues(bytes);
1006
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1007
+ }
760
1008
  /**
761
- * Build a stateful Claude-facet normalizer over a fresh {@link StreamAssembler}.
762
- * Each `push(native)` validates `native` → `SDKMessage`, drives the engine via
763
- * primitive calls, and drains the buffered `AgEvent[]`. `flush()` closes any
764
- * dangling open message (none, in Claude's complete-message model) and drains.
1009
+ * The inner Claude-facet normalizer over a fresh {@link StreamAssembler}: each
1010
+ * `push(native)` validates `native` → `SDKMessage`, drives the engine via
1011
+ * primitive calls, and drains the buffered `AgEvent[]`; `flush()` closes any
1012
+ * dangling open message and drains. `createClaudeNormalizer` wraps it in core's
1013
+ * withAtomicPush. It must stay deterministic (no clock, no randomness): a
1014
+ * rebuild re-drives it from the journal. Its one invoke-unique input, the
1015
+ * fallback id stem, comes from the caller, which mints and holds it.
765
1016
  */
766
- export function createClaudeNormalizer(options = {}) {
1017
+ function createInnerClaudeNormalizer(options, invokeStem) {
767
1018
  const a = new StreamAssembler();
768
1019
  // Task 8c leg 4 (guuey capstone finding A): the wire-visible `parentTurnId`
769
1020
  // label passed to subagent.start/.done (`turn_${parent_tool_use_id}`) is a
@@ -774,6 +1025,136 @@ export function createClaudeNormalizer(options = {}) {
774
1025
  // sub-session's own assistant arm at subagent.start time, so a later inner
775
1026
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
776
1027
  const subagentTurnByParentToolUseId = new Map();
1028
+ // INV-TURN (SPEC:743; sp-protocol ruling B, 2026-09-23): ONE turnId names
1029
+ // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1030
+ // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1031
+ // or a stream `message_start`) in the ordinary case, or the frame's own
1032
+ // `uuid` when a notice or a result opens it (a result-only turn). The id is
1033
+ // - unique per turn, across the invokes of a resumed session too (a resume
1034
+ // keeps `session_id` unless `forkSession` is set, so the old
1035
+ // `turn_${session_id}` collided across invokes; message ids never repeat);
1036
+ // - deterministic from the wire, so the same native replays to the same ids;
1037
+ // - known at turn.start, since the opening frame carries it;
1038
+ // - `turn_`-prefixed.
1039
+ // Open from the first frame that needs a turn; the turn's result frame
1040
+ // (either arm) closes it and clears it, so the next frame opens a new one.
1041
+ //
1042
+ // Two guards keep an id naming ONE turn even on odd wire:
1043
+ // - a CLOSED id is never reopened: a late frame reusing a closed turn's
1044
+ // message id opens its turn under its own frame uuid instead;
1045
+ // - `isSDKMessage` validates only discriminants, so a missing or non-string
1046
+ // id/uuid falls back to a positional `turn_<stem>_frame_<n>` rather than a
1047
+ // shared `turn_undefined`. The stem is per invoke (DC-10: a bare
1048
+ // `turn_frame_<n>` repeated across the invokes one Reducer folds), and the
1049
+ // counter is deterministic from the wire, so an atomic-push rebuild
1050
+ // reproduces every delivered id.
1051
+ // Nested (subagent) frames never open or name a top-level turn.
1052
+ let openTopTurnId;
1053
+ const closedTopTurnIds = new Set();
1054
+ let framesSeen = 0;
1055
+ function mintId(candidate) {
1056
+ return typeof candidate === "string" && candidate.length > 0 ? `turn_${candidate}` : undefined;
1057
+ }
1058
+ function topTurnId(openingId, frameUuid) {
1059
+ if (openTopTurnId === undefined) {
1060
+ const byId = mintId(openingId);
1061
+ const byUuid = mintId(frameUuid);
1062
+ openTopTurnId =
1063
+ byId !== undefined && !closedTopTurnIds.has(byId)
1064
+ ? byId
1065
+ : byUuid !== undefined && !closedTopTurnIds.has(byUuid)
1066
+ ? byUuid
1067
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1068
+ }
1069
+ return openTopTurnId;
1070
+ }
1071
+ // The result frame closes the open turn (or, for a result-only turn, the one
1072
+ // it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
1073
+ // notice or stream opened it: the CL-09 result-only API-error path, a
1074
+ // startup-failure result, a local-command result) is OPENED here with an
1075
+ // explicit turn.start before anything else the result emits (INV-TURN,
1076
+ // SPEC:743: every turn is opened by exactly one turn.start and closed by
1077
+ // exactly one terminal; sp-protocol, 2026-09-23). Through the B commit such a
1078
+ // turn was only closed, and reduce() minted a stub record whose threadId was
1079
+ // the turnId. An open turn already has its turn.start (openMessage).
1080
+ function closingTopTurnId(resultUuid, sessionId) {
1081
+ let turnId = openTopTurnId;
1082
+ if (turnId === undefined) {
1083
+ turnId = topTurnId(resultUuid, undefined);
1084
+ a.openTurn(turnId, options.threadId ?? sessionId);
1085
+ }
1086
+ openTopTurnId = undefined;
1087
+ closedTopTurnIds.add(turnId);
1088
+ return turnId;
1089
+ }
1090
+ // A NESTED (subagent) turn is one per subagent run, keyed by the spawning
1091
+ // `parent_tool_use_id`: `turn_` + that run's first nested message id. Through
1092
+ // 0.6.4 it was `turn_${session_id}` too, which merged every subagent run of a
1093
+ // session into one nested turn (and, if a subagent's frames carry the
1094
+ // parent's session_id, collided with the top-level turn itself). It must
1095
+ // never equal the synthetic `parentTurnId` label `turn_${parent_tool_use_id}`
1096
+ // (guuey capstone finding A), and a message id never does.
1097
+ function nestedTurnId(parentToolUseId, firstMessageId, frameUuid) {
1098
+ const known = subagentTurnByParentToolUseId.get(parentToolUseId);
1099
+ if (known !== undefined && !closedRuns.has(parentToolUseId))
1100
+ return known;
1101
+ // A new run, or a frame arriving for a run that already CLOSED: mint a fresh
1102
+ // id (a closed nested id is never reopened, as for top-level turns).
1103
+ const byId = mintId(firstMessageId);
1104
+ const byUuid = mintId(frameUuid);
1105
+ const minted = byId !== undefined && !closedNestedTurnIds.has(byId)
1106
+ ? byId
1107
+ : byUuid !== undefined && !closedNestedTurnIds.has(byUuid)
1108
+ ? byUuid
1109
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1110
+ closedRuns.delete(parentToolUseId);
1111
+ subagentTurnByParentToolUseId.set(parentToolUseId, minted);
1112
+ return minted;
1113
+ }
1114
+ const openRuns = new Map();
1115
+ const closedRuns = new Set();
1116
+ const closedNestedTurnIds = new Set();
1117
+ // Nested turnId → its FIRST API error frame's close (released at run close).
1118
+ const nestedStashedErrors = new Map();
1119
+ // task_started: task_id → the spawning tool_use_id, for a task_notification
1120
+ // that carries only its task_id.
1121
+ const toolUseIdByTaskId = new Map();
1122
+ function openRun(parentToolUseId, turnId, parentTurnId) {
1123
+ if (openRuns.has(parentToolUseId))
1124
+ return;
1125
+ openRuns.set(parentToolUseId, { turnId, parentTurnId });
1126
+ a.subagentStart(turnId, parentTurnId);
1127
+ }
1128
+ function closeRun(parentToolUseId, close) {
1129
+ const run = openRuns.get(parentToolUseId);
1130
+ if (run === undefined)
1131
+ return;
1132
+ openRuns.delete(parentToolUseId);
1133
+ closedRuns.add(parentToolUseId);
1134
+ closedNestedTurnIds.add(run.turnId);
1135
+ const stashed = nestedStashedErrors.get(run.turnId);
1136
+ nestedStashedErrors.delete(run.turnId);
1137
+ if (stashed !== undefined) {
1138
+ a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1139
+ }
1140
+ else if (close.kind === "success") {
1141
+ a.closeTurnDone(run.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
1142
+ }
1143
+ else if (close.kind === "error") {
1144
+ a.closeTurnError(run.turnId, { message: close.message, ...(close.code !== undefined ? { code: close.code } : {}) });
1145
+ }
1146
+ else {
1147
+ a.emit({ type: "turn.abort", turnId: run.turnId, reason: close.reason });
1148
+ }
1149
+ a.subagentDone(run.turnId, run.parentTurnId);
1150
+ }
1151
+ // Flush only: every run still open, innermost (latest-opened) first, as
1152
+ // INV-FLUSH orders its own closes.
1153
+ function abortOpenRuns() {
1154
+ for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1155
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1156
+ }
1157
+ }
777
1158
  // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
778
1159
  // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
779
1160
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
@@ -785,6 +1166,17 @@ export function createClaudeNormalizer(options = {}) {
785
1166
  // convention" per the adaptation brief.
786
1167
  const messageIdsByUuid = new Map();
787
1168
  const deniedLiveByToolUseId = new Map();
1169
+ // Every toolCallId that already got its FINAL tool.done in this invoke. The
1170
+ // result's permission_denials aggregate skips these: re-emitting tool.start +
1171
+ // tool.done{denied} for a call already closed is a duplicate start and a second
1172
+ // final tool.done (INV-BLOCK; rd-14 P14 parks it; the M22 double-fold hazard).
1173
+ const closedToolCallIds = new Set();
1174
+ // SDK message id → the `diagnostics` value already carried for it (see the
1175
+ // assistant branch): one carry per response, not one per frame.
1176
+ const diagnosticsCarried = new Map();
1177
+ // rd-15: top-level turnId → the closing response's non-null stop_details (credit
1178
+ // tokens stripped) and the message it describes, emitted on that turn's turn.done.
1179
+ const stopDetailsByTurn = new Map();
788
1180
  // The live denial's diagnostic fields, camelCased — the providerMetadata bag
789
1181
  // on the enriched `<turnId>:denials` tool.done. undefined when the live
790
1182
  // frame carried none of them (no empty bag).
@@ -818,8 +1210,10 @@ export function createClaudeNormalizer(options = {}) {
818
1210
  // (cf. `<turnId>:denials`, `<toolCallId>:result`). Nothing is fabricated: the
819
1211
  // blocks, their order and their content are the SDK's own.
820
1212
  const lifecyclesBySdkId = new Map();
821
- /** Seal the deferred message (and its subagent bracket), if one is open. */
822
- function closePendingMessage() {
1213
+ /** Seal the deferred message, if one is open (a run's bracket closes separately; see `openRun`).
1214
+ * `atFlush`: the stream ENDED here, so open stream blocks close without minting content
1215
+ * (INV-FLUSH (3), draft.4; see `finalizeStreamBlock`). */
1216
+ function closePendingMessage(atFlush = false) {
823
1217
  if (pending === undefined)
824
1218
  return;
825
1219
  const p = pending;
@@ -830,12 +1224,12 @@ export function createClaudeNormalizer(options = {}) {
830
1224
  // produced) so no lifecycle dangles under the seal.
831
1225
  if (p.streamBlocks.size > 0) {
832
1226
  for (const idx of [...p.streamBlocks.keys()].sort((x, y) => x - y)) {
833
- finalizeStreamBlock(p, idx);
1227
+ finalizeStreamBlock(p, idx, atFlush);
834
1228
  }
835
1229
  }
836
1230
  a.closeMessage(p.emittedId, p.usage);
837
- if (p.parentTurnId !== undefined)
838
- a.subagentDone(p.turnId, p.parentTurnId);
1231
+ // The subagent bracket is per RUN now (see `openRun`), so sealing a nested
1232
+ // message no longer closes its nested turn.
839
1233
  }
840
1234
  // ─── workspace#7: stream_event mapping helpers ──────────────────────────────
841
1235
  // Unmappable stream frames — an orphan delta after a fold-binding frame
@@ -843,7 +1237,7 @@ export function createClaudeNormalizer(options = {}) {
843
1237
  // ride the uniform lossless carry (`kind` is the frame's own discriminant,
844
1238
  // per the ext.anthropic.frame convention). Nothing is silently dropped.
845
1239
  function carryStreamFrame(msg) {
846
- a.emitExt("anthropic", "frame", { kind: "stream_event", frame: JsonValue.parse(msg) });
1240
+ a.emitExt("anthropic", "frame", { kind: "stream_event", frame: carryVerbatim(msg) });
847
1241
  }
848
1242
  // `ttft_ms` (time to first token, on the partial envelope) has no core home —
849
1243
  // it rides the message.metadata merge channel, wire name verbatim (the
@@ -898,18 +1292,39 @@ export function createClaudeNormalizer(options = {}) {
898
1292
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
899
1293
  // (same end-then-opaque order as the complete arm), the MANDATORY
900
1294
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
901
- function finalizeStreamBlock(p, index) {
1295
+ // `atFlush` (INV-FLUSH (3), draft.4; the founder's fold/flush ruling, "snapshot
1296
+ // fold + honest flush; opaque at flush forbidden"; sp-claude's leg C1): the
1297
+ // stream ENDED with this block open, so the close lands NO new content. The
1298
+ // lifecycle closes stay (text.end with its already-received citations,
1299
+ // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
1300
+ // (it is authoritative, and a truncated partial_json would mint an input the
1301
+ // model never finished), no reasoning.opaque (a signature is replay-load-
1302
+ // bearing, and the turn is aborted anyway), no compaction content.block, and
1303
+ // no `phase` on reasoning.end. A binding frame that seals the message
1304
+ // mid-stream (not a flush) still finalizes as its content_block_stop would.
1305
+ function finalizeStreamBlock(p, index, atFlush = false) {
902
1306
  const b = p.streamBlocks.get(index);
903
1307
  if (b === undefined)
904
1308
  return;
905
1309
  p.streamBlocks.delete(index);
906
1310
  const messageId = p.emittedId;
1311
+ if (atFlush) {
1312
+ if (b.kind === "text")
1313
+ a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1314
+ else if (b.kind === "reasoning")
1315
+ a.reasoningEnd(b.id, messageId, undefined);
1316
+ return;
1317
+ }
907
1318
  switch (b.kind) {
908
1319
  case "text":
909
1320
  a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
910
1321
  return;
911
1322
  case "reasoning":
912
- a.reasoningEnd(b.id, messageId);
1323
+ // draft.4 `phase` for a STREAMED narration block: known only once the
1324
+ // complete frame arrived (after the start), so it rides reasoning.end
1325
+ // (§5 phase timing), and only if the block's text is non-empty
1326
+ // (§8.0 item 27). Never a post-seal event.
1327
+ a.reasoningEnd(b.id, messageId, b.narration && b.hasText ? { phase: "interim" } : undefined);
913
1328
  if (b.redacted !== undefined) {
914
1329
  a.reasoningOpaque(b.id, messageId, { kind: "redacted", value: b.redacted, provider: "anthropic" });
915
1330
  }
@@ -957,7 +1372,9 @@ export function createClaudeNormalizer(options = {}) {
957
1372
  const ev = msg.event;
958
1373
  if (ev.type === "message_start") {
959
1374
  const m = ev.message;
960
- const turnId = turnIdFor(msg.session_id, m.id);
1375
+ const turnId = msg.parent_tool_use_id !== null
1376
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1377
+ : topTurnId(m.id, msg.uuid);
961
1378
  const parentTurnId = msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
962
1379
  // Same continuation test as the complete arm: a message_start naming the
963
1380
  // message already open just joins it (and marks it streamed).
@@ -978,8 +1395,7 @@ export function createClaudeNormalizer(options = {}) {
978
1395
  // lifecycle counter, same emittedId derivation — so the complete frame
979
1396
  // that follows JOINS this lifecycle and is content-suppressed.
980
1397
  if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
981
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
982
- a.subagentStart(turnId, parentTurnId);
1398
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
983
1399
  }
984
1400
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
985
1401
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -993,6 +1409,7 @@ export function createClaudeNormalizer(options = {}) {
993
1409
  streamed: true,
994
1410
  streamBlocks: new Map(),
995
1411
  ttftCarried: false,
1412
+ framedThrough: 0,
996
1413
  turnBindingCarried: false,
997
1414
  };
998
1415
  pending = open;
@@ -1054,14 +1471,21 @@ export function createClaudeNormalizer(options = {}) {
1054
1471
  case "thinking": {
1055
1472
  const id = `${messageId}:reasoning:${index}`;
1056
1473
  a.reasoningStart(id, messageId);
1057
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: block.signature, redacted: undefined });
1474
+ p.streamBlocks.set(index, {
1475
+ kind: "reasoning",
1476
+ id,
1477
+ signature: block.signature,
1478
+ redacted: undefined,
1479
+ hasText: false,
1480
+ narration: false,
1481
+ });
1058
1482
  return;
1059
1483
  }
1060
1484
  case "redacted_thinking": {
1061
1485
  // Arrives complete (never delta'd); end + the redacted opaque land at stop.
1062
1486
  const id = `${messageId}:reasoning:${index}`;
1063
1487
  a.reasoningStart(id, messageId);
1064
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data });
1488
+ p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data, hasText: false, narration: false });
1065
1489
  return;
1066
1490
  }
1067
1491
  case "tool_use":
@@ -1105,6 +1529,7 @@ export function createClaudeNormalizer(options = {}) {
1105
1529
  // Arrives complete inside the start frame — same tool.done mapping as
1106
1530
  // the complete arm's mcp_tool_result case.
1107
1531
  const outcome = block.is_error ? "error" : "ok";
1532
+ closedToolCallIds.add(block.tool_use_id);
1108
1533
  a.toolDone({
1109
1534
  toolCallId: block.tool_use_id,
1110
1535
  content: mcpToolResultContentToAgBlocks(block.content),
@@ -1121,7 +1546,7 @@ export function createClaudeNormalizer(options = {}) {
1121
1546
  a.contentBlock(messageId, {
1122
1547
  type: "provider-raw",
1123
1548
  vendor: "anthropic",
1124
- raw: JsonValue.parse(block),
1549
+ raw: carryVerbatim(block),
1125
1550
  });
1126
1551
  p.streamBlocks.set(index, { kind: "emitted" });
1127
1552
  return;
@@ -1141,17 +1566,35 @@ export function createClaudeNormalizer(options = {}) {
1141
1566
  return;
1142
1567
  }
1143
1568
  if (d.type === "thinking_delta" && b.kind === "reasoning") {
1569
+ if (typeof d.thinking === "string" && d.thinking.length > 0)
1570
+ b.hasText = true;
1144
1571
  // Claude Code stamps a RUNTIME-ONLY `estimated_tokens` (number | null;
1145
1572
  // undeclared on BetaThinkingDelta) on each thinking_delta. Under
1146
1573
  // Fable 5.1's default `display: omitted` the `thinking` text is '' and
1147
- // that estimate is the delta's entire payload — carried verbatim as
1148
- // providerMetadata (wire name kept; null kept: "no estimate yet" is a
1149
- // real value). Absent key ⇒ no providerMetadata, byte-identical.
1574
+ // that estimate is the delta's entire payload — carried verbatim (wire
1575
+ // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
1576
+ // no bag, byte-identical.
1577
+ //
1578
+ // X5 (sp-rnd, 2026-09-23): it rides the delta's host-only `_meta`, not
1579
+ // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
1580
+ // that must round-trip to the provider), and the Messages API never
1581
+ // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
1582
+ // on start events, so the estimate is now LIVE-ONLY (it used to fold
1583
+ // last-value-wins onto the reasoning block) — the same standing as its
1584
+ // `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
1585
+ // consumer read the folded value (guuey/ggui checked via sp-team-main).
1586
+ // `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
1587
+ // primitive (the reasoning.start precedent in `emitAssistantBlock`), and
1588
+ // the sugar's only extra step, de-cumulation, is a pass-through for a
1589
+ // non-cumulative delta like this one.
1150
1590
  const rawDelta = d;
1151
- const estimate = isJsonObject(rawDelta) && "estimated_tokens" in rawDelta
1152
- ? AgProviderMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] })
1153
- : undefined;
1154
- a.reasoningDelta(b.id, messageId, d.thinking, estimate !== undefined ? { providerMetadata: estimate } : undefined);
1591
+ if (isJsonObject(rawDelta) && "estimated_tokens" in rawDelta) {
1592
+ const estimate = AgMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] });
1593
+ a.emit({ type: "reasoning.delta", id: b.id, messageId, delta: d.thinking, _meta: estimate });
1594
+ }
1595
+ else {
1596
+ a.reasoningDelta(b.id, messageId, d.thinking);
1597
+ }
1155
1598
  return;
1156
1599
  }
1157
1600
  if (d.type === "input_json_delta" && b.kind === "tool") {
@@ -1218,7 +1661,14 @@ export function createClaudeNormalizer(options = {}) {
1218
1661
  // A future stream event type — lossless carry.
1219
1662
  carryStreamFrame(msg);
1220
1663
  }
1221
- function registerUuid(uuid, ids) {
1664
+ // The turn each retractable message was emitted under, so a retraction's
1665
+ // `message.remove` names its OWNER explicitly (INV-OWNER) instead of taking
1666
+ // the assembler's last-turn backfill, which overlapping subagent runs can skew.
1667
+ const turnByMessageId = new Map();
1668
+ function registerUuid(uuid, ids, turnId) {
1669
+ if (turnId !== undefined)
1670
+ for (const id of ids)
1671
+ turnByMessageId.set(id, turnId);
1222
1672
  if (uuid === undefined || ids.length === 0)
1223
1673
  return;
1224
1674
  const existing = messageIdsByUuid.get(uuid);
@@ -1242,14 +1692,63 @@ export function createClaudeNormalizer(options = {}) {
1242
1692
  if (ids === undefined)
1243
1693
  continue;
1244
1694
  for (const id of ids) {
1245
- a.emit({ type: "message.remove", id });
1695
+ const owner = turnByMessageId.get(id);
1696
+ a.emit({ type: "message.remove", id, ...(owner !== undefined ? { turnId: owner } : {}) });
1697
+ }
1698
+ }
1699
+ }
1700
+ // Emit a result's permission_denials as tool.start + tool.done denied pairs,
1701
+ // inside a dedicated carrier message: the assistant message is already
1702
+ // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
1703
+ // closed turns. BOTH result arms call it, at the same point (after the seal
1704
+ // and the run closes, before result-meta and the close). Through 0.6.4 only
1705
+ // the success arm did, so an error-subtype result (SDKResultError declares
1706
+ // permission_denials too, e.g. error_max_turns after a denied tool) dropped
1707
+ // its denials.
1708
+ function emitDenialsCarrier(turnId, denials, sessionId) {
1709
+ // Skip every denial whose call already has its final tool.done in this
1710
+ // invoke: a harness-stamped denied tool_result (the user branch), an
1711
+ // mcp_tool_result, or an earlier carrier (a repeated id, in this list or a
1712
+ // later result's). A denial for an id not yet closed still gets its pair.
1713
+ const fresh = [];
1714
+ for (const d of denials) {
1715
+ if (closedToolCallIds.has(d.tool_use_id))
1716
+ continue;
1717
+ closedToolCallIds.add(d.tool_use_id);
1718
+ fresh.push(d);
1719
+ }
1720
+ if (fresh.length > 0) {
1721
+ const denialMsgId = `${turnId}:denials`;
1722
+ a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? sessionId });
1723
+ for (const denial of fresh) {
1724
+ // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
1725
+ // "handled" via existing-home mapping): enrich with the live
1726
+ // standalone denial notice recorded above (keyed by tool_use_id),
1727
+ // when one preceded this aggregate — the actual rejection text
1728
+ // returned to the model, plus decision-reason/agent-id context —
1729
+ // rather than leaving a bare empty-content stub. No second
1730
+ // tool.start/tool.done pair is ever emitted for the live frame
1731
+ // itself (see the dedicated `permission_denied` branch below).
1732
+ const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1733
+ const liveFields = liveDenialMeta(live);
1734
+ const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1735
+ a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1736
+ a.toolDone({
1737
+ toolCallId: denial.tool_use_id,
1738
+ content: live !== undefined ? [{ type: "text", text: live.message }] : [],
1739
+ outcome: "denied",
1740
+ ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
1741
+ });
1246
1742
  }
1743
+ a.closeMessage(denialMsgId);
1247
1744
  }
1248
1745
  }
1249
1746
  function drive(msg) {
1250
1747
  if (msg.type === "assistant") {
1251
1748
  const m = msg.message;
1252
- const turnId = turnIdFor(msg.session_id, m.id);
1749
+ const turnId = msg.parent_tool_use_id !== null
1750
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1751
+ : topTurnId(m.id, msg.uuid);
1253
1752
  const parentTurnId = msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1254
1753
  // guuey#26: does this frame CONTINUE the message left open by the previous
1255
1754
  // frame? Same SDK message id, same turn, same nesting — anything else is a
@@ -1308,7 +1807,7 @@ export function createClaudeNormalizer(options = {}) {
1308
1807
  // Structured plain-JSON shape per its own doc (evolves additively);
1309
1808
  // JsonValue.parse both validates that invariant and satisfies the
1310
1809
  // wrapper-meta channel's type without an unchecked cast.
1311
- wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1810
+ wrapperMetaRaw["context_usage"] = carryVerbatim(msg.context_usage);
1312
1811
  }
1313
1812
  // `usage_report` (0.3.273): the structured twin of the /usage report,
1314
1813
  // riding the synthetic assistant message that delivers its text (session
@@ -1322,7 +1821,7 @@ export function createClaudeNormalizer(options = {}) {
1322
1821
  // claude.ai-subscriber sessions", and the capture harness authenticates
1323
1822
  // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1324
1823
  if (msg.usage_report !== undefined) {
1325
- wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
1824
+ wrapperMetaRaw["usage_report"] = carryVerbatim(msg.usage_report);
1326
1825
  }
1327
1826
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1328
1827
  // the indexes of THIS frame's content blocks that are user-facing narration
@@ -1340,6 +1839,28 @@ export function createClaudeNormalizer(options = {}) {
1340
1839
  if (narrationBlockIndexes !== undefined) {
1341
1840
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1342
1841
  }
1842
+ // `message.diagnostics` (a Messages API response field, first seen live on
1843
+ // sp-probe's defer-tool-sonnet5-resume-unavailable, 7c6880f): per-response
1844
+ // diagnostics, there `{cache_miss_reason: {type: "tools_changed",
1845
+ // cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
1846
+ // Response-only (never sent back on replay), so it rides host-only `_meta`
1847
+ // (SPEC §12, the X5 split), verbatim with its wire name. Undeclared on
1848
+ // @anthropic-ai/sdk 0.93.0's BetaMessage, so read through the JSON
1849
+ // boundary; null (its usual value) carries nothing. It is per RESPONSE,
1850
+ // and the CLI repeats the same message object on every frame of a
1851
+ // multi-frame message, so it is carried once per SDK message id (again
1852
+ // only if the value changes).
1853
+ const rawMessage = m;
1854
+ const diagnostics = isJsonObject(rawMessage) && isJsonObject(rawMessage["diagnostics"])
1855
+ ? carryVerbatim(rawMessage["diagnostics"])
1856
+ : undefined;
1857
+ if (diagnostics !== undefined) {
1858
+ const diagnosticsKey = JSON.stringify(diagnostics);
1859
+ if (diagnosticsCarried.get(m.id) !== diagnosticsKey) {
1860
+ wrapperMetaRaw["diagnostics"] = diagnostics;
1861
+ diagnosticsCarried.set(m.id, diagnosticsKey);
1862
+ }
1863
+ }
1343
1864
  // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1344
1865
  // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1345
1866
  // The CLI stamps them on the synthetic API-error assistant frame, the one
@@ -1366,31 +1887,50 @@ export function createClaudeNormalizer(options = {}) {
1366
1887
  wrapperMetaRaw["api_error"] = apiError;
1367
1888
  const apiErrorParams = rawAssistant["api_error_params"];
1368
1889
  if (isJsonObject(apiErrorParams))
1369
- wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
1890
+ wrapperMetaRaw["api_error_params"] = carryVerbatim(apiErrorParams);
1370
1891
  }
1371
1892
  const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1372
1893
  if (assistantApiErrorCode !== undefined) {
1373
1894
  wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1374
1895
  }
1896
+ // rd-15 (founder ruling 2026-09-24: defer the neutral remedy field, fix the
1897
+ // vendor carries; a 0.7.0 carry with zero golden moves). Three more
1898
+ // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
1899
+ // 0.3.280 (so read through the JSON boundary), carried verbatim under their
1900
+ // wire names on the frame's first block's host-only `_meta` (the X5 route,
1901
+ // which folds onto block._meta; never providerMetadata, SPEC §12):
1902
+ // - `error_details`: "Raw API error message: preserves details (e.g.
1903
+ // prompt-too-long token counts) that user-facing content discards"
1904
+ // (the CLI's own schema doc; the same datum is typed on the StopFailure
1905
+ // hook input, sdk.d.ts:9154);
1906
+ // - `advisor_model`: "Advisor model that produced this message, when
1907
+ // applicable";
1908
+ // - `attribution_agent`: "agent name parsed from querySource".
1909
+ // A non-string value is not carried. No committed native carries any of
1910
+ // them, so no golden moves.
1911
+ if (isJsonObject(rawAssistant)) {
1912
+ for (const key of ["error_details", "advisor_model", "attribution_agent"]) {
1913
+ const v = rawAssistant[key];
1914
+ if (typeof v === "string")
1915
+ wrapperMetaRaw[key] = v;
1916
+ }
1917
+ }
1375
1918
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1376
1919
  // the bag below, once `open` is known — their once-per-message flag is
1377
1920
  // shared with the stream arm's carry.
1378
- // A non-null parent_tool_use_id ⇒ this assistant message is a NESTED turn
1379
- // (subagent). subagent.start is the SOLE nested-turn opener (spec §4/§5) and
1380
- // seeds the turn so openMessage does NOT synthesize a duplicate turn.start.
1381
- // guuey#26: a CONTINUATION frame joins the message (and, when nested, the
1382
- // subagent bracket) the previous frame opened — no second subagent.start,
1383
- // no second message.start.
1921
+ // A non-null parent_tool_use_id ⇒ this assistant message belongs to a
1922
+ // NESTED turn (subagent run). subagent.start is the SOLE nested-turn opener
1923
+ // (spec §4/§5), emitted once per run by `openRun`, and seeds the turn so
1924
+ // openMessage does NOT synthesize a duplicate turn.start. guuey#26: a
1925
+ // CONTINUATION frame joins the message the previous frame opened — no
1926
+ // second message.start.
1384
1927
  let open;
1385
1928
  if (continued !== undefined) {
1386
1929
  open = continued;
1387
1930
  }
1388
1931
  else {
1389
- if (parentTurnId !== undefined) {
1390
- if (msg.parent_tool_use_id !== null) {
1391
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
1392
- }
1393
- a.subagentStart(turnId, parentTurnId);
1932
+ if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
1933
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1394
1934
  }
1395
1935
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
1396
1936
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -1408,6 +1948,7 @@ export function createClaudeNormalizer(options = {}) {
1408
1948
  streamed: false,
1409
1949
  streamBlocks: new Map(),
1410
1950
  ttftCarried: false,
1951
+ framedThrough: 0,
1411
1952
  turnBindingCarried: false,
1412
1953
  };
1413
1954
  pending = open;
@@ -1420,6 +1961,22 @@ export function createClaudeNormalizer(options = {}) {
1420
1961
  });
1421
1962
  }
1422
1963
  const messageId = open.emittedId;
1964
+ // rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
1965
+ // {type, category, explanation, fallbacks?}) is carried verbatim on its
1966
+ // turn's closing turn.done.messageMetadata, which folds onto the message it
1967
+ // names (SPEC §5 turn.done row). The CLOSING response's value only: a later
1968
+ // response of the turn without one clears it. Every `fallback_credit_token`,
1969
+ // at any depth, is deleted first (a provider credit token is never
1970
+ // emitted). Null (every committed golden) carries nothing. Keyed by turn,
1971
+ // so a nested (subagent) response never touches its parent's entry, and
1972
+ // only top-level turns close with turn.done.
1973
+ const stopDetails = m.stop_details;
1974
+ if (isJsonObject(stopDetails)) {
1975
+ stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
1976
+ }
1977
+ else if (stopDetailsByTurn.get(turnId)?.messageId !== messageId) {
1978
+ stopDetailsByTurn.delete(turnId);
1979
+ }
1423
1980
  // - `user_message_uuid` (0.3.258): the client uuid of the user message
1424
1981
  // this turn answers, stamped on the turn's FIRST reply frame only
1425
1982
  // (wrapper-level sibling per its own doc — never inside
@@ -1461,13 +2018,62 @@ export function createClaudeNormalizer(options = {}) {
1461
2018
  wrapperMetaRaw["resume_reason"] = resumeReason;
1462
2019
  }
1463
2020
  }
1464
- const wrapperMeta = Object.keys(wrapperMetaRaw).length > 0 ? AgProviderMeta.parse(wrapperMetaRaw) : undefined;
2021
+ // X5 (sp-rnd re-cut, 2026-09-23): the bag mixes two kinds of fact. SPEC
2022
+ // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2023
+ // round-trip to the provider) and `_meta` host-only side metadata.
2024
+ // `narration_block_indexes` and the API-error triad are CLI-wrapper facts
2025
+ // the Messages API never consumes, so where the bag anchors on a BLOCK they
2026
+ // ride that block's start event `_meta` (`reduce()` folds it onto
2027
+ // `block._meta`, keeping the per-frame anchoring). The rest keeps
2028
+ // `providerMetadata`. The split is by key, so the combined bag, and the
2029
+ // `message.metadata` path below that uses it, stay byte-identical
2030
+ // (message.metadata is already `AgMeta`).
2031
+ //
2032
+ // Consumer check (sp-team-main, 2026-09-23): ggui has none of these names.
2033
+ // No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
2034
+ // the native frame. guuey asked that the triad move as ONE unit; the
2035
+ // result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
2036
+ const replayRaw = {};
2037
+ const hostRaw = {};
2038
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2039
+ if (HOST_ONLY_WRAPPER_KEYS.has(k))
2040
+ hostRaw[k] = v;
2041
+ else
2042
+ replayRaw[k] = v;
2043
+ }
2044
+ const wrapperMeta = Object.keys(replayRaw).length > 0 ? AgProviderMeta.parse(replayRaw) : undefined;
2045
+ const hostMeta = Object.keys(hostRaw).length > 0 ? AgMeta.parse(hostRaw) : undefined;
2046
+ let anchored = NOTHING_ANCHORED;
1465
2047
  // workspace#7 dedupe: a STREAMED lifecycle already emitted every block
1466
2048
  // incrementally (stream ids reuse the content `index`, identical to the
1467
2049
  // arithmetic below) — this complete frame must not re-synthesize them.
1468
2050
  // Everything below the block loop (wrapper carry via message.metadata,
1469
2051
  // usage, error close, uuid registration) still runs.
1470
2052
  const suppressed = open.streamed;
2053
+ // draft.4 `phase` (§8.0 item 27, a SHOULD per the founder's A.10.5
2054
+ // ruling): a `thinking` block listed in `narration_block_indexes` whose
2055
+ // text is NON-EMPTY is interim narration → `phase:"interim"` on that
2056
+ // reasoning block. A listed empty block (display "omitted") gets none.
2057
+ // The index is FRAME-local. Never inferred from position, text or turn
2058
+ // end; never decoded from the signature; the vendor list itself still
2059
+ // rides host-only `_meta` verbatim (X5).
2060
+ const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2061
+ if (suppressed && narrationIndexes.size > 0) {
2062
+ // STREAMED: the complete frame precedes its blocks' content_block_stop
2063
+ // (CB-13; thinking-fable51 frames [62] signature → [63] frame → [64]
2064
+ // stop), so each listed frame-local index names stream block
2065
+ // `framedThrough + idx` (the frame covers the next blocks after those
2066
+ // earlier frames covered). It is marked only while it is still OPEN;
2067
+ // the phase then rides its reasoning.end, if its streamed text was
2068
+ // non-empty. A block that already sealed stays unmarked, never a
2069
+ // post-seal event and never a neighbouring block.
2070
+ for (const idx of narrationIndexes) {
2071
+ const frameBlock = m.content[idx];
2072
+ const streamBlock = open.streamBlocks.get(open.framedThrough + idx);
2073
+ if (frameBlock?.type === "thinking" && streamBlock?.kind === "reasoning")
2074
+ streamBlock.narration = true;
2075
+ }
2076
+ }
1471
2077
  if (!suppressed) {
1472
2078
  // A plain indexed loop, not `.forEach` — see `mcpToolResultContentToAgBlocks`'s
1473
2079
  // doc: `.forEach`'s callback parameter inference degrades to implicit `any`
@@ -1484,16 +2090,42 @@ export function createClaudeNormalizer(options = {}) {
1484
2090
  // (`<id>:text:0` twice would clobber in the fold). The wrapper carry
1485
2091
  // stays anchored to this FRAME's first block: `aborted` /
1486
2092
  // `resumed_from_incomplete_thinking` are per-frame facts.
1487
- emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined);
2093
+ // NON-STREAMED: the marker is known before the first delta, so it
2094
+ // rides reasoning.start (§5 phase timing).
2095
+ const interim = narrationIndexes.has(i) && block.type === "thinking" && typeof block.thinking === "string" && block.thinking.length > 0
2096
+ ? "interim"
2097
+ : undefined;
2098
+ const landed = emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined, i === 0 ? hostMeta : undefined, interim);
2099
+ if (block.type === "mcp_tool_result")
2100
+ closedToolCallIds.add(block.tool_use_id);
2101
+ if (i === 0)
2102
+ anchored = landed;
1488
2103
  }
1489
2104
  open.blockIndex += m.content.length;
1490
2105
  }
2106
+ open.framedThrough += m.content.length;
1491
2107
  // Block-less frame (e.g. aborted before any content streamed) — or a
1492
2108
  // suppressed one, whose blocks were already sealed by the stream: no
1493
- // first block exists to anchor the wrapper carry — ride message.metadata.
1494
- if ((suppressed || m.content.length === 0) && wrapperMeta !== undefined) {
2109
+ // first block exists to anchor the wrapper carry — ride message.metadata
2110
+ // (the whole combined bag, unchanged).
2111
+ if ((suppressed || m.content.length === 0) && (wrapperMeta !== undefined || hostMeta !== undefined)) {
1495
2112
  a.emit({ type: "message.metadata", messageId, metadata: wrapperMetaRaw });
1496
2113
  }
2114
+ else {
2115
+ // Whatever the first block could not anchor rides the message instead,
2116
+ // in wire order, so it still folds: the host half after a tool call (no
2117
+ // `_meta` on tool.start), and BOTH halves after a compaction, an
2118
+ // mcp_tool_result or a content.block (no providerMetadata slot).
2119
+ const unanchored = {};
2120
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2121
+ const isHost = HOST_ONLY_WRAPPER_KEYS.has(k);
2122
+ if ((isHost && !anchored.host) || (!isHost && !anchored.replay))
2123
+ unanchored[k] = v;
2124
+ }
2125
+ if (Object.keys(unanchored).length > 0) {
2126
+ a.emit({ type: "message.metadata", messageId, metadata: unanchored });
2127
+ }
2128
+ }
1497
2129
  // The seal is DEFERRED (guuey#26) — the next frame may continue this same
1498
2130
  // message id. Usage is message-level and repeated per frame, so the newest
1499
2131
  // frame's copy is the one that rides the eventual `message.end` — field by
@@ -1516,45 +2148,40 @@ export function createClaudeNormalizer(options = {}) {
1516
2148
  // close.
1517
2149
  closePendingMessage();
1518
2150
  const errCode = msg.error;
1519
- // First error frame wins: a turn already carrying a stashed close keeps
1520
- // it (before CL-09's stash, the first error frame closed the turn).
1521
- if (!stashedTurnErrors.has(turnId)) {
1522
- stashedTurnErrors.set(turnId, {
1523
- message: errCode,
1524
- code: errCode,
1525
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1526
- // cousin of rate_limit/server_error) joins the retriable set.
1527
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1528
- // decommissioned model id) is deliberately EXCLUDED: explicit
1529
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1530
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1531
- // deliberate non-retriable: a billing-class code (the account is on
1532
- // hold — a first cousin of `billing_error`, cleared by the account
1533
- // holder, never by re-sending the turn).
1534
- //
1535
- // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1536
- // deliberate non-retriables recorded here for the same reason — an
1537
- // omission must never read as an oversight:
1538
- // - `verification_required`: the request is gated on an out-of-band
1539
- // human step (identity/org verification). Nothing about the turn
1540
- // changes by re-sending it; the block clears only when a person
1541
- // completes the verification.
1542
- // - `cloud_credential_error`: a credential/billing-class failure on
1543
- // the cloud-provider leg (a first cousin of `billing_error` and
1544
- // `account_on_hold`, not of `overloaded`) — a bad, expired or
1545
- // unauthorized credential is exactly as bad on the next attempt.
1546
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1547
- });
2151
+ const retriable = assistantErrorRetriable(errCode);
2152
+ if (msg.parent_tool_use_id !== null) {
2153
+ // A NESTED error frame (sp-protocol ruling 1, 2026-09-23): the error is
2154
+ // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2155
+ // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2156
+ // parent closes as an error only when its OWN result frame says so.
2157
+ // Through 0.6.4 (whenever subagent frames carried the parent's
2158
+ // session_id) a nested rate_limit closed a recovered parent as a
2159
+ // retriable error and, first-error-wins, masked a later top-level
2160
+ // billing_error. `subagent.done` carries no outcome (SPEC:648), so the
2161
+ // failure rides the NON-terminal `error` event (SPEC:609) on the nested
2162
+ // turn: live-only but truthful and correctly owned, and inside the
2163
+ // run's still-open bracket, so before its subagent.done. The folded gap
2164
+ // ("a nested turn has no failure outcome") is sp-protocol's to bar.
2165
+ a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2166
+ // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2167
+ // frame's close is stashed and released as the nested turn.error when
2168
+ // its run closes (see `closeRun`), whatever the Task result reports.
2169
+ if (!nestedStashedErrors.has(turnId))
2170
+ nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2171
+ }
2172
+ else if (!stashedTurnErrors.has(turnId)) {
2173
+ // First error frame wins: a turn already carrying a stashed close keeps
2174
+ // it (before CL-09's stash, the first error frame closed the turn).
2175
+ stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
1548
2176
  }
1549
2177
  }
1550
- // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
1551
- // message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
1552
- // in the same order, once nothing can continue this message.
2178
+ // `subagent.done` is NOT emitted here: it brackets the RUN (see `openRun`),
2179
+ // and this message's seal is deferred (guuey#26) until nothing can continue it.
1553
2180
  // Record this frame's own uuid → the messageId it produced, so a LATER
1554
2181
  // retraction naming this uuid can translate it (Finding #1). The EMITTED
1555
2182
  // id, so a retraction still names the message that actually exists on the
1556
2183
  // wire when this frame rode a derived carrier.
1557
- registerUuid(msg.uuid, [messageId]);
2184
+ registerUuid(msg.uuid, [messageId], turnId);
1558
2185
  return;
1559
2186
  }
1560
2187
  if (msg.type === "user") {
@@ -1585,6 +2212,50 @@ export function createClaudeNormalizer(options = {}) {
1585
2212
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1586
2213
  // adoption below depends on this ordering).
1587
2214
  closePendingMessage();
2215
+ // A tool_result answering a Task call ENDS that subagent run, by what it
2216
+ // reports (B-strict, see `openRun`): its nested terminal and bracket close
2217
+ // come before the result's own tool.done. A result for any other tool
2218
+ // closes nothing. A background launch ack keeps the run open.
2219
+ if (typeof msg.message.content !== "string") {
2220
+ let resultCount = 0;
2221
+ for (const b of msg.message.content)
2222
+ if (b.type === "tool_result")
2223
+ resultCount++;
2224
+ const rawUser = msg;
2225
+ const sibling = resultCount === 1 && isJsonObject(rawUser) ? rawUser["tool_use_result"] : undefined;
2226
+ const status = isJsonObject(sibling) && typeof sibling["status"] === "string" ? sibling["status"] : undefined;
2227
+ for (const b of msg.message.content) {
2228
+ if (b.type !== "tool_result" || !openRuns.has(b.tool_use_id))
2229
+ continue;
2230
+ if (b.is_error === true) {
2231
+ closeRun(b.tool_use_id, { kind: "error", message: toolResultText(b.content) ?? "subagent failed" });
2232
+ }
2233
+ else if (status !== "async_launched" && status !== "remote_launched") {
2234
+ closeRun(b.tool_use_id, { kind: "success" });
2235
+ }
2236
+ }
2237
+ }
2238
+ // A LIVE user frame with no tool_result block is content the CLI added to
2239
+ // the conversation itself (the SDKUserMessage doc; the host's own prompts
2240
+ // come back only as isReplay acks, returned above). The live case: the
2241
+ // CLI's `isSynthetic: true` nudge "[Your previous response had no visible
2242
+ // output. …]" after an empty reply (sp-probe's
2243
+ // defer-tool-sonnet5-resume-unavailable, 7c6880f, the corpus's only such
2244
+ // frame). This branch maps only tool_result blocks, so it had no event at
2245
+ // all, and the census could not see the text go (its path normalizes to
2246
+ // the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
2247
+ // the carry the replay gap above names. DISCLOSED: a frame MIXING
2248
+ // tool_results with other blocks still maps only its tool_results (none
2249
+ // in the corpus).
2250
+ let carriesToolResult = false;
2251
+ if (typeof msg.message.content !== "string") {
2252
+ for (const b of msg.message.content)
2253
+ if (b.type === "tool_result")
2254
+ carriesToolResult = true;
2255
+ }
2256
+ if (!carriesToolResult) {
2257
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(msg) });
2258
+ }
1588
2259
  // A user message carrying tool_result blocks → tool.done per result.
1589
2260
  // parent_tool_use_id (when set) identifies a subagent tool call — the
1590
2261
  // tool.done's turnId should point at that parent call's turn so the
@@ -1596,10 +2267,57 @@ export function createClaudeNormalizer(options = {}) {
1596
2267
  // it is unknown (e.g. a result delivered before its subagent.start
1597
2268
  // was ever observed) — defensive; leg 3's never-opened-turn guard now
1598
2269
  // parks loudly on that label instead of fabricating a phantom turn.
1599
- const toolTurnId = msg.parent_tool_use_id !== null
1600
- ? (subagentTurnByParentToolUseId.get(msg.parent_tool_use_id) ??
1601
- `turn_${msg.parent_tool_use_id}`)
1602
- : undefined;
2270
+ // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2271
+ // runs make the assembler's last-turn backfill unreliable). With no turn
2272
+ // open, the frame opens one first (below), so this is never undefined.
2273
+ // Nested: the run's OPEN nested turn. A nested frame for a run that has
2274
+ // CLOSED (e.g. a background agent's tool_result after the parent's
2275
+ // result), or for one this invoke NEVER opened (the stream started
2276
+ // mid-run), gets a fresh run named by its frame, as nested assistant
2277
+ // frames do: nothing lands on a nested turn after its subagent.done, or
2278
+ // on a turn nobody opened, and no id repeats across invokes.
2279
+ // INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
2280
+ // content event for a turn the stream has not opened; sp-protocol,
2281
+ // 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
2282
+ // invoke's first frame is the deferred call's tool_result, before
2283
+ // system/init; sp-probe's defer-resume capture) opens the turn it lands
2284
+ // in, named by this frame's uuid. The resumed invoke's assistant frames
2285
+ // then join it and its result closes it. Through c54eb7f its tool.done
2286
+ // had no turn and reduce() parked from the first event. Where that result
2287
+ // folds relative to the PREVIOUS invoke's open tool block is candidate
2288
+ // 20's bar question, not decided here.
2289
+ let opensWithToolResult = false;
2290
+ for (const b of content)
2291
+ if (b.type === "tool_result")
2292
+ opensWithToolResult = true;
2293
+ if (msg.parent_tool_use_id === null && openTopTurnId === undefined && opensWithToolResult) {
2294
+ const opened = topTurnId(msg.uuid, undefined);
2295
+ a.openTurn(opened, options.threadId ?? msg.session_id ?? opened);
2296
+ }
2297
+ let toolTurnId;
2298
+ if (msg.parent_tool_use_id !== null) {
2299
+ const parentToolUseId = msg.parent_tool_use_id;
2300
+ const run = openRuns.get(parentToolUseId);
2301
+ if (run !== undefined) {
2302
+ toolTurnId = run.turnId;
2303
+ }
2304
+ else {
2305
+ // A run that CLOSED, or one this invoke never opened (the stream
2306
+ // started mid-run: a background agent spanning invokes, a resume):
2307
+ // open a fresh run named by this frame, so its tool.done lands in a
2308
+ // turn that subagent.start opened (INV-TURN) and B-strict closes.
2309
+ // Through 0.7.0's DC-10 fix the never-opened case named the synthetic
2310
+ // `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
2311
+ // loudly"): a turn nobody opened, whose id REPEATED across the
2312
+ // invokes one Reducer folds (the rd-14 ids-across-invokes rule;
2313
+ // sp-protocol's message.start bar, wf_140b3183-767), and it parked.
2314
+ toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
2315
+ openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
2316
+ }
2317
+ }
2318
+ else {
2319
+ toolTurnId = openTopTurnId;
2320
+ }
1603
2321
  // tool_use_result sibling (SDK-injected rich MCP result; audit B7): carries
1604
2322
  // structuredContent (incl. render-cache markers) + _meta.ui the block-level
1605
2323
  // arm never sees. Applies only when the message has exactly ONE tool_result
@@ -1642,9 +2360,27 @@ export function createClaudeNormalizer(options = {}) {
1642
2360
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
1643
2361
  // collect every adopted messageId this frame produces below.
1644
2362
  const resultMessageIds = [];
2363
+ const nonExecutionById = readNonExecutionKinds(msg);
1645
2364
  for (const block of content) {
1646
2365
  if (block.type === "tool_result") {
1647
- const outcome = block.is_error === true ? "error" : "ok";
2366
+ // A harness-stamped denial (see isDenialKind) records as "denied"
2367
+ // with no isError, and the native block message stays in `content`,
2368
+ // so the model-facing reason survives (§2.2 draft.4: isError and
2369
+ // errorText belong to outcome "error"). Before this, the same call
2370
+ // folded "error" here and then "denied" again from the result's
2371
+ // permission_denials (sp-probe's resume-deny leg).
2372
+ // Second key (sp-protocol, same basis): when no kind is stamped, a
2373
+ // live `permission_denied` notice already seen for this id is the
2374
+ // harness's own denial record (the CLI emits it at decision time,
2375
+ // always before this result). No kind is stamped on a frame holding
2376
+ // more than one tool_result (2.1.280's stamper returns [] unless
2377
+ // exactly one), nor by a CLI that predates the stamp. A stamped kind
2378
+ // stays the primary key, so "interrupted" with a notice is still an
2379
+ // error.
2380
+ const kind = nonExecutionById.get(block.tool_use_id);
2381
+ const denied = block.is_error === true &&
2382
+ (kind !== undefined ? isDenialKind(kind) : deniedLiveByToolUseId.has(block.tool_use_id));
2383
+ const outcome = denied ? "denied" : block.is_error === true ? "error" : "ok";
1648
2384
  const toolContent = block.content === undefined ? [] : toolResultContentToAgBlocks(block.content);
1649
2385
  // `structuredContent` is not declared on `ToolResultBlockParam` in the
1650
2386
  // static SDK type, but the Claude Agent SDK injects it at runtime (spec §9
@@ -1656,11 +2392,22 @@ export function createClaudeNormalizer(options = {}) {
1656
2392
  : undefined;
1657
2393
  const resultMessageId = `${block.tool_use_id}:result`;
1658
2394
  resultMessageIds.push(resultMessageId);
2395
+ closedToolCallIds.add(block.tool_use_id);
2396
+ // This tool.done closes the call, so the result's permission_denials
2397
+ // carrier skips it. The live `permission_denied` notice for the id
2398
+ // (the CLI emits it from its canUseTool wrapper at decision time,
2399
+ // always before this tool_result) rides here instead, the same
2400
+ // providerMetadata the carrier gave it, so D drops nothing.
2401
+ const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2402
+ const resultProviderFields = {
2403
+ ...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
2404
+ ...(liveFields ?? {}),
2405
+ };
1659
2406
  a.toolDone({
1660
2407
  toolCallId: block.tool_use_id,
1661
2408
  content: toolContent,
1662
2409
  outcome,
1663
- isError: block.is_error === true,
2410
+ ...(denied ? {} : { isError: block.is_error === true }),
1664
2411
  turnId: toolTurnId,
1665
2412
  // SPEC §5 tool.done adoption (audit B10; Task 8b): the Claude SDK
1666
2413
  // closes the assistant message (message.end) BEFORE this tool_result
@@ -1684,15 +2431,15 @@ export function createClaudeNormalizer(options = {}) {
1684
2431
  : {}),
1685
2432
  ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
1686
2433
  ...(applySibling && siblingMeta !== undefined ? { _meta: siblingMeta } : {}),
1687
- ...(applySibling && siblingResourceLinks !== undefined
1688
- ? { providerMetadata: AgProviderMeta.parse({ resourceLinks: siblingResourceLinks }) }
2434
+ ...(Object.keys(resultProviderFields).length > 0
2435
+ ? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
1689
2436
  : {}),
1690
2437
  });
1691
2438
  }
1692
2439
  }
1693
2440
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
1694
2441
  // produced, so a later retraction naming this uuid can translate it.
1695
- registerUuid(msg.uuid, resultMessageIds);
2442
+ registerUuid(msg.uuid, resultMessageIds, toolTurnId);
1696
2443
  }
1697
2444
  return;
1698
2445
  }
@@ -1700,7 +2447,10 @@ export function createClaudeNormalizer(options = {}) {
1700
2447
  // guuey#26: the turn is closing — seal the open assistant message first
1701
2448
  // (message.end has always preceded the turn close).
1702
2449
  closePendingMessage();
1703
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2450
+ // B-strict: a subagent run still open (a background or unreported sub-run)
2451
+ // is NOT closed by its parent's result; it closes when the framework
2452
+ // reports it, or at flush.
2453
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1704
2454
  // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1705
2455
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1706
2456
  // the final assistant text in result — or, with is_error true, the error
@@ -1720,6 +2470,8 @@ export function createClaudeNormalizer(options = {}) {
1720
2470
  // discriminant-validated, and false/absent must stay on the success path
1721
2471
  // byte-for-byte. The stash entry is consumed either way.
1722
2472
  const stashedError = takeStashedTurnError(turnId);
2473
+ // Shape-guarded once for every close below (Tenet 6; see guardedTurnUsage).
2474
+ const turnUsage = guardedTurnUsage(msg);
1723
2475
  const apiErrorTurn = msg.is_error === true;
1724
2476
  const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1725
2477
  // structured_output (when a response schema is in effect) overrides the plain
@@ -1731,36 +2483,12 @@ export function createClaudeNormalizer(options = {}) {
1731
2483
  // CL-09: an API-error turn's denials take this same carrier, at the same
1732
2484
  // point — its close is deferred to this frame (below), so the turn is
1733
2485
  // still open here, like every other turn.
1734
- if (msg.permission_denials.length > 0) {
1735
- const denialMsgId = `${turnId}:denials`;
1736
- a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
1737
- for (const denial of msg.permission_denials) {
1738
- // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
1739
- // "handled" via existing-home mapping): enrich with the live
1740
- // standalone denial notice recorded above (keyed by tool_use_id),
1741
- // when one preceded this aggregate — the actual rejection text
1742
- // returned to the model, plus decision-reason/agent-id context —
1743
- // rather than leaving a bare empty-content stub. No second
1744
- // tool.start/tool.done pair is ever emitted for the live frame
1745
- // itself (see the dedicated `permission_denied` branch below).
1746
- const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1747
- const liveFields = liveDenialMeta(live);
1748
- const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1749
- a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1750
- a.toolDone({
1751
- toolCallId: denial.tool_use_id,
1752
- content: live !== undefined ? [{ type: "text", text: live.message }] : [],
1753
- outcome: "denied",
1754
- ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
1755
- });
1756
- }
1757
- a.closeMessage(denialMsgId);
1758
- }
2486
+ emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
1759
2487
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1760
2488
  // ride `ext.anthropic.result-meta` before the close (no core home on
1761
2489
  // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
1762
2490
  // API-error turn too, before its close like on every other turn.
1763
- const resultMeta = resultMetaPayload(msg);
2491
+ const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
1764
2492
  if (resultMeta !== undefined) {
1765
2493
  a.emitExt("anthropic", "result-meta", resultMeta);
1766
2494
  }
@@ -1771,33 +2499,51 @@ export function createClaudeNormalizer(options = {}) {
1771
2499
  // the fold keeps the cost of every round the turn ran before failing.
1772
2500
  a.closeTurnError(turnId, {
1773
2501
  ...stashedError,
1774
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2502
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1775
2503
  });
1776
2504
  return;
1777
2505
  }
1778
2506
  if (apiErrorTurn) {
1779
2507
  // No assistant error frame preceded this result (a producer that did
1780
2508
  // not yield it, or a normalizer that never saw it), so this result is
1781
- // the turn's only close. message = the result text, which on this frame
1782
- // is the API error text; code = the server's api_error_code when the
1783
- // CLI copied one through, else the generic "api_error"; retriable = the
1784
- // HTTP status says rate limit or server failure (see
1785
- // `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
1786
- // above.
1787
- const code = readApiErrorCode(msg) ?? "api_error";
2509
+ // the turn's only close. code = the server's api_error_code when the
2510
+ // CLI copied one through; else the CLI's own terminal_reason when it
2511
+ // names a cause other than a normal completion; else the generic
2512
+ // "api_error".
2513
+ // message = the result text (on an API error, its text), or the code
2514
+ // when that text is empty. retriable = the HTTP status says rate limit
2515
+ // or server failure (see `apiErrorStatusRetriable`); usage = the turn's
2516
+ // accrued usage, as above.
2517
+ // The terminal_reason step (sp-protocol, facet-local, 2026-09-23): the
2518
+ // CLI also sets is_error on a result that is NOT an API error. sp-probe's
2519
+ // resume-unavailable leg (7c6880f) is a resumed invoke whose deferred
2520
+ // tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
2521
+ // result "", no status, no api_error_code. Through b7dd7ff it closed
2522
+ // turn.error{message: "", code: "api_error"}, claiming an API failure
2523
+ // that never happened. `code` is free-form (SPEC :618), so this fills
2524
+ // existing fields from the frame's own value; a live API error
2525
+ // (terminal_reason "api_error", api-error-auth) is unchanged.
2526
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
1788
2527
  a.closeTurnError(turnId, {
1789
- message: typeof msg.result === "string" ? msg.result : code,
2528
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
1790
2529
  code,
1791
2530
  retriable: apiErrorStatusRetriable(msg.api_error_status),
1792
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2531
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1793
2532
  });
1794
2533
  return;
1795
2534
  }
2535
+ const finishReasonRaw = stopReasonRaw(msg.stop_reason);
2536
+ const stopDetails = stopDetailsByTurn.get(turnId);
2537
+ stopDetailsByTurn.delete(turnId);
1796
2538
  a.closeTurnDone(turnId, {
1797
2539
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1798
2540
  finishReason: mapStopReason(msg.stop_reason),
1799
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2541
+ ...(finishReasonRaw !== undefined ? { finishReasonRaw } : {}),
2542
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1800
2543
  safety,
2544
+ ...(stopDetails !== undefined
2545
+ ? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
2546
+ : {}),
1801
2547
  });
1802
2548
  return;
1803
2549
  }
@@ -1805,10 +2551,10 @@ export function createClaudeNormalizer(options = {}) {
1805
2551
  // At this point msg.subtype can only be an error variant (success handled above).
1806
2552
  // guuey#26: seal the open assistant message before the turn close.
1807
2553
  closePendingMessage();
1808
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2554
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1809
2555
  // CL-09: consume any stashed assistant-error close for this turnId — this
1810
- // frame emits it (below), and it cannot leak into a later turn's result
1811
- // (every turn of a session shares the turnId).
2556
+ // frame emits it (below). Each turn has its own id now, so an entry can
2557
+ // only ever be this turn's.
1812
2558
  const stashedError = takeStashedTurnError(turnId);
1813
2559
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1814
2560
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
@@ -1825,10 +2571,20 @@ export function createClaudeNormalizer(options = {}) {
1825
2571
  const retriable = startupFailureReason !== undefined
1826
2572
  ? startupFailureRetriable(startupFailureReason)
1827
2573
  : subtype !== "error_max_turns";
2574
+ // Denials ride the SAME carrier as on the success arm, at the same point.
2575
+ // This arm is discriminant-validated only, so the array is shape-guarded
2576
+ // (a malformed entry is skipped; Tenet 6: never throw).
2577
+ const rawDenials = isJsonObject(msg) ? msg["permission_denials"] : undefined;
2578
+ const denials = Array.isArray(rawDenials)
2579
+ ? rawDenials.flatMap((d) => isJsonObject(d) && typeof d["tool_name"] === "string" && typeof d["tool_use_id"] === "string"
2580
+ ? [{ tool_name: d["tool_name"], tool_use_id: d["tool_use_id"] }]
2581
+ : [])
2582
+ : [];
2583
+ emitDenialsCarrier(turnId, denials, msg.session_id);
1828
2584
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1829
2585
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1830
2586
  // success arm above (turn.error carries no metadata slot at all).
1831
- const resultMeta = resultMetaPayload(msg);
2587
+ const resultMeta = resultMetaPayload(msg, true);
1832
2588
  if (resultMeta !== undefined) {
1833
2589
  a.emitExt("anthropic", "result-meta", resultMeta);
1834
2590
  }
@@ -1839,21 +2595,10 @@ export function createClaudeNormalizer(options = {}) {
1839
2595
  // usage (the success arm's mapping). This arm is only
1840
2596
  // discriminant-validated, so the usage trio is shape-guarded first
1841
2597
  // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
1842
- // The guard covers every property `mapTurnUsage` dereferences: the
1843
- // `server_tool_use` object (null allowed, as typed) and each
1844
- // `modelUsage` entry — `usage: {}` or a null entry would otherwise
2598
+ // The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
2599
+ // dereferences — `usage: {}` or a null modelUsage entry would otherwise
1845
2600
  // throw here, after the stash was already consumed.
1846
- const raw = msg;
1847
- const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
1848
- const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
1849
- const usage = isJsonObject(raw) &&
1850
- isJsonObject(rawUsage) &&
1851
- (rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
1852
- isJsonObject(rawModelUsage) &&
1853
- Object.values(rawModelUsage).every(isJsonObject) &&
1854
- typeof raw["total_cost_usd"] === "number"
1855
- ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
1856
- : undefined;
2601
+ const usage = guardedTurnUsage(msg);
1857
2602
  a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
1858
2603
  return;
1859
2604
  }
@@ -1877,7 +2622,9 @@ export function createClaudeNormalizer(options = {}) {
1877
2622
  // promotion is strictly more lossless. Wrapper siblings ride the text
1878
2623
  // block's providerMetadata (camelCased per the facet's carry
1879
2624
  // convention, mirroring the 0.3.217 first-block precedent).
1880
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2625
+ // The open turn, or (between turns) the one this notice opens; the next
2626
+ // assistant frame then joins it and its result closes it.
2627
+ const turnId = topTurnId(msg.uuid, undefined);
1881
2628
  const noticeMeta = AgProviderMeta.parse({
1882
2629
  level: msg.level,
1883
2630
  ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
@@ -1920,7 +2667,7 @@ export function createClaudeNormalizer(options = {}) {
1920
2667
  // and non-folding, so the second copy of `retracted_message_uuids`
1921
2668
  // cannot double-fold (the M22 hazard). This is the only producer for R&D
1922
2669
  // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
1923
- a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
2670
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
1924
2671
  return;
1925
2672
  }
1926
2673
  if (msg.type === "system" && msg.subtype === "permission_denied") {
@@ -1968,7 +2715,37 @@ export function createClaudeNormalizer(options = {}) {
1968
2715
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
1969
2716
  const carriedKind = anthropicFrameKind(msg);
1970
2717
  if (carriedKind !== undefined) {
1971
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: JsonValue.parse(msg) });
2718
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
2719
+ // B-strict: a background sub-run's outcome arrives as task_notification,
2720
+ // correlated to its run by tool_use_id (or by task_id through the
2721
+ // task_started frame that named it).
2722
+ const raw = msg;
2723
+ if (isJsonObject(raw) && raw["type"] === "system" && typeof raw["task_id"] === "string") {
2724
+ const taskId = raw["task_id"];
2725
+ const named = typeof raw["tool_use_id"] === "string" ? raw["tool_use_id"] : undefined;
2726
+ if (raw["subtype"] === "task_started" && named !== undefined)
2727
+ toolUseIdByTaskId.set(taskId, named);
2728
+ if (raw["subtype"] === "task_notification") {
2729
+ const runKey = named ?? toolUseIdByTaskId.get(taskId);
2730
+ const status = raw["status"];
2731
+ if (runKey !== undefined && openRuns.has(runKey)) {
2732
+ if (status === "completed")
2733
+ closeRun(runKey, { kind: "success" });
2734
+ else if (status === "failed")
2735
+ closeRun(runKey, { kind: "error", message: typeof raw["summary"] === "string" && raw["summary"] !== "" ? raw["summary"] : "subagent failed", code: "failed" });
2736
+ else if (status === "stopped")
2737
+ closeRun(runKey, { kind: "aborted", reason: "stopped" });
2738
+ }
2739
+ }
2740
+ }
2741
+ return;
2742
+ }
2743
+ // A top-level type the union does not declare (see KNOWN_TOP_LEVEL_TYPES):
2744
+ // carried whole, never silently dropped. `msg.type` is typed as the union's
2745
+ // literals, but the frame is only discriminant-validated at runtime.
2746
+ const topLevelType = msg.type;
2747
+ if (!KNOWN_TOP_LEVEL_TYPES.has(topLevelType)) {
2748
+ a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
1972
2749
  return;
1973
2750
  }
1974
2751
  // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
@@ -1976,23 +2753,37 @@ export function createClaudeNormalizer(options = {}) {
1976
2753
  }
1977
2754
  return {
1978
2755
  push(native) {
1979
- if (!isSDKMessage(native)) {
2756
+ framesSeen++;
2757
+ // `native` is already plain JSON: withAtomicPush (createClaudeNormalizer)
2758
+ // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
2759
+ // frame is the same reference, anything else its JSON form).
2760
+ const frame = native;
2761
+ if (!isSDKMessage(frame)) {
1980
2762
  // Graceful guard (Tenet 6): route the raw payload through the lossless
1981
2763
  // vendor channel rather than throwing. Nest under `native` so a payload
1982
2764
  // that carries its own `type` key (the common malformed-SDKMessage shape
1983
2765
  // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
1984
2766
  // (emitExt spreads object payloads at the top level).
1985
- a.emitExt("anthropic", "unparsed", { native });
2767
+ // A copy: `frame` IS the host's object when it was already JSON, and
2768
+ // this raw channel would otherwise emit it by reference. JsonValue.parse
2769
+ // copies and, like every other carry here, drops an own "__proto__"
2770
+ // (sp-main 2026-09-24, matching sp-openai cf55e08 and the 0.6.6
2771
+ // reserved-key rule 314a183: an emitted map carries no own __proto__).
2772
+ a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
1986
2773
  return a.drain();
1987
2774
  }
1988
- drive(native);
2775
+ drive(frame);
1989
2776
  return a.drain();
1990
2777
  },
1991
2778
  flush() {
1992
2779
  // guuey#26: nothing can continue the deferred message now — seal it with
1993
- // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1994
- // to synthesize a bare `message.end`.
1995
- closePendingMessage();
2780
+ // its real usage rather than leaving INV-FLUSH to synthesize a bare
2781
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
2782
+ closePendingMessage(true);
2783
+ // B-strict: every subagent run still open closes here with its nested
2784
+ // terminal (turn.abort{stream-truncated}, or its stashed API error) and
2785
+ // its subagent.done, innermost first.
2786
+ abortOpenRuns();
1996
2787
  // CL-09: a turn whose assistant error frame stashed its close but whose
1997
2788
  // result frame never arrived still closes as that turn.error (no usage:
1998
2789
  // only a result carries the turn's), never as INV-FLUSH's synthesized
@@ -2005,6 +2796,34 @@ export function createClaudeNormalizer(options = {}) {
2005
2796
  },
2006
2797
  };
2007
2798
  }
2799
+ /**
2800
+ * Build the Claude-facet normalizer: the inner normalizer wrapped in core's
2801
+ * withAtomicPush (the fleet guard ruling, 2026-09-24, binding). push() never
2802
+ * throws (SPEC:933):
2803
+ * - each native is first read as plain JSON (core toJsonValueSafe): a host
2804
+ * may hand in the in-process object, whose members need not be JSON (an
2805
+ * undefined member, a Date, NaN, a BigInt, a function, a cycle); a JSON
2806
+ * frame passes by reference, anything else folds exactly as its JSON form,
2807
+ * which is what every capture already is (the SDK itself parses the CLI's
2808
+ * NDJSON, so no 0.3.280 SDK frame needs it);
2809
+ * - an envelope-valid but malformed frame (a required field missing or
2810
+ * mistyped below the isSDKMessage discriminants: 61 single-point fuzz
2811
+ * mutants of the corpus's 25 frame shapes threw, from ~17 sites, most after
2812
+ * the frame had emitted) no longer throws: its partial batch is discarded
2813
+ * with its state (the inner is rebuilt and re-driven from the journal) and
2814
+ * one core `error {message: "normalizer error", code: <constructor name>}`
2815
+ * takes the next seq. Over every committed native it fires zero times
2816
+ * (e2e agents/claude-agent-sdk/guard.corpus.test.ts).
2817
+ * The fallback id stem is held HERE, outside the rebuild's factory: drawn at
2818
+ * most once, and only when a fallback id is first needed, so the common path
2819
+ * never touches randomness (core's atomic-guard differential runs with it
2820
+ * poisoned) and a rebuild re-reads the same stem.
2821
+ */
2822
+ export function createClaudeNormalizer(options = {}) {
2823
+ let stem = options.invokeId;
2824
+ const invokeStem = () => (stem ??= `claude_${mintInvokeNonce()}`);
2825
+ return withAtomicPush(() => createInnerClaudeNormalizer(options, invokeStem));
2826
+ }
2008
2827
  export default createClaudeNormalizer;
2009
2828
  export { mapStopReason };
2010
2829
  //# sourceMappingURL=index.js.map