@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/src/index.ts CHANGED
@@ -47,6 +47,7 @@ import {
47
47
  JsonValue,
48
48
  type Normalizer,
49
49
  StreamAssembler,
50
+ withAtomicPush,
50
51
  type ToolOutcome,
51
52
  } from "@silverprotocol/core";
52
53
 
@@ -118,14 +119,25 @@ function mapStopReason(stop: BetaStopReason | string | null): AgFinishReason {
118
119
  }
119
120
  }
120
121
 
121
- // ─── derive stable ids ────────────────────────────────────────────────────────
122
- // A stable per-message turn id: the assistant message is the model's turn, so
123
- // the SDK session id names the turn (a top-level turn shares the session). When
124
- // absent, fall back to the message id.
125
- function turnIdFor(sessionId: string | undefined, messageId: string): string {
126
- return sessionId && sessionId.length > 0 ? `turn_${sessionId}` : `turn_${messageId}`;
122
+ // draft.4 (§8.0 graceful degradation / §10 item 23): when `mapStopReason` had to
123
+ // FALL BACK (a stop_reason this facet has no mapping for, e.g. one a newer
124
+ // Messages API ships), `turn.done.finishReasonRaw` carries the native value
125
+ // verbatim beside finishReason "unknown", so nothing about why the turn ended
126
+ // is lost. Set ONLY on the fallback: a mapped reason, and `null` (a real
127
+ // "stop"), carry no raw companion, so ordinary turns stay byte-identical.
128
+ function stopReasonRaw(stop: BetaStopReason | string | null): string | undefined {
129
+ return typeof stop === "string" && mapStopReason(stop) === "unknown" ? stop : undefined;
127
130
  }
128
131
 
132
+ // ─── derive stable ids ────────────────────────────────────────────────────────
133
+ // Turn ids are minted per TURN inside `createClaudeNormalizer()` (see
134
+ // `topTurnId` / `nestedTurnId`), never per session: through 0.6.4 the facet
135
+ // keyed every top-level turn on `turn_${session_id}`, so in a multi-turn
136
+ // invoke the second turn's message.start and content landed on T AFTER
137
+ // turn.done(T) (the assembler's seen-turn set suppressed a second
138
+ // turn.start), breaking INV-TURN (SPEC:743), and reduce() merged every turn
139
+ // of a session into one AgTurnRecord (sp-protocol, 2026-09-23).
140
+
129
141
  // ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
130
142
  function imageSource(source: ImageBlockSource): AgSource {
131
143
  if (source.type === "base64") {
@@ -185,6 +197,22 @@ function mapModelUsage(mu: SDKModelUsage): AgUsage {
185
197
  };
186
198
  }
187
199
 
200
+ // `server_tool_use` is typed `{web_search_requests, web_fetch_requests} | null`,
201
+ // but a result frame is discriminant-validated only, so a leaner producer (a
202
+ // proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
203
+ // member passed the `!== null` check and threw a TypeError out of push()
204
+ // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found by sp-protocol writing §10.23),
205
+ // and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
206
+ // anything else ⇒ absent.
207
+ function serverToolRequestCount(usage: unknown): number | undefined {
208
+ if (!isJsonObject(usage)) return undefined;
209
+ const stu = usage["server_tool_use"];
210
+ if (!isJsonObject(stu)) return undefined;
211
+ const search = stu["web_search_requests"];
212
+ const fetch = stu["web_fetch_requests"];
213
+ return typeof search === "number" && typeof fetch === "number" ? search + fetch : undefined;
214
+ }
215
+
188
216
  function mapTurnUsage(
189
217
  usage: SDKResultSuccessMsg["usage"],
190
218
  totalCostUsd: number,
@@ -201,10 +229,7 @@ function mapTurnUsage(
201
229
  cacheReadTokens: usage.cache_read_input_tokens,
202
230
  cacheWriteTokens: usage.cache_creation_input_tokens,
203
231
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
204
- serverToolRequests:
205
- usage.server_tool_use !== null
206
- ? usage.server_tool_use.web_search_requests + usage.server_tool_use.web_fetch_requests
207
- : undefined,
232
+ serverToolRequests: serverToolRequestCount(usage),
208
233
  costUsd: totalCostUsd,
209
234
  cumulative: true,
210
235
  ...(Object.keys(byModel).length > 0 ? { byModel } : {}),
@@ -289,7 +314,7 @@ function assistantContentBlockToAgBlock(block: BetaContentBlock): AgBlock {
289
314
  return {
290
315
  type: "provider-raw",
291
316
  vendor: "anthropic",
292
- raw: JsonValue.parse(block),
317
+ raw: carryVerbatim(block),
293
318
  };
294
319
  }
295
320
 
@@ -309,7 +334,7 @@ function toolResultContentToAgBlocks(content: NonNullable<ToolResultContent>): A
309
334
  } else if (part.type === "image") {
310
335
  out.push({ type: "image", source: imageSource(part.source) });
311
336
  } else {
312
- out.push({ type: "provider-raw", vendor: "anthropic", raw: JsonValue.parse(part) });
337
+ out.push({ type: "provider-raw", vendor: "anthropic", raw: carryVerbatim(part) });
313
338
  }
314
339
  }
315
340
  return out;
@@ -333,25 +358,104 @@ function mcpToolResultContentToAgBlocks(content: McpToolResultContent): AgBlock[
333
358
  return out;
334
359
  }
335
360
 
361
+ // `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on sp-probe's
362
+ // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
363
+ // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
364
+ // not carry the tool's own execution output (user-rejected / permission-rule /
365
+ // automode-* / interrupted / cancelled); absent means the tool ran to
366
+ // completion" (the CLI's own schema doc). Read through the JSON boundary; a
367
+ // malformed entry is skipped. The entry itself is NOT carried here (that carry
368
+ // is package 15's); only the kind decides the outcome below.
369
+ function readNonExecutionKinds(frame: unknown): Map<string, string> {
370
+ const out = new Map<string, string>();
371
+ if (!isJsonObject(frame)) return out;
372
+ const list = frame["tool_result_meta"];
373
+ if (!Array.isArray(list)) return out;
374
+ for (const entry of list) {
375
+ if (isJsonObject(entry) && typeof entry["id"] === "string" && typeof entry["non_execution_kind"] === "string") {
376
+ out.set(entry["id"], entry["non_execution_kind"]);
377
+ }
378
+ }
379
+ return out;
380
+ }
381
+
382
+ // The non_execution_kinds that mean the call was NOT PERMITTED to run →
383
+ // `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
384
+ // item 15 routes Claude's permission denials to it; sp-protocol, 2026-09-23).
385
+ // `interrupted`, `cancelled`, absent and any unknown value are not denials and
386
+ // keep "error" (no guessing).
387
+ function isDenialKind(kind: string | undefined): boolean {
388
+ return kind === "user-rejected" || kind === "permission-rule" || (kind !== undefined && kind.startsWith("automode-"));
389
+ }
390
+
391
+ // Which assistant `error` codes are transient (retriable). CL-09's stashed
392
+ // top-level close and a nested frame's non-terminal `error` share it.
393
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
394
+ // cousin of rate_limit/server_error) joins the retriable set.
395
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
396
+ // decommissioned model id) is deliberately EXCLUDED: explicit
397
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
398
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
399
+ // deliberate non-retriable: a billing-class code (the account is on
400
+ // hold — a first cousin of `billing_error`, cleared by the account
401
+ // holder, never by re-sending the turn).
402
+ //
403
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
404
+ // deliberate non-retriables recorded here for the same reason — an
405
+ // omission must never read as an oversight:
406
+ // - `verification_required`: the request is gated on an out-of-band
407
+ // human step (identity/org verification). Nothing about the turn
408
+ // changes by re-sending it; the block clears only when a person
409
+ // completes the verification.
410
+ // - `cloud_credential_error`: a credential/billing-class failure on
411
+ // the cloud-provider leg (a first cousin of `billing_error` and
412
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
413
+ // unauthorized credential is exactly as bad on the next attempt.
414
+ function assistantErrorRetriable(errCode: NonNullable<SDKAssistantError>): boolean {
415
+ return errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded";
416
+ }
417
+
336
418
  // ─── assistant content block fan-out (spec §4 mapping table) ──────────────────
337
419
  // Per content[] block, drive the engine to emit its lifecycle events under the
338
- // open message named by `messageId`. `blockProviderMetadata` is the refusal-
339
- // fallback `supersedes` carrier (playbook 2026-07-03 SDK-bump adaptation,
340
- // Finding #1 / §8 item 19): the caller passes it ONLY for blockIndex 0 of a
341
- // superseding message, mirroring the established "signature on first block"
342
- // precedent (§8 item 8, Gemini thoughtSignature). `text`/`thinking`/
343
- // `redacted_thinking`/`tool_use` family all have a providerMetadata slot on
344
- // their *.start event and land it there; the remaining rarer block-0 shapes
345
- // (image/resource/mcp_tool_result/compaction) have no providerMetadata slot on
346
- // `content.block` and drop the annotation (NOT the retraction itself, which
347
- // already executed via `message.remove` regardless — see `drive()`).
420
+ // open message named by `messageId`. The caller passes the frame's wrapper
421
+ // carry ONLY for blockIndex 0, mirroring the "signature on first block"
422
+ // precedent (§8 item 8, Gemini thoughtSignature), in two bags:
423
+ // - `blockProviderMetadata`: the REPLAY-side wrapper facts (`supersedes`,
424
+ // `resumed_from_incomplete_thinking`, `aborted`, `context_usage`,
425
+ // `usage_report`, the turn-binding family). `text` / `thinking` /
426
+ // `redacted_thinking` and the `tool_use` family land it on their *.start
427
+ // event. The rarer block-0 shapes (mcp_tool_result / compaction / the
428
+ // default content.block) never apply it, so those facts drop there (a
429
+ // disclosed, pre-existing gap; a retraction itself still executes via
430
+ // `message.remove` regardless, see `drive()`).
431
+ // - `blockMeta` (X5): the HOST-only wrapper facts (HOST_ONLY_WRAPPER_KEYS).
432
+ // Only text.start / reasoning.start get it, because `reduce()` folds their
433
+ // `_meta` onto the block.
434
+ // Returns which halves ANCHORED on a folded start event: `replay` when the
435
+ // block type has a providerMetadata slot the caller's bag landed on (text,
436
+ // thinking, redacted_thinking, the tool_use family), `host` when `blockMeta`
437
+ // landed (text / thinking / redacted_thinking only; tool.start folds no
438
+ // `_meta`). The caller routes every UNANCHORED half through the assistant
439
+ // message's `message.metadata`, so no wrapper fact is dropped. (Before this,
440
+ // a frame whose first block was a compaction, an mcp_tool_result or a
441
+ // content.block lost its replay half silently: those have no providerMetadata
442
+ // slot, and an mcp_tool_result's tool.done belongs to another message.) That fallback is message-level and
443
+ // merges REPLACE-by-key, so it does not say which frame the frame-relative
444
+ // `narration_block_indexes` belong to. In practice it is not reached: the CLI
445
+ // sends one content block per frame, narration marks thinking/text blocks, and
446
+ // an API-error frame starts with text.
447
+ type BlockAnchor = { readonly replay: boolean; readonly host: boolean };
448
+ const NOTHING_ANCHORED: BlockAnchor = { replay: false, host: false };
449
+
348
450
  function emitAssistantBlock(
349
451
  a: StreamAssembler,
350
452
  block: BetaContentBlock,
351
453
  messageId: string,
352
454
  blockIndex: number,
353
455
  blockProviderMetadata?: AgProviderMeta,
354
- ): void {
456
+ blockMeta?: AgMeta,
457
+ phase?: string,
458
+ ): BlockAnchor {
355
459
  switch (block.type) {
356
460
  case "text": {
357
461
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
@@ -361,22 +465,40 @@ function emitAssistantBlock(
361
465
  const id = `${messageId}:text:${blockIndex}`;
362
466
  const citations =
363
467
  block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
364
- a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
468
+ if (blockMeta !== undefined) {
469
+ // textStart's sugar has no `_meta` field; `a.emit()` is the base primitive.
470
+ a.emit({
471
+ type: "text.start",
472
+ id,
473
+ messageId,
474
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
475
+ _meta: blockMeta,
476
+ });
477
+ } else {
478
+ a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
479
+ }
365
480
  a.textDelta(id, messageId, block.text);
366
481
  a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
367
- return;
482
+ return { replay: true, host: blockMeta !== undefined };
368
483
  }
369
484
  case "thinking": {
370
485
  const id = `${messageId}:reasoning:${blockIndex}`;
371
- if (blockProviderMetadata !== undefined) {
372
- // reasoningStart's sugar signature has no providerMetadata parameter
373
- // (only textStart's does) — `a.emit()` is the documented base
374
- // primitive for exactly this case (schema DOES support it on
375
- // reasoning.start; StreamAssembler docstring: "guarantees no
376
- // AgClosedEventType is ever unreachable").
377
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
486
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
487
+ // reasoningStart's sugar signature has no providerMetadata or `_meta`
488
+ // parameter — `a.emit()` is the documented base primitive for exactly
489
+ // this case (schema DOES support both on reasoning.start;
490
+ // StreamAssembler docstring: "guarantees no AgClosedEventType is ever
491
+ // unreachable").
492
+ a.emit({
493
+ type: "reasoning.start",
494
+ id,
495
+ messageId,
496
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
497
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
498
+ ...(phase !== undefined ? { phase } : {}),
499
+ });
378
500
  } else {
379
- a.reasoningStart(id, messageId);
501
+ a.reasoningStart(id, messageId, phase !== undefined ? { phase } : undefined);
380
502
  }
381
503
  a.reasoningDelta(id, messageId, block.thinking);
382
504
  a.reasoningEnd(id, messageId);
@@ -390,13 +512,19 @@ function emitAssistantBlock(
390
512
  provider: "anthropic",
391
513
  });
392
514
  }
393
- return;
515
+ return { replay: true, host: blockMeta !== undefined };
394
516
  }
395
517
  case "redacted_thinking": {
396
518
  // No visible text; the redacted blob is the replay-load-bearing opaque part.
397
519
  const id = `${messageId}:reasoning:${blockIndex}`;
398
- if (blockProviderMetadata !== undefined) {
399
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
520
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
521
+ a.emit({
522
+ type: "reasoning.start",
523
+ id,
524
+ messageId,
525
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
526
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
527
+ });
400
528
  } else {
401
529
  a.reasoningStart(id, messageId);
402
530
  }
@@ -406,7 +534,7 @@ function emitAssistantBlock(
406
534
  value: block.data,
407
535
  provider: "anthropic",
408
536
  });
409
- return;
537
+ return { replay: true, host: blockMeta !== undefined };
410
538
  }
411
539
  case "tool_use":
412
540
  case "server_tool_use":
@@ -439,7 +567,7 @@ function emitAssistantBlock(
439
567
  });
440
568
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
441
569
  a.toolArgsAssembled(toolCallId, input);
442
- return;
570
+ return { replay: true, host: false };
443
571
  }
444
572
  case "mcp_tool_result": {
445
573
  // MCP tool results from the assistant side: map to tool.done with content + outcome.
@@ -452,7 +580,7 @@ function emitAssistantBlock(
452
580
  isError: block.is_error,
453
581
  messageId,
454
582
  });
455
- return;
583
+ return NOTHING_ANCHORED;
456
584
  }
457
585
  case "compaction": {
458
586
  // Compaction blocks carry a provider-produced context summary (spec §4).
@@ -466,12 +594,12 @@ function emitAssistantBlock(
466
594
  : undefined,
467
595
  provider: "anthropic",
468
596
  });
469
- return;
597
+ return NOTHING_ANCHORED;
470
598
  }
471
599
  default: {
472
600
  // image / resource / other rich content blocks ride content.block (spec §4).
473
601
  a.contentBlock(messageId, assistantContentBlockToAgBlock(block));
474
- return;
602
+ return NOTHING_ANCHORED;
475
603
  }
476
604
  }
477
605
  }
@@ -618,6 +746,31 @@ const CARRIED_STANDALONE_TYPES = new Set<string>([
618
746
  "conversation_reset",
619
747
  ]);
620
748
 
749
+ // The top-level `type` literals the SDKMessage union declares (0.3.280: 39
750
+ // members over these 11 types). A frame whose `type` is NOT among them is
751
+ // RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
752
+ // frame type). The first one observed: `command_lifecycle`
753
+ // ({command_uuid, state: "queued"|"started"|"completed"}, three per prompt,
754
+ // streaming-input mode; live on corpus/multi-result-sonnet5), the host
755
+ // prompt's queue lifecycle keyed by the caller's message uuid. Through the
756
+ // 0.7.0 stack it fell through `drive()` to the no-op, a silent drop against
757
+ // SPEC §8.0 graceful degradation. An unknown top-level type now rides the
758
+ // uniform carry, `ext.anthropic.frame{kind: <type>, frame}`, verbatim (§8 item
759
+ // 22), so the next runtime-only frame type is carried the day it ships.
760
+ const KNOWN_TOP_LEVEL_TYPES: ReadonlySet<string> = new Set([
761
+ "assistant",
762
+ "user",
763
+ "result",
764
+ "system",
765
+ "stream_event",
766
+ "tool_progress",
767
+ "auth_status",
768
+ "tool_use_summary",
769
+ "rate_limit_event",
770
+ "prompt_suggestion",
771
+ "conversation_reset",
772
+ ]);
773
+
621
774
  // Returns the uniform-carry `kind` string for `msg` if it is one of the arms
622
775
  // disposed `carried` in sdk-surface.json, else undefined (leaves router-plane
623
776
  // / dedicated-branch arms — including SDKPermissionDeniedMessage — untouched).
@@ -634,25 +787,97 @@ function anthropicFrameKind(msg: SDKMessage): string | undefined {
634
787
  // runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
635
788
  // carry it verbatim. A malformed list is ignored, never thrown on (Tenet 6);
636
789
  // `string[]` is itself a JsonValue, so no cast is needed downstream.
790
+ // A COPY, never the frame's own array: the value is emitted unparsed
791
+ // (result-meta, message.metadata), core's StreamAssembler does not copy, and
792
+ // push() hands a JSON frame through by reference, so returning `v` would let an
793
+ // emitted event share the host's live array (cto's aliasing audit).
637
794
  function readUserMessageUuids(v: unknown): string[] | undefined {
638
- return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? v : undefined;
795
+ return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? [...v] : undefined;
639
796
  }
640
797
 
798
+ // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
799
+ // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
800
+ // are CLI-wrapper facts the Messages API never consumes. See the split in
801
+ // drive()'s assistant branch.
802
+ const HOST_ONLY_WRAPPER_KEYS: ReadonlySet<string> = new Set([
803
+ "narration_block_indexes",
804
+ "diagnostics",
805
+ "api_error",
806
+ "api_error_params",
807
+ "api_error_code",
808
+ // rd-15 (founder: defer the field, fix the carries): three more @internal
809
+ // CLI assistant-wrapper strings, carried where the host can read them.
810
+ "error_details",
811
+ "advisor_model",
812
+ "attribution_agent",
813
+ ]);
814
+
641
815
  // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
642
816
  // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
643
817
  // 0.3.272 (a pass-through of the Messages API field that rides the assistant
644
818
  // wrapper), so it is read through the JSON boundary and shape-guarded here, never
645
- // cast. Integer indexes into `message.content`; an out-of-range or non-integer
646
- // member means the producer changed shape, so the whole array is refused rather
647
- // than half-carried.
819
+ // cast. Integer indexes into `message.content`; a non-integer or negative member
820
+ // means the producer changed shape, so the whole array is refused rather than
821
+ // half-carried. The upper bound is not checked here: an out-of-range index
822
+ // simply names no block where it is used (the draft.4 `phase` mapping).
823
+ // A copy for the same reason as readUserMessageUuids: the block-less wrapper
824
+ // path emits it in message.metadata unparsed.
648
825
  function readNarrationBlockIndexes(v: unknown): number[] | undefined {
649
826
  return Array.isArray(v) &&
650
827
  v.length > 0 &&
651
828
  v.every((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0)
652
- ? v
829
+ ? [...v]
653
830
  : undefined;
654
831
  }
655
832
 
833
+ // A provider- or harness-originated native subtree forwarded WHOLE: JSON-
834
+ // validated (a copy) and with every `fallback_credit_token` deleted at any
835
+ // depth (withoutCreditTokens). Every verbatim carrier of this facet goes
836
+ // through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
837
+ // carries, provider-raw blocks, and the CLI/API wrapper subtrees
838
+ // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats).
839
+ // Model- or tool-authored payloads (tool input, a deferred tool call, MCP
840
+ // structuredContent / _meta / resourceLinks, structured_output) are NOT
841
+ // stripped: a key there is user content, and the wire already carries the same
842
+ // data as the tool call or result.
843
+ function carryVerbatim(v: unknown): JsonValue {
844
+ return withoutCreditTokens(JsonValue.parse(v));
845
+ }
846
+
847
+ // rd-15 / SPEC §13.7 (queued): a provider credit or bearer token is never
848
+ // emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
849
+ // (top level and per fallback), so every key of that name is deleted at any
850
+ // depth; everything else is kept verbatim.
851
+ function withoutCreditTokens(v: JsonValue): JsonValue {
852
+ if (Array.isArray(v)) return v.map(withoutCreditTokens);
853
+ if (typeof v === "object" && v !== null) {
854
+ const out: { [k: string]: JsonValue } = {};
855
+ for (const [k, x] of Object.entries(v)) if (k !== "fallback_credit_token") out[k] = withoutCreditTokens(x);
856
+ return out;
857
+ }
858
+ return v;
859
+ }
860
+
861
+ // A tool_result's text, for a failed Task's nested turn.error message: the
862
+ // string content, or its text blocks joined; undefined when there is none.
863
+ function toolResultText(content: unknown): string | undefined {
864
+ if (typeof content === "string") return content !== "" ? content : undefined;
865
+ if (!Array.isArray(content)) return undefined;
866
+ const texts: string[] = [];
867
+ for (const b of content) if (isJsonObject(b) && b["type"] === "text" && typeof b["text"] === "string") texts.push(b["text"]);
868
+ const joined = texts.join("\n");
869
+ return joined !== "" ? joined : undefined;
870
+ }
871
+
872
+ // A result's `terminal_reason` when it names why the turn ended other than a
873
+ // normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
874
+ // live API error's own value is "api_error", which is also the generic code, so
875
+ // that close is unchanged. Typed as the SDK's TerminalReason union, but a newer
876
+ // CLI may send an undeclared value, so only a non-empty string is taken.
877
+ function closeCauseTerminalReason(v: unknown): string | undefined {
878
+ return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
879
+ }
880
+
656
881
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
657
882
  // on both frames that carry it (the API-error assistant frame and the
658
883
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -828,7 +1053,7 @@ function apiErrorStatusRetriable(status: unknown): boolean {
828
1053
  // value verbatim; it also drives `turn.error.retriable` (see
829
1054
  // `startupFailureRetriable`). Read through the JSON boundary because it is
830
1055
  // declared on that one arm only.
831
- function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | undefined {
1056
+ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: string]: JsonValue } | undefined {
832
1057
  const byModel: { [k: string]: JsonValue } = {};
833
1058
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
834
1059
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -844,7 +1069,7 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
844
1069
  // `unknown` (no cast) and let the isJsonObject guard narrow.
845
1070
  const raw: unknown = msg;
846
1071
  const subagentStats =
847
- isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
1072
+ isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? carryVerbatim(raw["subagent_stats"]) : undefined;
848
1073
  const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
849
1074
  // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
850
1075
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
@@ -854,6 +1079,29 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
854
1079
  // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
855
1080
  const apiErrorCode = readApiErrorCode(msg);
856
1081
  const startupFailureReason = readStartupFailureReason(msg);
1082
+ // `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
1083
+ // input}`): the tool call a host's PreToolUse `defer` decision parked, which
1084
+ // the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
1085
+ // the host needs it to act on the parked call. Through 0.6.4 the facet never
1086
+ // read it (a silent drop). Carried WHOLE and verbatim (the `subagent_stats`
1087
+ // precedent); whether it should instead map onto `turn.done.outcome.paused`
1088
+ // (asks) is a question routed to sp-protocol / sp-rnd. Fixture-only: no
1089
+ // capture sets a defer hook.
1090
+ const deferredToolUse =
1091
+ isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
1092
+ // `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
1093
+ // API error that ended the turn. It already decides `retriable` on an
1094
+ // is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
1095
+ // the census allowlist's "carry candidate the first time an error seed
1096
+ // surfaces it" (sp-probe's api-error-auth seed: 401). Absent or null ⇒ no key.
1097
+ const apiErrorStatus =
1098
+ isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1099
+ // `stop_reason` on a result that closes as turn.error: turn.error has no
1100
+ // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1101
+ // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1102
+ // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1103
+ const stopReason =
1104
+ closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
857
1105
  const payload: { [k: string]: JsonValue } = {
858
1106
  ...(typeof msg.fast_mode_disabled_reason === "string"
859
1107
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -868,11 +1116,39 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
868
1116
  ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
869
1117
  ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
870
1118
  ...(subagentStats !== undefined ? { subagentStats } : {}),
1119
+ ...(deferredToolUse !== undefined ? { deferredToolUse } : {}),
1120
+ ...(apiErrorStatus !== undefined ? { apiErrorStatus } : {}),
1121
+ ...(stopReason !== undefined ? { stopReason } : {}),
871
1122
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
872
1123
  };
873
1124
  return Object.keys(payload).length > 0 ? payload : undefined;
874
1125
  }
875
1126
 
1127
+ // A result frame's turn usage, or undefined when the frame's usage trio is not
1128
+ // the shape `mapTurnUsage` dereferences. Both result arms are
1129
+ // discriminant-validated only, so every call goes through this guard (Tenet 6:
1130
+ // a malformed frame must not throw out of push()); absent ⇒ no usage key.
1131
+ // The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
1132
+ // object and its minimal real shape (numeric input/output token counts, so an
1133
+ // empty `usage: {}` stays "no usage" as before), the `modelUsage` object and
1134
+ // each of its entries (`mapModelUsage`), and `total_cost_usd`.
1135
+ // `server_tool_use` is NOT required: `serverToolRequestCount` reads it totally,
1136
+ // so a leaner producer that omits it keeps the rest of its usage.
1137
+ function guardedTurnUsage(msg: SDKResultMsg): AgUsage | undefined {
1138
+ const raw: unknown = msg;
1139
+ if (!isJsonObject(raw)) return undefined;
1140
+ const rawUsage = raw["usage"];
1141
+ const rawModelUsage = raw["modelUsage"];
1142
+ return isJsonObject(rawUsage) &&
1143
+ typeof rawUsage["input_tokens"] === "number" &&
1144
+ typeof rawUsage["output_tokens"] === "number" &&
1145
+ isJsonObject(rawModelUsage) &&
1146
+ Object.values(rawModelUsage).every(isJsonObject) &&
1147
+ typeof raw["total_cost_usd"] === "number"
1148
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
1149
+ : undefined;
1150
+ }
1151
+
876
1152
  // ─── the stateful normalizer ──────────────────────────────────────────────────
877
1153
 
878
1154
  /** Options for {@link createClaudeNormalizer}. */
@@ -893,15 +1169,41 @@ export interface ClaudeNormalizerOptions {
893
1169
  * construction.
894
1170
  */
895
1171
  threadId?: string;
1172
+ /**
1173
+ * The stem of this invoke's POSITIONAL fallback turn ids,
1174
+ * `turn_<invokeId>_frame_<n>`, minted only for a top-level or nested turn
1175
+ * whose frame carries no usable message id or uuid (the normal path names a
1176
+ * turn by its SDK message id or frame uuid, unique by construction). A host
1177
+ * folds every invoke of a conversation into ONE Reducer, so a stem that
1178
+ * restarted with each invoke repeated those ids across invokes (DC-10, from
1179
+ * sp-protocol's D3 bar). Absent, each normalizer draws a random
1180
+ * `claude_<16 hex>` stem at most once, lazily (only when a fallback id is
1181
+ * first needed, so the common path draws no randomness), and holds it
1182
+ * OUTSIDE the atomic-push rebuild, so a rebuild reproduces it. Pass a fixed
1183
+ * value only where one invoke's output must be byte-reproducible (capture,
1184
+ * replay, tests), as vercel-ai's `invokeId`.
1185
+ */
1186
+ invokeId?: string;
1187
+ }
1188
+
1189
+ /** 64 random bits as 16 hex chars: the default per-invoke fallback id stem
1190
+ * (vercel-ai's mintInvokeNonce). */
1191
+ function mintInvokeNonce(): string {
1192
+ const bytes = new Uint8Array(8);
1193
+ globalThis.crypto.getRandomValues(bytes);
1194
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
896
1195
  }
897
1196
 
898
1197
  /**
899
- * Build a stateful Claude-facet normalizer over a fresh {@link StreamAssembler}.
900
- * Each `push(native)` validates `native` → `SDKMessage`, drives the engine via
901
- * primitive calls, and drains the buffered `AgEvent[]`. `flush()` closes any
902
- * dangling open message (none, in Claude's complete-message model) and drains.
1198
+ * The inner Claude-facet normalizer over a fresh {@link StreamAssembler}: each
1199
+ * `push(native)` validates `native` → `SDKMessage`, drives the engine via
1200
+ * primitive calls, and drains the buffered `AgEvent[]`; `flush()` closes any
1201
+ * dangling open message and drains. `createClaudeNormalizer` wraps it in core's
1202
+ * withAtomicPush. It must stay deterministic (no clock, no randomness): a
1203
+ * rebuild re-drives it from the journal. Its one invoke-unique input, the
1204
+ * fallback id stem, comes from the caller, which mints and holds it.
903
1205
  */
904
- export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): Normalizer {
1206
+ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeStem: () => string): Normalizer {
905
1207
  const a = new StreamAssembler();
906
1208
 
907
1209
  // Task 8c leg 4 (guuey capstone finding A): the wire-visible `parentTurnId`
@@ -914,6 +1216,182 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
914
1216
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
915
1217
  const subagentTurnByParentToolUseId = new Map<string, string>();
916
1218
 
1219
+ // INV-TURN (SPEC:743; sp-protocol ruling B, 2026-09-23): ONE turnId names
1220
+ // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1221
+ // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1222
+ // or a stream `message_start`) in the ordinary case, or the frame's own
1223
+ // `uuid` when a notice or a result opens it (a result-only turn). The id is
1224
+ // - unique per turn, across the invokes of a resumed session too (a resume
1225
+ // keeps `session_id` unless `forkSession` is set, so the old
1226
+ // `turn_${session_id}` collided across invokes; message ids never repeat);
1227
+ // - deterministic from the wire, so the same native replays to the same ids;
1228
+ // - known at turn.start, since the opening frame carries it;
1229
+ // - `turn_`-prefixed.
1230
+ // Open from the first frame that needs a turn; the turn's result frame
1231
+ // (either arm) closes it and clears it, so the next frame opens a new one.
1232
+ //
1233
+ // Two guards keep an id naming ONE turn even on odd wire:
1234
+ // - a CLOSED id is never reopened: a late frame reusing a closed turn's
1235
+ // message id opens its turn under its own frame uuid instead;
1236
+ // - `isSDKMessage` validates only discriminants, so a missing or non-string
1237
+ // id/uuid falls back to a positional `turn_<stem>_frame_<n>` rather than a
1238
+ // shared `turn_undefined`. The stem is per invoke (DC-10: a bare
1239
+ // `turn_frame_<n>` repeated across the invokes one Reducer folds), and the
1240
+ // counter is deterministic from the wire, so an atomic-push rebuild
1241
+ // reproduces every delivered id.
1242
+ // Nested (subagent) frames never open or name a top-level turn.
1243
+ let openTopTurnId: string | undefined;
1244
+ const closedTopTurnIds = new Set<string>();
1245
+ let framesSeen = 0;
1246
+ function mintId(candidate: unknown): string | undefined {
1247
+ return typeof candidate === "string" && candidate.length > 0 ? `turn_${candidate}` : undefined;
1248
+ }
1249
+ function topTurnId(openingId: unknown, frameUuid: unknown): string {
1250
+ if (openTopTurnId === undefined) {
1251
+ const byId = mintId(openingId);
1252
+ const byUuid = mintId(frameUuid);
1253
+ openTopTurnId =
1254
+ byId !== undefined && !closedTopTurnIds.has(byId)
1255
+ ? byId
1256
+ : byUuid !== undefined && !closedTopTurnIds.has(byUuid)
1257
+ ? byUuid
1258
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1259
+ }
1260
+ return openTopTurnId;
1261
+ }
1262
+ // The result frame closes the open turn (or, for a result-only turn, the one
1263
+ // it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
1264
+ // notice or stream opened it: the CL-09 result-only API-error path, a
1265
+ // startup-failure result, a local-command result) is OPENED here with an
1266
+ // explicit turn.start before anything else the result emits (INV-TURN,
1267
+ // SPEC:743: every turn is opened by exactly one turn.start and closed by
1268
+ // exactly one terminal; sp-protocol, 2026-09-23). Through the B commit such a
1269
+ // turn was only closed, and reduce() minted a stub record whose threadId was
1270
+ // the turnId. An open turn already has its turn.start (openMessage).
1271
+ function closingTopTurnId(resultUuid: unknown, sessionId: string): string {
1272
+ let turnId = openTopTurnId;
1273
+ if (turnId === undefined) {
1274
+ turnId = topTurnId(resultUuid, undefined);
1275
+ a.openTurn(turnId, options.threadId ?? sessionId);
1276
+ }
1277
+ openTopTurnId = undefined;
1278
+ closedTopTurnIds.add(turnId);
1279
+ return turnId;
1280
+ }
1281
+ // A NESTED (subagent) turn is one per subagent run, keyed by the spawning
1282
+ // `parent_tool_use_id`: `turn_` + that run's first nested message id. Through
1283
+ // 0.6.4 it was `turn_${session_id}` too, which merged every subagent run of a
1284
+ // session into one nested turn (and, if a subagent's frames carry the
1285
+ // parent's session_id, collided with the top-level turn itself). It must
1286
+ // never equal the synthetic `parentTurnId` label `turn_${parent_tool_use_id}`
1287
+ // (guuey capstone finding A), and a message id never does.
1288
+ function nestedTurnId(parentToolUseId: string, firstMessageId: unknown, frameUuid: unknown): string {
1289
+ const known = subagentTurnByParentToolUseId.get(parentToolUseId);
1290
+ if (known !== undefined && !closedRuns.has(parentToolUseId)) return known;
1291
+ // A new run, or a frame arriving for a run that already CLOSED: mint a fresh
1292
+ // id (a closed nested id is never reopened, as for top-level turns).
1293
+ const byId = mintId(firstMessageId);
1294
+ const byUuid = mintId(frameUuid);
1295
+ const minted =
1296
+ byId !== undefined && !closedNestedTurnIds.has(byId)
1297
+ ? byId
1298
+ : byUuid !== undefined && !closedNestedTurnIds.has(byUuid)
1299
+ ? byUuid
1300
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1301
+ closedRuns.delete(parentToolUseId);
1302
+ subagentTurnByParentToolUseId.set(parentToolUseId, minted);
1303
+ return minted;
1304
+ }
1305
+
1306
+ // ONE subagent bracket per RUN (sp-protocol ruling, 2026-09-23; INV-TURN,
1307
+ // SPEC:743; SPEC:807 "subagent.done: Close the nested turn"). Through 0.7.0's
1308
+ // B commit the bracket was per MESSAGE: a run of N nested messages emitted N
1309
+ // subagent.start/subagent.done pairs on its one id, closing it N times with
1310
+ // content after the first close. The run now opens once, at its first nested
1311
+ // frame, and closes exactly once, at whichever comes first: the spawning
1312
+ // Task's tool_result (any user frame, so a subagent's own sub-run closes
1313
+ // too), the turn's result frame, or flush. Parallel Task calls give
1314
+ // OVERLAPPING runs, and the assembler's last-turn backfill is a LIFO stack
1315
+ // that out-of-order closes skew. So the facet's turn-scoped events name their
1316
+ // owner: messages and their blocks by turnId / messageId, top-level tool.done
1317
+ // by the open turn, a retraction's message.remove by the removed message's
1318
+ // own turn. What still backfills: tool.args.* and ext.* (no turnId at all).
1319
+ // A top-level tool_result with NO turn open no longer lands on a closed turn:
1320
+ // since B-resume (37185be) it opens its own turn, named by its frame uuid (see
1321
+ // the user branch), and a nested one for a run this invoke never opened opens
1322
+ // a fresh run the same way.
1323
+ //
1324
+ // B-STRICT NESTED TERMINALS (draft.4, the founder's nested-turn ruling Q1,
1325
+ // 2026-09-24; sp-protocol's package, sp-claude's leg). A nested turn opens
1326
+ // with exactly one subagent.start and closes with exactly one turn.done |
1327
+ // turn.error | turn.abort carrying its turnId, IMMEDIATELY followed by its
1328
+ // subagent.done (a no-fold bracket close that restores the owner). The five
1329
+ // guards: the terminal carries the nested turnId; a nested turn.done uses
1330
+ // finishReason "unknown" (the SDK reports none); no nested success before the
1331
+ // framework reports the sub-run complete (the run may outlive its parent's
1332
+ // terminal); no usage on a nested terminal (the top-level turn is the
1333
+ // accounting boundary: Claude's parent cost already includes subagent spend);
1334
+ // a nested turnId never equals a top-level one (message ids / fallback ids).
1335
+ // The close, by what the framework reported (`NestedClose`):
1336
+ // - the spawning Task's tool_result: `is_error` → turn.error; AgentOutput
1337
+ // status "async_launched" / "remote_launched" (a BACKGROUND launch ack) →
1338
+ // the run stays OPEN; otherwise (status "completed", or no attributable
1339
+ // tool_use_result) the returned call is the completion report → turn.done
1340
+ // success;
1341
+ // - a correlated task_notification (a background run): completed → success,
1342
+ // failed → turn.error, stopped → turn.abort;
1343
+ // - a stashed nested API error (the assistant error frame; its live
1344
+ // non-terminal `error` stays) wins over any of these → turn.error;
1345
+ // - flush: a run still open closes as turn.abort{stream-truncated}, or as its
1346
+ // stashed API error.
1347
+ // The parent's result frame no longer closes runs: a still-open run is a
1348
+ // background (or unreported) sub-run, and closing it there would report an
1349
+ // outcome the framework never gave.
1350
+ type OpenRun = { readonly turnId: string; readonly parentTurnId: string };
1351
+ type NestedClose =
1352
+ | { readonly kind: "success" }
1353
+ | { readonly kind: "error"; readonly message: string; readonly code?: string }
1354
+ | { readonly kind: "aborted"; readonly reason: string };
1355
+ const openRuns = new Map<string, OpenRun>();
1356
+ const closedRuns = new Set<string>();
1357
+ const closedNestedTurnIds = new Set<string>();
1358
+ // Nested turnId → its FIRST API error frame's close (released at run close).
1359
+ const nestedStashedErrors = new Map<string, StashedTurnError>();
1360
+ // task_started: task_id → the spawning tool_use_id, for a task_notification
1361
+ // that carries only its task_id.
1362
+ const toolUseIdByTaskId = new Map<string, string>();
1363
+ function openRun(parentToolUseId: string, turnId: string, parentTurnId: string): void {
1364
+ if (openRuns.has(parentToolUseId)) return;
1365
+ openRuns.set(parentToolUseId, { turnId, parentTurnId });
1366
+ a.subagentStart(turnId, parentTurnId);
1367
+ }
1368
+ function closeRun(parentToolUseId: string, close: NestedClose): void {
1369
+ const run = openRuns.get(parentToolUseId);
1370
+ if (run === undefined) return;
1371
+ openRuns.delete(parentToolUseId);
1372
+ closedRuns.add(parentToolUseId);
1373
+ closedNestedTurnIds.add(run.turnId);
1374
+ const stashed = nestedStashedErrors.get(run.turnId);
1375
+ nestedStashedErrors.delete(run.turnId);
1376
+ if (stashed !== undefined) {
1377
+ a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1378
+ } else if (close.kind === "success") {
1379
+ a.closeTurnDone(run.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
1380
+ } else if (close.kind === "error") {
1381
+ a.closeTurnError(run.turnId, { message: close.message, ...(close.code !== undefined ? { code: close.code } : {}) });
1382
+ } else {
1383
+ a.emit({ type: "turn.abort", turnId: run.turnId, reason: close.reason });
1384
+ }
1385
+ a.subagentDone(run.turnId, run.parentTurnId);
1386
+ }
1387
+ // Flush only: every run still open, innermost (latest-opened) first, as
1388
+ // INV-FLUSH orders its own closes.
1389
+ function abortOpenRuns(): void {
1390
+ for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1391
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1392
+ }
1393
+ }
1394
+
917
1395
  // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
918
1396
  // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
919
1397
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
@@ -941,6 +1419,17 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
941
1419
  agentId?: string;
942
1420
  };
943
1421
  const deniedLiveByToolUseId = new Map<string, LiveDenial>();
1422
+ // Every toolCallId that already got its FINAL tool.done in this invoke. The
1423
+ // result's permission_denials aggregate skips these: re-emitting tool.start +
1424
+ // tool.done{denied} for a call already closed is a duplicate start and a second
1425
+ // final tool.done (INV-BLOCK; rd-14 P14 parks it; the M22 double-fold hazard).
1426
+ const closedToolCallIds = new Set<string>();
1427
+ // SDK message id → the `diagnostics` value already carried for it (see the
1428
+ // assistant branch): one carry per response, not one per frame.
1429
+ const diagnosticsCarried = new Map<string, string>();
1430
+ // rd-15: top-level turnId → the closing response's non-null stop_details (credit
1431
+ // tokens stripped) and the message it describes, emitted on that turn's turn.done.
1432
+ const stopDetailsByTurn = new Map<string, { readonly messageId: string; readonly value: JsonValue }>();
944
1433
 
945
1434
  // The live denial's diagnostic fields, camelCased — the providerMetadata bag
946
1435
  // on the enriched `<turnId>:denials` tool.done. undefined when the live
@@ -984,8 +1473,8 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
984
1473
  // engine-synthesized turn.abort.
985
1474
  // The FIRST error frame's fields win: a later error frame on the same turn
986
1475
  // leaves the stash alone. EVERY result frame consumes the entry, whichever
987
- // arm it is, because every turn of a session shares one turnId (`turnIdFor`)
988
- // and a stale entry must never leak into the next turn's result.
1476
+ // arm it is. Since the per-turn ids (INV-TURN, 2026-09-23) an entry can only
1477
+ // be its own turn's, so a stale one can no longer leak into the next turn.
989
1478
  type StashedTurnError = { readonly message: string; readonly code: string; readonly retriable: boolean };
990
1479
  const stashedTurnErrors = new Map<string, StashedTurnError>();
991
1480
 
@@ -1024,7 +1513,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1024
1513
  /** The id actually emitted (`sdkId`, or a derived carrier — see below). */
1025
1514
  readonly emittedId: string;
1026
1515
  readonly turnId: string;
1027
- /** Set iff this message opened a nested (subagent) turn, whose `subagent.done` is deferred with it. */
1516
+ /** Set iff this is a NESTED (subagent) message: the run's synthetic parent label (continuation test). */
1028
1517
  readonly parentTurnId: string | undefined;
1029
1518
  /** Content-block index to resume at, so a second frame's block never collides with the first's. */
1030
1519
  blockIndex: number;
@@ -1044,6 +1533,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1044
1533
  readonly streamBlocks: Map<number, StreamBlockState>;
1045
1534
  /** workspace#7 — `ttft_ms` carried at most once per message (message.metadata). */
1046
1535
  ttftCarried: boolean;
1536
+ /**
1537
+ * draft.4 `phase`: how many of this lifecycle's blocks earlier COMPLETE
1538
+ * frames already covered. A frame's blocks are the next ones after these,
1539
+ * so its frame-local index `i` names stream block `framedThrough + i`.
1540
+ */
1541
+ framedThrough: number;
1047
1542
  /**
1048
1543
  * The TURN-BINDING FAMILY, carried at most once per message, whichever
1049
1544
  * channel delivers it first: the stream arm's message.metadata carry
@@ -1070,7 +1565,17 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1070
1565
  // is clean punctuation.
1071
1566
  type StreamBlockState =
1072
1567
  | { kind: "text"; id: string; citations: AgCitation[] }
1073
- | { kind: "reasoning"; id: string; signature: string; redacted: string | undefined }
1568
+ | {
1569
+ kind: "reasoning";
1570
+ id: string;
1571
+ signature: string;
1572
+ redacted: string | undefined;
1573
+ // draft.4 `phase` (§8.0 item 27): whether any non-empty thinking text
1574
+ // streamed, and whether the complete frame listed this block in
1575
+ // `narration_block_indexes` while it was still open (CB-13).
1576
+ hasText: boolean;
1577
+ narration: boolean;
1578
+ }
1074
1579
  | { kind: "tool"; toolCallId: string; json: string; startInput: JsonValue }
1075
1580
  | { kind: "compaction"; content: string | null; encrypted: string | null }
1076
1581
  | { kind: "emitted" };
@@ -1083,8 +1588,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1083
1588
  // blocks, their order and their content are the SDK's own.
1084
1589
  const lifecyclesBySdkId = new Map<string, number>();
1085
1590
 
1086
- /** Seal the deferred message (and its subagent bracket), if one is open. */
1087
- function closePendingMessage(): void {
1591
+ /** Seal the deferred message, if one is open (a run's bracket closes separately; see `openRun`).
1592
+ * `atFlush`: the stream ENDED here, so open stream blocks close without minting content
1593
+ * (INV-FLUSH (3), draft.4; see `finalizeStreamBlock`). */
1594
+ function closePendingMessage(atFlush = false): void {
1088
1595
  if (pending === undefined) return;
1089
1596
  const p = pending;
1090
1597
  pending = undefined;
@@ -1094,11 +1601,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1094
1601
  // produced) so no lifecycle dangles under the seal.
1095
1602
  if (p.streamBlocks.size > 0) {
1096
1603
  for (const idx of [...p.streamBlocks.keys()].sort((x, y) => x - y)) {
1097
- finalizeStreamBlock(p, idx);
1604
+ finalizeStreamBlock(p, idx, atFlush);
1098
1605
  }
1099
1606
  }
1100
1607
  a.closeMessage(p.emittedId, p.usage);
1101
- if (p.parentTurnId !== undefined) a.subagentDone(p.turnId, p.parentTurnId);
1608
+ // The subagent bracket is per RUN now (see `openRun`), so sealing a nested
1609
+ // message no longer closes its nested turn.
1102
1610
  }
1103
1611
 
1104
1612
  // ─── workspace#7: stream_event mapping helpers ──────────────────────────────
@@ -1108,7 +1616,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1108
1616
  // ride the uniform lossless carry (`kind` is the frame's own discriminant,
1109
1617
  // per the ext.anthropic.frame convention). Nothing is silently dropped.
1110
1618
  function carryStreamFrame(msg: SDKPartial): void {
1111
- a.emitExt("anthropic", "frame", { kind: "stream_event", frame: JsonValue.parse(msg) });
1619
+ a.emitExt("anthropic", "frame", { kind: "stream_event", frame: carryVerbatim(msg) });
1112
1620
  }
1113
1621
 
1114
1622
  // `ttft_ms` (time to first token, on the partial envelope) has no core home —
@@ -1163,17 +1671,36 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1163
1671
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
1164
1672
  // (same end-then-opaque order as the complete arm), the MANDATORY
1165
1673
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
1166
- function finalizeStreamBlock(p: PendingMessage, index: number): void {
1674
+ // `atFlush` (INV-FLUSH (3), draft.4; the founder's fold/flush ruling, "snapshot
1675
+ // fold + honest flush; opaque at flush forbidden"; sp-claude's leg C1): the
1676
+ // stream ENDED with this block open, so the close lands NO new content. The
1677
+ // lifecycle closes stay (text.end with its already-received citations,
1678
+ // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
1679
+ // (it is authoritative, and a truncated partial_json would mint an input the
1680
+ // model never finished), no reasoning.opaque (a signature is replay-load-
1681
+ // bearing, and the turn is aborted anyway), no compaction content.block, and
1682
+ // no `phase` on reasoning.end. A binding frame that seals the message
1683
+ // mid-stream (not a flush) still finalizes as its content_block_stop would.
1684
+ function finalizeStreamBlock(p: PendingMessage, index: number, atFlush = false): void {
1167
1685
  const b = p.streamBlocks.get(index);
1168
1686
  if (b === undefined) return;
1169
1687
  p.streamBlocks.delete(index);
1170
1688
  const messageId = p.emittedId;
1689
+ if (atFlush) {
1690
+ if (b.kind === "text") a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1691
+ else if (b.kind === "reasoning") a.reasoningEnd(b.id, messageId, undefined);
1692
+ return;
1693
+ }
1171
1694
  switch (b.kind) {
1172
1695
  case "text":
1173
1696
  a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1174
1697
  return;
1175
1698
  case "reasoning":
1176
- a.reasoningEnd(b.id, messageId);
1699
+ // draft.4 `phase` for a STREAMED narration block: known only once the
1700
+ // complete frame arrived (after the start), so it rides reasoning.end
1701
+ // (§5 phase timing), and only if the block's text is non-empty
1702
+ // (§8.0 item 27). Never a post-seal event.
1703
+ a.reasoningEnd(b.id, messageId, b.narration && b.hasText ? { phase: "interim" } : undefined);
1177
1704
  if (b.redacted !== undefined) {
1178
1705
  a.reasoningOpaque(b.id, messageId, { kind: "redacted", value: b.redacted, provider: "anthropic" });
1179
1706
  } else if (b.signature.length > 0) {
@@ -1222,7 +1749,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1222
1749
 
1223
1750
  if (ev.type === "message_start") {
1224
1751
  const m = ev.message;
1225
- const turnId = turnIdFor(msg.session_id, m.id);
1752
+ const turnId =
1753
+ msg.parent_tool_use_id !== null
1754
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1755
+ : topTurnId(m.id, msg.uuid);
1226
1756
  const parentTurnId =
1227
1757
  msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1228
1758
  // Same continuation test as the complete arm: a message_start naming the
@@ -1245,8 +1775,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1245
1775
  // lifecycle counter, same emittedId derivation — so the complete frame
1246
1776
  // that follows JOINS this lifecycle and is content-suppressed.
1247
1777
  if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
1248
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
1249
- a.subagentStart(turnId, parentTurnId);
1778
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1250
1779
  }
1251
1780
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
1252
1781
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -1260,6 +1789,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1260
1789
  streamed: true,
1261
1790
  streamBlocks: new Map(),
1262
1791
  ttftCarried: false,
1792
+ framedThrough: 0,
1263
1793
  turnBindingCarried: false,
1264
1794
  };
1265
1795
  pending = open;
@@ -1323,14 +1853,21 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1323
1853
  case "thinking": {
1324
1854
  const id = `${messageId}:reasoning:${index}`;
1325
1855
  a.reasoningStart(id, messageId);
1326
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: block.signature, redacted: undefined });
1856
+ p.streamBlocks.set(index, {
1857
+ kind: "reasoning",
1858
+ id,
1859
+ signature: block.signature,
1860
+ redacted: undefined,
1861
+ hasText: false,
1862
+ narration: false,
1863
+ });
1327
1864
  return;
1328
1865
  }
1329
1866
  case "redacted_thinking": {
1330
1867
  // Arrives complete (never delta'd); end + the redacted opaque land at stop.
1331
1868
  const id = `${messageId}:reasoning:${index}`;
1332
1869
  a.reasoningStart(id, messageId);
1333
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data });
1870
+ p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data, hasText: false, narration: false });
1334
1871
  return;
1335
1872
  }
1336
1873
  case "tool_use":
@@ -1375,6 +1912,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1375
1912
  // Arrives complete inside the start frame — same tool.done mapping as
1376
1913
  // the complete arm's mcp_tool_result case.
1377
1914
  const outcome: ToolOutcome = block.is_error ? "error" : "ok";
1915
+ closedToolCallIds.add(block.tool_use_id);
1378
1916
  a.toolDone({
1379
1917
  toolCallId: block.tool_use_id,
1380
1918
  content: mcpToolResultContentToAgBlocks(block.content),
@@ -1391,7 +1929,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1391
1929
  a.contentBlock(messageId, {
1392
1930
  type: "provider-raw",
1393
1931
  vendor: "anthropic",
1394
- raw: JsonValue.parse(block),
1932
+ raw: carryVerbatim(block),
1395
1933
  });
1396
1934
  p.streamBlocks.set(index, { kind: "emitted" });
1397
1935
  return;
@@ -1412,18 +1950,33 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1412
1950
  return;
1413
1951
  }
1414
1952
  if (d.type === "thinking_delta" && b.kind === "reasoning") {
1953
+ if (typeof d.thinking === "string" && d.thinking.length > 0) b.hasText = true;
1415
1954
  // Claude Code stamps a RUNTIME-ONLY `estimated_tokens` (number | null;
1416
1955
  // undeclared on BetaThinkingDelta) on each thinking_delta. Under
1417
1956
  // Fable 5.1's default `display: omitted` the `thinking` text is '' and
1418
- // that estimate is the delta's entire payload — carried verbatim as
1419
- // providerMetadata (wire name kept; null kept: "no estimate yet" is a
1420
- // real value). Absent key ⇒ no providerMetadata, byte-identical.
1957
+ // that estimate is the delta's entire payload — carried verbatim (wire
1958
+ // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
1959
+ // no bag, byte-identical.
1960
+ //
1961
+ // X5 (sp-rnd, 2026-09-23): it rides the delta's host-only `_meta`, not
1962
+ // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
1963
+ // that must round-trip to the provider), and the Messages API never
1964
+ // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
1965
+ // on start events, so the estimate is now LIVE-ONLY (it used to fold
1966
+ // last-value-wins onto the reasoning block) — the same standing as its
1967
+ // `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
1968
+ // consumer read the folded value (guuey/ggui checked via sp-team-main).
1969
+ // `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
1970
+ // primitive (the reasoning.start precedent in `emitAssistantBlock`), and
1971
+ // the sugar's only extra step, de-cumulation, is a pass-through for a
1972
+ // non-cumulative delta like this one.
1421
1973
  const rawDelta: unknown = d;
1422
- const estimate =
1423
- isJsonObject(rawDelta) && "estimated_tokens" in rawDelta
1424
- ? AgProviderMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] })
1425
- : undefined;
1426
- a.reasoningDelta(b.id, messageId, d.thinking, estimate !== undefined ? { providerMetadata: estimate } : undefined);
1974
+ if (isJsonObject(rawDelta) && "estimated_tokens" in rawDelta) {
1975
+ const estimate = AgMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] });
1976
+ a.emit({ type: "reasoning.delta", id: b.id, messageId, delta: d.thinking, _meta: estimate });
1977
+ } else {
1978
+ a.reasoningDelta(b.id, messageId, d.thinking);
1979
+ }
1427
1980
  return;
1428
1981
  }
1429
1982
  if (d.type === "input_json_delta" && b.kind === "tool") {
@@ -1492,7 +2045,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1492
2045
  carryStreamFrame(msg);
1493
2046
  }
1494
2047
 
1495
- function registerUuid(uuid: string | undefined, ids: readonly string[]): void {
2048
+ // The turn each retractable message was emitted under, so a retraction's
2049
+ // `message.remove` names its OWNER explicitly (INV-OWNER) instead of taking
2050
+ // the assembler's last-turn backfill, which overlapping subagent runs can skew.
2051
+ const turnByMessageId = new Map<string, string>();
2052
+ function registerUuid(uuid: string | undefined, ids: readonly string[], turnId?: string): void {
2053
+ if (turnId !== undefined) for (const id of ids) turnByMessageId.set(id, turnId);
1496
2054
  if (uuid === undefined || ids.length === 0) return;
1497
2055
  const existing = messageIdsByUuid.get(uuid);
1498
2056
  if (existing !== undefined) existing.push(...ids);
@@ -1513,15 +2071,70 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1513
2071
  const ids = messageIdsByUuid.get(uuid);
1514
2072
  if (ids === undefined) continue;
1515
2073
  for (const id of ids) {
1516
- a.emit({ type: "message.remove", id });
2074
+ const owner = turnByMessageId.get(id);
2075
+ a.emit({ type: "message.remove", id, ...(owner !== undefined ? { turnId: owner } : {}) });
1517
2076
  }
1518
2077
  }
1519
2078
  }
1520
2079
 
2080
+ // Emit a result's permission_denials as tool.start + tool.done denied pairs,
2081
+ // inside a dedicated carrier message: the assistant message is already
2082
+ // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
2083
+ // closed turns. BOTH result arms call it, at the same point (after the seal
2084
+ // and the run closes, before result-meta and the close). Through 0.6.4 only
2085
+ // the success arm did, so an error-subtype result (SDKResultError declares
2086
+ // permission_denials too, e.g. error_max_turns after a denied tool) dropped
2087
+ // its denials.
2088
+ function emitDenialsCarrier(
2089
+ turnId: string,
2090
+ denials: ReadonlyArray<{ readonly tool_name: string; readonly tool_use_id: string }>,
2091
+ sessionId: string,
2092
+ ): void {
2093
+ // Skip every denial whose call already has its final tool.done in this
2094
+ // invoke: a harness-stamped denied tool_result (the user branch), an
2095
+ // mcp_tool_result, or an earlier carrier (a repeated id, in this list or a
2096
+ // later result's). A denial for an id not yet closed still gets its pair.
2097
+ const fresh: Array<{ readonly tool_name: string; readonly tool_use_id: string }> = [];
2098
+ for (const d of denials) {
2099
+ if (closedToolCallIds.has(d.tool_use_id)) continue;
2100
+ closedToolCallIds.add(d.tool_use_id);
2101
+ fresh.push(d);
2102
+ }
2103
+ if (fresh.length > 0) {
2104
+ const denialMsgId = `${turnId}:denials`;
2105
+ a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? sessionId });
2106
+ for (const denial of fresh) {
2107
+ // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
2108
+ // "handled" via existing-home mapping): enrich with the live
2109
+ // standalone denial notice recorded above (keyed by tool_use_id),
2110
+ // when one preceded this aggregate — the actual rejection text
2111
+ // returned to the model, plus decision-reason/agent-id context —
2112
+ // rather than leaving a bare empty-content stub. No second
2113
+ // tool.start/tool.done pair is ever emitted for the live frame
2114
+ // itself (see the dedicated `permission_denied` branch below).
2115
+ const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2116
+ const liveFields = liveDenialMeta(live);
2117
+ const liveMeta: AgProviderMeta | undefined =
2118
+ liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
2119
+ a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
2120
+ a.toolDone({
2121
+ toolCallId: denial.tool_use_id,
2122
+ content: live !== undefined ? [{ type: "text", text: live.message }] : [],
2123
+ outcome: "denied",
2124
+ ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
2125
+ });
2126
+ }
2127
+ a.closeMessage(denialMsgId);
2128
+ }
2129
+ }
2130
+
1521
2131
  function drive(msg: SDKMessage): void {
1522
2132
  if (msg.type === "assistant") {
1523
2133
  const m = msg.message;
1524
- const turnId = turnIdFor(msg.session_id, m.id);
2134
+ const turnId =
2135
+ msg.parent_tool_use_id !== null
2136
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
2137
+ : topTurnId(m.id, msg.uuid);
1525
2138
  const parentTurnId =
1526
2139
  msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1527
2140
 
@@ -1583,7 +2196,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1583
2196
  // Structured plain-JSON shape per its own doc (evolves additively);
1584
2197
  // JsonValue.parse both validates that invariant and satisfies the
1585
2198
  // wrapper-meta channel's type without an unchecked cast.
1586
- wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
2199
+ wrapperMetaRaw["context_usage"] = carryVerbatim(msg.context_usage);
1587
2200
  }
1588
2201
  // `usage_report` (0.3.273): the structured twin of the /usage report,
1589
2202
  // riding the synthetic assistant message that delivers its text (session
@@ -1597,7 +2210,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1597
2210
  // claude.ai-subscriber sessions", and the capture harness authenticates
1598
2211
  // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1599
2212
  if (msg.usage_report !== undefined) {
1600
- wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
2213
+ wrapperMetaRaw["usage_report"] = carryVerbatim(msg.usage_report);
1601
2214
  }
1602
2215
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1603
2216
  // the indexes of THIS frame's content blocks that are user-facing narration
@@ -1617,6 +2230,29 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1617
2230
  if (narrationBlockIndexes !== undefined) {
1618
2231
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1619
2232
  }
2233
+ // `message.diagnostics` (a Messages API response field, first seen live on
2234
+ // sp-probe's defer-tool-sonnet5-resume-unavailable, 7c6880f): per-response
2235
+ // diagnostics, there `{cache_miss_reason: {type: "tools_changed",
2236
+ // cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
2237
+ // Response-only (never sent back on replay), so it rides host-only `_meta`
2238
+ // (SPEC §12, the X5 split), verbatim with its wire name. Undeclared on
2239
+ // @anthropic-ai/sdk 0.93.0's BetaMessage, so read through the JSON
2240
+ // boundary; null (its usual value) carries nothing. It is per RESPONSE,
2241
+ // and the CLI repeats the same message object on every frame of a
2242
+ // multi-frame message, so it is carried once per SDK message id (again
2243
+ // only if the value changes).
2244
+ const rawMessage: unknown = m;
2245
+ const diagnostics =
2246
+ isJsonObject(rawMessage) && isJsonObject(rawMessage["diagnostics"])
2247
+ ? carryVerbatim(rawMessage["diagnostics"])
2248
+ : undefined;
2249
+ if (diagnostics !== undefined) {
2250
+ const diagnosticsKey = JSON.stringify(diagnostics);
2251
+ if (diagnosticsCarried.get(m.id) !== diagnosticsKey) {
2252
+ wrapperMetaRaw["diagnostics"] = diagnostics;
2253
+ diagnosticsCarried.set(m.id, diagnosticsKey);
2254
+ }
2255
+ }
1620
2256
  // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1621
2257
  // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1622
2258
  // The CLI stamps them on the synthetic API-error assistant frame, the one
@@ -1641,31 +2277,49 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1641
2277
  const apiError = rawAssistant["api_error"];
1642
2278
  if (typeof apiError === "string") wrapperMetaRaw["api_error"] = apiError;
1643
2279
  const apiErrorParams = rawAssistant["api_error_params"];
1644
- if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
2280
+ if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = carryVerbatim(apiErrorParams);
1645
2281
  }
1646
2282
  const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1647
2283
  if (assistantApiErrorCode !== undefined) {
1648
2284
  wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1649
2285
  }
2286
+ // rd-15 (founder ruling 2026-09-24: defer the neutral remedy field, fix the
2287
+ // vendor carries; a 0.7.0 carry with zero golden moves). Three more
2288
+ // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
2289
+ // 0.3.280 (so read through the JSON boundary), carried verbatim under their
2290
+ // wire names on the frame's first block's host-only `_meta` (the X5 route,
2291
+ // which folds onto block._meta; never providerMetadata, SPEC §12):
2292
+ // - `error_details`: "Raw API error message: preserves details (e.g.
2293
+ // prompt-too-long token counts) that user-facing content discards"
2294
+ // (the CLI's own schema doc; the same datum is typed on the StopFailure
2295
+ // hook input, sdk.d.ts:9154);
2296
+ // - `advisor_model`: "Advisor model that produced this message, when
2297
+ // applicable";
2298
+ // - `attribution_agent`: "agent name parsed from querySource".
2299
+ // A non-string value is not carried. No committed native carries any of
2300
+ // them, so no golden moves.
2301
+ if (isJsonObject(rawAssistant)) {
2302
+ for (const key of ["error_details", "advisor_model", "attribution_agent"]) {
2303
+ const v = rawAssistant[key];
2304
+ if (typeof v === "string") wrapperMetaRaw[key] = v;
2305
+ }
2306
+ }
1650
2307
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1651
2308
  // the bag below, once `open` is known — their once-per-message flag is
1652
2309
  // shared with the stream arm's carry.
1653
2310
 
1654
- // A non-null parent_tool_use_id ⇒ this assistant message is a NESTED turn
1655
- // (subagent). subagent.start is the SOLE nested-turn opener (spec §4/§5) and
1656
- // seeds the turn so openMessage does NOT synthesize a duplicate turn.start.
1657
- // guuey#26: a CONTINUATION frame joins the message (and, when nested, the
1658
- // subagent bracket) the previous frame opened — no second subagent.start,
1659
- // no second message.start.
2311
+ // A non-null parent_tool_use_id ⇒ this assistant message belongs to a
2312
+ // NESTED turn (subagent run). subagent.start is the SOLE nested-turn opener
2313
+ // (spec §4/§5), emitted once per run by `openRun`, and seeds the turn so
2314
+ // openMessage does NOT synthesize a duplicate turn.start. guuey#26: a
2315
+ // CONTINUATION frame joins the message the previous frame opened — no
2316
+ // second message.start.
1660
2317
  let open: PendingMessage;
1661
2318
  if (continued !== undefined) {
1662
2319
  open = continued;
1663
2320
  } else {
1664
- if (parentTurnId !== undefined) {
1665
- if (msg.parent_tool_use_id !== null) {
1666
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
1667
- }
1668
- a.subagentStart(turnId, parentTurnId);
2321
+ if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
2322
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1669
2323
  }
1670
2324
 
1671
2325
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
@@ -1684,6 +2338,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1684
2338
  streamed: false,
1685
2339
  streamBlocks: new Map(),
1686
2340
  ttftCarried: false,
2341
+ framedThrough: 0,
1687
2342
  turnBindingCarried: false,
1688
2343
  };
1689
2344
  pending = open;
@@ -1696,6 +2351,21 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1696
2351
  });
1697
2352
  }
1698
2353
  const messageId = open.emittedId;
2354
+ // rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
2355
+ // {type, category, explanation, fallbacks?}) is carried verbatim on its
2356
+ // turn's closing turn.done.messageMetadata, which folds onto the message it
2357
+ // names (SPEC §5 turn.done row). The CLOSING response's value only: a later
2358
+ // response of the turn without one clears it. Every `fallback_credit_token`,
2359
+ // at any depth, is deleted first (a provider credit token is never
2360
+ // emitted). Null (every committed golden) carries nothing. Keyed by turn,
2361
+ // so a nested (subagent) response never touches its parent's entry, and
2362
+ // only top-level turns close with turn.done.
2363
+ const stopDetails: unknown = m.stop_details;
2364
+ if (isJsonObject(stopDetails)) {
2365
+ stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
2366
+ } else if (stopDetailsByTurn.get(turnId)?.messageId !== messageId) {
2367
+ stopDetailsByTurn.delete(turnId);
2368
+ }
1699
2369
  // - `user_message_uuid` (0.3.258): the client uuid of the user message
1700
2370
  // this turn answers, stamped on the turn's FIRST reply frame only
1701
2371
  // (wrapper-level sibling per its own doc — never inside
@@ -1734,14 +2404,60 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1734
2404
  if (resumeReason !== undefined) wrapperMetaRaw["resume_reason"] = resumeReason;
1735
2405
  }
1736
2406
  }
2407
+ // X5 (sp-rnd re-cut, 2026-09-23): the bag mixes two kinds of fact. SPEC
2408
+ // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2409
+ // round-trip to the provider) and `_meta` host-only side metadata.
2410
+ // `narration_block_indexes` and the API-error triad are CLI-wrapper facts
2411
+ // the Messages API never consumes, so where the bag anchors on a BLOCK they
2412
+ // ride that block's start event `_meta` (`reduce()` folds it onto
2413
+ // `block._meta`, keeping the per-frame anchoring). The rest keeps
2414
+ // `providerMetadata`. The split is by key, so the combined bag, and the
2415
+ // `message.metadata` path below that uses it, stay byte-identical
2416
+ // (message.metadata is already `AgMeta`).
2417
+ //
2418
+ // Consumer check (sp-team-main, 2026-09-23): ggui has none of these names.
2419
+ // No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
2420
+ // the native frame. guuey asked that the triad move as ONE unit; the
2421
+ // result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
2422
+ const replayRaw: { [k: string]: JsonValue } = {};
2423
+ const hostRaw: { [k: string]: JsonValue } = {};
2424
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2425
+ if (HOST_ONLY_WRAPPER_KEYS.has(k)) hostRaw[k] = v;
2426
+ else replayRaw[k] = v;
2427
+ }
1737
2428
  const wrapperMeta: AgProviderMeta | undefined =
1738
- Object.keys(wrapperMetaRaw).length > 0 ? AgProviderMeta.parse(wrapperMetaRaw) : undefined;
2429
+ Object.keys(replayRaw).length > 0 ? AgProviderMeta.parse(replayRaw) : undefined;
2430
+ const hostMeta: AgMeta | undefined = Object.keys(hostRaw).length > 0 ? AgMeta.parse(hostRaw) : undefined;
2431
+ let anchored: BlockAnchor = NOTHING_ANCHORED;
1739
2432
  // workspace#7 dedupe: a STREAMED lifecycle already emitted every block
1740
2433
  // incrementally (stream ids reuse the content `index`, identical to the
1741
2434
  // arithmetic below) — this complete frame must not re-synthesize them.
1742
2435
  // Everything below the block loop (wrapper carry via message.metadata,
1743
2436
  // usage, error close, uuid registration) still runs.
1744
2437
  const suppressed = open.streamed;
2438
+ // draft.4 `phase` (§8.0 item 27, a SHOULD per the founder's A.10.5
2439
+ // ruling): a `thinking` block listed in `narration_block_indexes` whose
2440
+ // text is NON-EMPTY is interim narration → `phase:"interim"` on that
2441
+ // reasoning block. A listed empty block (display "omitted") gets none.
2442
+ // The index is FRAME-local. Never inferred from position, text or turn
2443
+ // end; never decoded from the signature; the vendor list itself still
2444
+ // rides host-only `_meta` verbatim (X5).
2445
+ const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2446
+ if (suppressed && narrationIndexes.size > 0) {
2447
+ // STREAMED: the complete frame precedes its blocks' content_block_stop
2448
+ // (CB-13; thinking-fable51 frames [62] signature → [63] frame → [64]
2449
+ // stop), so each listed frame-local index names stream block
2450
+ // `framedThrough + idx` (the frame covers the next blocks after those
2451
+ // earlier frames covered). It is marked only while it is still OPEN;
2452
+ // the phase then rides its reasoning.end, if its streamed text was
2453
+ // non-empty. A block that already sealed stays unmarked, never a
2454
+ // post-seal event and never a neighbouring block.
2455
+ for (const idx of narrationIndexes) {
2456
+ const frameBlock = m.content[idx];
2457
+ const streamBlock = open.streamBlocks.get(open.framedThrough + idx);
2458
+ if (frameBlock?.type === "thinking" && streamBlock?.kind === "reasoning") streamBlock.narration = true;
2459
+ }
2460
+ }
1745
2461
  if (!suppressed) {
1746
2462
  // A plain indexed loop, not `.forEach` — see `mcpToolResultContentToAgBlocks`'s
1747
2463
  // doc: `.forEach`'s callback parameter inference degrades to implicit `any`
@@ -1757,15 +2473,46 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1757
2473
  // (`<id>:text:0` twice would clobber in the fold). The wrapper carry
1758
2474
  // stays anchored to this FRAME's first block: `aborted` /
1759
2475
  // `resumed_from_incomplete_thinking` are per-frame facts.
1760
- emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined);
2476
+ // NON-STREAMED: the marker is known before the first delta, so it
2477
+ // rides reasoning.start (§5 phase timing).
2478
+ const interim =
2479
+ narrationIndexes.has(i) && block.type === "thinking" && typeof block.thinking === "string" && block.thinking.length > 0
2480
+ ? "interim"
2481
+ : undefined;
2482
+ const landed = emitAssistantBlock(
2483
+ a,
2484
+ block,
2485
+ messageId,
2486
+ open.blockIndex + i,
2487
+ i === 0 ? wrapperMeta : undefined,
2488
+ i === 0 ? hostMeta : undefined,
2489
+ interim,
2490
+ );
2491
+ if (block.type === "mcp_tool_result") closedToolCallIds.add(block.tool_use_id);
2492
+ if (i === 0) anchored = landed;
1761
2493
  }
1762
2494
  open.blockIndex += m.content.length;
1763
2495
  }
2496
+ open.framedThrough += m.content.length;
1764
2497
  // Block-less frame (e.g. aborted before any content streamed) — or a
1765
2498
  // suppressed one, whose blocks were already sealed by the stream: no
1766
- // first block exists to anchor the wrapper carry — ride message.metadata.
1767
- if ((suppressed || m.content.length === 0) && wrapperMeta !== undefined) {
2499
+ // first block exists to anchor the wrapper carry — ride message.metadata
2500
+ // (the whole combined bag, unchanged).
2501
+ if ((suppressed || m.content.length === 0) && (wrapperMeta !== undefined || hostMeta !== undefined)) {
1768
2502
  a.emit({ type: "message.metadata", messageId, metadata: wrapperMetaRaw });
2503
+ } else {
2504
+ // Whatever the first block could not anchor rides the message instead,
2505
+ // in wire order, so it still folds: the host half after a tool call (no
2506
+ // `_meta` on tool.start), and BOTH halves after a compaction, an
2507
+ // mcp_tool_result or a content.block (no providerMetadata slot).
2508
+ const unanchored: { [k: string]: JsonValue } = {};
2509
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2510
+ const isHost = HOST_ONLY_WRAPPER_KEYS.has(k);
2511
+ if ((isHost && !anchored.host) || (!isHost && !anchored.replay)) unanchored[k] = v;
2512
+ }
2513
+ if (Object.keys(unanchored).length > 0) {
2514
+ a.emit({ type: "message.metadata", messageId, metadata: unanchored });
2515
+ }
1769
2516
  }
1770
2517
  // The seal is DEFERRED (guuey#26) — the next frame may continue this same
1771
2518
  // message id. Usage is message-level and repeated per frame, so the newest
@@ -1790,47 +2537,40 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1790
2537
  // close.
1791
2538
  closePendingMessage();
1792
2539
  const errCode: NonNullable<SDKAssistantError> = msg.error;
1793
- // First error frame wins: a turn already carrying a stashed close keeps
1794
- // it (before CL-09's stash, the first error frame closed the turn).
1795
- if (!stashedTurnErrors.has(turnId)) {
1796
- stashedTurnErrors.set(turnId, {
1797
- message: errCode,
1798
- code: errCode,
1799
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1800
- // cousin of rate_limit/server_error) joins the retriable set.
1801
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1802
- // decommissioned model id) is deliberately EXCLUDED: explicit
1803
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1804
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1805
- // deliberate non-retriable: a billing-class code (the account is on
1806
- // hold — a first cousin of `billing_error`, cleared by the account
1807
- // holder, never by re-sending the turn).
1808
- //
1809
- // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1810
- // deliberate non-retriables recorded here for the same reason — an
1811
- // omission must never read as an oversight:
1812
- // - `verification_required`: the request is gated on an out-of-band
1813
- // human step (identity/org verification). Nothing about the turn
1814
- // changes by re-sending it; the block clears only when a person
1815
- // completes the verification.
1816
- // - `cloud_credential_error`: a credential/billing-class failure on
1817
- // the cloud-provider leg (a first cousin of `billing_error` and
1818
- // `account_on_hold`, not of `overloaded`) — a bad, expired or
1819
- // unauthorized credential is exactly as bad on the next attempt.
1820
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1821
- });
2540
+ const retriable = assistantErrorRetriable(errCode);
2541
+ if (msg.parent_tool_use_id !== null) {
2542
+ // A NESTED error frame (sp-protocol ruling 1, 2026-09-23): the error is
2543
+ // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2544
+ // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2545
+ // parent closes as an error only when its OWN result frame says so.
2546
+ // Through 0.6.4 (whenever subagent frames carried the parent's
2547
+ // session_id) a nested rate_limit closed a recovered parent as a
2548
+ // retriable error and, first-error-wins, masked a later top-level
2549
+ // billing_error. `subagent.done` carries no outcome (SPEC:648), so the
2550
+ // failure rides the NON-terminal `error` event (SPEC:609) on the nested
2551
+ // turn: live-only but truthful and correctly owned, and inside the
2552
+ // run's still-open bracket, so before its subagent.done. The folded gap
2553
+ // ("a nested turn has no failure outcome") is sp-protocol's to bar.
2554
+ a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2555
+ // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2556
+ // frame's close is stashed and released as the nested turn.error when
2557
+ // its run closes (see `closeRun`), whatever the Task result reports.
2558
+ if (!nestedStashedErrors.has(turnId)) nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2559
+ } else if (!stashedTurnErrors.has(turnId)) {
2560
+ // First error frame wins: a turn already carrying a stashed close keeps
2561
+ // it (before CL-09's stash, the first error frame closed the turn).
2562
+ stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
1822
2563
  }
1823
2564
  }
1824
2565
 
1825
- // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
1826
- // message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
1827
- // in the same order, once nothing can continue this message.
2566
+ // `subagent.done` is NOT emitted here: it brackets the RUN (see `openRun`),
2567
+ // and this message's seal is deferred (guuey#26) until nothing can continue it.
1828
2568
 
1829
2569
  // Record this frame's own uuid → the messageId it produced, so a LATER
1830
2570
  // retraction naming this uuid can translate it (Finding #1). The EMITTED
1831
2571
  // id, so a retraction still names the message that actually exists on the
1832
2572
  // wire when this frame rode a derived carrier.
1833
- registerUuid(msg.uuid, [messageId]);
2573
+ registerUuid(msg.uuid, [messageId], turnId);
1834
2574
  return;
1835
2575
  }
1836
2576
 
@@ -1861,6 +2601,44 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1861
2601
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1862
2602
  // adoption below depends on this ordering).
1863
2603
  closePendingMessage();
2604
+ // A tool_result answering a Task call ENDS that subagent run, by what it
2605
+ // reports (B-strict, see `openRun`): its nested terminal and bracket close
2606
+ // come before the result's own tool.done. A result for any other tool
2607
+ // closes nothing. A background launch ack keeps the run open.
2608
+ if (typeof msg.message.content !== "string") {
2609
+ let resultCount = 0;
2610
+ for (const b of msg.message.content) if (b.type === "tool_result") resultCount++;
2611
+ const rawUser: unknown = msg;
2612
+ const sibling = resultCount === 1 && isJsonObject(rawUser) ? rawUser["tool_use_result"] : undefined;
2613
+ const status = isJsonObject(sibling) && typeof sibling["status"] === "string" ? sibling["status"] : undefined;
2614
+ for (const b of msg.message.content) {
2615
+ if (b.type !== "tool_result" || !openRuns.has(b.tool_use_id)) continue;
2616
+ if (b.is_error === true) {
2617
+ closeRun(b.tool_use_id, { kind: "error", message: toolResultText(b.content) ?? "subagent failed" });
2618
+ } else if (status !== "async_launched" && status !== "remote_launched") {
2619
+ closeRun(b.tool_use_id, { kind: "success" });
2620
+ }
2621
+ }
2622
+ }
2623
+ // A LIVE user frame with no tool_result block is content the CLI added to
2624
+ // the conversation itself (the SDKUserMessage doc; the host's own prompts
2625
+ // come back only as isReplay acks, returned above). The live case: the
2626
+ // CLI's `isSynthetic: true` nudge "[Your previous response had no visible
2627
+ // output. …]" after an empty reply (sp-probe's
2628
+ // defer-tool-sonnet5-resume-unavailable, 7c6880f, the corpus's only such
2629
+ // frame). This branch maps only tool_result blocks, so it had no event at
2630
+ // all, and the census could not see the text go (its path normalizes to
2631
+ // the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
2632
+ // the carry the replay gap above names. DISCLOSED: a frame MIXING
2633
+ // tool_results with other blocks still maps only its tool_results (none
2634
+ // in the corpus).
2635
+ let carriesToolResult = false;
2636
+ if (typeof msg.message.content !== "string") {
2637
+ for (const b of msg.message.content) if (b.type === "tool_result") carriesToolResult = true;
2638
+ }
2639
+ if (!carriesToolResult) {
2640
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(msg) });
2641
+ }
1864
2642
  // A user message carrying tool_result blocks → tool.done per result.
1865
2643
  // parent_tool_use_id (when set) identifies a subagent tool call — the
1866
2644
  // tool.done's turnId should point at that parent call's turn so the
@@ -1872,11 +2650,53 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1872
2650
  // it is unknown (e.g. a result delivered before its subagent.start
1873
2651
  // was ever observed) — defensive; leg 3's never-opened-turn guard now
1874
2652
  // parks loudly on that label instead of fabricating a phantom turn.
1875
- const toolTurnId =
1876
- msg.parent_tool_use_id !== null
1877
- ? (subagentTurnByParentToolUseId.get(msg.parent_tool_use_id) ??
1878
- `turn_${msg.parent_tool_use_id}`)
1879
- : undefined;
2653
+ // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2654
+ // runs make the assembler's last-turn backfill unreliable). With no turn
2655
+ // open, the frame opens one first (below), so this is never undefined.
2656
+ // Nested: the run's OPEN nested turn. A nested frame for a run that has
2657
+ // CLOSED (e.g. a background agent's tool_result after the parent's
2658
+ // result), or for one this invoke NEVER opened (the stream started
2659
+ // mid-run), gets a fresh run named by its frame, as nested assistant
2660
+ // frames do: nothing lands on a nested turn after its subagent.done, or
2661
+ // on a turn nobody opened, and no id repeats across invokes.
2662
+ // INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
2663
+ // content event for a turn the stream has not opened; sp-protocol,
2664
+ // 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
2665
+ // invoke's first frame is the deferred call's tool_result, before
2666
+ // system/init; sp-probe's defer-resume capture) opens the turn it lands
2667
+ // in, named by this frame's uuid. The resumed invoke's assistant frames
2668
+ // then join it and its result closes it. Through c54eb7f its tool.done
2669
+ // had no turn and reduce() parked from the first event. Where that result
2670
+ // folds relative to the PREVIOUS invoke's open tool block is candidate
2671
+ // 20's bar question, not decided here.
2672
+ let opensWithToolResult = false;
2673
+ for (const b of content) if (b.type === "tool_result") opensWithToolResult = true;
2674
+ if (msg.parent_tool_use_id === null && openTopTurnId === undefined && opensWithToolResult) {
2675
+ const opened = topTurnId(msg.uuid, undefined);
2676
+ a.openTurn(opened, options.threadId ?? msg.session_id ?? opened);
2677
+ }
2678
+ let toolTurnId: string | undefined;
2679
+ if (msg.parent_tool_use_id !== null) {
2680
+ const parentToolUseId = msg.parent_tool_use_id;
2681
+ const run = openRuns.get(parentToolUseId);
2682
+ if (run !== undefined) {
2683
+ toolTurnId = run.turnId;
2684
+ } else {
2685
+ // A run that CLOSED, or one this invoke never opened (the stream
2686
+ // started mid-run: a background agent spanning invokes, a resume):
2687
+ // open a fresh run named by this frame, so its tool.done lands in a
2688
+ // turn that subagent.start opened (INV-TURN) and B-strict closes.
2689
+ // Through 0.7.0's DC-10 fix the never-opened case named the synthetic
2690
+ // `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
2691
+ // loudly"): a turn nobody opened, whose id REPEATED across the
2692
+ // invokes one Reducer folds (the rd-14 ids-across-invokes rule;
2693
+ // sp-protocol's message.start bar, wf_140b3183-767), and it parked.
2694
+ toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
2695
+ openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
2696
+ }
2697
+ } else {
2698
+ toolTurnId = openTopTurnId;
2699
+ }
1880
2700
  // tool_use_result sibling (SDK-injected rich MCP result; audit B7): carries
1881
2701
  // structuredContent (incl. render-cache markers) + _meta.ui the block-level
1882
2702
  // arm never sees. Applies only when the message has exactly ONE tool_result
@@ -1921,9 +2741,28 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1921
2741
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
1922
2742
  // collect every adopted messageId this frame produces below.
1923
2743
  const resultMessageIds: string[] = [];
2744
+ const nonExecutionById = readNonExecutionKinds(msg);
1924
2745
  for (const block of content) {
1925
2746
  if (block.type === "tool_result") {
1926
- const outcome: ToolOutcome = block.is_error === true ? "error" : "ok";
2747
+ // A harness-stamped denial (see isDenialKind) records as "denied"
2748
+ // with no isError, and the native block message stays in `content`,
2749
+ // so the model-facing reason survives (§2.2 draft.4: isError and
2750
+ // errorText belong to outcome "error"). Before this, the same call
2751
+ // folded "error" here and then "denied" again from the result's
2752
+ // permission_denials (sp-probe's resume-deny leg).
2753
+ // Second key (sp-protocol, same basis): when no kind is stamped, a
2754
+ // live `permission_denied` notice already seen for this id is the
2755
+ // harness's own denial record (the CLI emits it at decision time,
2756
+ // always before this result). No kind is stamped on a frame holding
2757
+ // more than one tool_result (2.1.280's stamper returns [] unless
2758
+ // exactly one), nor by a CLI that predates the stamp. A stamped kind
2759
+ // stays the primary key, so "interrupted" with a notice is still an
2760
+ // error.
2761
+ const kind = nonExecutionById.get(block.tool_use_id);
2762
+ const denied =
2763
+ block.is_error === true &&
2764
+ (kind !== undefined ? isDenialKind(kind) : deniedLiveByToolUseId.has(block.tool_use_id));
2765
+ const outcome: ToolOutcome = denied ? "denied" : block.is_error === true ? "error" : "ok";
1927
2766
  const toolContent =
1928
2767
  block.content === undefined ? [] : toolResultContentToAgBlocks(block.content);
1929
2768
  // `structuredContent` is not declared on `ToolResultBlockParam` in the
@@ -1937,11 +2776,22 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1937
2776
  : undefined;
1938
2777
  const resultMessageId = `${block.tool_use_id}:result`;
1939
2778
  resultMessageIds.push(resultMessageId);
2779
+ closedToolCallIds.add(block.tool_use_id);
2780
+ // This tool.done closes the call, so the result's permission_denials
2781
+ // carrier skips it. The live `permission_denied` notice for the id
2782
+ // (the CLI emits it from its canUseTool wrapper at decision time,
2783
+ // always before this tool_result) rides here instead, the same
2784
+ // providerMetadata the carrier gave it, so D drops nothing.
2785
+ const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2786
+ const resultProviderFields: { [k: string]: JsonValue } = {
2787
+ ...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
2788
+ ...(liveFields ?? {}),
2789
+ };
1940
2790
  a.toolDone({
1941
2791
  toolCallId: block.tool_use_id,
1942
2792
  content: toolContent,
1943
2793
  outcome,
1944
- isError: block.is_error === true,
2794
+ ...(denied ? {} : { isError: block.is_error === true }),
1945
2795
  turnId: toolTurnId,
1946
2796
  // SPEC §5 tool.done adoption (audit B10; Task 8b): the Claude SDK
1947
2797
  // closes the assistant message (message.end) BEFORE this tool_result
@@ -1965,15 +2815,15 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1965
2815
  : {}),
1966
2816
  ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
1967
2817
  ...(applySibling && siblingMeta !== undefined ? { _meta: siblingMeta } : {}),
1968
- ...(applySibling && siblingResourceLinks !== undefined
1969
- ? { providerMetadata: AgProviderMeta.parse({ resourceLinks: siblingResourceLinks }) }
2818
+ ...(Object.keys(resultProviderFields).length > 0
2819
+ ? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
1970
2820
  : {}),
1971
2821
  });
1972
2822
  }
1973
2823
  }
1974
2824
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
1975
2825
  // produced, so a later retraction naming this uuid can translate it.
1976
- registerUuid(msg.uuid, resultMessageIds);
2826
+ registerUuid(msg.uuid, resultMessageIds, toolTurnId);
1977
2827
  }
1978
2828
  return;
1979
2829
  }
@@ -1982,7 +2832,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1982
2832
  // guuey#26: the turn is closing — seal the open assistant message first
1983
2833
  // (message.end has always preceded the turn close).
1984
2834
  closePendingMessage();
1985
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2835
+ // B-strict: a subagent run still open (a background or unreported sub-run)
2836
+ // is NOT closed by its parent's result; it closes when the framework
2837
+ // reports it, or at flush.
2838
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1986
2839
  // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1987
2840
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1988
2841
  // the final assistant text in result — or, with is_error true, the error
@@ -2002,6 +2855,8 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2002
2855
  // discriminant-validated, and false/absent must stay on the success path
2003
2856
  // byte-for-byte. The stash entry is consumed either way.
2004
2857
  const stashedError = takeStashedTurnError(turnId);
2858
+ // Shape-guarded once for every close below (Tenet 6; see guardedTurnUsage).
2859
+ const turnUsage = guardedTurnUsage(msg);
2005
2860
  const apiErrorTurn = msg.is_error === true;
2006
2861
  const safety: AgSafety[] | undefined =
2007
2862
  msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
@@ -2015,37 +2870,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2015
2870
  // CL-09: an API-error turn's denials take this same carrier, at the same
2016
2871
  // point — its close is deferred to this frame (below), so the turn is
2017
2872
  // still open here, like every other turn.
2018
- if (msg.permission_denials.length > 0) {
2019
- const denialMsgId = `${turnId}:denials`;
2020
- a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
2021
- for (const denial of msg.permission_denials) {
2022
- // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
2023
- // "handled" via existing-home mapping): enrich with the live
2024
- // standalone denial notice recorded above (keyed by tool_use_id),
2025
- // when one preceded this aggregate — the actual rejection text
2026
- // returned to the model, plus decision-reason/agent-id context —
2027
- // rather than leaving a bare empty-content stub. No second
2028
- // tool.start/tool.done pair is ever emitted for the live frame
2029
- // itself (see the dedicated `permission_denied` branch below).
2030
- const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2031
- const liveFields = liveDenialMeta(live);
2032
- const liveMeta: AgProviderMeta | undefined =
2033
- liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
2034
- a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
2035
- a.toolDone({
2036
- toolCallId: denial.tool_use_id,
2037
- content: live !== undefined ? [{ type: "text", text: live.message }] : [],
2038
- outcome: "denied",
2039
- ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
2040
- });
2041
- }
2042
- a.closeMessage(denialMsgId);
2043
- }
2873
+ emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
2044
2874
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
2045
2875
  // ride `ext.anthropic.result-meta` before the close (no core home on
2046
2876
  // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
2047
2877
  // API-error turn too, before its close like on every other turn.
2048
- const resultMeta = resultMetaPayload(msg);
2878
+ const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
2049
2879
  if (resultMeta !== undefined) {
2050
2880
  a.emitExt("anthropic", "result-meta", resultMeta);
2051
2881
  }
@@ -2056,33 +2886,51 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2056
2886
  // the fold keeps the cost of every round the turn ran before failing.
2057
2887
  a.closeTurnError(turnId, {
2058
2888
  ...stashedError,
2059
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2889
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2060
2890
  });
2061
2891
  return;
2062
2892
  }
2063
2893
  if (apiErrorTurn) {
2064
2894
  // No assistant error frame preceded this result (a producer that did
2065
2895
  // not yield it, or a normalizer that never saw it), so this result is
2066
- // the turn's only close. message = the result text, which on this frame
2067
- // is the API error text; code = the server's api_error_code when the
2068
- // CLI copied one through, else the generic "api_error"; retriable = the
2069
- // HTTP status says rate limit or server failure (see
2070
- // `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
2071
- // above.
2072
- const code = readApiErrorCode(msg) ?? "api_error";
2896
+ // the turn's only close. code = the server's api_error_code when the
2897
+ // CLI copied one through; else the CLI's own terminal_reason when it
2898
+ // names a cause other than a normal completion; else the generic
2899
+ // "api_error".
2900
+ // message = the result text (on an API error, its text), or the code
2901
+ // when that text is empty. retriable = the HTTP status says rate limit
2902
+ // or server failure (see `apiErrorStatusRetriable`); usage = the turn's
2903
+ // accrued usage, as above.
2904
+ // The terminal_reason step (sp-protocol, facet-local, 2026-09-23): the
2905
+ // CLI also sets is_error on a result that is NOT an API error. sp-probe's
2906
+ // resume-unavailable leg (7c6880f) is a resumed invoke whose deferred
2907
+ // tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
2908
+ // result "", no status, no api_error_code. Through b7dd7ff it closed
2909
+ // turn.error{message: "", code: "api_error"}, claiming an API failure
2910
+ // that never happened. `code` is free-form (SPEC :618), so this fills
2911
+ // existing fields from the frame's own value; a live API error
2912
+ // (terminal_reason "api_error", api-error-auth) is unchanged.
2913
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
2073
2914
  a.closeTurnError(turnId, {
2074
- message: typeof msg.result === "string" ? msg.result : code,
2915
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
2075
2916
  code,
2076
2917
  retriable: apiErrorStatusRetriable(msg.api_error_status),
2077
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2918
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2078
2919
  });
2079
2920
  return;
2080
2921
  }
2922
+ const finishReasonRaw = stopReasonRaw(msg.stop_reason);
2923
+ const stopDetails = stopDetailsByTurn.get(turnId);
2924
+ stopDetailsByTurn.delete(turnId);
2081
2925
  a.closeTurnDone(turnId, {
2082
2926
  outcome: { type: "success", result: structuredOutput ?? msg.result },
2083
2927
  finishReason: mapStopReason(msg.stop_reason),
2084
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2928
+ ...(finishReasonRaw !== undefined ? { finishReasonRaw } : {}),
2929
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2085
2930
  safety,
2931
+ ...(stopDetails !== undefined
2932
+ ? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
2933
+ : {}),
2086
2934
  });
2087
2935
  return;
2088
2936
  }
@@ -2091,10 +2939,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2091
2939
  // At this point msg.subtype can only be an error variant (success handled above).
2092
2940
  // guuey#26: seal the open assistant message before the turn close.
2093
2941
  closePendingMessage();
2094
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2942
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
2095
2943
  // CL-09: consume any stashed assistant-error close for this turnId — this
2096
- // frame emits it (below), and it cannot leak into a later turn's result
2097
- // (every turn of a session shares the turnId).
2944
+ // frame emits it (below). Each turn has its own id now, so an entry can
2945
+ // only ever be this turn's.
2098
2946
  const stashedError = takeStashedTurnError(turnId);
2099
2947
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
2100
2948
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
@@ -2112,10 +2960,22 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2112
2960
  startupFailureReason !== undefined
2113
2961
  ? startupFailureRetriable(startupFailureReason)
2114
2962
  : subtype !== "error_max_turns";
2963
+ // Denials ride the SAME carrier as on the success arm, at the same point.
2964
+ // This arm is discriminant-validated only, so the array is shape-guarded
2965
+ // (a malformed entry is skipped; Tenet 6: never throw).
2966
+ const rawDenials: unknown = isJsonObject(msg) ? msg["permission_denials"] : undefined;
2967
+ const denials = Array.isArray(rawDenials)
2968
+ ? rawDenials.flatMap((d: unknown) =>
2969
+ isJsonObject(d) && typeof d["tool_name"] === "string" && typeof d["tool_use_id"] === "string"
2970
+ ? [{ tool_name: d["tool_name"], tool_use_id: d["tool_use_id"] }]
2971
+ : [],
2972
+ )
2973
+ : [];
2974
+ emitDenialsCarrier(turnId, denials, msg.session_id);
2115
2975
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
2116
2976
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
2117
2977
  // success arm above (turn.error carries no metadata slot at all).
2118
- const resultMeta = resultMetaPayload(msg);
2978
+ const resultMeta = resultMetaPayload(msg, true);
2119
2979
  if (resultMeta !== undefined) {
2120
2980
  a.emitExt("anthropic", "result-meta", resultMeta);
2121
2981
  }
@@ -2126,22 +2986,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2126
2986
  // usage (the success arm's mapping). This arm is only
2127
2987
  // discriminant-validated, so the usage trio is shape-guarded first
2128
2988
  // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
2129
- // The guard covers every property `mapTurnUsage` dereferences: the
2130
- // `server_tool_use` object (null allowed, as typed) and each
2131
- // `modelUsage` entry — `usage: {}` or a null entry would otherwise
2989
+ // The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
2990
+ // dereferences — `usage: {}` or a null modelUsage entry would otherwise
2132
2991
  // throw here, after the stash was already consumed.
2133
- const raw: unknown = msg;
2134
- const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
2135
- const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
2136
- const usage =
2137
- isJsonObject(raw) &&
2138
- isJsonObject(rawUsage) &&
2139
- (rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
2140
- isJsonObject(rawModelUsage) &&
2141
- Object.values(rawModelUsage).every(isJsonObject) &&
2142
- typeof raw["total_cost_usd"] === "number"
2143
- ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
2144
- : undefined;
2992
+ const usage = guardedTurnUsage(msg);
2145
2993
  a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
2146
2994
  return;
2147
2995
  }
@@ -2166,7 +3014,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2166
3014
  // promotion is strictly more lossless. Wrapper siblings ride the text
2167
3015
  // block's providerMetadata (camelCased per the facet's carry
2168
3016
  // convention, mirroring the 0.3.217 first-block precedent).
2169
- const turnId = turnIdFor(msg.session_id, msg.uuid);
3017
+ // The open turn, or (between turns) the one this notice opens; the next
3018
+ // assistant frame then joins it and its result closes it.
3019
+ const turnId = topTurnId(msg.uuid, undefined);
2170
3020
  const noticeMeta = AgProviderMeta.parse({
2171
3021
  level: msg.level,
2172
3022
  ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
@@ -2210,7 +3060,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2210
3060
  // and non-folding, so the second copy of `retracted_message_uuids`
2211
3061
  // cannot double-fold (the M22 hazard). This is the only producer for R&D
2212
3062
  // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
2213
- a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
3063
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
2214
3064
  return;
2215
3065
  }
2216
3066
 
@@ -2262,7 +3112,34 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2262
3112
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
2263
3113
  const carriedKind = anthropicFrameKind(msg);
2264
3114
  if (carriedKind !== undefined) {
2265
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: JsonValue.parse(msg) });
3115
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3116
+ // B-strict: a background sub-run's outcome arrives as task_notification,
3117
+ // correlated to its run by tool_use_id (or by task_id through the
3118
+ // task_started frame that named it).
3119
+ const raw: unknown = msg;
3120
+ if (isJsonObject(raw) && raw["type"] === "system" && typeof raw["task_id"] === "string") {
3121
+ const taskId = raw["task_id"];
3122
+ const named = typeof raw["tool_use_id"] === "string" ? raw["tool_use_id"] : undefined;
3123
+ if (raw["subtype"] === "task_started" && named !== undefined) toolUseIdByTaskId.set(taskId, named);
3124
+ if (raw["subtype"] === "task_notification") {
3125
+ const runKey = named ?? toolUseIdByTaskId.get(taskId);
3126
+ const status = raw["status"];
3127
+ if (runKey !== undefined && openRuns.has(runKey)) {
3128
+ if (status === "completed") closeRun(runKey, { kind: "success" });
3129
+ else if (status === "failed") closeRun(runKey, { kind: "error", message: typeof raw["summary"] === "string" && raw["summary"] !== "" ? raw["summary"] : "subagent failed", code: "failed" });
3130
+ else if (status === "stopped") closeRun(runKey, { kind: "aborted", reason: "stopped" });
3131
+ }
3132
+ }
3133
+ }
3134
+ return;
3135
+ }
3136
+
3137
+ // A top-level type the union does not declare (see KNOWN_TOP_LEVEL_TYPES):
3138
+ // carried whole, never silently dropped. `msg.type` is typed as the union's
3139
+ // literals, but the frame is only discriminant-validated at runtime.
3140
+ const topLevelType: string = msg.type;
3141
+ if (!KNOWN_TOP_LEVEL_TYPES.has(topLevelType)) {
3142
+ a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
2266
3143
  return;
2267
3144
  }
2268
3145
 
@@ -2272,23 +3149,37 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2272
3149
 
2273
3150
  return {
2274
3151
  push(native: JsonValue): AgEvent[] {
2275
- if (!isSDKMessage(native)) {
3152
+ framesSeen++;
3153
+ // `native` is already plain JSON: withAtomicPush (createClaudeNormalizer)
3154
+ // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3155
+ // frame is the same reference, anything else its JSON form).
3156
+ const frame = native;
3157
+ if (!isSDKMessage(frame)) {
2276
3158
  // Graceful guard (Tenet 6): route the raw payload through the lossless
2277
3159
  // vendor channel rather than throwing. Nest under `native` so a payload
2278
3160
  // that carries its own `type` key (the common malformed-SDKMessage shape
2279
3161
  // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
2280
3162
  // (emitExt spreads object payloads at the top level).
2281
- a.emitExt("anthropic", "unparsed", { native });
3163
+ // A copy: `frame` IS the host's object when it was already JSON, and
3164
+ // this raw channel would otherwise emit it by reference. JsonValue.parse
3165
+ // copies and, like every other carry here, drops an own "__proto__"
3166
+ // (sp-main 2026-09-24, matching sp-openai cf55e08 and the 0.6.6
3167
+ // reserved-key rule 314a183: an emitted map carries no own __proto__).
3168
+ a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
2282
3169
  return a.drain();
2283
3170
  }
2284
- drive(native);
3171
+ drive(frame);
2285
3172
  return a.drain();
2286
3173
  },
2287
3174
  flush(): AgEvent[] {
2288
3175
  // guuey#26: nothing can continue the deferred message now — seal it with
2289
- // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
2290
- // to synthesize a bare `message.end`.
2291
- closePendingMessage();
3176
+ // its real usage rather than leaving INV-FLUSH to synthesize a bare
3177
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3178
+ closePendingMessage(true);
3179
+ // B-strict: every subagent run still open closes here with its nested
3180
+ // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3181
+ // its subagent.done, innermost first.
3182
+ abortOpenRuns();
2292
3183
  // CL-09: a turn whose assistant error frame stashed its close but whose
2293
3184
  // result frame never arrived still closes as that turn.error (no usage:
2294
3185
  // only a result carries the turn's), never as INV-FLUSH's synthesized
@@ -2302,5 +3193,34 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2302
3193
  };
2303
3194
  }
2304
3195
 
3196
+ /**
3197
+ * Build the Claude-facet normalizer: the inner normalizer wrapped in core's
3198
+ * withAtomicPush (the fleet guard ruling, 2026-09-24, binding). push() never
3199
+ * throws (SPEC:933):
3200
+ * - each native is first read as plain JSON (core toJsonValueSafe): a host
3201
+ * may hand in the in-process object, whose members need not be JSON (an
3202
+ * undefined member, a Date, NaN, a BigInt, a function, a cycle); a JSON
3203
+ * frame passes by reference, anything else folds exactly as its JSON form,
3204
+ * which is what every capture already is (the SDK itself parses the CLI's
3205
+ * NDJSON, so no 0.3.280 SDK frame needs it);
3206
+ * - an envelope-valid but malformed frame (a required field missing or
3207
+ * mistyped below the isSDKMessage discriminants: 61 single-point fuzz
3208
+ * mutants of the corpus's 25 frame shapes threw, from ~17 sites, most after
3209
+ * the frame had emitted) no longer throws: its partial batch is discarded
3210
+ * with its state (the inner is rebuilt and re-driven from the journal) and
3211
+ * one core `error {message: "normalizer error", code: <constructor name>}`
3212
+ * takes the next seq. Over every committed native it fires zero times
3213
+ * (e2e agents/claude-agent-sdk/guard.corpus.test.ts).
3214
+ * The fallback id stem is held HERE, outside the rebuild's factory: drawn at
3215
+ * most once, and only when a fallback id is first needed, so the common path
3216
+ * never touches randomness (core's atomic-guard differential runs with it
3217
+ * poisoned) and a rebuild re-reads the same stem.
3218
+ */
3219
+ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): Normalizer {
3220
+ let stem = options.invokeId;
3221
+ const invokeStem = (): string => (stem ??= `claude_${mintInvokeNonce()}`);
3222
+ return withAtomicPush(() => createInnerClaudeNormalizer(options, invokeStem));
3223
+ }
3224
+
2305
3225
  export default createClaudeNormalizer;
2306
3226
  export { mapStopReason };