@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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
1
+ import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, withAtomicPush, } from "@silverprotocol/core";
2
2
  // ─── stop_reason → AgFinishReason (spec §4) ───────────────────────────────────
3
3
  // Anthropic BetaStopReason superset → the neutral finish-reason superset.
4
4
  function mapStopReason(stop) {
@@ -26,13 +26,23 @@ function mapStopReason(stop) {
26
26
  return "unknown";
27
27
  }
28
28
  }
29
- // ─── derive stable ids ────────────────────────────────────────────────────────
30
- // A stable per-message turn id: the assistant message is the model's turn, so
31
- // the SDK session id names the turn (a top-level turn shares the session). When
32
- // absent, fall back to the message id.
33
- function turnIdFor(sessionId, messageId) {
34
- return sessionId && sessionId.length > 0 ? `turn_${sessionId}` : `turn_${messageId}`;
29
+ // draft.4 (§8.0 graceful degradation / §10 item 23): when `mapStopReason` had to
30
+ // FALL BACK (a stop_reason this facet has no mapping for, e.g. one a newer
31
+ // Messages API ships), `turn.done.finishReasonRaw` carries the native value
32
+ // verbatim beside finishReason "unknown", so nothing about why the turn ended
33
+ // is lost. Set ONLY on the fallback: a mapped reason, and `null` (a real
34
+ // "stop"), carry no raw companion, so ordinary turns stay byte-identical.
35
+ function stopReasonRaw(stop) {
36
+ return typeof stop === "string" && mapStopReason(stop) === "unknown" ? stop : undefined;
35
37
  }
38
+ // ─── derive stable ids ────────────────────────────────────────────────────────
39
+ // Turn ids are minted per TURN inside `createClaudeNormalizer()` (see
40
+ // `topTurnId` / `nestedTurnId`), never per session: through 0.6.4 the facet
41
+ // keyed every top-level turn on `turn_${session_id}`, so in a multi-turn
42
+ // invoke the second turn's message.start and content landed on T AFTER
43
+ // turn.done(T) (the assembler's seen-turn set suppressed a second
44
+ // turn.start), breaking INV-TURN (SPEC:743), and reduce() merged every turn
45
+ // of a session into one AgTurnRecord (sp-protocol, 2026-09-23).
36
46
  // ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
37
47
  function imageSource(source) {
38
48
  if (source.type === "base64") {
@@ -90,6 +100,23 @@ function mapModelUsage(mu) {
90
100
  cumulative: true,
91
101
  };
92
102
  }
103
+ // `server_tool_use` is typed `{web_search_requests, web_fetch_requests} | null`,
104
+ // but a result frame is discriminant-validated only, so a leaner producer (a
105
+ // proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
106
+ // member passed the `!== null` check and threw a TypeError out of push()
107
+ // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found by sp-protocol writing §10.23),
108
+ // and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
109
+ // anything else ⇒ absent.
110
+ function serverToolRequestCount(usage) {
111
+ if (!isJsonObject(usage))
112
+ return undefined;
113
+ const stu = usage["server_tool_use"];
114
+ if (!isJsonObject(stu))
115
+ return undefined;
116
+ const search = stu["web_search_requests"];
117
+ const fetch = stu["web_fetch_requests"];
118
+ return typeof search === "number" && typeof fetch === "number" ? search + fetch : undefined;
119
+ }
93
120
  function mapTurnUsage(usage, totalCostUsd, modelUsage) {
94
121
  const byModel = {};
95
122
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -102,9 +129,7 @@ function mapTurnUsage(usage, totalCostUsd, modelUsage) {
102
129
  cacheReadTokens: usage.cache_read_input_tokens,
103
130
  cacheWriteTokens: usage.cache_creation_input_tokens,
104
131
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
105
- serverToolRequests: usage.server_tool_use !== null
106
- ? usage.server_tool_use.web_search_requests + usage.server_tool_use.web_fetch_requests
107
- : undefined,
132
+ serverToolRequests: serverToolRequestCount(usage),
108
133
  costUsd: totalCostUsd,
109
134
  cumulative: true,
110
135
  ...(Object.keys(byModel).length > 0 ? { byModel } : {}),
@@ -190,7 +215,7 @@ function assistantContentBlockToAgBlock(block) {
190
215
  return {
191
216
  type: "provider-raw",
192
217
  vendor: "anthropic",
193
- raw: JsonValue.parse(block),
218
+ raw: carryVerbatim(block),
194
219
  };
195
220
  }
196
221
  // ─── user/tool_result content fan-out (spec §2 — tool.done content blocks) ────
@@ -211,7 +236,7 @@ function toolResultContentToAgBlocks(content) {
211
236
  out.push({ type: "image", source: imageSource(part.source) });
212
237
  }
213
238
  else {
214
- out.push({ type: "provider-raw", vendor: "anthropic", raw: JsonValue.parse(part) });
239
+ out.push({ type: "provider-raw", vendor: "anthropic", raw: carryVerbatim(part) });
215
240
  }
216
241
  }
217
242
  return out;
@@ -234,19 +259,82 @@ function mcpToolResultContentToAgBlocks(content) {
234
259
  out.push({ type: "text", text: tb.text });
235
260
  return out;
236
261
  }
237
- // ─── assistant content block fan-out (spec §4 mapping table) ──────────────────
238
- // Per content[] block, drive the engine to emit its lifecycle events under the
239
- // open message named by `messageId`. `blockProviderMetadata` is the refusal-
240
- // fallback `supersedes` carrier (playbook 2026-07-03 SDK-bump adaptation,
241
- // Finding #1 / §8 item 19): the caller passes it ONLY for blockIndex 0 of a
242
- // superseding message, mirroring the established "signature on first block"
243
- // precedent (§8 item 8, Gemini thoughtSignature). `text`/`thinking`/
244
- // `redacted_thinking`/`tool_use` family all have a providerMetadata slot on
245
- // their *.start event and land it there; the remaining rarer block-0 shapes
246
- // (image/resource/mcp_tool_result/compaction) have no providerMetadata slot on
247
- // `content.block` and drop the annotation (NOT the retraction itself, which
248
- // already executed via `message.remove` regardless — see `drive()`).
249
- function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetadata) {
262
+ // `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on sp-probe's
263
+ // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
264
+ // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
265
+ // not carry the tool's own execution output (user-rejected / permission-rule /
266
+ // automode-* / interrupted / cancelled); absent means the tool ran to
267
+ // completion" (the CLI's own schema doc). Read through the JSON boundary; a
268
+ // malformed entry is skipped. The entry itself is NOT carried here (that carry
269
+ // is package 15's); only the kind decides the outcome below.
270
+ function readNonExecutionKinds(frame) {
271
+ const out = new Map();
272
+ if (!isJsonObject(frame))
273
+ return out;
274
+ const list = frame["tool_result_meta"];
275
+ if (!Array.isArray(list))
276
+ return out;
277
+ for (const entry of list) {
278
+ if (isJsonObject(entry) && typeof entry["id"] === "string" && typeof entry["non_execution_kind"] === "string") {
279
+ out.set(entry["id"], entry["non_execution_kind"]);
280
+ }
281
+ }
282
+ return out;
283
+ }
284
+ // rd-15 (founder ruling 2026-09-24, fix the carries): each `tool_result_meta`
285
+ // entry, keyed by its `id` (the tool_use_id), verbatim: {id, non_execution_kind?,
286
+ // user_feedback?, remedy?} per the CLI's schema ("@internal Display metadata for
287
+ // this message's tool_result blocks"). Read through the JSON boundary; an entry
288
+ // without a string id is skipped. It rides the matching tool.done's `_meta`.
289
+ function readToolResultMetaEntries(frame) {
290
+ const out = new Map();
291
+ if (!isJsonObject(frame))
292
+ return out;
293
+ const list = frame["tool_result_meta"];
294
+ if (!Array.isArray(list))
295
+ return out;
296
+ for (const entry of list) {
297
+ if (isJsonObject(entry) && typeof entry["id"] === "string")
298
+ out.set(entry["id"], JsonValue.parse(entry));
299
+ }
300
+ return out;
301
+ }
302
+ // The non_execution_kinds that mean the call was NOT PERMITTED to run →
303
+ // `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
304
+ // item 15 routes Claude's permission denials to it; sp-protocol, 2026-09-23).
305
+ // `interrupted`, `cancelled`, absent and any unknown value are not denials and
306
+ // keep "error" (no guessing).
307
+ function isDenialKind(kind) {
308
+ return kind === "user-rejected" || kind === "permission-rule" || (kind !== undefined && kind.startsWith("automode-"));
309
+ }
310
+ // Which assistant `error` codes are transient (retriable). CL-09's stashed
311
+ // top-level close and a nested frame's non-terminal `error` share it.
312
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
313
+ // cousin of rate_limit/server_error) joins the retriable set.
314
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
315
+ // decommissioned model id) is deliberately EXCLUDED: explicit
316
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
317
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
318
+ // deliberate non-retriable: a billing-class code (the account is on
319
+ // hold — a first cousin of `billing_error`, cleared by the account
320
+ // holder, never by re-sending the turn).
321
+ //
322
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
323
+ // deliberate non-retriables recorded here for the same reason — an
324
+ // omission must never read as an oversight:
325
+ // - `verification_required`: the request is gated on an out-of-band
326
+ // human step (identity/org verification). Nothing about the turn
327
+ // changes by re-sending it; the block clears only when a person
328
+ // completes the verification.
329
+ // - `cloud_credential_error`: a credential/billing-class failure on
330
+ // the cloud-provider leg (a first cousin of `billing_error` and
331
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
332
+ // unauthorized credential is exactly as bad on the next attempt.
333
+ function assistantErrorRetriable(errCode) {
334
+ return errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded";
335
+ }
336
+ const NOTHING_ANCHORED = { replay: false, host: false };
337
+ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetadata, blockMeta, phase, wireInput) {
250
338
  switch (block.type) {
251
339
  case "text": {
252
340
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
@@ -255,23 +343,42 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
255
343
  // a duplicate id-less supplement block.
256
344
  const id = `${messageId}:text:${blockIndex}`;
257
345
  const citations = block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
258
- a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
346
+ if (blockMeta !== undefined) {
347
+ // textStart's sugar has no `_meta` field; `a.emit()` is the base primitive.
348
+ a.emit({
349
+ type: "text.start",
350
+ id,
351
+ messageId,
352
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
353
+ _meta: blockMeta,
354
+ });
355
+ }
356
+ else {
357
+ a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
358
+ }
259
359
  a.textDelta(id, messageId, block.text);
260
360
  a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
261
- return;
361
+ return { replay: true, host: blockMeta !== undefined };
262
362
  }
263
363
  case "thinking": {
264
364
  const id = `${messageId}:reasoning:${blockIndex}`;
265
- if (blockProviderMetadata !== undefined) {
266
- // reasoningStart's sugar signature has no providerMetadata parameter
267
- // (only textStart's does) — `a.emit()` is the documented base
268
- // primitive for exactly this case (schema DOES support it on
269
- // reasoning.start; StreamAssembler docstring: "guarantees no
270
- // AgClosedEventType is ever unreachable").
271
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
365
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
366
+ // reasoningStart's sugar signature has no providerMetadata or `_meta`
367
+ // parameter — `a.emit()` is the documented base primitive for exactly
368
+ // this case (schema DOES support both on reasoning.start;
369
+ // StreamAssembler docstring: "guarantees no AgClosedEventType is ever
370
+ // unreachable").
371
+ a.emit({
372
+ type: "reasoning.start",
373
+ id,
374
+ messageId,
375
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
376
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
377
+ ...(phase !== undefined ? { phase } : {}),
378
+ });
272
379
  }
273
380
  else {
274
- a.reasoningStart(id, messageId);
381
+ a.reasoningStart(id, messageId, phase !== undefined ? { phase } : undefined);
275
382
  }
276
383
  a.reasoningDelta(id, messageId, block.thinking);
277
384
  a.reasoningEnd(id, messageId);
@@ -285,13 +392,19 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
285
392
  provider: "anthropic",
286
393
  });
287
394
  }
288
- return;
395
+ return { replay: true, host: blockMeta !== undefined };
289
396
  }
290
397
  case "redacted_thinking": {
291
398
  // No visible text; the redacted blob is the replay-load-bearing opaque part.
292
399
  const id = `${messageId}:reasoning:${blockIndex}`;
293
- if (blockProviderMetadata !== undefined) {
294
- a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
400
+ if (blockProviderMetadata !== undefined || blockMeta !== undefined) {
401
+ a.emit({
402
+ type: "reasoning.start",
403
+ id,
404
+ messageId,
405
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
406
+ ...(blockMeta !== undefined ? { _meta: blockMeta } : {}),
407
+ });
295
408
  }
296
409
  else {
297
410
  a.reasoningStart(id, messageId);
@@ -302,7 +415,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
302
415
  value: block.data,
303
416
  provider: "anthropic",
304
417
  });
305
- return;
418
+ return { replay: true, host: blockMeta !== undefined };
306
419
  }
307
420
  case "tool_use":
308
421
  case "server_tool_use":
@@ -333,8 +446,8 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
333
446
  ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
334
447
  });
335
448
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
336
- a.toolArgsAssembled(toolCallId, input);
337
- return;
449
+ a.toolArgsAssembled(toolCallId, input, wireInputFields(wireInput));
450
+ return { replay: true, host: false };
338
451
  }
339
452
  case "mcp_tool_result": {
340
453
  // MCP tool results from the assistant side: map to tool.done with content + outcome.
@@ -347,7 +460,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
347
460
  isError: block.is_error,
348
461
  messageId,
349
462
  });
350
- return;
463
+ return NOTHING_ANCHORED;
351
464
  }
352
465
  case "compaction": {
353
466
  // Compaction blocks carry a provider-produced context summary (spec §4).
@@ -360,12 +473,12 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
360
473
  : undefined,
361
474
  provider: "anthropic",
362
475
  });
363
- return;
476
+ return NOTHING_ANCHORED;
364
477
  }
365
478
  default: {
366
479
  // image / resource / other rich content blocks ride content.block (spec §4).
367
480
  a.contentBlock(messageId, assistantContentBlockToAgBlock(block));
368
- return;
481
+ return NOTHING_ANCHORED;
369
482
  }
370
483
  }
371
484
  }
@@ -510,6 +623,30 @@ const CARRIED_STANDALONE_TYPES = new Set([
510
623
  // thread-rotation mapping is a future spec decision, not a mechanical carry.
511
624
  "conversation_reset",
512
625
  ]);
626
+ // The top-level `type` literals the SDKMessage union declares (0.3.280: 39
627
+ // members over these 11 types). A frame whose `type` is NOT among them is
628
+ // RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
629
+ // frame type). The first one observed: `command_lifecycle`
630
+ // ({command_uuid, state: "queued"|"started"|"completed"}, three per prompt,
631
+ // streaming-input mode; live on corpus/multi-result-sonnet5), the host
632
+ // prompt's queue lifecycle keyed by the caller's message uuid. Through the
633
+ // 0.7.0 stack it fell through `drive()` to the no-op, a silent drop against
634
+ // SPEC §8.0 graceful degradation. An unknown top-level type now rides the
635
+ // uniform carry, `ext.anthropic.frame{kind: <type>, frame}`, verbatim (§8 item
636
+ // 22), so the next runtime-only frame type is carried the day it ships.
637
+ const KNOWN_TOP_LEVEL_TYPES = new Set([
638
+ "assistant",
639
+ "user",
640
+ "result",
641
+ "system",
642
+ "stream_event",
643
+ "tool_progress",
644
+ "auth_status",
645
+ "tool_use_summary",
646
+ "rate_limit_event",
647
+ "prompt_suggestion",
648
+ "conversation_reset",
649
+ ]);
513
650
  // Returns the uniform-carry `kind` string for `msg` if it is one of the arms
514
651
  // disposed `carried` in sdk-surface.json, else undefined (leaves router-plane
515
652
  // / dedicated-branch arms — including SDKPermissionDeniedMessage — untouched).
@@ -525,23 +662,166 @@ function anthropicFrameKind(msg) {
525
662
  // runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
526
663
  // carry it verbatim. A malformed list is ignored, never thrown on (Tenet 6);
527
664
  // `string[]` is itself a JsonValue, so no cast is needed downstream.
665
+ // A COPY, never the frame's own array: the value is emitted unparsed
666
+ // (result-meta, message.metadata), core's StreamAssembler does not copy, and
667
+ // push() hands a JSON frame through by reference, so returning `v` would let an
668
+ // emitted event share the host's live array (cto's aliasing audit).
528
669
  function readUserMessageUuids(v) {
529
- return Array.isArray(v) && v.every((s) => typeof s === "string") ? v : undefined;
670
+ return Array.isArray(v) && v.every((s) => typeof s === "string") ? [...v] : undefined;
530
671
  }
672
+ // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
673
+ // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
674
+ // are CLI-wrapper facts the Messages API never consumes. See the split in
675
+ // drive()'s assistant branch.
676
+ const HOST_ONLY_WRAPPER_KEYS = new Set([
677
+ "narration_block_indexes",
678
+ "diagnostics",
679
+ "api_error",
680
+ "api_error_params",
681
+ "api_error_code",
682
+ // rd-15 (founder: defer the field, fix the carries): three more @internal
683
+ // CLI assistant-wrapper strings, carried where the host can read them.
684
+ "error_details",
685
+ "advisor_model",
686
+ "attribution_agent",
687
+ ]);
531
688
  // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
532
689
  // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
533
690
  // 0.3.272 (a pass-through of the Messages API field that rides the assistant
534
691
  // wrapper), so it is read through the JSON boundary and shape-guarded here, never
535
- // cast. Integer indexes into `message.content`; an out-of-range or non-integer
536
- // member means the producer changed shape, so the whole array is refused rather
537
- // than half-carried.
692
+ // cast. Integer indexes into `message.content`; a non-integer or negative member
693
+ // means the producer changed shape, so the whole array is refused rather than
694
+ // half-carried. The upper bound is not checked here: an out-of-range index
695
+ // simply names no block where it is used (the draft.4 `phase` mapping).
696
+ // A copy for the same reason as readUserMessageUuids: the block-less wrapper
697
+ // path emits it in message.metadata unparsed.
538
698
  function readNarrationBlockIndexes(v) {
539
699
  return Array.isArray(v) &&
540
700
  v.length > 0 &&
541
701
  v.every((n) => typeof n === "number" && Number.isInteger(n) && n >= 0)
542
- ? v
702
+ ? [...v]
543
703
  : undefined;
544
704
  }
705
+ // A provider- or harness-originated native subtree forwarded WHOLE: JSON-
706
+ // validated (a copy) and with every `fallback_credit_token` deleted at any
707
+ // depth (withoutCreditTokens). Every verbatim carrier of this facet goes
708
+ // through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
709
+ // carries, provider-raw blocks, and the CLI/API wrapper subtrees
710
+ // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats).
711
+ // Model- or tool-authored payloads (tool input, a deferred tool call, MCP
712
+ // structuredContent / _meta / resourceLinks, structured_output) are NOT
713
+ // stripped: a key there is user content, and the wire already carries the same
714
+ // data as the tool call or result.
715
+ function carryVerbatim(v) {
716
+ return withoutCreditTokens(JsonValue.parse(v));
717
+ }
718
+ // rd-15 / SPEC §13.7 (queued): a provider credit or bearer token is never
719
+ // emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
720
+ // (top level and per fallback), so every key of that name is deleted at any
721
+ // depth; everything else is kept verbatim.
722
+ function withoutCreditTokens(v) {
723
+ if (Array.isArray(v))
724
+ return v.map(withoutCreditTokens);
725
+ if (typeof v === "object" && v !== null) {
726
+ const out = {};
727
+ for (const [k, x] of Object.entries(v))
728
+ if (k !== "fallback_credit_token")
729
+ out[k] = withoutCreditTokens(x);
730
+ return out;
731
+ }
732
+ return v;
733
+ }
734
+ // A tool_result's text, for a failed Task's nested turn.error message: the
735
+ // string content, or its text blocks joined; undefined when there is none.
736
+ function toolResultText(content) {
737
+ if (typeof content === "string")
738
+ return content !== "" ? content : undefined;
739
+ if (!Array.isArray(content))
740
+ return undefined;
741
+ const texts = [];
742
+ for (const b of content)
743
+ if (isJsonObject(b) && b["type"] === "text" && typeof b["text"] === "string")
744
+ texts.push(b["text"]);
745
+ const joined = texts.join("\n");
746
+ return joined !== "" ? joined : undefined;
747
+ }
748
+ // The namespace of the facet's own harness keys on a tool.done `_meta` (the
749
+ // subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta").
750
+ const HARNESS_META_PREFIX = "anthropic/";
751
+ // A tool.done's host-only `_meta`: the tool-authored MCP sibling `_meta` merged
752
+ // with the facet's own harness keys. The harness namespace is RESERVED: every
753
+ // sibling key under "anthropic/" is dropped before the harness keys are
754
+ // written, so a tool (a malicious MCP server) can never present a forged
755
+ // harness fact, such as an agent report or a remedy pointing a host at its URL,
756
+ // even for a call the facet writes no harness key for (sp-cto's read of the
757
+ // rd-15 carry; the CLI itself strips its own reserved `com.anthropic/` prefix
758
+ // from server `_meta`). Every other sibling key is kept verbatim. undefined
759
+ // when nothing remains.
760
+ function mergeHarnessMeta(sibling, harness) {
761
+ const out = {};
762
+ if (sibling !== undefined) {
763
+ for (const [k, v] of Object.entries(sibling))
764
+ if (!k.startsWith(HARNESS_META_PREFIX))
765
+ out[k] = v;
766
+ }
767
+ for (const [k, v] of Object.entries(harness))
768
+ out[k] = v;
769
+ return Object.keys(out).length > 0 ? out : undefined;
770
+ }
771
+ // `wire_tool_inputs` (CLI 2.1.280, @internal, undeclared in sdk.d.ts; first seen
772
+ // on sp-probe's subagent captures): "tool_use.input exactly as the API produced
773
+ // it, keyed by tool_use id, for a message whose message.content carries the
774
+ // client-normalized input. Round-tripped so a replayed history echoes each
775
+ // earlier tool call back to the API as the API emitted it" (the CLI's own
776
+ // schema doc). REPLAY-LOAD-BEARING, so it rides the tool-call block's
777
+ // providerMetadata (SPEC §12) as `wireInput`, on tool.args.assembled (the one
778
+ // event both arms emit once the complete frame is known; the reducer merges its
779
+ // providerMetadata by key). It is carried only when it DIFFERS from the input the
780
+ // event already holds, key order aside: every capture so far has the two
781
+ // identical, which stays byte-identical. Credit tokens are stripped
782
+ // (carryVerbatim).
783
+ function wireToolInput(frame, toolUseId) {
784
+ const map = isJsonObject(frame) ? frame["wire_tool_inputs"] : undefined;
785
+ if (!isJsonObject(map))
786
+ return undefined;
787
+ const entry = map[toolUseId];
788
+ return entry === undefined ? undefined : carryVerbatim(entry);
789
+ }
790
+ // The complete arm: the wire input for a tool_use block, when it differs from
791
+ // the block's own (client-normalized) content input.
792
+ function wireInputFor(frame, toolUseId, contentInput) {
793
+ const wire = wireToolInput(frame, toolUseId);
794
+ return wire !== undefined && !jsonEqual(wire, contentInput) ? wire : undefined;
795
+ }
796
+ function wireInputFields(wireInput) {
797
+ return wireInput !== undefined ? { providerMetadata: AgProviderMeta.parse({ wireInput }) } : undefined;
798
+ }
799
+ function isToolUseBlock(block) {
800
+ return block.type === "tool_use" || block.type === "server_tool_use" || block.type === "mcp_tool_use";
801
+ }
802
+ // Structural JSON equality, object key order ignored (a normalizer that only
803
+ // reordered keys changed nothing a replay depends on).
804
+ function jsonEqual(x, y) {
805
+ if (x === y)
806
+ return true;
807
+ if (Array.isArray(x) || Array.isArray(y)) {
808
+ return Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((v, i) => jsonEqual(v, y[i]));
809
+ }
810
+ if (isJsonObject(x) && isJsonObject(y)) {
811
+ const kx = Object.keys(x);
812
+ const ky = Object.keys(y);
813
+ return kx.length === ky.length && kx.every((k) => Object.hasOwn(y, k) && jsonEqual(x[k], y[k]));
814
+ }
815
+ return false;
816
+ }
817
+ // A result's `terminal_reason` when it names why the turn ended other than a
818
+ // normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
819
+ // live API error's own value is "api_error", which is also the generic code, so
820
+ // that close is unchanged. Typed as the SDK's TerminalReason union, but a newer
821
+ // CLI may send an undeclared value, so only a non-empty string is taken.
822
+ function closeCauseTerminalReason(v) {
823
+ return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
824
+ }
545
825
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
546
826
  // on both frames that carry it (the API-error assistant frame and the
547
827
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -713,7 +993,7 @@ function apiErrorStatusRetriable(status) {
713
993
  // value verbatim; it also drives `turn.error.retriable` (see
714
994
  // `startupFailureRetriable`). Read through the JSON boundary because it is
715
995
  // declared on that one arm only.
716
- function resultMetaPayload(msg) {
996
+ function resultMetaPayload(msg, closesAsError) {
717
997
  const byModel = {};
718
998
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
719
999
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -730,7 +1010,12 @@ function resultMetaPayload(msg) {
730
1010
  // Undeclared siblings are only reachable through the JSON boundary: widen to
731
1011
  // `unknown` (no cast) and let the isJsonObject guard narrow.
732
1012
  const raw = msg;
733
- const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
1013
+ // `origin` (SDKMessageOrigin, on the result arms): set on the result of a turn
1014
+ // the framework WOKE, not the user, e.g. {kind: "task-notification"} after a
1015
+ // background subagent reported (sp-probe's bg capture, 5ba11da). turn.start's
1016
+ // `trigger` is a frozen enum, so it rides here verbatim.
1017
+ const origin = isJsonObject(raw) && isJsonObject(raw["origin"]) ? carryVerbatim(raw["origin"]) : undefined;
1018
+ const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? carryVerbatim(raw["subagent_stats"]) : undefined;
734
1019
  const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
735
1020
  // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
736
1021
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
@@ -739,6 +1024,26 @@ function resultMetaPayload(msg) {
739
1024
  // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
740
1025
  const apiErrorCode = readApiErrorCode(msg);
741
1026
  const startupFailureReason = readStartupFailureReason(msg);
1027
+ // `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
1028
+ // input}`): the tool call a host's PreToolUse `defer` decision parked, which
1029
+ // the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
1030
+ // the host needs it to act on the parked call. Through 0.6.4 the facet never
1031
+ // read it (a silent drop). Carried WHOLE and verbatim (the `subagent_stats`
1032
+ // precedent); whether it should instead map onto `turn.done.outcome.paused`
1033
+ // (asks) is a question routed to sp-protocol / sp-rnd. Fixture-only: no
1034
+ // capture sets a defer hook.
1035
+ const deferredToolUse = isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
1036
+ // `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
1037
+ // API error that ended the turn. It already decides `retriable` on an
1038
+ // is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
1039
+ // the census allowlist's "carry candidate the first time an error seed
1040
+ // surfaces it" (sp-probe's api-error-auth seed: 401). Absent or null ⇒ no key.
1041
+ const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1042
+ // `stop_reason` on a result that closes as turn.error: turn.error has no
1043
+ // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1044
+ // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1045
+ // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1046
+ const stopReason = closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
742
1047
  const payload = {
743
1048
  ...(typeof msg.fast_mode_disabled_reason === "string"
744
1049
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -753,17 +1058,56 @@ function resultMetaPayload(msg) {
753
1058
  ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
754
1059
  ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
755
1060
  ...(subagentStats !== undefined ? { subagentStats } : {}),
1061
+ ...(origin !== undefined ? { origin } : {}),
1062
+ ...(deferredToolUse !== undefined ? { deferredToolUse } : {}),
1063
+ ...(apiErrorStatus !== undefined ? { apiErrorStatus } : {}),
1064
+ ...(stopReason !== undefined ? { stopReason } : {}),
756
1065
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
757
1066
  };
758
1067
  return Object.keys(payload).length > 0 ? payload : undefined;
759
1068
  }
1069
+ // A result frame's turn usage, or undefined when the frame's usage trio is not
1070
+ // the shape `mapTurnUsage` dereferences. Both result arms are
1071
+ // discriminant-validated only, so every call goes through this guard (Tenet 6:
1072
+ // a malformed frame must not throw out of push()); absent ⇒ no usage key.
1073
+ // The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
1074
+ // object and its minimal real shape (numeric input/output token counts, so an
1075
+ // empty `usage: {}` stays "no usage" as before), the `modelUsage` object and
1076
+ // each of its entries (`mapModelUsage`), and `total_cost_usd`.
1077
+ // `server_tool_use` is NOT required: `serverToolRequestCount` reads it totally,
1078
+ // so a leaner producer that omits it keeps the rest of its usage.
1079
+ function guardedTurnUsage(msg) {
1080
+ const raw = msg;
1081
+ if (!isJsonObject(raw))
1082
+ return undefined;
1083
+ const rawUsage = raw["usage"];
1084
+ const rawModelUsage = raw["modelUsage"];
1085
+ return isJsonObject(rawUsage) &&
1086
+ typeof rawUsage["input_tokens"] === "number" &&
1087
+ typeof rawUsage["output_tokens"] === "number" &&
1088
+ isJsonObject(rawModelUsage) &&
1089
+ Object.values(rawModelUsage).every(isJsonObject) &&
1090
+ typeof raw["total_cost_usd"] === "number"
1091
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
1092
+ : undefined;
1093
+ }
1094
+ /** 64 random bits as 16 hex chars: the default per-invoke fallback id stem
1095
+ * (vercel-ai's mintInvokeNonce). */
1096
+ function mintInvokeNonce() {
1097
+ const bytes = new Uint8Array(8);
1098
+ globalThis.crypto.getRandomValues(bytes);
1099
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1100
+ }
760
1101
  /**
761
- * Build a stateful Claude-facet normalizer over a fresh {@link StreamAssembler}.
762
- * Each `push(native)` validates `native` → `SDKMessage`, drives the engine via
763
- * primitive calls, and drains the buffered `AgEvent[]`. `flush()` closes any
764
- * dangling open message (none, in Claude's complete-message model) and drains.
1102
+ * The inner Claude-facet normalizer over a fresh {@link StreamAssembler}: each
1103
+ * `push(native)` validates `native` → `SDKMessage`, drives the engine via
1104
+ * primitive calls, and drains the buffered `AgEvent[]`; `flush()` closes any
1105
+ * dangling open message and drains. `createClaudeNormalizer` wraps it in core's
1106
+ * withAtomicPush. It must stay deterministic (no clock, no randomness): a
1107
+ * rebuild re-drives it from the journal. Its one invoke-unique input, the
1108
+ * fallback id stem, comes from the caller, which mints and holds it.
765
1109
  */
766
- export function createClaudeNormalizer(options = {}) {
1110
+ function createInnerClaudeNormalizer(options, invokeStem) {
767
1111
  const a = new StreamAssembler();
768
1112
  // Task 8c leg 4 (guuey capstone finding A): the wire-visible `parentTurnId`
769
1113
  // label passed to subagent.start/.done (`turn_${parent_tool_use_id}`) is a
@@ -774,6 +1118,141 @@ export function createClaudeNormalizer(options = {}) {
774
1118
  // sub-session's own assistant arm at subagent.start time, so a later inner
775
1119
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
776
1120
  const subagentTurnByParentToolUseId = new Map();
1121
+ // INV-TURN (SPEC:743; sp-protocol ruling B, 2026-09-23): ONE turnId names
1122
+ // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1123
+ // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1124
+ // or a stream `message_start`) in the ordinary case, or the frame's own
1125
+ // `uuid` when a notice or a result opens it (a result-only turn). The id is
1126
+ // - unique per turn, across the invokes of a resumed session too (a resume
1127
+ // keeps `session_id` unless `forkSession` is set, so the old
1128
+ // `turn_${session_id}` collided across invokes; message ids never repeat);
1129
+ // - deterministic from the wire, so the same native replays to the same ids;
1130
+ // - known at turn.start, since the opening frame carries it;
1131
+ // - `turn_`-prefixed.
1132
+ // Open from the first frame that needs a turn; the turn's result frame
1133
+ // (either arm) closes it and clears it, so the next frame opens a new one.
1134
+ //
1135
+ // Two guards keep an id naming ONE turn even on odd wire:
1136
+ // - a CLOSED id is never reopened: a late frame reusing a closed turn's
1137
+ // message id opens its turn under its own frame uuid instead;
1138
+ // - `isSDKMessage` validates only discriminants, so a missing or non-string
1139
+ // id/uuid falls back to a positional `turn_<stem>_frame_<n>` rather than a
1140
+ // shared `turn_undefined`. The stem is per invoke (DC-10: a bare
1141
+ // `turn_frame_<n>` repeated across the invokes one Reducer folds), and the
1142
+ // counter is deterministic from the wire, so an atomic-push rebuild
1143
+ // reproduces every delivered id.
1144
+ // Nested (subagent) frames never open or name a top-level turn.
1145
+ let openTopTurnId;
1146
+ const closedTopTurnIds = new Set();
1147
+ let framesSeen = 0;
1148
+ function mintId(candidate) {
1149
+ return typeof candidate === "string" && candidate.length > 0 ? `turn_${candidate}` : undefined;
1150
+ }
1151
+ function topTurnId(openingId, frameUuid) {
1152
+ if (openTopTurnId === undefined) {
1153
+ const byId = mintId(openingId);
1154
+ const byUuid = mintId(frameUuid);
1155
+ openTopTurnId =
1156
+ byId !== undefined && !closedTopTurnIds.has(byId)
1157
+ ? byId
1158
+ : byUuid !== undefined && !closedTopTurnIds.has(byUuid)
1159
+ ? byUuid
1160
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1161
+ }
1162
+ return openTopTurnId;
1163
+ }
1164
+ // The result frame closes the open turn (or, for a result-only turn, the one
1165
+ // it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
1166
+ // notice or stream opened it: the CL-09 result-only API-error path, a
1167
+ // startup-failure result, a local-command result) is OPENED here with an
1168
+ // explicit turn.start before anything else the result emits (INV-TURN,
1169
+ // SPEC:743: every turn is opened by exactly one turn.start and closed by
1170
+ // exactly one terminal; sp-protocol, 2026-09-23). Through the B commit such a
1171
+ // turn was only closed, and reduce() minted a stub record whose threadId was
1172
+ // the turnId. An open turn already has its turn.start (openMessage).
1173
+ function closingTopTurnId(resultUuid, sessionId) {
1174
+ let turnId = openTopTurnId;
1175
+ if (turnId === undefined) {
1176
+ turnId = topTurnId(resultUuid, undefined);
1177
+ a.openTurn(turnId, options.threadId ?? sessionId);
1178
+ }
1179
+ openTopTurnId = undefined;
1180
+ closedTopTurnIds.add(turnId);
1181
+ return turnId;
1182
+ }
1183
+ // A NESTED (subagent) turn is one per subagent run, keyed by the spawning
1184
+ // `parent_tool_use_id`: `turn_` + that run's first nested message id. Through
1185
+ // 0.6.4 it was `turn_${session_id}` too, which merged every subagent run of a
1186
+ // session into one nested turn (and, if a subagent's frames carry the
1187
+ // parent's session_id, collided with the top-level turn itself). It must
1188
+ // never equal the synthetic `parentTurnId` label `turn_${parent_tool_use_id}`
1189
+ // (guuey capstone finding A), and a message id never does.
1190
+ function nestedTurnId(parentToolUseId, firstMessageId, frameUuid) {
1191
+ const known = subagentTurnByParentToolUseId.get(parentToolUseId);
1192
+ if (known !== undefined && !closedRuns.has(parentToolUseId))
1193
+ return known;
1194
+ // A new run, or a frame arriving for a run that already CLOSED: mint a fresh
1195
+ // id (a closed nested id is never reopened, as for top-level turns).
1196
+ const byId = mintId(firstMessageId);
1197
+ const byUuid = mintId(frameUuid);
1198
+ const minted = byId !== undefined && !closedNestedTurnIds.has(byId)
1199
+ ? byId
1200
+ : byUuid !== undefined && !closedNestedTurnIds.has(byUuid)
1201
+ ? byUuid
1202
+ : `turn_${invokeStem()}_frame_${framesSeen}`;
1203
+ closedRuns.delete(parentToolUseId);
1204
+ subagentTurnByParentToolUseId.set(parentToolUseId, minted);
1205
+ return minted;
1206
+ }
1207
+ const openRuns = new Map();
1208
+ const closedRuns = new Set();
1209
+ const closedNestedTurnIds = new Set();
1210
+ // Nested turnId → its FIRST API error frame's close (released at run close).
1211
+ const nestedStashedErrors = new Map();
1212
+ // task_started: task_id → the spawning tool_use_id, for a task_notification
1213
+ // that carries only its task_id.
1214
+ const toolUseIdByTaskId = new Map();
1215
+ // The ids of every Agent (or legacy Task) tool call seen in this invoke. Only
1216
+ // a result for one of these can carry an AgentOutput: a third-party tool whose
1217
+ // result happens to hold an `agentId` (a CRM, a ticketing system, any agent
1218
+ // registry) is not Anthropic's Agent run report (sp-cto's read of f2c75d8).
1219
+ const agentCallIds = new Set();
1220
+ function openRun(parentToolUseId, turnId, parentTurnId) {
1221
+ if (openRuns.has(parentToolUseId))
1222
+ return;
1223
+ openRuns.set(parentToolUseId, { turnId, parentTurnId });
1224
+ a.subagentStart(turnId, parentTurnId);
1225
+ }
1226
+ function closeRun(parentToolUseId, close) {
1227
+ const run = openRuns.get(parentToolUseId);
1228
+ if (run === undefined)
1229
+ return;
1230
+ openRuns.delete(parentToolUseId);
1231
+ closedRuns.add(parentToolUseId);
1232
+ closedNestedTurnIds.add(run.turnId);
1233
+ const stashed = nestedStashedErrors.get(run.turnId);
1234
+ nestedStashedErrors.delete(run.turnId);
1235
+ if (stashed !== undefined) {
1236
+ a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1237
+ }
1238
+ else if (close.kind === "success") {
1239
+ a.closeTurnDone(run.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
1240
+ }
1241
+ else if (close.kind === "error") {
1242
+ a.closeTurnError(run.turnId, { message: close.message, ...(close.code !== undefined ? { code: close.code } : {}) });
1243
+ }
1244
+ else {
1245
+ a.emit({ type: "turn.abort", turnId: run.turnId, reason: close.reason });
1246
+ }
1247
+ a.subagentDone(run.turnId, run.parentTurnId);
1248
+ }
1249
+ // Flush only: every run still open, innermost (latest-opened) first, as
1250
+ // INV-FLUSH orders its own closes.
1251
+ function abortOpenRuns() {
1252
+ for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1253
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1254
+ }
1255
+ }
777
1256
  // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
778
1257
  // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
779
1258
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
@@ -785,6 +1264,17 @@ export function createClaudeNormalizer(options = {}) {
785
1264
  // convention" per the adaptation brief.
786
1265
  const messageIdsByUuid = new Map();
787
1266
  const deniedLiveByToolUseId = new Map();
1267
+ // Every toolCallId that already got its FINAL tool.done in this invoke. The
1268
+ // result's permission_denials aggregate skips these: re-emitting tool.start +
1269
+ // tool.done{denied} for a call already closed is a duplicate start and a second
1270
+ // final tool.done (INV-BLOCK; rd-14 P14 parks it; the M22 double-fold hazard).
1271
+ const closedToolCallIds = new Set();
1272
+ // SDK message id → the `diagnostics` value already carried for it (see the
1273
+ // assistant branch): one carry per response, not one per frame.
1274
+ const diagnosticsCarried = new Map();
1275
+ // rd-15: top-level turnId → the closing response's non-null stop_details (credit
1276
+ // tokens stripped) and the message it describes, emitted on that turn's turn.done.
1277
+ const stopDetailsByTurn = new Map();
788
1278
  // The live denial's diagnostic fields, camelCased — the providerMetadata bag
789
1279
  // on the enriched `<turnId>:denials` tool.done. undefined when the live
790
1280
  // frame carried none of them (no empty bag).
@@ -818,8 +1308,10 @@ export function createClaudeNormalizer(options = {}) {
818
1308
  // (cf. `<turnId>:denials`, `<toolCallId>:result`). Nothing is fabricated: the
819
1309
  // blocks, their order and their content are the SDK's own.
820
1310
  const lifecyclesBySdkId = new Map();
821
- /** Seal the deferred message (and its subagent bracket), if one is open. */
822
- function closePendingMessage() {
1311
+ /** Seal the deferred message, if one is open (a run's bracket closes separately; see `openRun`).
1312
+ * `atFlush`: the stream ENDED here, so open stream blocks close without minting content
1313
+ * (INV-FLUSH (3), draft.4; see `finalizeStreamBlock`). */
1314
+ function closePendingMessage(atFlush = false) {
823
1315
  if (pending === undefined)
824
1316
  return;
825
1317
  const p = pending;
@@ -830,12 +1322,12 @@ export function createClaudeNormalizer(options = {}) {
830
1322
  // produced) so no lifecycle dangles under the seal.
831
1323
  if (p.streamBlocks.size > 0) {
832
1324
  for (const idx of [...p.streamBlocks.keys()].sort((x, y) => x - y)) {
833
- finalizeStreamBlock(p, idx);
1325
+ finalizeStreamBlock(p, idx, atFlush);
834
1326
  }
835
1327
  }
836
1328
  a.closeMessage(p.emittedId, p.usage);
837
- if (p.parentTurnId !== undefined)
838
- a.subagentDone(p.turnId, p.parentTurnId);
1329
+ // The subagent bracket is per RUN now (see `openRun`), so sealing a nested
1330
+ // message no longer closes its nested turn.
839
1331
  }
840
1332
  // ─── workspace#7: stream_event mapping helpers ──────────────────────────────
841
1333
  // Unmappable stream frames — an orphan delta after a fold-binding frame
@@ -843,7 +1335,7 @@ export function createClaudeNormalizer(options = {}) {
843
1335
  // ride the uniform lossless carry (`kind` is the frame's own discriminant,
844
1336
  // per the ext.anthropic.frame convention). Nothing is silently dropped.
845
1337
  function carryStreamFrame(msg) {
846
- a.emitExt("anthropic", "frame", { kind: "stream_event", frame: JsonValue.parse(msg) });
1338
+ a.emitExt("anthropic", "frame", { kind: "stream_event", frame: carryVerbatim(msg) });
847
1339
  }
848
1340
  // `ttft_ms` (time to first token, on the partial envelope) has no core home —
849
1341
  // it rides the message.metadata merge channel, wire name verbatim (the
@@ -898,18 +1390,39 @@ export function createClaudeNormalizer(options = {}) {
898
1390
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
899
1391
  // (same end-then-opaque order as the complete arm), the MANDATORY
900
1392
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
901
- function finalizeStreamBlock(p, index) {
1393
+ // `atFlush` (INV-FLUSH (3), draft.4; the founder's fold/flush ruling, "snapshot
1394
+ // fold + honest flush; opaque at flush forbidden"; sp-claude's leg C1): the
1395
+ // stream ENDED with this block open, so the close lands NO new content. The
1396
+ // lifecycle closes stay (text.end with its already-received citations,
1397
+ // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
1398
+ // (it is authoritative, and a truncated partial_json would mint an input the
1399
+ // model never finished), no reasoning.opaque (a signature is replay-load-
1400
+ // bearing, and the turn is aborted anyway), no compaction content.block, and
1401
+ // no `phase` on reasoning.end. A binding frame that seals the message
1402
+ // mid-stream (not a flush) still finalizes as its content_block_stop would.
1403
+ function finalizeStreamBlock(p, index, atFlush = false) {
902
1404
  const b = p.streamBlocks.get(index);
903
1405
  if (b === undefined)
904
1406
  return;
905
1407
  p.streamBlocks.delete(index);
906
1408
  const messageId = p.emittedId;
1409
+ if (atFlush) {
1410
+ if (b.kind === "text")
1411
+ a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
1412
+ else if (b.kind === "reasoning")
1413
+ a.reasoningEnd(b.id, messageId, undefined);
1414
+ return;
1415
+ }
907
1416
  switch (b.kind) {
908
1417
  case "text":
909
1418
  a.textEnd(b.id, messageId, b.citations.length > 0 ? { citations: b.citations } : undefined);
910
1419
  return;
911
1420
  case "reasoning":
912
- a.reasoningEnd(b.id, messageId);
1421
+ // draft.4 `phase` for a STREAMED narration block: known only once the
1422
+ // complete frame arrived (after the start), so it rides reasoning.end
1423
+ // (§5 phase timing), and only if the block's text is non-empty
1424
+ // (§8.0 item 27). Never a post-seal event.
1425
+ a.reasoningEnd(b.id, messageId, b.narration && b.hasText ? { phase: "interim" } : undefined);
913
1426
  if (b.redacted !== undefined) {
914
1427
  a.reasoningOpaque(b.id, messageId, { kind: "redacted", value: b.redacted, provider: "anthropic" });
915
1428
  }
@@ -930,7 +1443,9 @@ export function createClaudeNormalizer(options = {}) {
930
1443
  input = b.startInput;
931
1444
  }
932
1445
  }
933
- a.toolArgsAssembled(b.toolCallId, input);
1446
+ // The stream's input IS the API's own (partial_json), so the wire input
1447
+ // is carried only if it still differs from it (see wireInputFor).
1448
+ a.toolArgsAssembled(b.toolCallId, input, wireInputFields(b.wireInput !== undefined && !jsonEqual(b.wireInput, input) ? b.wireInput : undefined));
934
1449
  return;
935
1450
  }
936
1451
  case "compaction":
@@ -957,7 +1472,9 @@ export function createClaudeNormalizer(options = {}) {
957
1472
  const ev = msg.event;
958
1473
  if (ev.type === "message_start") {
959
1474
  const m = ev.message;
960
- const turnId = turnIdFor(msg.session_id, m.id);
1475
+ const turnId = msg.parent_tool_use_id !== null
1476
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1477
+ : topTurnId(m.id, msg.uuid);
961
1478
  const parentTurnId = msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
962
1479
  // Same continuation test as the complete arm: a message_start naming the
963
1480
  // message already open just joins it (and marks it streamed).
@@ -978,8 +1495,7 @@ export function createClaudeNormalizer(options = {}) {
978
1495
  // lifecycle counter, same emittedId derivation — so the complete frame
979
1496
  // that follows JOINS this lifecycle and is content-suppressed.
980
1497
  if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
981
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
982
- a.subagentStart(turnId, parentTurnId);
1498
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
983
1499
  }
984
1500
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
985
1501
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -993,6 +1509,7 @@ export function createClaudeNormalizer(options = {}) {
993
1509
  streamed: true,
994
1510
  streamBlocks: new Map(),
995
1511
  ttftCarried: false,
1512
+ framedThrough: 0,
996
1513
  turnBindingCarried: false,
997
1514
  };
998
1515
  pending = open;
@@ -1054,14 +1571,21 @@ export function createClaudeNormalizer(options = {}) {
1054
1571
  case "thinking": {
1055
1572
  const id = `${messageId}:reasoning:${index}`;
1056
1573
  a.reasoningStart(id, messageId);
1057
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: block.signature, redacted: undefined });
1574
+ p.streamBlocks.set(index, {
1575
+ kind: "reasoning",
1576
+ id,
1577
+ signature: block.signature,
1578
+ redacted: undefined,
1579
+ hasText: false,
1580
+ narration: false,
1581
+ });
1058
1582
  return;
1059
1583
  }
1060
1584
  case "redacted_thinking": {
1061
1585
  // Arrives complete (never delta'd); end + the redacted opaque land at stop.
1062
1586
  const id = `${messageId}:reasoning:${index}`;
1063
1587
  a.reasoningStart(id, messageId);
1064
- p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data });
1588
+ p.streamBlocks.set(index, { kind: "reasoning", id, signature: "", redacted: block.data, hasText: false, narration: false });
1065
1589
  return;
1066
1590
  }
1067
1591
  case "tool_use":
@@ -1105,6 +1629,7 @@ export function createClaudeNormalizer(options = {}) {
1105
1629
  // Arrives complete inside the start frame — same tool.done mapping as
1106
1630
  // the complete arm's mcp_tool_result case.
1107
1631
  const outcome = block.is_error ? "error" : "ok";
1632
+ closedToolCallIds.add(block.tool_use_id);
1108
1633
  a.toolDone({
1109
1634
  toolCallId: block.tool_use_id,
1110
1635
  content: mcpToolResultContentToAgBlocks(block.content),
@@ -1121,7 +1646,7 @@ export function createClaudeNormalizer(options = {}) {
1121
1646
  a.contentBlock(messageId, {
1122
1647
  type: "provider-raw",
1123
1648
  vendor: "anthropic",
1124
- raw: JsonValue.parse(block),
1649
+ raw: carryVerbatim(block),
1125
1650
  });
1126
1651
  p.streamBlocks.set(index, { kind: "emitted" });
1127
1652
  return;
@@ -1141,17 +1666,35 @@ export function createClaudeNormalizer(options = {}) {
1141
1666
  return;
1142
1667
  }
1143
1668
  if (d.type === "thinking_delta" && b.kind === "reasoning") {
1669
+ if (typeof d.thinking === "string" && d.thinking.length > 0)
1670
+ b.hasText = true;
1144
1671
  // Claude Code stamps a RUNTIME-ONLY `estimated_tokens` (number | null;
1145
1672
  // undeclared on BetaThinkingDelta) on each thinking_delta. Under
1146
1673
  // Fable 5.1's default `display: omitted` the `thinking` text is '' and
1147
- // that estimate is the delta's entire payload — carried verbatim as
1148
- // providerMetadata (wire name kept; null kept: "no estimate yet" is a
1149
- // real value). Absent key ⇒ no providerMetadata, byte-identical.
1674
+ // that estimate is the delta's entire payload — carried verbatim (wire
1675
+ // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
1676
+ // no bag, byte-identical.
1677
+ //
1678
+ // X5 (sp-rnd, 2026-09-23): it rides the delta's host-only `_meta`, not
1679
+ // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
1680
+ // that must round-trip to the provider), and the Messages API never
1681
+ // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
1682
+ // on start events, so the estimate is now LIVE-ONLY (it used to fold
1683
+ // last-value-wins onto the reasoning block) — the same standing as its
1684
+ // `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
1685
+ // consumer read the folded value (guuey/ggui checked via sp-team-main).
1686
+ // `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
1687
+ // primitive (the reasoning.start precedent in `emitAssistantBlock`), and
1688
+ // the sugar's only extra step, de-cumulation, is a pass-through for a
1689
+ // non-cumulative delta like this one.
1150
1690
  const rawDelta = d;
1151
- const estimate = isJsonObject(rawDelta) && "estimated_tokens" in rawDelta
1152
- ? AgProviderMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] })
1153
- : undefined;
1154
- a.reasoningDelta(b.id, messageId, d.thinking, estimate !== undefined ? { providerMetadata: estimate } : undefined);
1691
+ if (isJsonObject(rawDelta) && "estimated_tokens" in rawDelta) {
1692
+ const estimate = AgMeta.parse({ estimated_tokens: rawDelta["estimated_tokens"] });
1693
+ a.emit({ type: "reasoning.delta", id: b.id, messageId, delta: d.thinking, _meta: estimate });
1694
+ }
1695
+ else {
1696
+ a.reasoningDelta(b.id, messageId, d.thinking);
1697
+ }
1155
1698
  return;
1156
1699
  }
1157
1700
  if (d.type === "input_json_delta" && b.kind === "tool") {
@@ -1218,7 +1761,14 @@ export function createClaudeNormalizer(options = {}) {
1218
1761
  // A future stream event type — lossless carry.
1219
1762
  carryStreamFrame(msg);
1220
1763
  }
1221
- function registerUuid(uuid, ids) {
1764
+ // The turn each retractable message was emitted under, so a retraction's
1765
+ // `message.remove` names its OWNER explicitly (INV-OWNER) instead of taking
1766
+ // the assembler's last-turn backfill, which overlapping subagent runs can skew.
1767
+ const turnByMessageId = new Map();
1768
+ function registerUuid(uuid, ids, turnId) {
1769
+ if (turnId !== undefined)
1770
+ for (const id of ids)
1771
+ turnByMessageId.set(id, turnId);
1222
1772
  if (uuid === undefined || ids.length === 0)
1223
1773
  return;
1224
1774
  const existing = messageIdsByUuid.get(uuid);
@@ -1242,14 +1792,63 @@ export function createClaudeNormalizer(options = {}) {
1242
1792
  if (ids === undefined)
1243
1793
  continue;
1244
1794
  for (const id of ids) {
1245
- a.emit({ type: "message.remove", id });
1795
+ const owner = turnByMessageId.get(id);
1796
+ a.emit({ type: "message.remove", id, ...(owner !== undefined ? { turnId: owner } : {}) });
1246
1797
  }
1247
1798
  }
1248
1799
  }
1800
+ // Emit a result's permission_denials as tool.start + tool.done denied pairs,
1801
+ // inside a dedicated carrier message: the assistant message is already
1802
+ // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
1803
+ // closed turns. BOTH result arms call it, at the same point (after the seal
1804
+ // and the run closes, before result-meta and the close). Through 0.6.4 only
1805
+ // the success arm did, so an error-subtype result (SDKResultError declares
1806
+ // permission_denials too, e.g. error_max_turns after a denied tool) dropped
1807
+ // its denials.
1808
+ function emitDenialsCarrier(turnId, denials, sessionId) {
1809
+ // Skip every denial whose call already has its final tool.done in this
1810
+ // invoke: a harness-stamped denied tool_result (the user branch), an
1811
+ // mcp_tool_result, or an earlier carrier (a repeated id, in this list or a
1812
+ // later result's). A denial for an id not yet closed still gets its pair.
1813
+ const fresh = [];
1814
+ for (const d of denials) {
1815
+ if (closedToolCallIds.has(d.tool_use_id))
1816
+ continue;
1817
+ closedToolCallIds.add(d.tool_use_id);
1818
+ fresh.push(d);
1819
+ }
1820
+ if (fresh.length > 0) {
1821
+ const denialMsgId = `${turnId}:denials`;
1822
+ a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? sessionId });
1823
+ for (const denial of fresh) {
1824
+ // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
1825
+ // "handled" via existing-home mapping): enrich with the live
1826
+ // standalone denial notice recorded above (keyed by tool_use_id),
1827
+ // when one preceded this aggregate — the actual rejection text
1828
+ // returned to the model, plus decision-reason/agent-id context —
1829
+ // rather than leaving a bare empty-content stub. No second
1830
+ // tool.start/tool.done pair is ever emitted for the live frame
1831
+ // itself (see the dedicated `permission_denied` branch below).
1832
+ const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1833
+ const liveFields = liveDenialMeta(live);
1834
+ const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1835
+ a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1836
+ a.toolDone({
1837
+ toolCallId: denial.tool_use_id,
1838
+ content: live !== undefined ? [{ type: "text", text: live.message }] : [],
1839
+ outcome: "denied",
1840
+ ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
1841
+ });
1842
+ }
1843
+ a.closeMessage(denialMsgId);
1844
+ }
1845
+ }
1249
1846
  function drive(msg) {
1250
1847
  if (msg.type === "assistant") {
1251
1848
  const m = msg.message;
1252
- const turnId = turnIdFor(msg.session_id, m.id);
1849
+ const turnId = msg.parent_tool_use_id !== null
1850
+ ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1851
+ : topTurnId(m.id, msg.uuid);
1253
1852
  const parentTurnId = msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
1254
1853
  // guuey#26: does this frame CONTINUE the message left open by the previous
1255
1854
  // frame? Same SDK message id, same turn, same nesting — anything else is a
@@ -1308,7 +1907,7 @@ export function createClaudeNormalizer(options = {}) {
1308
1907
  // Structured plain-JSON shape per its own doc (evolves additively);
1309
1908
  // JsonValue.parse both validates that invariant and satisfies the
1310
1909
  // wrapper-meta channel's type without an unchecked cast.
1311
- wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1910
+ wrapperMetaRaw["context_usage"] = carryVerbatim(msg.context_usage);
1312
1911
  }
1313
1912
  // `usage_report` (0.3.273): the structured twin of the /usage report,
1314
1913
  // riding the synthetic assistant message that delivers its text (session
@@ -1322,7 +1921,7 @@ export function createClaudeNormalizer(options = {}) {
1322
1921
  // claude.ai-subscriber sessions", and the capture harness authenticates
1323
1922
  // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1324
1923
  if (msg.usage_report !== undefined) {
1325
- wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
1924
+ wrapperMetaRaw["usage_report"] = carryVerbatim(msg.usage_report);
1326
1925
  }
1327
1926
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1328
1927
  // the indexes of THIS frame's content blocks that are user-facing narration
@@ -1340,6 +1939,28 @@ export function createClaudeNormalizer(options = {}) {
1340
1939
  if (narrationBlockIndexes !== undefined) {
1341
1940
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1342
1941
  }
1942
+ // `message.diagnostics` (a Messages API response field, first seen live on
1943
+ // sp-probe's defer-tool-sonnet5-resume-unavailable, 7c6880f): per-response
1944
+ // diagnostics, there `{cache_miss_reason: {type: "tools_changed",
1945
+ // cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
1946
+ // Response-only (never sent back on replay), so it rides host-only `_meta`
1947
+ // (SPEC §12, the X5 split), verbatim with its wire name. Undeclared on
1948
+ // @anthropic-ai/sdk 0.93.0's BetaMessage, so read through the JSON
1949
+ // boundary; null (its usual value) carries nothing. It is per RESPONSE,
1950
+ // and the CLI repeats the same message object on every frame of a
1951
+ // multi-frame message, so it is carried once per SDK message id (again
1952
+ // only if the value changes).
1953
+ const rawMessage = m;
1954
+ const diagnostics = isJsonObject(rawMessage) && isJsonObject(rawMessage["diagnostics"])
1955
+ ? carryVerbatim(rawMessage["diagnostics"])
1956
+ : undefined;
1957
+ if (diagnostics !== undefined) {
1958
+ const diagnosticsKey = JSON.stringify(diagnostics);
1959
+ if (diagnosticsCarried.get(m.id) !== diagnosticsKey) {
1960
+ wrapperMetaRaw["diagnostics"] = diagnostics;
1961
+ diagnosticsCarried.set(m.id, diagnosticsKey);
1962
+ }
1963
+ }
1343
1964
  // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1344
1965
  // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1345
1966
  // The CLI stamps them on the synthetic API-error assistant frame, the one
@@ -1366,31 +1987,50 @@ export function createClaudeNormalizer(options = {}) {
1366
1987
  wrapperMetaRaw["api_error"] = apiError;
1367
1988
  const apiErrorParams = rawAssistant["api_error_params"];
1368
1989
  if (isJsonObject(apiErrorParams))
1369
- wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
1990
+ wrapperMetaRaw["api_error_params"] = carryVerbatim(apiErrorParams);
1370
1991
  }
1371
1992
  const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1372
1993
  if (assistantApiErrorCode !== undefined) {
1373
1994
  wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1374
1995
  }
1996
+ // rd-15 (founder ruling 2026-09-24: defer the neutral remedy field, fix the
1997
+ // vendor carries; a 0.7.0 carry with zero golden moves). Three more
1998
+ // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
1999
+ // 0.3.280 (so read through the JSON boundary), carried verbatim under their
2000
+ // wire names on the frame's first block's host-only `_meta` (the X5 route,
2001
+ // which folds onto block._meta; never providerMetadata, SPEC §12):
2002
+ // - `error_details`: "Raw API error message: preserves details (e.g.
2003
+ // prompt-too-long token counts) that user-facing content discards"
2004
+ // (the CLI's own schema doc; the same datum is typed on the StopFailure
2005
+ // hook input, sdk.d.ts:9154);
2006
+ // - `advisor_model`: "Advisor model that produced this message, when
2007
+ // applicable";
2008
+ // - `attribution_agent`: "agent name parsed from querySource".
2009
+ // A non-string value is not carried. No committed native carries any of
2010
+ // them, so no golden moves.
2011
+ if (isJsonObject(rawAssistant)) {
2012
+ for (const key of ["error_details", "advisor_model", "attribution_agent"]) {
2013
+ const v = rawAssistant[key];
2014
+ if (typeof v === "string")
2015
+ wrapperMetaRaw[key] = v;
2016
+ }
2017
+ }
1375
2018
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1376
2019
  // the bag below, once `open` is known — their once-per-message flag is
1377
2020
  // shared with the stream arm's carry.
1378
- // A non-null parent_tool_use_id ⇒ this assistant message is a NESTED turn
1379
- // (subagent). subagent.start is the SOLE nested-turn opener (spec §4/§5) and
1380
- // seeds the turn so openMessage does NOT synthesize a duplicate turn.start.
1381
- // guuey#26: a CONTINUATION frame joins the message (and, when nested, the
1382
- // subagent bracket) the previous frame opened — no second subagent.start,
1383
- // no second message.start.
2021
+ // A non-null parent_tool_use_id ⇒ this assistant message belongs to a
2022
+ // NESTED turn (subagent run). subagent.start is the SOLE nested-turn opener
2023
+ // (spec §4/§5), emitted once per run by `openRun`, and seeds the turn so
2024
+ // openMessage does NOT synthesize a duplicate turn.start. guuey#26: a
2025
+ // CONTINUATION frame joins the message the previous frame opened — no
2026
+ // second message.start.
1384
2027
  let open;
1385
2028
  if (continued !== undefined) {
1386
2029
  open = continued;
1387
2030
  }
1388
2031
  else {
1389
- if (parentTurnId !== undefined) {
1390
- if (msg.parent_tool_use_id !== null) {
1391
- subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
1392
- }
1393
- a.subagentStart(turnId, parentTurnId);
2032
+ if (parentTurnId !== undefined && msg.parent_tool_use_id !== null) {
2033
+ openRun(msg.parent_tool_use_id, turnId, parentTurnId);
1394
2034
  }
1395
2035
  const lifecycle = lifecyclesBySdkId.get(m.id) ?? 0;
1396
2036
  lifecyclesBySdkId.set(m.id, lifecycle + 1);
@@ -1408,6 +2048,7 @@ export function createClaudeNormalizer(options = {}) {
1408
2048
  streamed: false,
1409
2049
  streamBlocks: new Map(),
1410
2050
  ttftCarried: false,
2051
+ framedThrough: 0,
1411
2052
  turnBindingCarried: false,
1412
2053
  };
1413
2054
  pending = open;
@@ -1420,6 +2061,22 @@ export function createClaudeNormalizer(options = {}) {
1420
2061
  });
1421
2062
  }
1422
2063
  const messageId = open.emittedId;
2064
+ // rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
2065
+ // {type, category, explanation, fallbacks?}) is carried verbatim on its
2066
+ // turn's closing turn.done.messageMetadata, which folds onto the message it
2067
+ // names (SPEC §5 turn.done row). The CLOSING response's value only: a later
2068
+ // response of the turn without one clears it. Every `fallback_credit_token`,
2069
+ // at any depth, is deleted first (a provider credit token is never
2070
+ // emitted). Null (every committed golden) carries nothing. Keyed by turn,
2071
+ // so a nested (subagent) response never touches its parent's entry, and
2072
+ // only top-level turns close with turn.done.
2073
+ const stopDetails = m.stop_details;
2074
+ if (isJsonObject(stopDetails)) {
2075
+ stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
2076
+ }
2077
+ else if (stopDetailsByTurn.get(turnId)?.messageId !== messageId) {
2078
+ stopDetailsByTurn.delete(turnId);
2079
+ }
1423
2080
  // - `user_message_uuid` (0.3.258): the client uuid of the user message
1424
2081
  // this turn answers, stamped on the turn's FIRST reply frame only
1425
2082
  // (wrapper-level sibling per its own doc — never inside
@@ -1461,13 +2118,76 @@ export function createClaudeNormalizer(options = {}) {
1461
2118
  wrapperMetaRaw["resume_reason"] = resumeReason;
1462
2119
  }
1463
2120
  }
1464
- const wrapperMeta = Object.keys(wrapperMetaRaw).length > 0 ? AgProviderMeta.parse(wrapperMetaRaw) : undefined;
2121
+ // X5 (sp-rnd re-cut, 2026-09-23): the bag mixes two kinds of fact. SPEC
2122
+ // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2123
+ // round-trip to the provider) and `_meta` host-only side metadata.
2124
+ // `narration_block_indexes` and the API-error triad are CLI-wrapper facts
2125
+ // the Messages API never consumes, so where the bag anchors on a BLOCK they
2126
+ // ride that block's start event `_meta` (`reduce()` folds it onto
2127
+ // `block._meta`, keeping the per-frame anchoring). The rest keeps
2128
+ // `providerMetadata`. The split is by key, so the combined bag, and the
2129
+ // `message.metadata` path below that uses it, stay byte-identical
2130
+ // (message.metadata is already `AgMeta`).
2131
+ //
2132
+ // Consumer check (sp-team-main, 2026-09-23): ggui has none of these names.
2133
+ // No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
2134
+ // the native frame. guuey asked that the triad move as ONE unit; the
2135
+ // result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
2136
+ const replayRaw = {};
2137
+ const hostRaw = {};
2138
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2139
+ if (HOST_ONLY_WRAPPER_KEYS.has(k))
2140
+ hostRaw[k] = v;
2141
+ else
2142
+ replayRaw[k] = v;
2143
+ }
2144
+ const wrapperMeta = Object.keys(replayRaw).length > 0 ? AgProviderMeta.parse(replayRaw) : undefined;
2145
+ const hostMeta = Object.keys(hostRaw).length > 0 ? AgMeta.parse(hostRaw) : undefined;
2146
+ let anchored = NOTHING_ANCHORED;
1465
2147
  // workspace#7 dedupe: a STREAMED lifecycle already emitted every block
1466
2148
  // incrementally (stream ids reuse the content `index`, identical to the
1467
2149
  // arithmetic below) — this complete frame must not re-synthesize them.
1468
2150
  // Everything below the block loop (wrapper carry via message.metadata,
1469
2151
  // usage, error close, uuid registration) still runs.
1470
2152
  const suppressed = open.streamed;
2153
+ // draft.4 `phase` (§8.0 item 27, a SHOULD per the founder's A.10.5
2154
+ // ruling): a `thinking` block listed in `narration_block_indexes` whose
2155
+ // text is NON-EMPTY is interim narration → `phase:"interim"` on that
2156
+ // reasoning block. A listed empty block (display "omitted") gets none.
2157
+ // The index is FRAME-local. Never inferred from position, text or turn
2158
+ // end; never decoded from the signature; the vendor list itself still
2159
+ // rides host-only `_meta` verbatim (X5).
2160
+ const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2161
+ if (suppressed && narrationIndexes.size > 0) {
2162
+ // STREAMED: the complete frame precedes its blocks' content_block_stop
2163
+ // (CB-13; thinking-fable51 frames [62] signature → [63] frame → [64]
2164
+ // stop), so each listed frame-local index names stream block
2165
+ // `framedThrough + idx` (the frame covers the next blocks after those
2166
+ // earlier frames covered). It is marked only while it is still OPEN;
2167
+ // the phase then rides its reasoning.end, if its streamed text was
2168
+ // non-empty. A block that already sealed stays unmarked, never a
2169
+ // post-seal event and never a neighbouring block.
2170
+ for (const idx of narrationIndexes) {
2171
+ const frameBlock = m.content[idx];
2172
+ const streamBlock = open.streamBlocks.get(open.framedThrough + idx);
2173
+ if (frameBlock?.type === "thinking" && streamBlock?.kind === "reasoning")
2174
+ streamBlock.narration = true;
2175
+ }
2176
+ }
2177
+ if (suppressed) {
2178
+ // STREAMED: record each open tool block's `wire_tool_inputs` entry (the
2179
+ // complete frame precedes the block's content_block_stop, CB-13); its
2180
+ // tool.args.assembled carries it only if it differs from the streamed input.
2181
+ for (let i = 0; i < m.content.length; i++) {
2182
+ const frameBlock = m.content[i];
2183
+ const streamBlock = open.streamBlocks.get(open.framedThrough + i);
2184
+ if (frameBlock !== undefined && isToolUseBlock(frameBlock) && streamBlock?.kind === "tool") {
2185
+ const wire = wireToolInput(msg, frameBlock.id);
2186
+ if (wire !== undefined)
2187
+ streamBlock.wireInput = wire;
2188
+ }
2189
+ }
2190
+ }
1471
2191
  if (!suppressed) {
1472
2192
  // A plain indexed loop, not `.forEach` — see `mcpToolResultContentToAgBlocks`'s
1473
2193
  // doc: `.forEach`'s callback parameter inference degrades to implicit `any`
@@ -1484,16 +2204,48 @@ export function createClaudeNormalizer(options = {}) {
1484
2204
  // (`<id>:text:0` twice would clobber in the fold). The wrapper carry
1485
2205
  // stays anchored to this FRAME's first block: `aborted` /
1486
2206
  // `resumed_from_incomplete_thinking` are per-frame facts.
1487
- emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined);
2207
+ // NON-STREAMED: the marker is known before the first delta, so it
2208
+ // rides reasoning.start (§5 phase timing).
2209
+ const interim = narrationIndexes.has(i) && block.type === "thinking" && typeof block.thinking === "string" && block.thinking.length > 0
2210
+ ? "interim"
2211
+ : undefined;
2212
+ const landed = emitAssistantBlock(a, block, messageId, open.blockIndex + i, i === 0 ? wrapperMeta : undefined, i === 0 ? hostMeta : undefined, interim, isToolUseBlock(block) ? wireInputFor(msg, block.id, block.input) : undefined);
2213
+ if (block.type === "mcp_tool_result")
2214
+ closedToolCallIds.add(block.tool_use_id);
2215
+ if (i === 0)
2216
+ anchored = landed;
1488
2217
  }
1489
2218
  open.blockIndex += m.content.length;
1490
2219
  }
2220
+ open.framedThrough += m.content.length;
2221
+ // Record this frame's Agent/Task calls (the complete frame arrives in both
2222
+ // modes, streamed or not), so their results can be recognized as reports.
2223
+ for (const block of m.content) {
2224
+ if (block.type === "tool_use" && (block.name === "Agent" || block.name === "Task"))
2225
+ agentCallIds.add(block.id);
2226
+ }
1491
2227
  // Block-less frame (e.g. aborted before any content streamed) — or a
1492
2228
  // suppressed one, whose blocks were already sealed by the stream: no
1493
- // first block exists to anchor the wrapper carry — ride message.metadata.
1494
- if ((suppressed || m.content.length === 0) && wrapperMeta !== undefined) {
2229
+ // first block exists to anchor the wrapper carry — ride message.metadata
2230
+ // (the whole combined bag, unchanged).
2231
+ if ((suppressed || m.content.length === 0) && (wrapperMeta !== undefined || hostMeta !== undefined)) {
1495
2232
  a.emit({ type: "message.metadata", messageId, metadata: wrapperMetaRaw });
1496
2233
  }
2234
+ else {
2235
+ // Whatever the first block could not anchor rides the message instead,
2236
+ // in wire order, so it still folds: the host half after a tool call (no
2237
+ // `_meta` on tool.start), and BOTH halves after a compaction, an
2238
+ // mcp_tool_result or a content.block (no providerMetadata slot).
2239
+ const unanchored = {};
2240
+ for (const [k, v] of Object.entries(wrapperMetaRaw)) {
2241
+ const isHost = HOST_ONLY_WRAPPER_KEYS.has(k);
2242
+ if ((isHost && !anchored.host) || (!isHost && !anchored.replay))
2243
+ unanchored[k] = v;
2244
+ }
2245
+ if (Object.keys(unanchored).length > 0) {
2246
+ a.emit({ type: "message.metadata", messageId, metadata: unanchored });
2247
+ }
2248
+ }
1497
2249
  // The seal is DEFERRED (guuey#26) — the next frame may continue this same
1498
2250
  // message id. Usage is message-level and repeated per frame, so the newest
1499
2251
  // frame's copy is the one that rides the eventual `message.end` — field by
@@ -1516,45 +2268,40 @@ export function createClaudeNormalizer(options = {}) {
1516
2268
  // close.
1517
2269
  closePendingMessage();
1518
2270
  const errCode = msg.error;
1519
- // First error frame wins: a turn already carrying a stashed close keeps
1520
- // it (before CL-09's stash, the first error frame closed the turn).
1521
- if (!stashedTurnErrors.has(turnId)) {
1522
- stashedTurnErrors.set(turnId, {
1523
- message: errCode,
1524
- code: errCode,
1525
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1526
- // cousin of rate_limit/server_error) joins the retriable set.
1527
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1528
- // decommissioned model id) is deliberately EXCLUDED: explicit
1529
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1530
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1531
- // deliberate non-retriable: a billing-class code (the account is on
1532
- // hold — a first cousin of `billing_error`, cleared by the account
1533
- // holder, never by re-sending the turn).
1534
- //
1535
- // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1536
- // deliberate non-retriables recorded here for the same reason — an
1537
- // omission must never read as an oversight:
1538
- // - `verification_required`: the request is gated on an out-of-band
1539
- // human step (identity/org verification). Nothing about the turn
1540
- // changes by re-sending it; the block clears only when a person
1541
- // completes the verification.
1542
- // - `cloud_credential_error`: a credential/billing-class failure on
1543
- // the cloud-provider leg (a first cousin of `billing_error` and
1544
- // `account_on_hold`, not of `overloaded`) — a bad, expired or
1545
- // unauthorized credential is exactly as bad on the next attempt.
1546
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1547
- });
2271
+ const retriable = assistantErrorRetriable(errCode);
2272
+ if (msg.parent_tool_use_id !== null) {
2273
+ // A NESTED error frame (sp-protocol ruling 1, 2026-09-23): the error is
2274
+ // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2275
+ // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2276
+ // parent closes as an error only when its OWN result frame says so.
2277
+ // Through 0.6.4 (whenever subagent frames carried the parent's
2278
+ // session_id) a nested rate_limit closed a recovered parent as a
2279
+ // retriable error and, first-error-wins, masked a later top-level
2280
+ // billing_error. `subagent.done` carries no outcome (SPEC:648), so the
2281
+ // failure rides the NON-terminal `error` event (SPEC:609) on the nested
2282
+ // turn: live-only but truthful and correctly owned, and inside the
2283
+ // run's still-open bracket, so before its subagent.done. The folded gap
2284
+ // ("a nested turn has no failure outcome") is sp-protocol's to bar.
2285
+ a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2286
+ // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2287
+ // frame's close is stashed and released as the nested turn.error when
2288
+ // its run closes (see `closeRun`), whatever the Task result reports.
2289
+ if (!nestedStashedErrors.has(turnId))
2290
+ nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2291
+ }
2292
+ else if (!stashedTurnErrors.has(turnId)) {
2293
+ // First error frame wins: a turn already carrying a stashed close keeps
2294
+ // it (before CL-09's stash, the first error frame closed the turn).
2295
+ stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
1548
2296
  }
1549
2297
  }
1550
- // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
1551
- // message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
1552
- // in the same order, once nothing can continue this message.
2298
+ // `subagent.done` is NOT emitted here: it brackets the RUN (see `openRun`),
2299
+ // and this message's seal is deferred (guuey#26) until nothing can continue it.
1553
2300
  // Record this frame's own uuid → the messageId it produced, so a LATER
1554
2301
  // retraction naming this uuid can translate it (Finding #1). The EMITTED
1555
2302
  // id, so a retraction still names the message that actually exists on the
1556
2303
  // wire when this frame rode a derived carrier.
1557
- registerUuid(msg.uuid, [messageId]);
2304
+ registerUuid(msg.uuid, [messageId], turnId);
1558
2305
  return;
1559
2306
  }
1560
2307
  if (msg.type === "user") {
@@ -1585,6 +2332,50 @@ export function createClaudeNormalizer(options = {}) {
1585
2332
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1586
2333
  // adoption below depends on this ordering).
1587
2334
  closePendingMessage();
2335
+ // A tool_result answering a Task call ENDS that subagent run, by what it
2336
+ // reports (B-strict, see `openRun`): its nested terminal and bracket close
2337
+ // come before the result's own tool.done. A result for any other tool
2338
+ // closes nothing. A background launch ack keeps the run open.
2339
+ if (typeof msg.message.content !== "string") {
2340
+ let resultCount = 0;
2341
+ for (const b of msg.message.content)
2342
+ if (b.type === "tool_result")
2343
+ resultCount++;
2344
+ const rawUser = msg;
2345
+ const sibling = resultCount === 1 && isJsonObject(rawUser) ? rawUser["tool_use_result"] : undefined;
2346
+ const status = isJsonObject(sibling) && typeof sibling["status"] === "string" ? sibling["status"] : undefined;
2347
+ for (const b of msg.message.content) {
2348
+ if (b.type !== "tool_result" || !openRuns.has(b.tool_use_id))
2349
+ continue;
2350
+ if (b.is_error === true) {
2351
+ closeRun(b.tool_use_id, { kind: "error", message: toolResultText(b.content) ?? "subagent failed" });
2352
+ }
2353
+ else if (status !== "async_launched" && status !== "remote_launched") {
2354
+ closeRun(b.tool_use_id, { kind: "success" });
2355
+ }
2356
+ }
2357
+ }
2358
+ // A LIVE user frame with no tool_result block is content the CLI added to
2359
+ // the conversation itself (the SDKUserMessage doc; the host's own prompts
2360
+ // come back only as isReplay acks, returned above). The live case: the
2361
+ // CLI's `isSynthetic: true` nudge "[Your previous response had no visible
2362
+ // output. …]" after an empty reply (sp-probe's
2363
+ // defer-tool-sonnet5-resume-unavailable, 7c6880f, the corpus's only such
2364
+ // frame). This branch maps only tool_result blocks, so it had no event at
2365
+ // all, and the census could not see the text go (its path normalizes to
2366
+ // the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
2367
+ // the carry the replay gap above names. DISCLOSED: a frame MIXING
2368
+ // tool_results with other blocks still maps only its tool_results (none
2369
+ // in the corpus).
2370
+ let carriesToolResult = false;
2371
+ if (typeof msg.message.content !== "string") {
2372
+ for (const b of msg.message.content)
2373
+ if (b.type === "tool_result")
2374
+ carriesToolResult = true;
2375
+ }
2376
+ if (!carriesToolResult) {
2377
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(msg) });
2378
+ }
1588
2379
  // A user message carrying tool_result blocks → tool.done per result.
1589
2380
  // parent_tool_use_id (when set) identifies a subagent tool call — the
1590
2381
  // tool.done's turnId should point at that parent call's turn so the
@@ -1596,10 +2387,57 @@ export function createClaudeNormalizer(options = {}) {
1596
2387
  // it is unknown (e.g. a result delivered before its subagent.start
1597
2388
  // was ever observed) — defensive; leg 3's never-opened-turn guard now
1598
2389
  // parks loudly on that label instead of fabricating a phantom turn.
1599
- const toolTurnId = msg.parent_tool_use_id !== null
1600
- ? (subagentTurnByParentToolUseId.get(msg.parent_tool_use_id) ??
1601
- `turn_${msg.parent_tool_use_id}`)
1602
- : undefined;
2390
+ // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2391
+ // runs make the assembler's last-turn backfill unreliable). With no turn
2392
+ // open, the frame opens one first (below), so this is never undefined.
2393
+ // Nested: the run's OPEN nested turn. A nested frame for a run that has
2394
+ // CLOSED (e.g. a background agent's tool_result after the parent's
2395
+ // result), or for one this invoke NEVER opened (the stream started
2396
+ // mid-run), gets a fresh run named by its frame, as nested assistant
2397
+ // frames do: nothing lands on a nested turn after its subagent.done, or
2398
+ // on a turn nobody opened, and no id repeats across invokes.
2399
+ // INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
2400
+ // content event for a turn the stream has not opened; sp-protocol,
2401
+ // 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
2402
+ // invoke's first frame is the deferred call's tool_result, before
2403
+ // system/init; sp-probe's defer-resume capture) opens the turn it lands
2404
+ // in, named by this frame's uuid. The resumed invoke's assistant frames
2405
+ // then join it and its result closes it. Through c54eb7f its tool.done
2406
+ // had no turn and reduce() parked from the first event. Where that result
2407
+ // folds relative to the PREVIOUS invoke's open tool block is candidate
2408
+ // 20's bar question, not decided here.
2409
+ let opensWithToolResult = false;
2410
+ for (const b of content)
2411
+ if (b.type === "tool_result")
2412
+ opensWithToolResult = true;
2413
+ if (msg.parent_tool_use_id === null && openTopTurnId === undefined && opensWithToolResult) {
2414
+ const opened = topTurnId(msg.uuid, undefined);
2415
+ a.openTurn(opened, options.threadId ?? msg.session_id ?? opened);
2416
+ }
2417
+ let toolTurnId;
2418
+ if (msg.parent_tool_use_id !== null) {
2419
+ const parentToolUseId = msg.parent_tool_use_id;
2420
+ const run = openRuns.get(parentToolUseId);
2421
+ if (run !== undefined) {
2422
+ toolTurnId = run.turnId;
2423
+ }
2424
+ else {
2425
+ // A run that CLOSED, or one this invoke never opened (the stream
2426
+ // started mid-run: a background agent spanning invokes, a resume):
2427
+ // open a fresh run named by this frame, so its tool.done lands in a
2428
+ // turn that subagent.start opened (INV-TURN) and B-strict closes.
2429
+ // Through 0.7.0's DC-10 fix the never-opened case named the synthetic
2430
+ // `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
2431
+ // loudly"): a turn nobody opened, whose id REPEATED across the
2432
+ // invokes one Reducer folds (the rd-14 ids-across-invokes rule;
2433
+ // sp-protocol's message.start bar, wf_140b3183-767), and it parked.
2434
+ toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
2435
+ openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
2436
+ }
2437
+ }
2438
+ else {
2439
+ toolTurnId = openTopTurnId;
2440
+ }
1603
2441
  // tool_use_result sibling (SDK-injected rich MCP result; audit B7): carries
1604
2442
  // structuredContent (incl. render-cache markers) + _meta.ui the block-level
1605
2443
  // arm never sees. Applies only when the message has exactly ONE tool_result
@@ -1615,6 +2453,21 @@ export function createClaudeNormalizer(options = {}) {
1615
2453
  const siblingMeta = sibling !== undefined && isJsonObject(sibling["_meta"])
1616
2454
  ? AgMeta.parse(sibling["_meta"])
1617
2455
  : undefined;
2456
+ // The Agent tool's Output (AgentOutput, sdk-tools.d.ts): the subagent's
2457
+ // run report ("the completed shape is the subagent's final report ...
2458
+ // plus run totals — render from it instead of parsing the tool_result
2459
+ // text"), or the background launch ack (status async_launched, isAsync,
2460
+ // outputFile). Recognized by its `agentId` on the result of a call this
2461
+ // invoke saw as an Agent (or Task) tool_use (`agentCallIds`). It rides the Agent call's
2462
+ // tool.done host-only `_meta` under "anthropic/agentOutput", verbatim
2463
+ // minus `content` (already the tool.done content) and `prompt` (already
2464
+ // the tool input). Its `usage` is the subagent's own and stays out of
2465
+ // AgUsage (B-strict: the parent's accounting already includes it).
2466
+ // sp-probe's subagent captures (5ba11da) surfaced every one of these
2467
+ // fields as a census drop.
2468
+ const agentOutput = sibling !== undefined && typeof sibling["agentId"] === "string"
2469
+ ? carryVerbatim(Object.fromEntries(Object.entries(sibling).filter(([k]) => k !== "content" && k !== "prompt")))
2470
+ : undefined;
1618
2471
  const siblingHasUi = siblingMeta !== undefined && siblingMeta["ui"] !== undefined;
1619
2472
  // 0.3.257 sibling: `resourceLinks` — the MCP result's `resource_link`
1620
2473
  // content blocks (files returned by reference: {uri, name, title?,
@@ -1642,9 +2495,28 @@ export function createClaudeNormalizer(options = {}) {
1642
2495
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
1643
2496
  // collect every adopted messageId this frame produces below.
1644
2497
  const resultMessageIds = [];
2498
+ const nonExecutionById = readNonExecutionKinds(msg);
2499
+ const toolResultMetaById = readToolResultMetaEntries(msg);
1645
2500
  for (const block of content) {
1646
2501
  if (block.type === "tool_result") {
1647
- const outcome = block.is_error === true ? "error" : "ok";
2502
+ // A harness-stamped denial (see isDenialKind) records as "denied"
2503
+ // with no isError, and the native block message stays in `content`,
2504
+ // so the model-facing reason survives (§2.2 draft.4: isError and
2505
+ // errorText belong to outcome "error"). Before this, the same call
2506
+ // folded "error" here and then "denied" again from the result's
2507
+ // permission_denials (sp-probe's resume-deny leg).
2508
+ // Second key (sp-protocol, same basis): when no kind is stamped, a
2509
+ // live `permission_denied` notice already seen for this id is the
2510
+ // harness's own denial record (the CLI emits it at decision time,
2511
+ // always before this result). No kind is stamped on a frame holding
2512
+ // more than one tool_result (2.1.280's stamper returns [] unless
2513
+ // exactly one), nor by a CLI that predates the stamp. A stamped kind
2514
+ // stays the primary key, so "interrupted" with a notice is still an
2515
+ // error.
2516
+ const kind = nonExecutionById.get(block.tool_use_id);
2517
+ const denied = block.is_error === true &&
2518
+ (kind !== undefined ? isDenialKind(kind) : deniedLiveByToolUseId.has(block.tool_use_id));
2519
+ const outcome = denied ? "denied" : block.is_error === true ? "error" : "ok";
1648
2520
  const toolContent = block.content === undefined ? [] : toolResultContentToAgBlocks(block.content);
1649
2521
  // `structuredContent` is not declared on `ToolResultBlockParam` in the
1650
2522
  // static SDK type, but the Claude Agent SDK injects it at runtime (spec §9
@@ -1656,11 +2528,22 @@ export function createClaudeNormalizer(options = {}) {
1656
2528
  : undefined;
1657
2529
  const resultMessageId = `${block.tool_use_id}:result`;
1658
2530
  resultMessageIds.push(resultMessageId);
2531
+ closedToolCallIds.add(block.tool_use_id);
2532
+ // This tool.done closes the call, so the result's permission_denials
2533
+ // carrier skips it. The live `permission_denied` notice for the id
2534
+ // (the CLI emits it from its canUseTool wrapper at decision time,
2535
+ // always before this tool_result) rides here instead, the same
2536
+ // providerMetadata the carrier gave it, so D drops nothing.
2537
+ const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2538
+ const resultProviderFields = {
2539
+ ...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
2540
+ ...(liveFields ?? {}),
2541
+ };
1659
2542
  a.toolDone({
1660
2543
  toolCallId: block.tool_use_id,
1661
2544
  content: toolContent,
1662
2545
  outcome,
1663
- isError: block.is_error === true,
2546
+ ...(denied ? {} : { isError: block.is_error === true }),
1664
2547
  turnId: toolTurnId,
1665
2548
  // SPEC §5 tool.done adoption (audit B10; Task 8b): the Claude SDK
1666
2549
  // closes the assistant message (message.end) BEFORE this tool_result
@@ -1683,16 +2566,29 @@ export function createClaudeNormalizer(options = {}) {
1683
2566
  ? { structuredContent: sc }
1684
2567
  : {}),
1685
2568
  ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
1686
- ...(applySibling && siblingMeta !== undefined ? { _meta: siblingMeta } : {}),
1687
- ...(applySibling && siblingResourceLinks !== undefined
1688
- ? { providerMetadata: AgProviderMeta.parse({ resourceLinks: siblingResourceLinks }) }
2569
+ // The facet's harness keys, the Agent run report ("anthropic/agentOutput")
2570
+ // and rd-15's CLI `tool_result_meta` entry ("anthropic/toolResultMeta"),
2571
+ // ride the same `_meta`, MERGED into the MCP sibling's `_meta` (never
2572
+ // replacing it), so they fold with the tool-result block. The
2573
+ // "anthropic/" namespace is the harness's own: see `mergeHarnessMeta`.
2574
+ ...(() => {
2575
+ const report = applySibling && agentCallIds.has(block.tool_use_id) ? agentOutput : undefined;
2576
+ const entry = toolResultMetaById.get(block.tool_use_id);
2577
+ const merged = mergeHarnessMeta(applySibling ? siblingMeta : undefined, {
2578
+ ...(report !== undefined ? { "anthropic/agentOutput": report } : {}),
2579
+ ...(entry !== undefined ? { "anthropic/toolResultMeta": entry } : {}),
2580
+ });
2581
+ return merged !== undefined ? { _meta: merged } : {};
2582
+ })(),
2583
+ ...(Object.keys(resultProviderFields).length > 0
2584
+ ? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
1689
2585
  : {}),
1690
2586
  });
1691
2587
  }
1692
2588
  }
1693
2589
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
1694
2590
  // produced, so a later retraction naming this uuid can translate it.
1695
- registerUuid(msg.uuid, resultMessageIds);
2591
+ registerUuid(msg.uuid, resultMessageIds, toolTurnId);
1696
2592
  }
1697
2593
  return;
1698
2594
  }
@@ -1700,7 +2596,10 @@ export function createClaudeNormalizer(options = {}) {
1700
2596
  // guuey#26: the turn is closing — seal the open assistant message first
1701
2597
  // (message.end has always preceded the turn close).
1702
2598
  closePendingMessage();
1703
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2599
+ // B-strict: a subagent run still open (a background or unreported sub-run)
2600
+ // is NOT closed by its parent's result; it closes when the framework
2601
+ // reports it, or at flush.
2602
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1704
2603
  // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1705
2604
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1706
2605
  // the final assistant text in result — or, with is_error true, the error
@@ -1720,6 +2619,8 @@ export function createClaudeNormalizer(options = {}) {
1720
2619
  // discriminant-validated, and false/absent must stay on the success path
1721
2620
  // byte-for-byte. The stash entry is consumed either way.
1722
2621
  const stashedError = takeStashedTurnError(turnId);
2622
+ // Shape-guarded once for every close below (Tenet 6; see guardedTurnUsage).
2623
+ const turnUsage = guardedTurnUsage(msg);
1723
2624
  const apiErrorTurn = msg.is_error === true;
1724
2625
  const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1725
2626
  // structured_output (when a response schema is in effect) overrides the plain
@@ -1731,36 +2632,12 @@ export function createClaudeNormalizer(options = {}) {
1731
2632
  // CL-09: an API-error turn's denials take this same carrier, at the same
1732
2633
  // point — its close is deferred to this frame (below), so the turn is
1733
2634
  // still open here, like every other turn.
1734
- if (msg.permission_denials.length > 0) {
1735
- const denialMsgId = `${turnId}:denials`;
1736
- a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
1737
- for (const denial of msg.permission_denials) {
1738
- // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
1739
- // "handled" via existing-home mapping): enrich with the live
1740
- // standalone denial notice recorded above (keyed by tool_use_id),
1741
- // when one preceded this aggregate — the actual rejection text
1742
- // returned to the model, plus decision-reason/agent-id context —
1743
- // rather than leaving a bare empty-content stub. No second
1744
- // tool.start/tool.done pair is ever emitted for the live frame
1745
- // itself (see the dedicated `permission_denied` branch below).
1746
- const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1747
- const liveFields = liveDenialMeta(live);
1748
- const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1749
- a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1750
- a.toolDone({
1751
- toolCallId: denial.tool_use_id,
1752
- content: live !== undefined ? [{ type: "text", text: live.message }] : [],
1753
- outcome: "denied",
1754
- ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
1755
- });
1756
- }
1757
- a.closeMessage(denialMsgId);
1758
- }
2635
+ emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
1759
2636
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1760
2637
  // ride `ext.anthropic.result-meta` before the close (no core home on
1761
2638
  // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
1762
2639
  // API-error turn too, before its close like on every other turn.
1763
- const resultMeta = resultMetaPayload(msg);
2640
+ const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
1764
2641
  if (resultMeta !== undefined) {
1765
2642
  a.emitExt("anthropic", "result-meta", resultMeta);
1766
2643
  }
@@ -1771,33 +2648,51 @@ export function createClaudeNormalizer(options = {}) {
1771
2648
  // the fold keeps the cost of every round the turn ran before failing.
1772
2649
  a.closeTurnError(turnId, {
1773
2650
  ...stashedError,
1774
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2651
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1775
2652
  });
1776
2653
  return;
1777
2654
  }
1778
2655
  if (apiErrorTurn) {
1779
2656
  // No assistant error frame preceded this result (a producer that did
1780
2657
  // not yield it, or a normalizer that never saw it), so this result is
1781
- // the turn's only close. message = the result text, which on this frame
1782
- // is the API error text; code = the server's api_error_code when the
1783
- // CLI copied one through, else the generic "api_error"; retriable = the
1784
- // HTTP status says rate limit or server failure (see
1785
- // `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
1786
- // above.
1787
- const code = readApiErrorCode(msg) ?? "api_error";
2658
+ // the turn's only close. code = the server's api_error_code when the
2659
+ // CLI copied one through; else the CLI's own terminal_reason when it
2660
+ // names a cause other than a normal completion; else the generic
2661
+ // "api_error".
2662
+ // message = the result text (on an API error, its text), or the code
2663
+ // when that text is empty. retriable = the HTTP status says rate limit
2664
+ // or server failure (see `apiErrorStatusRetriable`); usage = the turn's
2665
+ // accrued usage, as above.
2666
+ // The terminal_reason step (sp-protocol, facet-local, 2026-09-23): the
2667
+ // CLI also sets is_error on a result that is NOT an API error. sp-probe's
2668
+ // resume-unavailable leg (7c6880f) is a resumed invoke whose deferred
2669
+ // tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
2670
+ // result "", no status, no api_error_code. Through b7dd7ff it closed
2671
+ // turn.error{message: "", code: "api_error"}, claiming an API failure
2672
+ // that never happened. `code` is free-form (SPEC :618), so this fills
2673
+ // existing fields from the frame's own value; a live API error
2674
+ // (terminal_reason "api_error", api-error-auth) is unchanged.
2675
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
1788
2676
  a.closeTurnError(turnId, {
1789
- message: typeof msg.result === "string" ? msg.result : code,
2677
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
1790
2678
  code,
1791
2679
  retriable: apiErrorStatusRetriable(msg.api_error_status),
1792
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2680
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1793
2681
  });
1794
2682
  return;
1795
2683
  }
2684
+ const finishReasonRaw = stopReasonRaw(msg.stop_reason);
2685
+ const stopDetails = stopDetailsByTurn.get(turnId);
2686
+ stopDetailsByTurn.delete(turnId);
1796
2687
  a.closeTurnDone(turnId, {
1797
2688
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1798
2689
  finishReason: mapStopReason(msg.stop_reason),
1799
- usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2690
+ ...(finishReasonRaw !== undefined ? { finishReasonRaw } : {}),
2691
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
1800
2692
  safety,
2693
+ ...(stopDetails !== undefined
2694
+ ? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
2695
+ : {}),
1801
2696
  });
1802
2697
  return;
1803
2698
  }
@@ -1805,10 +2700,10 @@ export function createClaudeNormalizer(options = {}) {
1805
2700
  // At this point msg.subtype can only be an error variant (success handled above).
1806
2701
  // guuey#26: seal the open assistant message before the turn close.
1807
2702
  closePendingMessage();
1808
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2703
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id);
1809
2704
  // CL-09: consume any stashed assistant-error close for this turnId — this
1810
- // frame emits it (below), and it cannot leak into a later turn's result
1811
- // (every turn of a session shares the turnId).
2705
+ // frame emits it (below). Each turn has its own id now, so an entry can
2706
+ // only ever be this turn's.
1812
2707
  const stashedError = takeStashedTurnError(turnId);
1813
2708
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1814
2709
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
@@ -1825,10 +2720,20 @@ export function createClaudeNormalizer(options = {}) {
1825
2720
  const retriable = startupFailureReason !== undefined
1826
2721
  ? startupFailureRetriable(startupFailureReason)
1827
2722
  : subtype !== "error_max_turns";
2723
+ // Denials ride the SAME carrier as on the success arm, at the same point.
2724
+ // This arm is discriminant-validated only, so the array is shape-guarded
2725
+ // (a malformed entry is skipped; Tenet 6: never throw).
2726
+ const rawDenials = isJsonObject(msg) ? msg["permission_denials"] : undefined;
2727
+ const denials = Array.isArray(rawDenials)
2728
+ ? rawDenials.flatMap((d) => isJsonObject(d) && typeof d["tool_name"] === "string" && typeof d["tool_use_id"] === "string"
2729
+ ? [{ tool_name: d["tool_name"], tool_use_id: d["tool_use_id"] }]
2730
+ : [])
2731
+ : [];
2732
+ emitDenialsCarrier(turnId, denials, msg.session_id);
1828
2733
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1829
2734
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1830
2735
  // success arm above (turn.error carries no metadata slot at all).
1831
- const resultMeta = resultMetaPayload(msg);
2736
+ const resultMeta = resultMetaPayload(msg, true);
1832
2737
  if (resultMeta !== undefined) {
1833
2738
  a.emitExt("anthropic", "result-meta", resultMeta);
1834
2739
  }
@@ -1839,21 +2744,10 @@ export function createClaudeNormalizer(options = {}) {
1839
2744
  // usage (the success arm's mapping). This arm is only
1840
2745
  // discriminant-validated, so the usage trio is shape-guarded first
1841
2746
  // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
1842
- // The guard covers every property `mapTurnUsage` dereferences: the
1843
- // `server_tool_use` object (null allowed, as typed) and each
1844
- // `modelUsage` entry — `usage: {}` or a null entry would otherwise
2747
+ // The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
2748
+ // dereferences — `usage: {}` or a null modelUsage entry would otherwise
1845
2749
  // throw here, after the stash was already consumed.
1846
- const raw = msg;
1847
- const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
1848
- const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
1849
- const usage = isJsonObject(raw) &&
1850
- isJsonObject(rawUsage) &&
1851
- (rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
1852
- isJsonObject(rawModelUsage) &&
1853
- Object.values(rawModelUsage).every(isJsonObject) &&
1854
- typeof raw["total_cost_usd"] === "number"
1855
- ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
1856
- : undefined;
2750
+ const usage = guardedTurnUsage(msg);
1857
2751
  a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
1858
2752
  return;
1859
2753
  }
@@ -1877,7 +2771,9 @@ export function createClaudeNormalizer(options = {}) {
1877
2771
  // promotion is strictly more lossless. Wrapper siblings ride the text
1878
2772
  // block's providerMetadata (camelCased per the facet's carry
1879
2773
  // convention, mirroring the 0.3.217 first-block precedent).
1880
- const turnId = turnIdFor(msg.session_id, msg.uuid);
2774
+ // The open turn, or (between turns) the one this notice opens; the next
2775
+ // assistant frame then joins it and its result closes it.
2776
+ const turnId = topTurnId(msg.uuid, undefined);
1881
2777
  const noticeMeta = AgProviderMeta.parse({
1882
2778
  level: msg.level,
1883
2779
  ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
@@ -1920,7 +2816,7 @@ export function createClaudeNormalizer(options = {}) {
1920
2816
  // and non-folding, so the second copy of `retracted_message_uuids`
1921
2817
  // cannot double-fold (the M22 hazard). This is the only producer for R&D
1922
2818
  // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
1923
- a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
2819
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
1924
2820
  return;
1925
2821
  }
1926
2822
  if (msg.type === "system" && msg.subtype === "permission_denied") {
@@ -1968,7 +2864,37 @@ export function createClaudeNormalizer(options = {}) {
1968
2864
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
1969
2865
  const carriedKind = anthropicFrameKind(msg);
1970
2866
  if (carriedKind !== undefined) {
1971
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: JsonValue.parse(msg) });
2867
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
2868
+ // B-strict: a background sub-run's outcome arrives as task_notification,
2869
+ // correlated to its run by tool_use_id (or by task_id through the
2870
+ // task_started frame that named it).
2871
+ const raw = msg;
2872
+ if (isJsonObject(raw) && raw["type"] === "system" && typeof raw["task_id"] === "string") {
2873
+ const taskId = raw["task_id"];
2874
+ const named = typeof raw["tool_use_id"] === "string" ? raw["tool_use_id"] : undefined;
2875
+ if (raw["subtype"] === "task_started" && named !== undefined)
2876
+ toolUseIdByTaskId.set(taskId, named);
2877
+ if (raw["subtype"] === "task_notification") {
2878
+ const runKey = named ?? toolUseIdByTaskId.get(taskId);
2879
+ const status = raw["status"];
2880
+ if (runKey !== undefined && openRuns.has(runKey)) {
2881
+ if (status === "completed")
2882
+ closeRun(runKey, { kind: "success" });
2883
+ else if (status === "failed")
2884
+ closeRun(runKey, { kind: "error", message: typeof raw["summary"] === "string" && raw["summary"] !== "" ? raw["summary"] : "subagent failed", code: "failed" });
2885
+ else if (status === "stopped")
2886
+ closeRun(runKey, { kind: "aborted", reason: "stopped" });
2887
+ }
2888
+ }
2889
+ }
2890
+ return;
2891
+ }
2892
+ // A top-level type the union does not declare (see KNOWN_TOP_LEVEL_TYPES):
2893
+ // carried whole, never silently dropped. `msg.type` is typed as the union's
2894
+ // literals, but the frame is only discriminant-validated at runtime.
2895
+ const topLevelType = msg.type;
2896
+ if (!KNOWN_TOP_LEVEL_TYPES.has(topLevelType)) {
2897
+ a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
1972
2898
  return;
1973
2899
  }
1974
2900
  // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
@@ -1976,23 +2902,37 @@ export function createClaudeNormalizer(options = {}) {
1976
2902
  }
1977
2903
  return {
1978
2904
  push(native) {
1979
- if (!isSDKMessage(native)) {
2905
+ framesSeen++;
2906
+ // `native` is already plain JSON: withAtomicPush (createClaudeNormalizer)
2907
+ // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
2908
+ // frame is the same reference, anything else its JSON form).
2909
+ const frame = native;
2910
+ if (!isSDKMessage(frame)) {
1980
2911
  // Graceful guard (Tenet 6): route the raw payload through the lossless
1981
2912
  // vendor channel rather than throwing. Nest under `native` so a payload
1982
2913
  // that carries its own `type` key (the common malformed-SDKMessage shape
1983
2914
  // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
1984
2915
  // (emitExt spreads object payloads at the top level).
1985
- a.emitExt("anthropic", "unparsed", { native });
2916
+ // A copy: `frame` IS the host's object when it was already JSON, and
2917
+ // this raw channel would otherwise emit it by reference. JsonValue.parse
2918
+ // copies and, like every other carry here, drops an own "__proto__"
2919
+ // (sp-main 2026-09-24, matching sp-openai cf55e08 and the 0.6.6
2920
+ // reserved-key rule 314a183: an emitted map carries no own __proto__).
2921
+ a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
1986
2922
  return a.drain();
1987
2923
  }
1988
- drive(native);
2924
+ drive(frame);
1989
2925
  return a.drain();
1990
2926
  },
1991
2927
  flush() {
1992
2928
  // guuey#26: nothing can continue the deferred message now — seal it with
1993
- // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1994
- // to synthesize a bare `message.end`.
1995
- closePendingMessage();
2929
+ // its real usage rather than leaving INV-FLUSH to synthesize a bare
2930
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
2931
+ closePendingMessage(true);
2932
+ // B-strict: every subagent run still open closes here with its nested
2933
+ // terminal (turn.abort{stream-truncated}, or its stashed API error) and
2934
+ // its subagent.done, innermost first.
2935
+ abortOpenRuns();
1996
2936
  // CL-09: a turn whose assistant error frame stashed its close but whose
1997
2937
  // result frame never arrived still closes as that turn.error (no usage:
1998
2938
  // only a result carries the turn's), never as INV-FLUSH's synthesized
@@ -2005,6 +2945,34 @@ export function createClaudeNormalizer(options = {}) {
2005
2945
  },
2006
2946
  };
2007
2947
  }
2948
+ /**
2949
+ * Build the Claude-facet normalizer: the inner normalizer wrapped in core's
2950
+ * withAtomicPush (the fleet guard ruling, 2026-09-24, binding). push() never
2951
+ * throws (SPEC:933):
2952
+ * - each native is first read as plain JSON (core toJsonValueSafe): a host
2953
+ * may hand in the in-process object, whose members need not be JSON (an
2954
+ * undefined member, a Date, NaN, a BigInt, a function, a cycle); a JSON
2955
+ * frame passes by reference, anything else folds exactly as its JSON form,
2956
+ * which is what every capture already is (the SDK itself parses the CLI's
2957
+ * NDJSON, so no 0.3.280 SDK frame needs it);
2958
+ * - an envelope-valid but malformed frame (a required field missing or
2959
+ * mistyped below the isSDKMessage discriminants: 61 single-point fuzz
2960
+ * mutants of the corpus's 25 frame shapes threw, from ~17 sites, most after
2961
+ * the frame had emitted) no longer throws: its partial batch is discarded
2962
+ * with its state (the inner is rebuilt and re-driven from the journal) and
2963
+ * one core `error {message: "normalizer error", code: <constructor name>}`
2964
+ * takes the next seq. Over every committed native it fires zero times
2965
+ * (e2e agents/claude-agent-sdk/guard.corpus.test.ts).
2966
+ * The fallback id stem is held HERE, outside the rebuild's factory: drawn at
2967
+ * most once, and only when a fallback id is first needed, so the common path
2968
+ * never touches randomness (core's atomic-guard differential runs with it
2969
+ * poisoned) and a rebuild re-reads the same stem.
2970
+ */
2971
+ export function createClaudeNormalizer(options = {}) {
2972
+ let stem = options.invokeId;
2973
+ const invokeStem = () => (stem ??= `claude_${mintInvokeNonce()}`);
2974
+ return withAtomicPush(() => createInnerClaudeNormalizer(options, invokeStem));
2975
+ }
2008
2976
  export default createClaudeNormalizer;
2009
2977
  export { mapStopReason };
2010
2978
  //# sourceMappingURL=index.js.map