@silverprotocol/claude-agent-sdk 0.6.7 → 0.7.1

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,121 @@ 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
+ // rd-15 (founder ruling 2026-09-24, fix the carries): each `tool_result_meta`
383
+ // entry, keyed by its `id` (the tool_use_id), verbatim: {id, non_execution_kind?,
384
+ // user_feedback?, remedy?} per the CLI's schema ("@internal Display metadata for
385
+ // this message's tool_result blocks"). Read through the JSON boundary; an entry
386
+ // without a string id is skipped. It rides the matching tool.done's `_meta`.
387
+ function readToolResultMetaEntries(frame: unknown): Map<string, JsonValue> {
388
+ const out = new Map<string, JsonValue>();
389
+ if (!isJsonObject(frame)) return out;
390
+ const list = frame["tool_result_meta"];
391
+ if (!Array.isArray(list)) return out;
392
+ for (const entry of list) {
393
+ if (isJsonObject(entry) && typeof entry["id"] === "string") out.set(entry["id"], JsonValue.parse(entry));
394
+ }
395
+ return out;
396
+ }
397
+
398
+ // The non_execution_kinds that mean the call was NOT PERMITTED to run →
399
+ // `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
400
+ // item 15 routes Claude's permission denials to it; sp-protocol, 2026-09-23).
401
+ // `interrupted`, `cancelled`, absent and any unknown value are not denials and
402
+ // keep "error" (no guessing).
403
+ function isDenialKind(kind: string | undefined): boolean {
404
+ return kind === "user-rejected" || kind === "permission-rule" || (kind !== undefined && kind.startsWith("automode-"));
405
+ }
406
+
407
+ // Which assistant `error` codes are transient (retriable). CL-09's stashed
408
+ // top-level close and a nested frame's non-terminal `error` share it.
409
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
410
+ // cousin of rate_limit/server_error) joins the retriable set.
411
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
412
+ // decommissioned model id) is deliberately EXCLUDED: explicit
413
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
414
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
415
+ // deliberate non-retriable: a billing-class code (the account is on
416
+ // hold — a first cousin of `billing_error`, cleared by the account
417
+ // holder, never by re-sending the turn).
418
+ //
419
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
420
+ // deliberate non-retriables recorded here for the same reason — an
421
+ // omission must never read as an oversight:
422
+ // - `verification_required`: the request is gated on an out-of-band
423
+ // human step (identity/org verification). Nothing about the turn
424
+ // changes by re-sending it; the block clears only when a person
425
+ // completes the verification.
426
+ // - `cloud_credential_error`: a credential/billing-class failure on
427
+ // the cloud-provider leg (a first cousin of `billing_error` and
428
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
429
+ // unauthorized credential is exactly as bad on the next attempt.
430
+ function assistantErrorRetriable(errCode: NonNullable<SDKAssistantError>): boolean {
431
+ return errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded";
432
+ }
433
+
336
434
  // ─── assistant content block fan-out (spec §4 mapping table) ──────────────────
337
435
  // 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()`).
436
+ // open message named by `messageId`. The caller passes the frame's wrapper
437
+ // carry ONLY for blockIndex 0, mirroring the "signature on first block"
438
+ // precedent (§8 item 8, Gemini thoughtSignature), in two bags:
439
+ // - `blockProviderMetadata`: the REPLAY-side wrapper facts (`supersedes`,
440
+ // `resumed_from_incomplete_thinking`, `aborted`, `context_usage`,
441
+ // `usage_report`, the turn-binding family). `text` / `thinking` /
442
+ // `redacted_thinking` and the `tool_use` family land it on their *.start
443
+ // event. The rarer block-0 shapes (mcp_tool_result / compaction / the
444
+ // default content.block) never apply it, so those facts drop there (a
445
+ // disclosed, pre-existing gap; a retraction itself still executes via
446
+ // `message.remove` regardless, see `drive()`).
447
+ // - `blockMeta` (X5): the HOST-only wrapper facts (HOST_ONLY_WRAPPER_KEYS).
448
+ // Only text.start / reasoning.start get it, because `reduce()` folds their
449
+ // `_meta` onto the block.
450
+ // Returns which halves ANCHORED on a folded start event: `replay` when the
451
+ // block type has a providerMetadata slot the caller's bag landed on (text,
452
+ // thinking, redacted_thinking, the tool_use family), `host` when `blockMeta`
453
+ // landed (text / thinking / redacted_thinking only; tool.start folds no
454
+ // `_meta`). The caller routes every UNANCHORED half through the assistant
455
+ // message's `message.metadata`, so no wrapper fact is dropped. (Before this,
456
+ // a frame whose first block was a compaction, an mcp_tool_result or a
457
+ // content.block lost its replay half silently: those have no providerMetadata
458
+ // slot, and an mcp_tool_result's tool.done belongs to another message.) That fallback is message-level and
459
+ // merges REPLACE-by-key, so it does not say which frame the frame-relative
460
+ // `narration_block_indexes` belong to. In practice it is not reached: the CLI
461
+ // sends one content block per frame, narration marks thinking/text blocks, and
462
+ // an API-error frame starts with text.
463
+ type BlockAnchor = { readonly replay: boolean; readonly host: boolean };
464
+ const NOTHING_ANCHORED: BlockAnchor = { replay: false, host: false };
465
+
348
466
  function emitAssistantBlock(
349
467
  a: StreamAssembler,
350
468
  block: BetaContentBlock,
351
469
  messageId: string,
352
470
  blockIndex: number,
353
471
  blockProviderMetadata?: AgProviderMeta,
354
- ): void {
472
+ blockMeta?: AgMeta,
473
+ phase?: string,
474
+ wireInput?: JsonValue,
475
+ ): BlockAnchor {
355
476
  switch (block.type) {
356
477
  case "text": {
357
478
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
@@ -361,22 +482,40 @@ function emitAssistantBlock(
361
482
  const id = `${messageId}:text:${blockIndex}`;
362
483
  const citations =
363
484
  block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
364
- a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
485
+ if (blockMeta !== undefined) {
486
+ // textStart's sugar has no `_meta` field; `a.emit()` is the base primitive.
487
+ a.emit({
488
+ type: "text.start",
489
+ id,
490
+ messageId,
491
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
492
+ _meta: blockMeta,
493
+ });
494
+ } else {
495
+ a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
496
+ }
365
497
  a.textDelta(id, messageId, block.text);
366
498
  a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
367
- return;
499
+ return { replay: true, host: blockMeta !== undefined };
368
500
  }
369
501
  case "thinking": {
370
502
  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 });
503
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
504
+ // reasoningStart's sugar signature has no providerMetadata or `_meta`
505
+ // parameter — `a.emit()` is the documented base primitive for exactly
506
+ // this case (schema DOES support both on reasoning.start;
507
+ // StreamAssembler docstring: "guarantees no AgClosedEventType is ever
508
+ // unreachable").
509
+ a.emit({
510
+ type: "reasoning.start",
511
+ id,
512
+ messageId,
513
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
514
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
515
+ ...(phase !== undefined ? { phase } : {}),
516
+ });
378
517
  } else {
379
- a.reasoningStart(id, messageId);
518
+ a.reasoningStart(id, messageId, phase !== undefined ? { phase } : undefined);
380
519
  }
381
520
  a.reasoningDelta(id, messageId, block.thinking);
382
521
  a.reasoningEnd(id, messageId);
@@ -390,13 +529,19 @@ function emitAssistantBlock(
390
529
  provider: "anthropic",
391
530
  });
392
531
  }
393
- return;
532
+ return { replay: true, host: blockMeta !== undefined };
394
533
  }
395
534
  case "redacted_thinking": {
396
535
  // No visible text; the redacted blob is the replay-load-bearing opaque part.
397
536
  const id = `${messageId}:reasoning:${blockIndex}`;
398
- if (blockProviderMetadata !== undefined) {
399
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
537
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
538
+ a.emit({
539
+ type: "reasoning.start",
540
+ id,
541
+ messageId,
542
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
543
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
544
+ });
400
545
  } else {
401
546
  a.reasoningStart(id, messageId);
402
547
  }
@@ -406,7 +551,7 @@ function emitAssistantBlock(
406
551
  value: block.data,
407
552
  provider: "anthropic",
408
553
  });
409
- return;
554
+ return { replay: true, host: blockMeta !== undefined };
410
555
  }
411
556
  case "tool_use":
412
557
  case "server_tool_use":
@@ -438,8 +583,8 @@ function emitAssistantBlock(
438
583
  ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
439
584
  });
440
585
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
441
- a.toolArgsAssembled(toolCallId, input);
442
- return;
586
+ a.toolArgsAssembled(toolCallId, input, wireInputFields(wireInput));
587
+ return { replay: true, host: false };
443
588
  }
444
589
  case "mcp_tool_result": {
445
590
  // MCP tool results from the assistant side: map to tool.done with content + outcome.
@@ -452,7 +597,7 @@ function emitAssistantBlock(
452
597
  isError: block.is_error,
453
598
  messageId,
454
599
  });
455
- return;
600
+ return NOTHING_ANCHORED;
456
601
  }
457
602
  case "compaction": {
458
603
  // Compaction blocks carry a provider-produced context summary (spec §4).
@@ -466,12 +611,12 @@ function emitAssistantBlock(
466
611
  : undefined,
467
612
  provider: "anthropic",
468
613
  });
469
- return;
614
+ return NOTHING_ANCHORED;
470
615
  }
471
616
  default: {
472
617
  // image / resource / other rich content blocks ride content.block (spec §4).
473
618
  a.contentBlock(messageId, assistantContentBlockToAgBlock(block));
474
- return;
619
+ return NOTHING_ANCHORED;
475
620
  }
476
621
  }
477
622
  }
@@ -618,6 +763,31 @@ const CARRIED_STANDALONE_TYPES = new Set<string>([
618
763
  "conversation_reset",
619
764
  ]);
620
765
 
766
+ // The top-level `type` literals the SDKMessage union declares (0.3.280: 39
767
+ // members over these 11 types). A frame whose `type` is NOT among them is
768
+ // RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
769
+ // frame type). The first one observed: `command_lifecycle`
770
+ // ({command_uuid, state: "queued"|"started"|"completed"}, three per prompt,
771
+ // streaming-input mode; live on corpus/multi-result-sonnet5), the host
772
+ // prompt's queue lifecycle keyed by the caller's message uuid. Through the
773
+ // 0.7.0 stack it fell through `drive()` to the no-op, a silent drop against
774
+ // SPEC §8.0 graceful degradation. An unknown top-level type now rides the
775
+ // uniform carry, `ext.anthropic.frame{kind: <type>, frame}`, verbatim (§8 item
776
+ // 22), so the next runtime-only frame type is carried the day it ships.
777
+ const KNOWN_TOP_LEVEL_TYPES: ReadonlySet<string> = new Set([
778
+ "assistant",
779
+ "user",
780
+ "result",
781
+ "system",
782
+ "stream_event",
783
+ "tool_progress",
784
+ "auth_status",
785
+ "tool_use_summary",
786
+ "rate_limit_event",
787
+ "prompt_suggestion",
788
+ "conversation_reset",
789
+ ]);
790
+
621
791
  // Returns the uniform-carry `kind` string for `msg` if it is one of the arms
622
792
  // disposed `carried` in sdk-surface.json, else undefined (leaves router-plane
623
793
  // / dedicated-branch arms — including SDKPermissionDeniedMessage — untouched).
@@ -634,25 +804,168 @@ function anthropicFrameKind(msg: SDKMessage): string | undefined {
634
804
  // runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
635
805
  // carry it verbatim. A malformed list is ignored, never thrown on (Tenet 6);
636
806
  // `string[]` is itself a JsonValue, so no cast is needed downstream.
807
+ // A COPY, never the frame's own array: the value is emitted unparsed
808
+ // (result-meta, message.metadata), core's StreamAssembler does not copy, and
809
+ // push() hands a JSON frame through by reference, so returning `v` would let an
810
+ // emitted event share the host's live array (cto's aliasing audit).
637
811
  function readUserMessageUuids(v: unknown): string[] | undefined {
638
- return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? v : undefined;
812
+ return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? [...v] : undefined;
639
813
  }
640
814
 
815
+ // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
816
+ // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
817
+ // are CLI-wrapper facts the Messages API never consumes. See the split in
818
+ // drive()'s assistant branch.
819
+ const HOST_ONLY_WRAPPER_KEYS: ReadonlySet<string> = new Set([
820
+ "narration_block_indexes",
821
+ "diagnostics",
822
+ "api_error",
823
+ "api_error_params",
824
+ "api_error_code",
825
+ // rd-15 (founder: defer the field, fix the carries): three more @internal
826
+ // CLI assistant-wrapper strings, carried where the host can read them.
827
+ "error_details",
828
+ "advisor_model",
829
+ "attribution_agent",
830
+ ]);
831
+
641
832
  // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
642
833
  // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
643
834
  // 0.3.272 (a pass-through of the Messages API field that rides the assistant
644
835
  // 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.
836
+ // cast. Integer indexes into `message.content`; a non-integer or negative member
837
+ // means the producer changed shape, so the whole array is refused rather than
838
+ // half-carried. The upper bound is not checked here: an out-of-range index
839
+ // simply names no block where it is used (the draft.4 `phase` mapping).
840
+ // A copy for the same reason as readUserMessageUuids: the block-less wrapper
841
+ // path emits it in message.metadata unparsed.
648
842
  function readNarrationBlockIndexes(v: unknown): number[] | undefined {
649
843
  return Array.isArray(v) &&
650
844
  v.length > 0 &&
651
845
  v.every((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0)
652
- ? v
846
+ ? [...v]
653
847
  : undefined;
654
848
  }
655
849
 
850
+ // A provider- or harness-originated native subtree forwarded WHOLE: JSON-
851
+ // validated (a copy) and with every `fallback_credit_token` deleted at any
852
+ // depth (withoutCreditTokens). Every verbatim carrier of this facet goes
853
+ // through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
854
+ // carries, provider-raw blocks, and the CLI/API wrapper subtrees
855
+ // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats).
856
+ // Model- or tool-authored payloads (tool input, a deferred tool call, MCP
857
+ // structuredContent / _meta / resourceLinks, structured_output) are NOT
858
+ // stripped: a key there is user content, and the wire already carries the same
859
+ // data as the tool call or result.
860
+ function carryVerbatim(v: unknown): JsonValue {
861
+ return withoutCreditTokens(JsonValue.parse(v));
862
+ }
863
+
864
+ // rd-15 / SPEC §13.7 (queued): a provider credit or bearer token is never
865
+ // emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
866
+ // (top level and per fallback), so every key of that name is deleted at any
867
+ // depth; everything else is kept verbatim.
868
+ function withoutCreditTokens(v: JsonValue): JsonValue {
869
+ if (Array.isArray(v)) return v.map(withoutCreditTokens);
870
+ if (typeof v === "object" && v !== null) {
871
+ const out: { [k: string]: JsonValue } = {};
872
+ for (const [k, x] of Object.entries(v)) if (k !== "fallback_credit_token") out[k] = withoutCreditTokens(x);
873
+ return out;
874
+ }
875
+ return v;
876
+ }
877
+
878
+ // A tool_result's text, for a failed Task's nested turn.error message: the
879
+ // string content, or its text blocks joined; undefined when there is none.
880
+ function toolResultText(content: unknown): string | undefined {
881
+ if (typeof content === "string") return content !== "" ? content : undefined;
882
+ if (!Array.isArray(content)) return undefined;
883
+ const texts: string[] = [];
884
+ for (const b of content) if (isJsonObject(b) && b["type"] === "text" && typeof b["text"] === "string") texts.push(b["text"]);
885
+ const joined = texts.join("\n");
886
+ return joined !== "" ? joined : undefined;
887
+ }
888
+
889
+ // The namespace of the facet's own harness keys on a tool.done `_meta` (the
890
+ // subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta").
891
+ const HARNESS_META_PREFIX = "anthropic/";
892
+
893
+ // A tool.done's host-only `_meta`: the tool-authored MCP sibling `_meta` merged
894
+ // with the facet's own harness keys. The harness namespace is RESERVED: every
895
+ // sibling key under "anthropic/" is dropped before the harness keys are
896
+ // written, so a tool (a malicious MCP server) can never present a forged
897
+ // harness fact, such as an agent report or a remedy pointing a host at its URL,
898
+ // even for a call the facet writes no harness key for (sp-cto's read of the
899
+ // rd-15 carry; the CLI itself strips its own reserved `com.anthropic/` prefix
900
+ // from server `_meta`). Every other sibling key is kept verbatim. undefined
901
+ // when nothing remains.
902
+ function mergeHarnessMeta(sibling: AgMeta | undefined, harness: { [k: string]: JsonValue }): AgMeta | undefined {
903
+ const out: AgMeta = {};
904
+ if (sibling !== undefined) {
905
+ for (const [k, v] of Object.entries(sibling)) if (!k.startsWith(HARNESS_META_PREFIX)) out[k] = v;
906
+ }
907
+ for (const [k, v] of Object.entries(harness)) out[k] = v;
908
+ return Object.keys(out).length > 0 ? out : undefined;
909
+ }
910
+
911
+ // `wire_tool_inputs` (CLI 2.1.280, @internal, undeclared in sdk.d.ts; first seen
912
+ // on sp-probe's subagent captures): "tool_use.input exactly as the API produced
913
+ // it, keyed by tool_use id, for a message whose message.content carries the
914
+ // client-normalized input. Round-tripped so a replayed history echoes each
915
+ // earlier tool call back to the API as the API emitted it" (the CLI's own
916
+ // schema doc). REPLAY-LOAD-BEARING, so it rides the tool-call block's
917
+ // providerMetadata (SPEC §12) as `wireInput`, on tool.args.assembled (the one
918
+ // event both arms emit once the complete frame is known; the reducer merges its
919
+ // providerMetadata by key). It is carried only when it DIFFERS from the input the
920
+ // event already holds, key order aside: every capture so far has the two
921
+ // identical, which stays byte-identical. Credit tokens are stripped
922
+ // (carryVerbatim).
923
+ function wireToolInput(frame: unknown, toolUseId: string): JsonValue | undefined {
924
+ const map = isJsonObject(frame) ? frame["wire_tool_inputs"] : undefined;
925
+ if (!isJsonObject(map)) return undefined;
926
+ const entry = map[toolUseId];
927
+ return entry === undefined ? undefined : carryVerbatim(entry);
928
+ }
929
+
930
+ // The complete arm: the wire input for a tool_use block, when it differs from
931
+ // the block's own (client-normalized) content input.
932
+ function wireInputFor(frame: unknown, toolUseId: string, contentInput: unknown): JsonValue | undefined {
933
+ const wire = wireToolInput(frame, toolUseId);
934
+ return wire !== undefined && !jsonEqual(wire, contentInput) ? wire : undefined;
935
+ }
936
+
937
+ function wireInputFields(wireInput: JsonValue | undefined): { providerMetadata: AgProviderMeta } | undefined {
938
+ return wireInput !== undefined ? { providerMetadata: AgProviderMeta.parse({ wireInput }) } : undefined;
939
+ }
940
+
941
+ function isToolUseBlock(block: BetaContentBlock): block is Extract<BetaContentBlock, { type: "tool_use" | "server_tool_use" | "mcp_tool_use" }> {
942
+ return block.type === "tool_use" || block.type === "server_tool_use" || block.type === "mcp_tool_use";
943
+ }
944
+
945
+ // Structural JSON equality, object key order ignored (a normalizer that only
946
+ // reordered keys changed nothing a replay depends on).
947
+ function jsonEqual(x: unknown, y: unknown): boolean {
948
+ if (x === y) return true;
949
+ if (Array.isArray(x) || Array.isArray(y)) {
950
+ return Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((v, i) => jsonEqual(v, y[i]));
951
+ }
952
+ if (isJsonObject(x) && isJsonObject(y)) {
953
+ const kx = Object.keys(x);
954
+ const ky = Object.keys(y);
955
+ return kx.length === ky.length && kx.every((k) => Object.hasOwn(y, k) && jsonEqual(x[k], y[k]));
956
+ }
957
+ return false;
958
+ }
959
+
960
+ // A result's `terminal_reason` when it names why the turn ended other than a
961
+ // normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
962
+ // live API error's own value is "api_error", which is also the generic code, so
963
+ // that close is unchanged. Typed as the SDK's TerminalReason union, but a newer
964
+ // CLI may send an undeclared value, so only a non-empty string is taken.
965
+ function closeCauseTerminalReason(v: unknown): string | undefined {
966
+ return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
967
+ }
968
+
656
969
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
657
970
  // on both frames that carry it (the API-error assistant frame and the
658
971
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -828,7 +1141,7 @@ function apiErrorStatusRetriable(status: unknown): boolean {
828
1141
  // value verbatim; it also drives `turn.error.retriable` (see
829
1142
  // `startupFailureRetriable`). Read through the JSON boundary because it is
830
1143
  // declared on that one arm only.
831
- function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | undefined {
1144
+ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: string]: JsonValue } | undefined {
832
1145
  const byModel: { [k: string]: JsonValue } = {};
833
1146
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
834
1147
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -843,8 +1156,13 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
843
1156
  // Undeclared siblings are only reachable through the JSON boundary: widen to
844
1157
  // `unknown` (no cast) and let the isJsonObject guard narrow.
845
1158
  const raw: unknown = msg;
1159
+ // `origin` (SDKMessageOrigin, on the result arms): set on the result of a turn
1160
+ // the framework WOKE, not the user, e.g. {kind: "task-notification"} after a
1161
+ // background subagent reported (sp-probe's bg capture, 5ba11da). turn.start's
1162
+ // `trigger` is a frozen enum, so it rides here verbatim.
1163
+ const origin = isJsonObject(raw) && isJsonObject(raw["origin"]) ? carryVerbatim(raw["origin"]) : undefined;
846
1164
  const subagentStats =
847
- isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
1165
+ isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? carryVerbatim(raw["subagent_stats"]) : undefined;
848
1166
  const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
849
1167
  // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
850
1168
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
@@ -854,6 +1172,29 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
854
1172
  // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
855
1173
  const apiErrorCode = readApiErrorCode(msg);
856
1174
  const startupFailureReason = readStartupFailureReason(msg);
1175
+ // `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
1176
+ // input}`): the tool call a host's PreToolUse `defer` decision parked, which
1177
+ // the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
1178
+ // the host needs it to act on the parked call. Through 0.6.4 the facet never
1179
+ // read it (a silent drop). Carried WHOLE and verbatim (the `subagent_stats`
1180
+ // precedent); whether it should instead map onto `turn.done.outcome.paused`
1181
+ // (asks) is a question routed to sp-protocol / sp-rnd. Fixture-only: no
1182
+ // capture sets a defer hook.
1183
+ const deferredToolUse =
1184
+ isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
1185
+ // `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
1186
+ // API error that ended the turn. It already decides `retriable` on an
1187
+ // is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
1188
+ // the census allowlist's "carry candidate the first time an error seed
1189
+ // surfaces it" (sp-probe's api-error-auth seed: 401). Absent or null ⇒ no key.
1190
+ const apiErrorStatus =
1191
+ isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1192
+ // `stop_reason` on a result that closes as turn.error: turn.error has no
1193
+ // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1194
+ // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1195
+ // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1196
+ const stopReason =
1197
+ closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
857
1198
  const payload: { [k: string]: JsonValue } = {
858
1199
  ...(typeof msg.fast_mode_disabled_reason === "string"
859
1200
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -868,11 +1209,40 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
868
1209
  ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
869
1210
  ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
870
1211
  ...(subagentStats !== undefined ? { subagentStats } : {}),
1212
+ ...(origin !== undefined ? { origin } : {}),
1213
+ ...(deferredToolUse !== undefined ? { deferredToolUse } : {}),
1214
+ ...(apiErrorStatus !== undefined ? { apiErrorStatus } : {}),
1215
+ ...(stopReason !== undefined ? { stopReason } : {}),
871
1216
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
872
1217
  };
873
1218
  return Object.keys(payload).length > 0 ? payload : undefined;
874
1219
  }
875
1220
 
1221
+ // A result frame's turn usage, or undefined when the frame's usage trio is not
1222
+ // the shape `mapTurnUsage` dereferences. Both result arms are
1223
+ // discriminant-validated only, so every call goes through this guard (Tenet 6:
1224
+ // a malformed frame must not throw out of push()); absent ⇒ no usage key.
1225
+ // The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
1226
+ // object and its minimal real shape (numeric input/output token counts, so an
1227
+ // empty `usage: {}` stays "no usage" as before), the `modelUsage` object and
1228
+ // each of its entries (`mapModelUsage`), and `total_cost_usd`.
1229
+ // `server_tool_use` is NOT required: `serverToolRequestCount` reads it totally,
1230
+ // so a leaner producer that omits it keeps the rest of its usage.
1231
+ function guardedTurnUsage(msg: SDKResultMsg): AgUsage | undefined {
1232
+ const raw: unknown = msg;
1233
+ if (!isJsonObject(raw)) return undefined;
1234
+ const rawUsage = raw["usage"];
1235
+ const rawModelUsage = raw["modelUsage"];
1236
+ return isJsonObject(rawUsage) &&
1237
+ typeof rawUsage["input_tokens"] === "number" &&
1238
+ typeof rawUsage["output_tokens"] === "number" &&
1239
+ isJsonObject(rawModelUsage) &&
1240
+ Object.values(rawModelUsage).every(isJsonObject) &&
1241
+ typeof raw["total_cost_usd"] === "number"
1242
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
1243
+ : undefined;
1244
+ }
1245
+
876
1246
  // ─── the stateful normalizer ──────────────────────────────────────────────────
877
1247
 
878
1248
  /** Options for {@link createClaudeNormalizer}. */
@@ -893,15 +1263,41 @@ export interface ClaudeNormalizerOptions {
893
1263
  * construction.
894
1264
  */
895
1265
  threadId?: string;
1266
+ /**
1267
+ * The stem of this invoke's POSITIONAL fallback turn ids,
1268
+ * `turn_<invokeId>_frame_<n>`, minted only for a top-level or nested turn
1269
+ * whose frame carries no usable message id or uuid (the normal path names a
1270
+ * turn by its SDK message id or frame uuid, unique by construction). A host
1271
+ * folds every invoke of a conversation into ONE Reducer, so a stem that
1272
+ * restarted with each invoke repeated those ids across invokes (DC-10, from
1273
+ * sp-protocol's D3 bar). Absent, each normalizer draws a random
1274
+ * `claude_<16 hex>` stem at most once, lazily (only when a fallback id is
1275
+ * first needed, so the common path draws no randomness), and holds it
1276
+ * OUTSIDE the atomic-push rebuild, so a rebuild reproduces it. Pass a fixed
1277
+ * value only where one invoke's output must be byte-reproducible (capture,
1278
+ * replay, tests), as vercel-ai's `invokeId`.
1279
+ */
1280
+ invokeId?: string;
1281
+ }
1282
+
1283
+ /** 64 random bits as 16 hex chars: the default per-invoke fallback id stem
1284
+ * (vercel-ai's mintInvokeNonce). */
1285
+ function mintInvokeNonce(): string {
1286
+ const bytes = new Uint8Array(8);
1287
+ globalThis.crypto.getRandomValues(bytes);
1288
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
896
1289
  }
897
1290
 
898
1291
  /**
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.
1292
+ * The inner Claude-facet normalizer over a fresh {@link StreamAssembler}: each
1293
+ * `push(native)` validates `native` → `SDKMessage`, drives the engine via
1294
+ * primitive calls, and drains the buffered `AgEvent[]`; `flush()` closes any
1295
+ * dangling open message and drains. `createClaudeNormalizer` wraps it in core's
1296
+ * withAtomicPush. It must stay deterministic (no clock, no randomness): a
1297
+ * rebuild re-drives it from the journal. Its one invoke-unique input, the
1298
+ * fallback id stem, comes from the caller, which mints and holds it.
903
1299
  */
904
- export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): Normalizer {
1300
+ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeStem: () => string): Normalizer {
905
1301
  const a = new StreamAssembler();
906
1302
 
907
1303
  // Task 8c leg 4 (guuey capstone finding A): the wire-visible `parentTurnId`
@@ -914,6 +1310,187 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
914
1310
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
915
1311
  const subagentTurnByParentToolUseId = new Map<string, string>();
916
1312
 
1313
+ // INV-TURN (SPEC:743; sp-protocol ruling B, 2026-09-23): ONE turnId names
1314
+ // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1315
+ // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1316
+ // or a stream `message_start`) in the ordinary case, or the frame's own
1317
+ // `uuid` when a notice or a result opens it (a result-only turn). The id is
1318
+ // - unique per turn, across the invokes of a resumed session too (a resume
1319
+ // keeps `session_id` unless `forkSession` is set, so the old
1320
+ // `turn_${session_id}` collided across invokes; message ids never repeat);
1321
+ // - deterministic from the wire, so the same native replays to the same ids;
1322
+ // - known at turn.start, since the opening frame carries it;
1323
+ // - `turn_`-prefixed.
1324
+ // Open from the first frame that needs a turn; the turn's result frame
1325
+ // (either arm) closes it and clears it, so the next frame opens a new one.
1326
+ //
1327
+ // Two guards keep an id naming ONE turn even on odd wire:
1328
+ // - a CLOSED id is never reopened: a late frame reusing a closed turn's
1329
+ // message id opens its turn under its own frame uuid instead;
1330
+ // - `isSDKMessage` validates only discriminants, so a missing or non-string
1331
+ // id/uuid falls back to a positional `turn_<stem>_frame_<n>` rather than a
1332
+ // shared `turn_undefined`. The stem is per invoke (DC-10: a bare
1333
+ // `turn_frame_<n>` repeated across the invokes one Reducer folds), and the
1334
+ // counter is deterministic from the wire, so an atomic-push rebuild
1335
+ // reproduces every delivered id.
1336
+ // Nested (subagent) frames never open or name a top-level turn.
1337
+ let openTopTurnId: string | undefined;
1338
+ const closedTopTurnIds = new Set<string>();
1339
+ let framesSeen = 0;
1340
+ function mintId(candidate: unknown): string | undefined {
1341
+ return typeof candidate === "string" && candidate.length > 0 ? `turn_${candidate}` : undefined;
1342
+ }
1343
+ function topTurnId(openingId: unknown, frameUuid: unknown): string {
1344
+ if (openTopTurnId === undefined) {
1345
+ const byId = mintId(openingId);
1346
+ const byUuid = mintId(frameUuid);
1347
+ openTopTurnId =
1348
+ byId !== undefined && !closedTopTurnIds.has(byId)
1349
+ ? byId
1350
+ : byUuid !== undefined && !closedTopTurnIds.has(byUuid)
1351
+ ? byUuid
1352
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1353
+ }
1354
+ return openTopTurnId;
1355
+ }
1356
+ // The result frame closes the open turn (or, for a result-only turn, the one
1357
+ // it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
1358
+ // notice or stream opened it: the CL-09 result-only API-error path, a
1359
+ // startup-failure result, a local-command result) is OPENED here with an
1360
+ // explicit turn.start before anything else the result emits (INV-TURN,
1361
+ // SPEC:743: every turn is opened by exactly one turn.start and closed by
1362
+ // exactly one terminal; sp-protocol, 2026-09-23). Through the B commit such a
1363
+ // turn was only closed, and reduce() minted a stub record whose threadId was
1364
+ // the turnId. An open turn already has its turn.start (openMessage).
1365
+ function closingTopTurnId(resultUuid: unknown, sessionId: string): string {
1366
+ let turnId = openTopTurnId;
1367
+ if (turnId === undefined) {
1368
+ turnId = topTurnId(resultUuid, undefined);
1369
+ a.openTurn(turnId, options.threadId ?? sessionId);
1370
+ }
1371
+ openTopTurnId = undefined;
1372
+ closedTopTurnIds.add(turnId);
1373
+ return turnId;
1374
+ }
1375
+ // A NESTED (subagent) turn is one per subagent run, keyed by the spawning
1376
+ // `parent_tool_use_id`: `turn_` + that run's first nested message id. Through
1377
+ // 0.6.4 it was `turn_${session_id}` too, which merged every subagent run of a
1378
+ // session into one nested turn (and, if a subagent's frames carry the
1379
+ // parent's session_id, collided with the top-level turn itself). It must
1380
+ // never equal the synthetic `parentTurnId` label `turn_${parent_tool_use_id}`
1381
+ // (guuey capstone finding A), and a message id never does.
1382
+ function nestedTurnId(parentToolUseId: string, firstMessageId: unknown, frameUuid: unknown): string {
1383
+ const known = subagentTurnByParentToolUseId.get(parentToolUseId);
1384
+ if (known !== undefined && !closedRuns.has(parentToolUseId)) return known;
1385
+ // A new run, or a frame arriving for a run that already CLOSED: mint a fresh
1386
+ // id (a closed nested id is never reopened, as for top-level turns).
1387
+ const byId = mintId(firstMessageId);
1388
+ const byUuid = mintId(frameUuid);
1389
+ const minted =
1390
+ byId !== undefined && !closedNestedTurnIds.has(byId)
1391
+ ? byId
1392
+ : byUuid !== undefined && !closedNestedTurnIds.has(byUuid)
1393
+ ? byUuid
1394
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1395
+ closedRuns.delete(parentToolUseId);
1396
+ subagentTurnByParentToolUseId.set(parentToolUseId, minted);
1397
+ return minted;
1398
+ }
1399
+
1400
+ // ONE subagent bracket per RUN (sp-protocol ruling, 2026-09-23; INV-TURN,
1401
+ // SPEC:743; SPEC:807 "subagent.done: Close the nested turn"). Through 0.7.0's
1402
+ // B commit the bracket was per MESSAGE: a run of N nested messages emitted N
1403
+ // subagent.start/subagent.done pairs on its one id, closing it N times with
1404
+ // content after the first close. The run now opens once, at its first nested
1405
+ // frame, and closes exactly once, at whichever comes first: the spawning
1406
+ // Task's tool_result (any user frame, so a subagent's own sub-run closes
1407
+ // too), the turn's result frame, or flush. Parallel Task calls give
1408
+ // OVERLAPPING runs, and the assembler's last-turn backfill is a LIFO stack
1409
+ // that out-of-order closes skew. So the facet's turn-scoped events name their
1410
+ // owner: messages and their blocks by turnId / messageId, top-level tool.done
1411
+ // by the open turn, a retraction's message.remove by the removed message's
1412
+ // own turn. What still backfills: tool.args.* and ext.* (no turnId at all).
1413
+ // A top-level tool_result with NO turn open no longer lands on a closed turn:
1414
+ // since B-resume (37185be) it opens its own turn, named by its frame uuid (see
1415
+ // the user branch), and a nested one for a run this invoke never opened opens
1416
+ // a fresh run the same way.
1417
+ //
1418
+ // B-STRICT NESTED TERMINALS (draft.4, the founder's nested-turn ruling Q1,
1419
+ // 2026-09-24; sp-protocol's package, sp-claude's leg). A nested turn opens
1420
+ // with exactly one subagent.start and closes with exactly one turn.done |
1421
+ // turn.error | turn.abort carrying its turnId, IMMEDIATELY followed by its
1422
+ // subagent.done (a no-fold bracket close that restores the owner). The five
1423
+ // guards: the terminal carries the nested turnId; a nested turn.done uses
1424
+ // finishReason "unknown" (the SDK reports none); no nested success before the
1425
+ // framework reports the sub-run complete (the run may outlive its parent's
1426
+ // terminal); no usage on a nested terminal (the top-level turn is the
1427
+ // accounting boundary: Claude's parent cost already includes subagent spend);
1428
+ // a nested turnId never equals a top-level one (message ids / fallback ids).
1429
+ // The close, by what the framework reported (`NestedClose`):
1430
+ // - the spawning Task's tool_result: `is_error` → turn.error; AgentOutput
1431
+ // status "async_launched" / "remote_launched" (a BACKGROUND launch ack) →
1432
+ // the run stays OPEN; otherwise (status "completed", or no attributable
1433
+ // tool_use_result) the returned call is the completion report → turn.done
1434
+ // success;
1435
+ // - a correlated task_notification (a background run): completed → success,
1436
+ // failed → turn.error, stopped → turn.abort;
1437
+ // - a stashed nested API error (the assistant error frame; its live
1438
+ // non-terminal `error` stays) wins over any of these → turn.error;
1439
+ // - flush: a run still open closes as turn.abort{stream-truncated}, or as its
1440
+ // stashed API error.
1441
+ // The parent's result frame no longer closes runs: a still-open run is a
1442
+ // background (or unreported) sub-run, and closing it there would report an
1443
+ // outcome the framework never gave.
1444
+ type OpenRun = { readonly turnId: string; readonly parentTurnId: string };
1445
+ type NestedClose =
1446
+ | { readonly kind: "success" }
1447
+ | { readonly kind: "error"; readonly message: string; readonly code?: string }
1448
+ | { readonly kind: "aborted"; readonly reason: string };
1449
+ const openRuns = new Map<string, OpenRun>();
1450
+ const closedRuns = new Set<string>();
1451
+ const closedNestedTurnIds = new Set<string>();
1452
+ // Nested turnId → its FIRST API error frame's close (released at run close).
1453
+ const nestedStashedErrors = new Map<string, StashedTurnError>();
1454
+ // task_started: task_id → the spawning tool_use_id, for a task_notification
1455
+ // that carries only its task_id.
1456
+ const toolUseIdByTaskId = new Map<string, string>();
1457
+ // The ids of every Agent (or legacy Task) tool call seen in this invoke. Only
1458
+ // a result for one of these can carry an AgentOutput: a third-party tool whose
1459
+ // result happens to hold an `agentId` (a CRM, a ticketing system, any agent
1460
+ // registry) is not Anthropic's Agent run report (sp-cto's read of f2c75d8).
1461
+ const agentCallIds = new Set<string>();
1462
+ function openRun(parentToolUseId: string, turnId: string, parentTurnId: string): void {
1463
+ if (openRuns.has(parentToolUseId)) return;
1464
+ openRuns.set(parentToolUseId, { turnId, parentTurnId });
1465
+ a.subagentStart(turnId, parentTurnId);
1466
+ }
1467
+ function closeRun(parentToolUseId: string, close: NestedClose): void {
1468
+ const run = openRuns.get(parentToolUseId);
1469
+ if (run === undefined) return;
1470
+ openRuns.delete(parentToolUseId);
1471
+ closedRuns.add(parentToolUseId);
1472
+ closedNestedTurnIds.add(run.turnId);
1473
+ const stashed = nestedStashedErrors.get(run.turnId);
1474
+ nestedStashedErrors.delete(run.turnId);
1475
+ if (stashed !== undefined) {
1476
+ a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1477
+ } else if (close.kind === "success") {
1478
+ a.closeTurnDone(run.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
1479
+ } else if (close.kind === "error") {
1480
+ a.closeTurnError(run.turnId, { message: close.message, ...(close.code !== undefined ? { code: close.code } : {}) });
1481
+ } else {
1482
+ a.emit({ type: "turn.abort", turnId: run.turnId, reason: close.reason });
1483
+ }
1484
+ a.subagentDone(run.turnId, run.parentTurnId);
1485
+ }
1486
+ // Flush only: every run still open, innermost (latest-opened) first, as
1487
+ // INV-FLUSH orders its own closes.
1488
+ function abortOpenRuns(): void {
1489
+ for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1490
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1491
+ }
1492
+ }
1493
+
917
1494
  // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
918
1495
  // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
919
1496
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
@@ -941,6 +1518,17 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
941
1518
  agentId?: string;
942
1519
  };
943
1520
  const deniedLiveByToolUseId = new Map<string, LiveDenial>();
1521
+ // Every toolCallId that already got its FINAL tool.done in this invoke. The
1522
+ // result's permission_denials aggregate skips these: re-emitting tool.start +
1523
+ // tool.done{denied} for a call already closed is a duplicate start and a second
1524
+ // final tool.done (INV-BLOCK; rd-14 P14 parks it; the M22 double-fold hazard).
1525
+ const closedToolCallIds = new Set<string>();
1526
+ // SDK message id → the `diagnostics` value already carried for it (see the
1527
+ // assistant branch): one carry per response, not one per frame.
1528
+ const diagnosticsCarried = new Map<string, string>();
1529
+ // rd-15: top-level turnId → the closing response's non-null stop_details (credit
1530
+ // tokens stripped) and the message it describes, emitted on that turn's turn.done.
1531
+ const stopDetailsByTurn = new Map<string, { readonly messageId: string; readonly value: JsonValue }>();
944
1532
 
945
1533
  // The live denial's diagnostic fields, camelCased — the providerMetadata bag
946
1534
  // on the enriched `<turnId>:denials` tool.done. undefined when the live
@@ -984,8 +1572,8 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
984
1572
  // engine-synthesized turn.abort.
985
1573
  // The FIRST error frame's fields win: a later error frame on the same turn
986
1574
  // 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.
1575
+ // arm it is. Since the per-turn ids (INV-TURN, 2026-09-23) an entry can only
1576
+ // be its own turn's, so a stale one can no longer leak into the next turn.
989
1577
  type StashedTurnError = { readonly message: string; readonly code: string; readonly retriable: boolean };
990
1578
  const stashedTurnErrors = new Map<string, StashedTurnError>();
991
1579
 
@@ -1024,7 +1612,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1024
1612
  /** The id actually emitted (`sdkId`, or a derived carrier — see below). */
1025
1613
  readonly emittedId: string;
1026
1614
  readonly turnId: string;
1027
- /** Set iff this message opened a nested (subagent) turn, whose `subagent.done` is deferred with it. */
1615
+ /** Set iff this is a NESTED (subagent) message: the run's synthetic parent label (continuation test). */
1028
1616
  readonly parentTurnId: string | undefined;
1029
1617
  /** Content-block index to resume at, so a second frame's block never collides with the first's. */
1030
1618
  blockIndex: number;
@@ -1044,6 +1632,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1044
1632
  readonly streamBlocks: Map<number, StreamBlockState>;
1045
1633
  /** workspace#7 — `ttft_ms` carried at most once per message (message.metadata). */
1046
1634
  ttftCarried: boolean;
1635
+ /**
1636
+ * draft.4 `phase`: how many of this lifecycle's blocks earlier COMPLETE
1637
+ * frames already covered. A frame's blocks are the next ones after these,
1638
+ * so its frame-local index `i` names stream block `framedThrough + i`.
1639
+ */
1640
+ framedThrough: number;
1047
1641
  /**
1048
1642
  * The TURN-BINDING FAMILY, carried at most once per message, whichever
1049
1643
  * channel delivers it first: the stream arm's message.metadata carry
@@ -1070,8 +1664,18 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1070
1664
  // is clean punctuation.
1071
1665
  type StreamBlockState =
1072
1666
  | { kind: "text"; id: string; citations: AgCitation[] }
1073
- | { kind: "reasoning"; id: string; signature: string; redacted: string | undefined }
1074
- | { kind: "tool"; toolCallId: string; json: string; startInput: JsonValue }
1667
+ | {
1668
+ kind: "reasoning";
1669
+ id: string;
1670
+ signature: string;
1671
+ redacted: string | undefined;
1672
+ // draft.4 `phase` (§8.0 item 27): whether any non-empty thinking text
1673
+ // streamed, and whether the complete frame listed this block in
1674
+ // `narration_block_indexes` while it was still open (CB-13).
1675
+ hasText: boolean;
1676
+ narration: boolean;
1677
+ }
1678
+ | { kind: "tool"; toolCallId: string; json: string; startInput: JsonValue; wireInput?: JsonValue }
1075
1679
  | { kind: "compaction"; content: string | null; encrypted: string | null }
1076
1680
  | { kind: "emitted" };
1077
1681
  let pending: PendingMessage | undefined;
@@ -1083,8 +1687,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1083
1687
  // blocks, their order and their content are the SDK's own.
1084
1688
  const lifecyclesBySdkId = new Map<string, number>();
1085
1689
 
1086
- /** Seal the deferred message (and its subagent bracket), if one is open. */
1087
- function closePendingMessage(): void {
1690
+ /** Seal the deferred message, if one is open (a run's bracket closes separately; see `openRun`).
1691
+ * `atFlush`: the stream ENDED here, so open stream blocks close without minting content
1692
+ * (INV-FLUSH (3), draft.4; see `finalizeStreamBlock`). */
1693
+ function closePendingMessage(atFlush = false): void {
1088
1694
  if (pending === undefined) return;
1089
1695
  const p = pending;
1090
1696
  pending = undefined;
@@ -1094,11 +1700,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1094
1700
  // produced) so no lifecycle dangles under the seal.
1095
1701
  if (p.streamBlocks.size > 0) {
1096
1702
  for (const idx of [...p.streamBlocks.keys()].sort((x, y) => x - y)) {
1097
- finalizeStreamBlock(p, idx);
1703
+ finalizeStreamBlock(p, idx, atFlush);
1098
1704
  }
1099
1705
  }
1100
1706
  a.closeMessage(p.emittedId, p.usage);
1101
- if (p.parentTurnId !== undefined) a.subagentDone(p.turnId, p.parentTurnId);
1707
+ // The subagent bracket is per RUN now (see `openRun`), so sealing a nested
1708
+ // message no longer closes its nested turn.
1102
1709
  }
1103
1710
 
1104
1711
  // ─── workspace#7: stream_event mapping helpers ──────────────────────────────
@@ -1108,7 +1715,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1108
1715
  // ride the uniform lossless carry (`kind` is the frame's own discriminant,
1109
1716
  // per the ext.anthropic.frame convention). Nothing is silently dropped.
1110
1717
  function carryStreamFrame(msg: SDKPartial): void {
1111
- a.emitExt("anthropic", "frame", { kind: "stream_event", frame: JsonValue.parse(msg) });
1718
+ a.emitExt("anthropic", "frame", { kind: "stream_event", frame: carryVerbatim(msg) });
1112
1719
  }
1113
1720
 
1114
1721
  // `ttft_ms` (time to first token, on the partial envelope) has no core home —
@@ -1163,17 +1770,36 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1163
1770
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
1164
1771
  // (same end-then-opaque order as the complete arm), the MANDATORY
1165
1772
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
1166
- function finalizeStreamBlock(p: PendingMessage, index: number): void {
1773
+ // `atFlush` (INV-FLUSH (3), draft.4; the founder's fold/flush ruling, "snapshot
1774
+ // fold + honest flush; opaque at flush forbidden"; sp-claude's leg C1): the
1775
+ // stream ENDED with this block open, so the close lands NO new content. The
1776
+ // lifecycle closes stay (text.end with its already-received citations,
1777
+ // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
1778
+ // (it is authoritative, and a truncated partial_json would mint an input the
1779
+ // model never finished), no reasoning.opaque (a signature is replay-load-
1780
+ // bearing, and the turn is aborted anyway), no compaction content.block, and
1781
+ // no `phase` on reasoning.end. A binding frame that seals the message
1782
+ // mid-stream (not a flush) still finalizes as its content_block_stop would.
1783
+ function finalizeStreamBlock(p: PendingMessage, index: number, atFlush = false): void {
1167
1784
  const b = p.streamBlocks.get(index);
1168
1785
  if (b === undefined) return;
1169
1786
  p.streamBlocks.delete(index);
1170
1787
  const messageId = p.emittedId;
1788
+ if (atFlush) {
1789
+ if (b.kind === "text") a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1790
+ else if (b.kind === "reasoning") a.reasoningEnd(b.id, messageId, undefined);
1791
+ return;
1792
+ }
1171
1793
  switch (b.kind) {
1172
1794
  case "text":
1173
1795
  a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1174
1796
  return;
1175
1797
  case "reasoning":
1176
- a.reasoningEnd(b.id, messageId);
1798
+ // draft.4 `phase` for a STREAMED narration block: known only once the
1799
+ // complete frame arrived (after the start), so it rides reasoning.end
1800
+ // (§5 phase timing), and only if the block's text is non-empty
1801
+ // (§8.0 item 27). Never a post-seal event.
1802
+ a.reasoningEnd(b.id, messageId, b.narration && b.hasText ? { phase: "interim" } : undefined);
1177
1803
  if (b.redacted !== undefined) {
1178
1804
  a.reasoningOpaque(b.id, messageId, { kind: "redacted", value: b.redacted, provider: "anthropic" });
1179
1805
  } else if (b.signature.length > 0) {
@@ -1192,7 +1818,13 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1192
1818
  input = b.startInput;
1193
1819
  }
1194
1820
  }
1195
- a.toolArgsAssembled(b.toolCallId, input);
1821
+ // The stream's input IS the API's own (partial_json), so the wire input
1822
+ // is carried only if it still differs from it (see wireInputFor).
1823
+ a.toolArgsAssembled(
1824
+ b.toolCallId,
1825
+ input,
1826
+ wireInputFields(b.wireInput !== undefined && !jsonEqual(b.wireInput, input) ? b.wireInput : undefined),
1827
+ );
1196
1828
  return;
1197
1829
  }
1198
1830
  case "compaction":
@@ -1222,7 +1854,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1222
1854
 
1223
1855
  if (ev.type === "message_start") {
1224
1856
  const m = ev.message;
1225
- const turnId = turnIdFor(msg.session_id, m.id);
1857
+ const turnId =
1858
+ msg.parent_tool_use_id !== null
1859
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1860
+ : topTurnId(m.id, msg.uuid);
1226
1861
  const parentTurnId =
1227
1862
  msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1228
1863
  // Same continuation test as the complete arm: a message_start naming the
@@ -1245,8 +1880,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1245
1880
  // lifecycle counter, same emittedId derivation — so the complete frame
1246
1881
  // that follows JOINS this lifecycle and is content-suppressed.
1247
1882
  if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
1248
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
1249
- a.subagentStart(turnId, parentTurnId);
1883
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1250
1884
  }
1251
1885
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
1252
1886
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -1260,6 +1894,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1260
1894
  streamed: true,
1261
1895
  streamBlocks: new Map(),
1262
1896
  ttftCarried: false,
1897
+ framedThrough: 0,
1263
1898
  turnBindingCarried: false,
1264
1899
  };
1265
1900
  pending = open;
@@ -1323,14 +1958,21 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1323
1958
  case "thinking": {
1324
1959
  const id = `${messageId}:reasoning:${index}`;
1325
1960
  a.reasoningStart(id, messageId);
1326
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: block.signature, redacted: undefined });
1961
+ p.streamBlocks.set(index, {
1962
+ kind: "reasoning",
1963
+ id,
1964
+ signature: block.signature,
1965
+ redacted: undefined,
1966
+ hasText: false,
1967
+ narration: false,
1968
+ });
1327
1969
  return;
1328
1970
  }
1329
1971
  case "redacted_thinking": {
1330
1972
  // Arrives complete (never delta'd); end + the redacted opaque land at stop.
1331
1973
  const id = `${messageId}:reasoning:${index}`;
1332
1974
  a.reasoningStart(id, messageId);
1333
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data });
1975
+ p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data, hasText: false, narration: false });
1334
1976
  return;
1335
1977
  }
1336
1978
  case "tool_use":
@@ -1375,6 +2017,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1375
2017
  // Arrives complete inside the start frame — same tool.done mapping as
1376
2018
  // the complete arm's mcp_tool_result case.
1377
2019
  const outcome: ToolOutcome = block.is_error ? "error" : "ok";
2020
+ closedToolCallIds.add(block.tool_use_id);
1378
2021
  a.toolDone({
1379
2022
  toolCallId: block.tool_use_id,
1380
2023
  content: mcpToolResultContentToAgBlocks(block.content),
@@ -1391,7 +2034,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1391
2034
  a.contentBlock(messageId, {
1392
2035
  type: "provider-raw",
1393
2036
  vendor: "anthropic",
1394
- raw: JsonValue.parse(block),
2037
+ raw: carryVerbatim(block),
1395
2038
  });
1396
2039
  p.streamBlocks.set(index, { kind: "emitted" });
1397
2040
  return;
@@ -1412,18 +2055,33 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1412
2055
  return;
1413
2056
  }
1414
2057
  if (d.type === "thinking_delta" && b.kind === "reasoning") {
2058
+ if (typeof d.thinking === "string" && d.thinking.length > 0) b.hasText = true;
1415
2059
  // Claude Code stamps a RUNTIME-ONLY `estimated_tokens` (number | null;
1416
2060
  // undeclared on BetaThinkingDelta) on each thinking_delta. Under
1417
2061
  // 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.
2062
+ // that estimate is the delta's entire payload — carried verbatim (wire
2063
+ // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
2064
+ // no bag, byte-identical.
2065
+ //
2066
+ // X5 (sp-rnd, 2026-09-23): it rides the delta's host-only `_meta`, not
2067
+ // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
2068
+ // that must round-trip to the provider), and the Messages API never
2069
+ // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
2070
+ // on start events, so the estimate is now LIVE-ONLY (it used to fold
2071
+ // last-value-wins onto the reasoning block) — the same standing as its
2072
+ // `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
2073
+ // consumer read the folded value (guuey/ggui checked via sp-team-main).
2074
+ // `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
2075
+ // primitive (the reasoning.start precedent in `emitAssistantBlock`), and
2076
+ // the sugar's only extra step, de-cumulation, is a pass-through for a
2077
+ // non-cumulative delta like this one.
1421
2078
  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);
2079
+ if (isJsonObject(rawDelta) && "estimated_tokens" in rawDelta) {
2080
+ const estimate = AgMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] });
2081
+ a.emit({ type: "reasoning.delta", id: b.id, messageId, delta: d.thinking, _meta: estimate });
2082
+ } else {
2083
+ a.reasoningDelta(b.id, messageId, d.thinking);
2084
+ }
1427
2085
  return;
1428
2086
  }
1429
2087
  if (d.type === "input_json_delta" && b.kind === "tool") {
@@ -1492,7 +2150,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1492
2150
  carryStreamFrame(msg);
1493
2151
  }
1494
2152
 
1495
- function registerUuid(uuid: string | undefined, ids: readonly string[]): void {
2153
+ // The turn each retractable message was emitted under, so a retraction's
2154
+ // `message.remove` names its OWNER explicitly (INV-OWNER) instead of taking
2155
+ // the assembler's last-turn backfill, which overlapping subagent runs can skew.
2156
+ const turnByMessageId = new Map<string, string>();
2157
+ function registerUuid(uuid: string | undefined, ids: readonly string[], turnId?: string): void {
2158
+ if (turnId !== undefined) for (const id of ids) turnByMessageId.set(id, turnId);
1496
2159
  if (uuid === undefined || ids.length === 0) return;
1497
2160
  const existing = messageIdsByUuid.get(uuid);
1498
2161
  if (existing !== undefined) existing.push(...ids);
@@ -1513,15 +2176,70 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1513
2176
  const ids = messageIdsByUuid.get(uuid);
1514
2177
  if (ids === undefined) continue;
1515
2178
  for (const id of ids) {
1516
- a.emit({ type: "message.remove", id });
2179
+ const owner = turnByMessageId.get(id);
2180
+ a.emit({ type: "message.remove", id, ...(owner !== undefined ? { turnId: owner } : {}) });
2181
+ }
2182
+ }
2183
+ }
2184
+
2185
+ // Emit a result's permission_denials as tool.start + tool.done denied pairs,
2186
+ // inside a dedicated carrier message: the assistant message is already
2187
+ // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
2188
+ // closed turns. BOTH result arms call it, at the same point (after the seal
2189
+ // and the run closes, before result-meta and the close). Through 0.6.4 only
2190
+ // the success arm did, so an error-subtype result (SDKResultError declares
2191
+ // permission_denials too, e.g. error_max_turns after a denied tool) dropped
2192
+ // its denials.
2193
+ function emitDenialsCarrier(
2194
+ turnId: string,
2195
+ denials: ReadonlyArray<{ readonly tool_name: string; readonly tool_use_id: string }>,
2196
+ sessionId: string,
2197
+ ): void {
2198
+ // Skip every denial whose call already has its final tool.done in this
2199
+ // invoke: a harness-stamped denied tool_result (the user branch), an
2200
+ // mcp_tool_result, or an earlier carrier (a repeated id, in this list or a
2201
+ // later result's). A denial for an id not yet closed still gets its pair.
2202
+ const fresh: Array<{ readonly tool_name: string; readonly tool_use_id: string }> = [];
2203
+ for (const d of denials) {
2204
+ if (closedToolCallIds.has(d.tool_use_id)) continue;
2205
+ closedToolCallIds.add(d.tool_use_id);
2206
+ fresh.push(d);
2207
+ }
2208
+ if (fresh.length > 0) {
2209
+ const denialMsgId = `${turnId}:denials`;
2210
+ a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? sessionId });
2211
+ for (const denial of fresh) {
2212
+ // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
2213
+ // "handled" via existing-home mapping): enrich with the live
2214
+ // standalone denial notice recorded above (keyed by tool_use_id),
2215
+ // when one preceded this aggregate — the actual rejection text
2216
+ // returned to the model, plus decision-reason/agent-id context —
2217
+ // rather than leaving a bare empty-content stub. No second
2218
+ // tool.start/tool.done pair is ever emitted for the live frame
2219
+ // itself (see the dedicated `permission_denied` branch below).
2220
+ const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2221
+ const liveFields = liveDenialMeta(live);
2222
+ const liveMeta: AgProviderMeta | undefined =
2223
+ liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
2224
+ a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
2225
+ a.toolDone({
2226
+ toolCallId: denial.tool_use_id,
2227
+ content: live !== undefined ? [{ type: "text", text: live.message }] : [],
2228
+ outcome: "denied",
2229
+ ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
2230
+ });
1517
2231
  }
2232
+ a.closeMessage(denialMsgId);
1518
2233
  }
1519
2234
  }
1520
2235
 
1521
2236
  function drive(msg: SDKMessage): void {
1522
2237
  if (msg.type === "assistant") {
1523
2238
  const m = msg.message;
1524
- const turnId = turnIdFor(msg.session_id, m.id);
2239
+ const turnId =
2240
+ msg.parent_tool_use_id !== null
2241
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
2242
+ : topTurnId(m.id, msg.uuid);
1525
2243
  const parentTurnId =
1526
2244
  msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1527
2245
 
@@ -1583,7 +2301,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1583
2301
  // Structured plain-JSON shape per its own doc (evolves additively);
1584
2302
  // JsonValue.parse both validates that invariant and satisfies the
1585
2303
  // wrapper-meta channel's type without an unchecked cast.
1586
- wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
2304
+ wrapperMetaRaw["context_usage"] = carryVerbatim(msg.context_usage);
1587
2305
  }
1588
2306
  // `usage_report` (0.3.273): the structured twin of the /usage report,
1589
2307
  // riding the synthetic assistant message that delivers its text (session
@@ -1597,7 +2315,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1597
2315
  // claude.ai-subscriber sessions", and the capture harness authenticates
1598
2316
  // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1599
2317
  if (msg.usage_report !== undefined) {
1600
- wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
2318
+ wrapperMetaRaw["usage_report"] = carryVerbatim(msg.usage_report);
1601
2319
  }
1602
2320
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1603
2321
  // the indexes of THIS frame's content blocks that are user-facing narration
@@ -1617,6 +2335,29 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1617
2335
  if (narrationBlockIndexes !== undefined) {
1618
2336
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1619
2337
  }
2338
+ // `message.diagnostics` (a Messages API response field, first seen live on
2339
+ // sp-probe's defer-tool-sonnet5-resume-unavailable, 7c6880f): per-response
2340
+ // diagnostics, there `{cache_miss_reason: {type: "tools_changed",
2341
+ // cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
2342
+ // Response-only (never sent back on replay), so it rides host-only `_meta`
2343
+ // (SPEC §12, the X5 split), verbatim with its wire name. Undeclared on
2344
+ // @anthropic-ai/sdk 0.93.0's BetaMessage, so read through the JSON
2345
+ // boundary; null (its usual value) carries nothing. It is per RESPONSE,
2346
+ // and the CLI repeats the same message object on every frame of a
2347
+ // multi-frame message, so it is carried once per SDK message id (again
2348
+ // only if the value changes).
2349
+ const rawMessage: unknown = m;
2350
+ const diagnostics =
2351
+ isJsonObject(rawMessage) && isJsonObject(rawMessage["diagnostics"])
2352
+ ? carryVerbatim(rawMessage["diagnostics"])
2353
+ : undefined;
2354
+ if (diagnostics !== undefined) {
2355
+ const diagnosticsKey = JSON.stringify(diagnostics);
2356
+ if (diagnosticsCarried.get(m.id) !== diagnosticsKey) {
2357
+ wrapperMetaRaw["diagnostics"] = diagnostics;
2358
+ diagnosticsCarried.set(m.id, diagnosticsKey);
2359
+ }
2360
+ }
1620
2361
  // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1621
2362
  // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1622
2363
  // The CLI stamps them on the synthetic API-error assistant frame, the one
@@ -1641,31 +2382,49 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1641
2382
  const apiError = rawAssistant["api_error"];
1642
2383
  if (typeof apiError === "string") wrapperMetaRaw["api_error"] = apiError;
1643
2384
  const apiErrorParams = rawAssistant["api_error_params"];
1644
- if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
2385
+ if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = carryVerbatim(apiErrorParams);
1645
2386
  }
1646
2387
  const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1647
2388
  if (assistantApiErrorCode !== undefined) {
1648
2389
  wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1649
2390
  }
2391
+ // rd-15 (founder ruling 2026-09-24: defer the neutral remedy field, fix the
2392
+ // vendor carries; a 0.7.0 carry with zero golden moves). Three more
2393
+ // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
2394
+ // 0.3.280 (so read through the JSON boundary), carried verbatim under their
2395
+ // wire names on the frame's first block's host-only `_meta` (the X5 route,
2396
+ // which folds onto block._meta; never providerMetadata, SPEC §12):
2397
+ // - `error_details`: "Raw API error message: preserves details (e.g.
2398
+ // prompt-too-long token counts) that user-facing content discards"
2399
+ // (the CLI's own schema doc; the same datum is typed on the StopFailure
2400
+ // hook input, sdk.d.ts:9154);
2401
+ // - `advisor_model`: "Advisor model that produced this message, when
2402
+ // applicable";
2403
+ // - `attribution_agent`: "agent name parsed from querySource".
2404
+ // A non-string value is not carried. No committed native carries any of
2405
+ // them, so no golden moves.
2406
+ if (isJsonObject(rawAssistant)) {
2407
+ for (const key of ["error_details", "advisor_model", "attribution_agent"]) {
2408
+ const v = rawAssistant[key];
2409
+ if (typeof v === "string") wrapperMetaRaw[key] = v;
2410
+ }
2411
+ }
1650
2412
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1651
2413
  // the bag below, once `open` is known — their once-per-message flag is
1652
2414
  // shared with the stream arm's carry.
1653
2415
 
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.
2416
+ // A non-null parent_tool_use_id ⇒ this assistant message belongs to a
2417
+ // NESTED turn (subagent run). subagent.start is the SOLE nested-turn opener
2418
+ // (spec §4/§5), emitted once per run by `openRun`, and seeds the turn so
2419
+ // openMessage does NOT synthesize a duplicate turn.start. guuey#26: a
2420
+ // CONTINUATION frame joins the message the previous frame opened — no
2421
+ // second message.start.
1660
2422
  let open: PendingMessage;
1661
2423
  if (continued !== undefined) {
1662
2424
  open = continued;
1663
2425
  } 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);
2426
+ if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
2427
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1669
2428
  }
1670
2429
 
1671
2430
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
@@ -1684,6 +2443,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1684
2443
  streamed: false,
1685
2444
  streamBlocks: new Map(),
1686
2445
  ttftCarried: false,
2446
+ framedThrough: 0,
1687
2447
  turnBindingCarried: false,
1688
2448
  };
1689
2449
  pending = open;
@@ -1696,6 +2456,21 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1696
2456
  });
1697
2457
  }
1698
2458
  const messageId = open.emittedId;
2459
+ // rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
2460
+ // {type, category, explanation, fallbacks?}) is carried verbatim on its
2461
+ // turn's closing turn.done.messageMetadata, which folds onto the message it
2462
+ // names (SPEC §5 turn.done row). The CLOSING response's value only: a later
2463
+ // response of the turn without one clears it. Every `fallback_credit_token`,
2464
+ // at any depth, is deleted first (a provider credit token is never
2465
+ // emitted). Null (every committed golden) carries nothing. Keyed by turn,
2466
+ // so a nested (subagent) response never touches its parent's entry, and
2467
+ // only top-level turns close with turn.done.
2468
+ const stopDetails: unknown = m.stop_details;
2469
+ if (isJsonObject(stopDetails)) {
2470
+ stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
2471
+ } else if (stopDetailsByTurn.get(turnId)?.messageId !== messageId) {
2472
+ stopDetailsByTurn.delete(turnId);
2473
+ }
1699
2474
  // - `user_message_uuid` (0.3.258): the client uuid of the user message
1700
2475
  // this turn answers, stamped on the turn's FIRST reply frame only
1701
2476
  // (wrapper-level sibling per its own doc — never inside
@@ -1734,14 +2509,73 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1734
2509
  if (resumeReason !== undefined) wrapperMetaRaw["resume_reason"] = resumeReason;
1735
2510
  }
1736
2511
  }
2512
+ // X5 (sp-rnd re-cut, 2026-09-23): the bag mixes two kinds of fact. SPEC
2513
+ // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2514
+ // round-trip to the provider) and `_meta` host-only side metadata.
2515
+ // `narration_block_indexes` and the API-error triad are CLI-wrapper facts
2516
+ // the Messages API never consumes, so where the bag anchors on a BLOCK they
2517
+ // ride that block's start event `_meta` (`reduce()` folds it onto
2518
+ // `block._meta`, keeping the per-frame anchoring). The rest keeps
2519
+ // `providerMetadata`. The split is by key, so the combined bag, and the
2520
+ // `message.metadata` path below that uses it, stay byte-identical
2521
+ // (message.metadata is already `AgMeta`).
2522
+ //
2523
+ // Consumer check (sp-team-main, 2026-09-23): ggui has none of these names.
2524
+ // No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
2525
+ // the native frame. guuey asked that the triad move as ONE unit; the
2526
+ // result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
2527
+ const replayRaw: { [k: string]: JsonValue } = {};
2528
+ const hostRaw: { [k: string]: JsonValue } = {};
2529
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2530
+ if (HOST_ONLY_WRAPPER_KEYS.has(k)) hostRaw[k] = v;
2531
+ else replayRaw[k] = v;
2532
+ }
1737
2533
  const wrapperMeta: AgProviderMeta | undefined =
1738
- Object.keys(wrapperMetaRaw).length > 0 ? AgProviderMeta.parse(wrapperMetaRaw) : undefined;
2534
+ Object.keys(replayRaw).length > 0 ? AgProviderMeta.parse(replayRaw) : undefined;
2535
+ const hostMeta: AgMeta | undefined = Object.keys(hostRaw).length > 0 ? AgMeta.parse(hostRaw) : undefined;
2536
+ let anchored: BlockAnchor = NOTHING_ANCHORED;
1739
2537
  // workspace#7 dedupe: a STREAMED lifecycle already emitted every block
1740
2538
  // incrementally (stream ids reuse the content `index`, identical to the
1741
2539
  // arithmetic below) — this complete frame must not re-synthesize them.
1742
2540
  // Everything below the block loop (wrapper carry via message.metadata,
1743
2541
  // usage, error close, uuid registration) still runs.
1744
2542
  const suppressed = open.streamed;
2543
+ // draft.4 `phase` (§8.0 item 27, a SHOULD per the founder's A.10.5
2544
+ // ruling): a `thinking` block listed in `narration_block_indexes` whose
2545
+ // text is NON-EMPTY is interim narration → `phase:"interim"` on that
2546
+ // reasoning block. A listed empty block (display "omitted") gets none.
2547
+ // The index is FRAME-local. Never inferred from position, text or turn
2548
+ // end; never decoded from the signature; the vendor list itself still
2549
+ // rides host-only `_meta` verbatim (X5).
2550
+ const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2551
+ if (suppressed && narrationIndexes.size > 0) {
2552
+ // STREAMED: the complete frame precedes its blocks' content_block_stop
2553
+ // (CB-13; thinking-fable51 frames [62] signature → [63] frame → [64]
2554
+ // stop), so each listed frame-local index names stream block
2555
+ // `framedThrough + idx` (the frame covers the next blocks after those
2556
+ // earlier frames covered). It is marked only while it is still OPEN;
2557
+ // the phase then rides its reasoning.end, if its streamed text was
2558
+ // non-empty. A block that already sealed stays unmarked, never a
2559
+ // post-seal event and never a neighbouring block.
2560
+ for (const idx of narrationIndexes) {
2561
+ const frameBlock = m.content[idx];
2562
+ const streamBlock = open.streamBlocks.get(open.framedThrough + idx);
2563
+ if (frameBlock?.type === "thinking" && streamBlock?.kind === "reasoning") streamBlock.narration = true;
2564
+ }
2565
+ }
2566
+ if (suppressed) {
2567
+ // STREAMED: record each open tool block's `wire_tool_inputs` entry (the
2568
+ // complete frame precedes the block's content_block_stop, CB-13); its
2569
+ // tool.args.assembled carries it only if it differs from the streamed input.
2570
+ for (let i = 0; i < m.content.length; i++) {
2571
+ const frameBlock = m.content[i];
2572
+ const streamBlock = open.streamBlocks.get(open.framedThrough + i);
2573
+ if (frameBlock !== undefined && isToolUseBlock(frameBlock) && streamBlock?.kind === "tool") {
2574
+ const wire = wireToolInput(msg, frameBlock.id);
2575
+ if (wire !== undefined) streamBlock.wireInput = wire;
2576
+ }
2577
+ }
2578
+ }
1745
2579
  if (!suppressed) {
1746
2580
  // A plain indexed loop, not `.forEach` — see `mcpToolResultContentToAgBlocks`'s
1747
2581
  // doc: `.forEach`'s callback parameter inference degrades to implicit `any`
@@ -1757,15 +2591,52 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1757
2591
  // (`<id>:text:0` twice would clobber in the fold). The wrapper carry
1758
2592
  // stays anchored to this FRAME's first block: `aborted` /
1759
2593
  // `resumed_from_incomplete_thinking` are per-frame facts.
1760
- emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined);
2594
+ // NON-STREAMED: the marker is known before the first delta, so it
2595
+ // rides reasoning.start (§5 phase timing).
2596
+ const interim =
2597
+ narrationIndexes.has(i) && block.type === "thinking" && typeof block.thinking === "string" && block.thinking.length > 0
2598
+ ? "interim"
2599
+ : undefined;
2600
+ const landed = emitAssistantBlock(
2601
+ a,
2602
+ block,
2603
+ messageId,
2604
+ open.blockIndex + i,
2605
+ i === 0 ? wrapperMeta : undefined,
2606
+ i === 0 ? hostMeta : undefined,
2607
+ interim,
2608
+ isToolUseBlock(block) ? wireInputFor(msg, block.id, block.input) : undefined,
2609
+ );
2610
+ if (block.type === "mcp_tool_result") closedToolCallIds.add(block.tool_use_id);
2611
+ if (i === 0) anchored = landed;
1761
2612
  }
1762
2613
  open.blockIndex += m.content.length;
1763
2614
  }
2615
+ open.framedThrough += m.content.length;
2616
+ // Record this frame's Agent/Task calls (the complete frame arrives in both
2617
+ // modes, streamed or not), so their results can be recognized as reports.
2618
+ for (const block of m.content) {
2619
+ if (block.type === "tool_use" && (block.name === "Agent" || block.name === "Task")) agentCallIds.add(block.id);
2620
+ }
1764
2621
  // Block-less frame (e.g. aborted before any content streamed) — or a
1765
2622
  // 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) {
2623
+ // first block exists to anchor the wrapper carry — ride message.metadata
2624
+ // (the whole combined bag, unchanged).
2625
+ if ((suppressed || m.content.length === 0) && (wrapperMeta !== undefined || hostMeta !== undefined)) {
1768
2626
  a.emit({ type: "message.metadata", messageId, metadata: wrapperMetaRaw });
2627
+ } else {
2628
+ // Whatever the first block could not anchor rides the message instead,
2629
+ // in wire order, so it still folds: the host half after a tool call (no
2630
+ // `_meta` on tool.start), and BOTH halves after a compaction, an
2631
+ // mcp_tool_result or a content.block (no providerMetadata slot).
2632
+ const unanchored: { [k: string]: JsonValue } = {};
2633
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2634
+ const isHost = HOST_ONLY_WRAPPER_KEYS.has(k);
2635
+ if ((isHost && !anchored.host) || (!isHost && !anchored.replay)) unanchored[k] = v;
2636
+ }
2637
+ if (Object.keys(unanchored).length > 0) {
2638
+ a.emit({ type: "message.metadata", messageId, metadata: unanchored });
2639
+ }
1769
2640
  }
1770
2641
  // The seal is DEFERRED (guuey#26) — the next frame may continue this same
1771
2642
  // message id. Usage is message-level and repeated per frame, so the newest
@@ -1790,47 +2661,40 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1790
2661
  // close.
1791
2662
  closePendingMessage();
1792
2663
  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
- });
2664
+ const retriable = assistantErrorRetriable(errCode);
2665
+ if (msg.parent_tool_use_id !== null) {
2666
+ // A NESTED error frame (sp-protocol ruling 1, 2026-09-23): the error is
2667
+ // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2668
+ // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2669
+ // parent closes as an error only when its OWN result frame says so.
2670
+ // Through 0.6.4 (whenever subagent frames carried the parent's
2671
+ // session_id) a nested rate_limit closed a recovered parent as a
2672
+ // retriable error and, first-error-wins, masked a later top-level
2673
+ // billing_error. `subagent.done` carries no outcome (SPEC:648), so the
2674
+ // failure rides the NON-terminal `error` event (SPEC:609) on the nested
2675
+ // turn: live-only but truthful and correctly owned, and inside the
2676
+ // run's still-open bracket, so before its subagent.done. The folded gap
2677
+ // ("a nested turn has no failure outcome") is sp-protocol's to bar.
2678
+ a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2679
+ // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2680
+ // frame's close is stashed and released as the nested turn.error when
2681
+ // its run closes (see `closeRun`), whatever the Task result reports.
2682
+ if (!nestedStashedErrors.has(turnId)) nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2683
+ } else if (!stashedTurnErrors.has(turnId)) {
2684
+ // First error frame wins: a turn already carrying a stashed close keeps
2685
+ // it (before CL-09's stash, the first error frame closed the turn).
2686
+ stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
1822
2687
  }
1823
2688
  }
1824
2689
 
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.
2690
+ // `subagent.done` is NOT emitted here: it brackets the RUN (see `openRun`),
2691
+ // and this message's seal is deferred (guuey#26) until nothing can continue it.
1828
2692
 
1829
2693
  // Record this frame's own uuid → the messageId it produced, so a LATER
1830
2694
  // retraction naming this uuid can translate it (Finding #1). The EMITTED
1831
2695
  // id, so a retraction still names the message that actually exists on the
1832
2696
  // wire when this frame rode a derived carrier.
1833
- registerUuid(msg.uuid, [messageId]);
2697
+ registerUuid(msg.uuid, [messageId], turnId);
1834
2698
  return;
1835
2699
  }
1836
2700
 
@@ -1861,6 +2725,44 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1861
2725
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1862
2726
  // adoption below depends on this ordering).
1863
2727
  closePendingMessage();
2728
+ // A tool_result answering a Task call ENDS that subagent run, by what it
2729
+ // reports (B-strict, see `openRun`): its nested terminal and bracket close
2730
+ // come before the result's own tool.done. A result for any other tool
2731
+ // closes nothing. A background launch ack keeps the run open.
2732
+ if (typeof msg.message.content !== "string") {
2733
+ let resultCount = 0;
2734
+ for (const b of msg.message.content) if (b.type === "tool_result") resultCount++;
2735
+ const rawUser: unknown = msg;
2736
+ const sibling = resultCount === 1 && isJsonObject(rawUser) ? rawUser["tool_use_result"] : undefined;
2737
+ const status = isJsonObject(sibling) && typeof sibling["status"] === "string" ? sibling["status"] : undefined;
2738
+ for (const b of msg.message.content) {
2739
+ if (b.type !== "tool_result" || !openRuns.has(b.tool_use_id)) continue;
2740
+ if (b.is_error === true) {
2741
+ closeRun(b.tool_use_id, { kind: "error", message: toolResultText(b.content) ?? "subagent failed" });
2742
+ } else if (status !== "async_launched" && status !== "remote_launched") {
2743
+ closeRun(b.tool_use_id, { kind: "success" });
2744
+ }
2745
+ }
2746
+ }
2747
+ // A LIVE user frame with no tool_result block is content the CLI added to
2748
+ // the conversation itself (the SDKUserMessage doc; the host's own prompts
2749
+ // come back only as isReplay acks, returned above). The live case: the
2750
+ // CLI's `isSynthetic: true` nudge "[Your previous response had no visible
2751
+ // output. …]" after an empty reply (sp-probe's
2752
+ // defer-tool-sonnet5-resume-unavailable, 7c6880f, the corpus's only such
2753
+ // frame). This branch maps only tool_result blocks, so it had no event at
2754
+ // all, and the census could not see the text go (its path normalizes to
2755
+ // the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
2756
+ // the carry the replay gap above names. DISCLOSED: a frame MIXING
2757
+ // tool_results with other blocks still maps only its tool_results (none
2758
+ // in the corpus).
2759
+ let carriesToolResult = false;
2760
+ if (typeof msg.message.content !== "string") {
2761
+ for (const b of msg.message.content) if (b.type === "tool_result") carriesToolResult = true;
2762
+ }
2763
+ if (!carriesToolResult) {
2764
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(msg) });
2765
+ }
1864
2766
  // A user message carrying tool_result blocks → tool.done per result.
1865
2767
  // parent_tool_use_id (when set) identifies a subagent tool call — the
1866
2768
  // tool.done's turnId should point at that parent call's turn so the
@@ -1872,11 +2774,53 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1872
2774
  // it is unknown (e.g. a result delivered before its subagent.start
1873
2775
  // was ever observed) — defensive; leg 3's never-opened-turn guard now
1874
2776
  // 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;
2777
+ // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2778
+ // runs make the assembler's last-turn backfill unreliable). With no turn
2779
+ // open, the frame opens one first (below), so this is never undefined.
2780
+ // Nested: the run's OPEN nested turn. A nested frame for a run that has
2781
+ // CLOSED (e.g. a background agent's tool_result after the parent's
2782
+ // result), or for one this invoke NEVER opened (the stream started
2783
+ // mid-run), gets a fresh run named by its frame, as nested assistant
2784
+ // frames do: nothing lands on a nested turn after its subagent.done, or
2785
+ // on a turn nobody opened, and no id repeats across invokes.
2786
+ // INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
2787
+ // content event for a turn the stream has not opened; sp-protocol,
2788
+ // 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
2789
+ // invoke's first frame is the deferred call's tool_result, before
2790
+ // system/init; sp-probe's defer-resume capture) opens the turn it lands
2791
+ // in, named by this frame's uuid. The resumed invoke's assistant frames
2792
+ // then join it and its result closes it. Through c54eb7f its tool.done
2793
+ // had no turn and reduce() parked from the first event. Where that result
2794
+ // folds relative to the PREVIOUS invoke's open tool block is candidate
2795
+ // 20's bar question, not decided here.
2796
+ let opensWithToolResult = false;
2797
+ for (const b of content) if (b.type === "tool_result") opensWithToolResult = true;
2798
+ if (msg.parent_tool_use_id === null && openTopTurnId === undefined && opensWithToolResult) {
2799
+ const opened = topTurnId(msg.uuid, undefined);
2800
+ a.openTurn(opened, options.threadId ?? msg.session_id ?? opened);
2801
+ }
2802
+ let toolTurnId: string | undefined;
2803
+ if (msg.parent_tool_use_id !== null) {
2804
+ const parentToolUseId = msg.parent_tool_use_id;
2805
+ const run = openRuns.get(parentToolUseId);
2806
+ if (run !== undefined) {
2807
+ toolTurnId = run.turnId;
2808
+ } else {
2809
+ // A run that CLOSED, or one this invoke never opened (the stream
2810
+ // started mid-run: a background agent spanning invokes, a resume):
2811
+ // open a fresh run named by this frame, so its tool.done lands in a
2812
+ // turn that subagent.start opened (INV-TURN) and B-strict closes.
2813
+ // Through 0.7.0's DC-10 fix the never-opened case named the synthetic
2814
+ // `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
2815
+ // loudly"): a turn nobody opened, whose id REPEATED across the
2816
+ // invokes one Reducer folds (the rd-14 ids-across-invokes rule;
2817
+ // sp-protocol's message.start bar, wf_140b3183-767), and it parked.
2818
+ toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
2819
+ openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
2820
+ }
2821
+ } else {
2822
+ toolTurnId = openTopTurnId;
2823
+ }
1880
2824
  // tool_use_result sibling (SDK-injected rich MCP result; audit B7): carries
1881
2825
  // structuredContent (incl. render-cache markers) + _meta.ui the block-level
1882
2826
  // arm never sees. Applies only when the message has exactly ONE tool_result
@@ -1895,6 +2839,22 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1895
2839
  sibling !== undefined && isJsonObject(sibling["_meta"])
1896
2840
  ? AgMeta.parse(sibling["_meta"])
1897
2841
  : undefined;
2842
+ // The Agent tool's Output (AgentOutput, sdk-tools.d.ts): the subagent's
2843
+ // run report ("the completed shape is the subagent's final report ...
2844
+ // plus run totals — render from it instead of parsing the tool_result
2845
+ // text"), or the background launch ack (status async_launched, isAsync,
2846
+ // outputFile). Recognized by its `agentId` on the result of a call this
2847
+ // invoke saw as an Agent (or Task) tool_use (`agentCallIds`). It rides the Agent call's
2848
+ // tool.done host-only `_meta` under "anthropic/agentOutput", verbatim
2849
+ // minus `content` (already the tool.done content) and `prompt` (already
2850
+ // the tool input). Its `usage` is the subagent's own and stays out of
2851
+ // AgUsage (B-strict: the parent's accounting already includes it).
2852
+ // sp-probe's subagent captures (5ba11da) surfaced every one of these
2853
+ // fields as a census drop.
2854
+ const agentOutput =
2855
+ sibling !== undefined && typeof sibling["agentId"] === "string"
2856
+ ? carryVerbatim(Object.fromEntries(Object.entries(sibling).filter(([k]) => k !== "content" && k !== "prompt")))
2857
+ : undefined;
1898
2858
  const siblingHasUi = siblingMeta !== undefined && siblingMeta["ui"] !== undefined;
1899
2859
  // 0.3.257 sibling: `resourceLinks` — the MCP result's `resource_link`
1900
2860
  // content blocks (files returned by reference: {uri, name, title?,
@@ -1921,9 +2881,29 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1921
2881
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
1922
2882
  // collect every adopted messageId this frame produces below.
1923
2883
  const resultMessageIds: string[] = [];
2884
+ const nonExecutionById = readNonExecutionKinds(msg);
2885
+ const toolResultMetaById = readToolResultMetaEntries(msg);
1924
2886
  for (const block of content) {
1925
2887
  if (block.type === "tool_result") {
1926
- const outcome: ToolOutcome = block.is_error === true ? "error" : "ok";
2888
+ // A harness-stamped denial (see isDenialKind) records as "denied"
2889
+ // with no isError, and the native block message stays in `content`,
2890
+ // so the model-facing reason survives (§2.2 draft.4: isError and
2891
+ // errorText belong to outcome "error"). Before this, the same call
2892
+ // folded "error" here and then "denied" again from the result's
2893
+ // permission_denials (sp-probe's resume-deny leg).
2894
+ // Second key (sp-protocol, same basis): when no kind is stamped, a
2895
+ // live `permission_denied` notice already seen for this id is the
2896
+ // harness's own denial record (the CLI emits it at decision time,
2897
+ // always before this result). No kind is stamped on a frame holding
2898
+ // more than one tool_result (2.1.280's stamper returns [] unless
2899
+ // exactly one), nor by a CLI that predates the stamp. A stamped kind
2900
+ // stays the primary key, so "interrupted" with a notice is still an
2901
+ // error.
2902
+ const kind = nonExecutionById.get(block.tool_use_id);
2903
+ const denied =
2904
+ block.is_error === true &&
2905
+ (kind !== undefined ? isDenialKind(kind) : deniedLiveByToolUseId.has(block.tool_use_id));
2906
+ const outcome: ToolOutcome = denied ? "denied" : block.is_error === true ? "error" : "ok";
1927
2907
  const toolContent =
1928
2908
  block.content === undefined ? [] : toolResultContentToAgBlocks(block.content);
1929
2909
  // `structuredContent` is not declared on `ToolResultBlockParam` in the
@@ -1937,11 +2917,22 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1937
2917
  : undefined;
1938
2918
  const resultMessageId = `${block.tool_use_id}:result`;
1939
2919
  resultMessageIds.push(resultMessageId);
2920
+ closedToolCallIds.add(block.tool_use_id);
2921
+ // This tool.done closes the call, so the result's permission_denials
2922
+ // carrier skips it. The live `permission_denied` notice for the id
2923
+ // (the CLI emits it from its canUseTool wrapper at decision time,
2924
+ // always before this tool_result) rides here instead, the same
2925
+ // providerMetadata the carrier gave it, so D drops nothing.
2926
+ const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2927
+ const resultProviderFields: { [k: string]: JsonValue } = {
2928
+ ...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
2929
+ ...(liveFields ?? {}),
2930
+ };
1940
2931
  a.toolDone({
1941
2932
  toolCallId: block.tool_use_id,
1942
2933
  content: toolContent,
1943
2934
  outcome,
1944
- isError: block.is_error === true,
2935
+ ...(denied ? {} : { isError: block.is_error === true }),
1945
2936
  turnId: toolTurnId,
1946
2937
  // SPEC §5 tool.done adoption (audit B10; Task 8b): the Claude SDK
1947
2938
  // closes the assistant message (message.end) BEFORE this tool_result
@@ -1964,16 +2955,29 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1964
2955
  ? { structuredContent: sc }
1965
2956
  : {}),
1966
2957
  ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
1967
- ...(applySibling && siblingMeta !== undefined ? { _meta: siblingMeta } : {}),
1968
- ...(applySibling && siblingResourceLinks !== undefined
1969
- ? { providerMetadata: AgProviderMeta.parse({ resourceLinks: siblingResourceLinks }) }
2958
+ // The facet's harness keys, the Agent run report ("anthropic/agentOutput")
2959
+ // and rd-15's CLI `tool_result_meta` entry ("anthropic/toolResultMeta"),
2960
+ // ride the same `_meta`, MERGED into the MCP sibling's `_meta` (never
2961
+ // replacing it), so they fold with the tool-result block. The
2962
+ // "anthropic/" namespace is the harness's own: see `mergeHarnessMeta`.
2963
+ ...(() => {
2964
+ const report = applySibling && agentCallIds.has(block.tool_use_id) ? agentOutput : undefined;
2965
+ const entry = toolResultMetaById.get(block.tool_use_id);
2966
+ const merged = mergeHarnessMeta(applySibling ? siblingMeta : undefined, {
2967
+ ...(report !== undefined ? { "anthropic/agentOutput": report } : {}),
2968
+ ...(entry !== undefined ? { "anthropic/toolResultMeta": entry } : {}),
2969
+ });
2970
+ return merged !== undefined ? { _meta: merged } : {};
2971
+ })(),
2972
+ ...(Object.keys(resultProviderFields).length > 0
2973
+ ? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
1970
2974
  : {}),
1971
2975
  });
1972
2976
  }
1973
2977
  }
1974
2978
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
1975
2979
  // produced, so a later retraction naming this uuid can translate it.
1976
- registerUuid(msg.uuid, resultMessageIds);
2980
+ registerUuid(msg.uuid, resultMessageIds, toolTurnId);
1977
2981
  }
1978
2982
  return;
1979
2983
  }
@@ -1982,7 +2986,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1982
2986
  // guuey#26: the turn is closing — seal the open assistant message first
1983
2987
  // (message.end has always preceded the turn close).
1984
2988
  closePendingMessage();
1985
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2989
+ // B-strict: a subagent run still open (a background or unreported sub-run)
2990
+ // is NOT closed by its parent's result; it closes when the framework
2991
+ // reports it, or at flush.
2992
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1986
2993
  // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1987
2994
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1988
2995
  // the final assistant text in result — or, with is_error true, the error
@@ -2002,6 +3009,8 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2002
3009
  // discriminant-validated, and false/absent must stay on the success path
2003
3010
  // byte-for-byte. The stash entry is consumed either way.
2004
3011
  const stashedError = takeStashedTurnError(turnId);
3012
+ // Shape-guarded once for every close below (Tenet 6; see guardedTurnUsage).
3013
+ const turnUsage = guardedTurnUsage(msg);
2005
3014
  const apiErrorTurn = msg.is_error === true;
2006
3015
  const safety: AgSafety[] | undefined =
2007
3016
  msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
@@ -2015,37 +3024,12 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2015
3024
  // CL-09: an API-error turn's denials take this same carrier, at the same
2016
3025
  // point — its close is deferred to this frame (below), so the turn is
2017
3026
  // 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
- }
3027
+ emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
2044
3028
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
2045
3029
  // ride `ext.anthropic.result-meta` before the close (no core home on
2046
3030
  // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
2047
3031
  // API-error turn too, before its close like on every other turn.
2048
- const resultMeta = resultMetaPayload(msg);
3032
+ const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
2049
3033
  if (resultMeta !== undefined) {
2050
3034
  a.emitExt("anthropic", "result-meta", resultMeta);
2051
3035
  }
@@ -2056,33 +3040,51 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2056
3040
  // the fold keeps the cost of every round the turn ran before failing.
2057
3041
  a.closeTurnError(turnId, {
2058
3042
  ...stashedError,
2059
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
3043
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2060
3044
  });
2061
3045
  return;
2062
3046
  }
2063
3047
  if (apiErrorTurn) {
2064
3048
  // No assistant error frame preceded this result (a producer that did
2065
3049
  // 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";
3050
+ // the turn's only close. code = the server's api_error_code when the
3051
+ // CLI copied one through; else the CLI's own terminal_reason when it
3052
+ // names a cause other than a normal completion; else the generic
3053
+ // "api_error".
3054
+ // message = the result text (on an API error, its text), or the code
3055
+ // when that text is empty. retriable = the HTTP status says rate limit
3056
+ // or server failure (see `apiErrorStatusRetriable`); usage = the turn's
3057
+ // accrued usage, as above.
3058
+ // The terminal_reason step (sp-protocol, facet-local, 2026-09-23): the
3059
+ // CLI also sets is_error on a result that is NOT an API error. sp-probe's
3060
+ // resume-unavailable leg (7c6880f) is a resumed invoke whose deferred
3061
+ // tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
3062
+ // result "", no status, no api_error_code. Through b7dd7ff it closed
3063
+ // turn.error{message: "", code: "api_error"}, claiming an API failure
3064
+ // that never happened. `code` is free-form (SPEC :618), so this fills
3065
+ // existing fields from the frame's own value; a live API error
3066
+ // (terminal_reason "api_error", api-error-auth) is unchanged.
3067
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
2073
3068
  a.closeTurnError(turnId, {
2074
- message: typeof msg.result === "string" ? msg.result : code,
3069
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
2075
3070
  code,
2076
3071
  retriable: apiErrorStatusRetriable(msg.api_error_status),
2077
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
3072
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2078
3073
  });
2079
3074
  return;
2080
3075
  }
3076
+ const finishReasonRaw = stopReasonRaw(msg.stop_reason);
3077
+ const stopDetails = stopDetailsByTurn.get(turnId);
3078
+ stopDetailsByTurn.delete(turnId);
2081
3079
  a.closeTurnDone(turnId, {
2082
3080
  outcome: { type: "success", result: structuredOutput ?? msg.result },
2083
3081
  finishReason: mapStopReason(msg.stop_reason),
2084
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
3082
+ ...(finishReasonRaw !== undefined ? { finishReasonRaw } : {}),
3083
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2085
3084
  safety,
3085
+ ...(stopDetails !== undefined
3086
+ ? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
3087
+ : {}),
2086
3088
  });
2087
3089
  return;
2088
3090
  }
@@ -2091,10 +3093,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2091
3093
  // At this point msg.subtype can only be an error variant (success handled above).
2092
3094
  // guuey#26: seal the open assistant message before the turn close.
2093
3095
  closePendingMessage();
2094
- const turnId = turnIdFor(msg.session_id, msg.uuid);
3096
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
2095
3097
  // 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).
3098
+ // frame emits it (below). Each turn has its own id now, so an entry can
3099
+ // only ever be this turn's.
2098
3100
  const stashedError = takeStashedTurnError(turnId);
2099
3101
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
2100
3102
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
@@ -2112,10 +3114,22 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2112
3114
  startupFailureReason !== undefined
2113
3115
  ? startupFailureRetriable(startupFailureReason)
2114
3116
  : subtype !== "error_max_turns";
3117
+ // Denials ride the SAME carrier as on the success arm, at the same point.
3118
+ // This arm is discriminant-validated only, so the array is shape-guarded
3119
+ // (a malformed entry is skipped; Tenet 6: never throw).
3120
+ const rawDenials: unknown = isJsonObject(msg) ? msg["permission_denials"] : undefined;
3121
+ const denials = Array.isArray(rawDenials)
3122
+ ? rawDenials.flatMap((d: unknown) =>
3123
+ isJsonObject(d) && typeof d["tool_name"] === "string" && typeof d["tool_use_id"] === "string"
3124
+ ? [{ tool_name: d["tool_name"], tool_use_id: d["tool_use_id"] }]
3125
+ : [],
3126
+ )
3127
+ : [];
3128
+ emitDenialsCarrier(turnId, denials, msg.session_id);
2115
3129
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
2116
3130
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
2117
3131
  // success arm above (turn.error carries no metadata slot at all).
2118
- const resultMeta = resultMetaPayload(msg);
3132
+ const resultMeta = resultMetaPayload(msg, true);
2119
3133
  if (resultMeta !== undefined) {
2120
3134
  a.emitExt("anthropic", "result-meta", resultMeta);
2121
3135
  }
@@ -2126,22 +3140,10 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2126
3140
  // usage (the success arm's mapping). This arm is only
2127
3141
  // discriminant-validated, so the usage trio is shape-guarded first
2128
3142
  // (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
3143
+ // The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
3144
+ // dereferences — `usage: {}` or a null modelUsage entry would otherwise
2132
3145
  // 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;
3146
+ const usage = guardedTurnUsage(msg);
2145
3147
  a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
2146
3148
  return;
2147
3149
  }
@@ -2166,7 +3168,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2166
3168
  // promotion is strictly more lossless. Wrapper siblings ride the text
2167
3169
  // block's providerMetadata (camelCased per the facet's carry
2168
3170
  // convention, mirroring the 0.3.217 first-block precedent).
2169
- const turnId = turnIdFor(msg.session_id, msg.uuid);
3171
+ // The open turn, or (between turns) the one this notice opens; the next
3172
+ // assistant frame then joins it and its result closes it.
3173
+ const turnId = topTurnId(msg.uuid, undefined);
2170
3174
  const noticeMeta = AgProviderMeta.parse({
2171
3175
  level: msg.level,
2172
3176
  ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
@@ -2210,7 +3214,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2210
3214
  // and non-folding, so the second copy of `retracted_message_uuids`
2211
3215
  // cannot double-fold (the M22 hazard). This is the only producer for R&D
2212
3216
  // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
2213
- a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
3217
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
2214
3218
  return;
2215
3219
  }
2216
3220
 
@@ -2262,7 +3266,34 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2262
3266
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
2263
3267
  const carriedKind = anthropicFrameKind(msg);
2264
3268
  if (carriedKind !== undefined) {
2265
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: JsonValue.parse(msg) });
3269
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3270
+ // B-strict: a background sub-run's outcome arrives as task_notification,
3271
+ // correlated to its run by tool_use_id (or by task_id through the
3272
+ // task_started frame that named it).
3273
+ const raw: unknown = msg;
3274
+ if (isJsonObject(raw) && raw["type"] === "system" && typeof raw["task_id"] === "string") {
3275
+ const taskId = raw["task_id"];
3276
+ const named = typeof raw["tool_use_id"] === "string" ? raw["tool_use_id"] : undefined;
3277
+ if (raw["subtype"] === "task_started" && named !== undefined) toolUseIdByTaskId.set(taskId, named);
3278
+ if (raw["subtype"] === "task_notification") {
3279
+ const runKey = named ?? toolUseIdByTaskId.get(taskId);
3280
+ const status = raw["status"];
3281
+ if (runKey !== undefined && openRuns.has(runKey)) {
3282
+ if (status === "completed") closeRun(runKey, { kind: "success" });
3283
+ else if (status === "failed") closeRun(runKey, { kind: "error", message: typeof raw["summary"] === "string" && raw["summary"] !== "" ? raw["summary"] : "subagent failed", code: "failed" });
3284
+ else if (status === "stopped") closeRun(runKey, { kind: "aborted", reason: "stopped" });
3285
+ }
3286
+ }
3287
+ }
3288
+ return;
3289
+ }
3290
+
3291
+ // A top-level type the union does not declare (see KNOWN_TOP_LEVEL_TYPES):
3292
+ // carried whole, never silently dropped. `msg.type` is typed as the union's
3293
+ // literals, but the frame is only discriminant-validated at runtime.
3294
+ const topLevelType: string = msg.type;
3295
+ if (!KNOWN_TOP_LEVEL_TYPES.has(topLevelType)) {
3296
+ a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
2266
3297
  return;
2267
3298
  }
2268
3299
 
@@ -2272,23 +3303,37 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2272
3303
 
2273
3304
  return {
2274
3305
  push(native: JsonValue): AgEvent[] {
2275
- if (!isSDKMessage(native)) {
3306
+ framesSeen++;
3307
+ // `native` is already plain JSON: withAtomicPush (createClaudeNormalizer)
3308
+ // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3309
+ // frame is the same reference, anything else its JSON form).
3310
+ const frame = native;
3311
+ if (!isSDKMessage(frame)) {
2276
3312
  // Graceful guard (Tenet 6): route the raw payload through the lossless
2277
3313
  // vendor channel rather than throwing. Nest under `native` so a payload
2278
3314
  // that carries its own `type` key (the common malformed-SDKMessage shape
2279
3315
  // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
2280
3316
  // (emitExt spreads object payloads at the top level).
2281
- a.emitExt("anthropic", "unparsed", { native });
3317
+ // A copy: `frame` IS the host's object when it was already JSON, and
3318
+ // this raw channel would otherwise emit it by reference. JsonValue.parse
3319
+ // copies and, like every other carry here, drops an own "__proto__"
3320
+ // (sp-main 2026-09-24, matching sp-openai cf55e08 and the 0.6.6
3321
+ // reserved-key rule 314a183: an emitted map carries no own __proto__).
3322
+ a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
2282
3323
  return a.drain();
2283
3324
  }
2284
- drive(native);
3325
+ drive(frame);
2285
3326
  return a.drain();
2286
3327
  },
2287
3328
  flush(): AgEvent[] {
2288
3329
  // 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();
3330
+ // its real usage rather than leaving INV-FLUSH to synthesize a bare
3331
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3332
+ closePendingMessage(true);
3333
+ // B-strict: every subagent run still open closes here with its nested
3334
+ // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3335
+ // its subagent.done, innermost first.
3336
+ abortOpenRuns();
2292
3337
  // CL-09: a turn whose assistant error frame stashed its close but whose
2293
3338
  // result frame never arrived still closes as that turn.error (no usage:
2294
3339
  // only a result carries the turn's), never as INV-FLUSH's synthesized
@@ -2302,5 +3347,34 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
2302
3347
  };
2303
3348
  }
2304
3349
 
3350
+ /**
3351
+ * Build the Claude-facet normalizer: the inner normalizer wrapped in core's
3352
+ * withAtomicPush (the fleet guard ruling, 2026-09-24, binding). push() never
3353
+ * throws (SPEC:933):
3354
+ * - each native is first read as plain JSON (core toJsonValueSafe): a host
3355
+ * may hand in the in-process object, whose members need not be JSON (an
3356
+ * undefined member, a Date, NaN, a BigInt, a function, a cycle); a JSON
3357
+ * frame passes by reference, anything else folds exactly as its JSON form,
3358
+ * which is what every capture already is (the SDK itself parses the CLI's
3359
+ * NDJSON, so no 0.3.280 SDK frame needs it);
3360
+ * - an envelope-valid but malformed frame (a required field missing or
3361
+ * mistyped below the isSDKMessage discriminants: 61 single-point fuzz
3362
+ * mutants of the corpus's 25 frame shapes threw, from ~17 sites, most after
3363
+ * the frame had emitted) no longer throws: its partial batch is discarded
3364
+ * with its state (the inner is rebuilt and re-driven from the journal) and
3365
+ * one core `error {message: "normalizer error", code: <constructor name>}`
3366
+ * takes the next seq. Over every committed native it fires zero times
3367
+ * (e2e agents/claude-agent-sdk/guard.corpus.test.ts).
3368
+ * The fallback id stem is held HERE, outside the rebuild's factory: drawn at
3369
+ * most once, and only when a fallback id is first needed, so the common path
3370
+ * never touches randomness (core's atomic-guard differential runs with it
3371
+ * poisoned) and a rebuild re-reads the same stem.
3372
+ */
3373
+ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): Normalizer {
3374
+ let stem = options.invokeId;
3375
+ const invokeStem = (): string => (stem ??= `claude_${mintInvokeNonce()}`);
3376
+ return withAtomicPush(() => createInnerClaudeNormalizer(options, invokeStem));
3377
+ }
3378
+
2305
3379
  export default createClaudeNormalizer;
2306
3380
  export { mapStopReason };