@silverprotocol/claude-agent-sdk 0.12.4 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -48,6 +48,7 @@ import {
48
48
  JsonValue,
49
49
  type Normalizer,
50
50
  StreamAssembler,
51
+ toJsonValueSafe,
51
52
  withAtomicPush,
52
53
  type ToolOutcome,
53
54
  } from "@silverprotocol/core";
@@ -416,7 +417,7 @@ function toolResultContentToAgBlocks(content: NonNullable<ToolResultContent>): A
416
417
 
417
418
  // Assistant-side mcp_tool_result content → AgBlock[] (distinct shape from the
418
419
  // user-side tool_result content mapped by `toolResultContentToAgBlocks` above).
419
- // A `for...of` loop, not `.map` — playbook 2026-07-03 SDK-bump adaptation: the
420
+ // A `for...of` loop, not `.map` — the 2026-07-03 SDK-bump adaptation: the
420
421
  // 0.3.199 `SDKMessage` union widened enough that `.map`/`.forEach`/`.filter`
421
422
  // callback PARAMETER inference silently degrades to implicit `any` on this
422
423
  // content shape (a known TS limitation calling an array method on a value typed
@@ -483,12 +484,12 @@ function isDenialKind(kind: string | undefined): boolean {
483
484
 
484
485
  // Which assistant `error` codes are transient (retriable). An API-error turn's
485
486
  // stashed top-level close and a nested frame's non-terminal `error` share it.
486
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
487
+ // `overloaded` (transient capacity error, a first
487
488
  // cousin of rate_limit/server_error) joins the retriable set.
488
489
  // `model_not_found` (a permanent misconfiguration — e.g. a stale/
489
490
  // decommissioned model id) is deliberately EXCLUDED: explicit
490
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
491
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
491
+ // false-by-omission, not an oversight (the 2026-07-03 SDK-bump
492
+ // adaptation). `account_on_hold` (0.3.258) is likewise a
492
493
  // deliberate non-retriable: a billing-class code (the account is on
493
494
  // hold — a first cousin of `billing_error`, cleared by the account
494
495
  // holder, never by re-sending the turn).
@@ -520,7 +521,7 @@ function assistantErrorRetriable(errCode: NonNullable<SDKAssistantError>): boole
520
521
  // default content.block) never apply it, so those facts drop there (a
521
522
  // disclosed, pre-existing gap; a retraction itself still executes via
522
523
  // `message.remove` regardless, see `drive()`).
523
- // - `blockMeta` (X5): the HOST-only wrapper facts (HOST_ONLY_WRAPPER_KEYS).
524
+ // - `blockMeta`: the HOST-only wrapper facts (HOST_ONLY_WRAPPER_KEYS).
524
525
  // Only text.start / reasoning.start get it, because `reduce()` folds their
525
526
  // `_meta` onto the block.
526
527
  // Returns which halves ANCHORED on a folded start event: `replay` when the
@@ -553,7 +554,7 @@ function emitAssistantBlock(
553
554
  case "text": {
554
555
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
555
556
  // citations are already known at the point text.end fires — they ride the
556
- // STREAMED-text citations carrier (audit M22: text.end.citations), never as
557
+ // STREAMED-text citations carrier (text.end.citations), never as
557
558
  // a duplicate id-less supplement block.
558
559
  const id = `${messageId}:text:${blockIndex}`;
559
560
  const citations =
@@ -749,15 +750,17 @@ function isSDKMessage(v: unknown): v is SDKMessage {
749
750
  // Task* subagent-progress family) with NO existing AgJSON vocabulary home.
750
751
  //
751
752
  // The Task* family (task_started/task_progress/task_updated/task_notification)
752
- // was STUDIED against the facet's ALREADY-derived subagent lifecycle
753
- // (parent_tool_use_id -> subagentStart/Done in `drive()` below) and
754
- // deliberately NOT folded into it: `tool_use_id` is OPTIONAL on every Task*
755
- // arm (a `task_type:"local_workflow"` background task carries NONE at all —
756
- // this family is a broader "tasks panel" superset, not 1:1 with Task-tool
757
- // subagent adoption), and task_progress/task_notification's own
753
+ // rides this carry whole. Its content is not folded into the subagent
754
+ // lifecycle: `tool_use_id` is OPTIONAL on every Task* arm (a
755
+ // `task_type:"local_workflow"` background task carries NONE at all — this
756
+ // family is a broader "tasks panel" superset, not 1:1 with Task-tool subagent
757
+ // adoption), and task_progress/task_notification's own
758
758
  // `summary`/`last_tool_name` would DUPLICATE content the nested subagent's
759
- // own tool_use/tool_result stream already conveys once correlation resolves
760
- // — the M22 double-fold hazard. `description` enrichment onto
759
+ // own tool_use/tool_result stream already conveys — a double fold. One part
760
+ // IS mapped: a task_notification correlated to an open run (by tool_use_id,
761
+ // or by task_id through its task_started) closes that run with its nested
762
+ // terminal and subagent.done (B-strict, SPEC §8.0 item 29), before the
763
+ // frame's carry (see `drive()`). `description` enrichment onto
761
764
  // subagent.start was also considered and rejected: `subagent.start`'s
762
765
  // schema carries no providerMetadata slot (only agentId/agentName), and
763
766
  // reaching it would require bypassing the `subagentStart()` sugar
@@ -774,14 +777,14 @@ function isSDKMessage(v: unknown): v is SDKMessage {
774
777
  // carried, not forced onto an unrelated event.
775
778
  //
776
779
  // SDKPermissionDeniedMessage is the ONE arm that DOES map onto an existing
777
- // home (the W1 `<turnId>:denials` carrier, audit M19) — see the dedicated
780
+ // home (the `<turnId>:denials` carrier) — see the dedicated
778
781
  // branch + `deniedLiveByToolUseId` in `createClaudeNormalizer()` below; it
779
782
  // is deliberately EXCLUDED from the carried sets here.
780
783
  //
781
784
  // SDKModelRefusalFallbackMessage is HALF-mapped: its retraction goes to
782
785
  // `message.remove` (§8 item 19) and the rest of the frame has no home. It is
783
786
  // NOT in the sets below either. Its dedicated branch does the retraction and
784
- // then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
787
+ // then emits the same `ext.anthropic.frame` carry itself (since 2026-09-23, on
785
788
  // the item-22 reading for half-mapped frames — see that branch).
786
789
  //
787
790
  // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
@@ -888,7 +891,7 @@ function readUserMessageUuids(v: unknown): string[] | undefined {
888
891
  return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? [...v] : undefined;
889
892
  }
890
893
 
891
- // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
894
+ // Since 2026-09-23: the assistant-wrapper keys that ride a block's HOST-ONLY
892
895
  // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
893
896
  // are CLI-wrapper facts the Messages API never consumes. See the split in
894
897
  // drive()'s assistant branch.
@@ -1098,10 +1101,13 @@ function readStartupFailureReason(v: unknown): string | undefined {
1098
1101
  // The type's own lead sentence frames the whole enum as a refusal to start:
1099
1102
  // "Why Claude Code refused to start, so a host can offer the fix instead of a
1100
1103
  // retry." So a PRESENT reason means NOT retriable, except for the values
1101
- // upstream itself EXPLICITLY describes as retriable. Through 0.3.292 that set is
1102
- // exactly one value:
1104
+ // upstream itself EXPLICITLY describes as retriable. Through 0.3.296 that set is
1105
+ // exactly two values:
1103
1106
  // - `worktree_unverified`: "the session's worktree could not be verified
1104
1107
  // right now; retrying may succeed."
1108
+ // - `org_config_required_unavailable` (0.3.296): the organization's required
1109
+ // policy limits and managed settings "could not be loaded (network, proxy,
1110
+ // or an Anthropic error); retrying may succeed."
1105
1111
  // Three more values read as if they might clear on their own, but upstream
1106
1112
  // never says a retry helps, so each is a deliberate non-retriable — explicit
1107
1113
  // false-by-omission (the model_not_found / account_on_hold voice in the
@@ -1117,12 +1123,13 @@ function readStartupFailureReason(v: unknown): string | undefined {
1117
1123
  // Every other documented value (org_pin_api_key_conflict, provider_not_allowed,
1118
1124
  // org_pin_mismatch, managed_settings_invalid, gateway_signin_required,
1119
1125
  // gateway_access_denied, proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
1120
- // worktree_resume_refused, cli_version_too_old, bypass_root) names a
1121
- // configuration, policy or environment fix, and an unknown future value
1126
+ // worktree_resume_refused, cli_version_too_old, bypass_root, and 0.3.296's
1127
+ // org_config_refused: "signing in again or an admin's change is the fix, not a
1128
+ // retry") names a configuration, policy or environment fix, and an unknown future value
1122
1129
  // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
1123
1130
  // reason never reaches this function: the error arm keeps its old rule, so
1124
1131
  // older producers are byte-identical.
1125
- const RETRIABLE_STARTUP_FAILURE_REASONS = new Set<string>(["worktree_unverified"]);
1132
+ const RETRIABLE_STARTUP_FAILURE_REASONS = new Set<string>(["worktree_unverified", "org_config_required_unavailable"]);
1126
1133
  function startupFailureRetriable(reason: string): boolean {
1127
1134
  return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
1128
1135
  }
@@ -1139,6 +1146,22 @@ function apiErrorStatusRetriable(status: unknown): boolean {
1139
1146
  return typeof status === "number" && (status === 429 || status >= 500);
1140
1147
  }
1141
1148
 
1149
+ // The error fields an is_error success result carries by itself, when no
1150
+ // assistant error frame decided its close first: code = the server's
1151
+ // api_error_code when the CLI copied one through; else the CLI's own
1152
+ // terminal_reason when it names a cause other than a normal completion; else
1153
+ // the generic "api_error". message = the result text (on an API error, its
1154
+ // text), or the code when that text is empty. retriable = the HTTP status says
1155
+ // rate limit or server failure (see `apiErrorStatusRetriable`).
1156
+ function resultErrorFields(msg: SDKResultSuccessMsg): { readonly message: string; readonly code: string; readonly retriable: boolean } {
1157
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
1158
+ return {
1159
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
1160
+ code,
1161
+ retriable: apiErrorStatusRetriable(msg.api_error_status),
1162
+ };
1163
+ }
1164
+
1142
1165
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
1143
1166
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
1144
1167
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -1422,7 +1445,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1422
1445
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
1423
1446
  const subagentTurnByParentToolUseId = new Map<string, string>();
1424
1447
 
1425
- // INV-TURN (SPEC:743; ruling B, 2026-09-23): ONE turnId names
1448
+ // INV-TURN (SPEC:743; ruled 2026-09-23): ONE turnId names
1426
1449
  // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1427
1450
  // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1428
1451
  // or a stream `message_start`) in the ordinary case, or the frame's own
@@ -1547,7 +1570,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1547
1570
  // the user branch), and a nested one for a run this invoke never opened opens
1548
1571
  // a fresh run the same way.
1549
1572
  //
1550
- // B-STRICT NESTED TERMINALS (draft.4, the nested-turn ruling Q1,
1573
+ // B-STRICT NESTED TERMINALS (draft.4, the nested-turn ruling,
1551
1574
  // 2026-09-24). A nested turn opens
1552
1575
  // with exactly one subagent.start and closes with exactly one turn.done |
1553
1576
  // turn.error | turn.abort carrying its turnId, IMMEDIATELY followed by its
@@ -1583,6 +1606,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1583
1606
  const closedNestedTurnIds = new Set<string>();
1584
1607
  // Nested turnId → its FIRST API error frame's close (released at run close).
1585
1608
  const nestedStashedErrors = new Map<string, StashedTurnError>();
1609
+ // Nested turnIds whose stashed close came from a refusal frame (see the
1610
+ // top-level `refusedTurns`): closed by the framework, the run closes as
1611
+ // turn.done{finishReason:"refusal"}; at flush it stays turn.error.
1612
+ const refusedNestedTurns = new Set<string>();
1586
1613
  // task_started: task_id → the spawning tool_use_id, for a task_notification
1587
1614
  // that carries only its task_id.
1588
1615
  const toolUseIdByTaskId = new Map<string, string>();
@@ -1596,7 +1623,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1596
1623
  openRuns.set(parentToolUseId, { turnId, parentTurnId });
1597
1624
  a.subagentStart(turnId, parentTurnId);
1598
1625
  }
1599
- function closeRun(parentToolUseId: string, close: NestedClose): void {
1626
+ function closeRun(parentToolUseId: string, close: NestedClose, atFlush = false): void {
1600
1627
  const run = openRuns.get(parentToolUseId);
1601
1628
  if (run === undefined) return;
1602
1629
  openRuns.delete(parentToolUseId);
@@ -1604,7 +1631,18 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1604
1631
  closedNestedTurnIds.add(run.turnId);
1605
1632
  const stashed = nestedStashedErrors.get(run.turnId);
1606
1633
  nestedStashedErrors.delete(run.turnId);
1607
- if (stashed !== undefined) {
1634
+ const refused = refusedNestedTurns.delete(run.turnId);
1635
+ if (stashed !== undefined && refused && !atFlush) {
1636
+ // A refusal frame decided this nested close, and the framework ended the
1637
+ // run: the block signal rides finishReason (as the top-level refusal
1638
+ // close), with no usage (a nested terminal carries none, SPEC §8.0 item
1639
+ // 29). At flush it stays turn.error below (INV-FLUSH).
1640
+ a.closeTurnDone(run.turnId, {
1641
+ outcome: { type: "error", message: stashed.message, code: stashed.code, retriable: stashed.retriable },
1642
+ finishReason: "refusal",
1643
+ safety: [{ category: "refusal", blocked: true }],
1644
+ });
1645
+ } else if (stashed !== undefined) {
1608
1646
  a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1609
1647
  } else if (close.kind === "success") {
1610
1648
  a.closeTurnDone(run.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
@@ -1619,12 +1657,12 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1619
1657
  // INV-FLUSH orders its own closes.
1620
1658
  function abortOpenRuns(): void {
1621
1659
  for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1622
- closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1660
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" }, true);
1623
1661
  }
1624
1662
  }
1625
1663
 
1626
- // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
1627
- // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
1664
+ // Refusal-fallback retraction (§8 item 19; the 2026-07-03 SDK-bump
1665
+ // adaptation). `supersedes` / `retracted_message_uuids`
1628
1666
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
1629
1667
  // DIFFERENT id space from the messageIds this facet actually emits (`m.id`
1630
1668
  // for an assistant frame's `message.start`, `${tool_use_id}:result` for an
@@ -1638,10 +1676,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1638
1676
  // home mapping): live per-denial diagnostic recorded by the standalone
1639
1677
  // `permission_denied` frame (fires DURING the turn, before the terminal
1640
1678
  // result) — keyed by tool_use_id so the terminal `permission_denials[]`
1641
- // aggregate (the ALREADY-handled W1 `<turnId>:denials` carrier, audit M19)
1679
+ // aggregate (the ALREADY-handled `<turnId>:denials` carrier)
1642
1680
  // can enrich its tool.done with the actual rejection text + decision-reason
1643
1681
  // context, instead of emitting a SECOND tool.start/tool.done pair for the
1644
- // same denial (the M22 double-fold hazard).
1682
+ // same denial (a double fold).
1645
1683
  type LiveDenial = {
1646
1684
  message: string;
1647
1685
  decisionReasonType?: string;
@@ -1709,6 +1747,14 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1709
1747
  // be its own turn's, so a stale one can no longer leak into the next turn.
1710
1748
  type StashedTurnError = { readonly message: string; readonly code: string; readonly retriable: boolean };
1711
1749
  const stashedTurnErrors = new Map<string, StashedTurnError>();
1750
+ // Top-level turnIds whose stashed close came from a refusal frame: an
1751
+ // assistant error frame whose message.stop_reason is "refusal". CLI 2.1.280
1752
+ // sends a refusal it does not retry as such a frame (error
1753
+ // "invalid_request"), then a result with is_error true. Its result closes
1754
+ // the turn as turn.done{outcome error, finishReason "refusal", safety}, so
1755
+ // the block signal reaches the fold (SPEC §4); a flush with no result keeps
1756
+ // the stashed turn.error (INV-TURN lists the flush closes).
1757
+ const refusedTurns = new Set<string>();
1712
1758
 
1713
1759
  /** Remove and return the stashed error close for `turnId`, if any. */
1714
1760
  function takeStashedTurnError(turnId: string): StashedTurnError | undefined {
@@ -1914,12 +1960,12 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1914
1960
  });
1915
1961
  }
1916
1962
 
1917
- // Emit what the block's content_block_stop produces — text.end (with the M22
1963
+ // Emit what the block's content_block_stop produces — text.end (with the
1918
1964
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
1919
1965
  // (same end-then-opaque order as the complete arm), the MANDATORY
1920
1966
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
1921
1967
  // `atFlush` (INV-FLUSH (3), draft.4; the fold/flush ruling, "snapshot
1922
- // fold + honest flush; opaque at flush forbidden"; leg C1): the
1968
+ // fold + honest flush; opaque at flush forbidden"): the
1923
1969
  // stream ENDED with this block open, so the close lands NO new content. The
1924
1970
  // lifecycle closes stay (text.end with its already-received citations,
1925
1971
  // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
@@ -1961,7 +2007,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1961
2007
  let input: JsonValue = b.startInput;
1962
2008
  if (b.json.length > 0) {
1963
2009
  try {
1964
- input = JsonValue.parse(JSON.parse(b.json));
2010
+ // The parsed string is vendor data that push()'s native read never
2011
+ // saw, so it is bounded here as every native payload is: a node past
2012
+ // JSON_SAFE_MAX_DEPTH becomes core's max-depth mark, and the event
2013
+ // stays inside AG_EVENT_MAX_DEPTH.
2014
+ input = JsonValue.parse(toJsonValueSafe(JSON.parse(b.json)));
1965
2015
  } catch {
1966
2016
  input = b.startInput;
1967
2017
  }
@@ -2220,7 +2270,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2220
2270
  // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
2221
2271
  // no bag, byte-identical.
2222
2272
  //
2223
- // X5 (2026-09-23): it rides the delta's host-only `_meta`, not
2273
+ // Since 2026-09-23: it rides the delta's host-only `_meta`, not
2224
2274
  // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
2225
2275
  // that must round-trip to the provider), and the Messages API never
2226
2276
  // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
@@ -2252,7 +2302,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2252
2302
  return;
2253
2303
  }
2254
2304
  if (d.type === "citations_delta" && b.kind === "text") {
2255
- // Buffered — the M22 streamed-citations carrier is text.end, at stop.
2305
+ // Buffered — the streamed-citations carrier is text.end, at stop.
2256
2306
  b.citations.push(...mapCitations([d.citation]));
2257
2307
  return;
2258
2308
  }
@@ -2353,7 +2403,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2353
2403
 
2354
2404
  // Emit a result's permission_denials as tool.start + tool.done denied pairs,
2355
2405
  // inside a dedicated carrier message: the assistant message is already
2356
- // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
2406
+ // sealed, and INV-MSG forbids attaching to sealed messages or
2357
2407
  // closed turns. BOTH result arms call it, at the same point (after the seal
2358
2408
  // and the run closes, before result-meta and the close). Through 0.6.4 only
2359
2409
  // the success arm did, so an error-subtype result (SDKResultError declares
@@ -2426,7 +2476,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2426
2476
  : undefined;
2427
2477
  if (continued === undefined) closePendingMessage();
2428
2478
 
2429
- // Finding #1 (critical): this frame supersedes prior delivered messages
2479
+ // Refusal-fallback retraction: this frame supersedes prior delivered messages
2430
2480
  // (refusal-fallback retry) — evict them "on arrival", per the field's own
2431
2481
  // doc, before opening the canonical replacement below. Idempotent with
2432
2482
  // the end-of-turn `model_refusal_fallback` notice (see the `system`
@@ -2568,7 +2618,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2568
2618
  // vendor carries; a 0.7.0 carry with zero golden moves). Three more
2569
2619
  // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
2570
2620
  // 0.3.280 (so read through the JSON boundary), carried verbatim under their
2571
- // wire names on the frame's first block's host-only `_meta` (the X5 route,
2621
+ // wire names on the frame's first block's host-only `_meta` (the wrapper-key route,
2572
2622
  // which folds onto block._meta; never providerMetadata, SPEC §12):
2573
2623
  // - `error_details`: "Raw API error message: preserves details (e.g.
2574
2624
  // prompt-too-long token counts) that user-facing content discards"
@@ -2645,8 +2695,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2645
2695
  // response of the turn without one clears it. Every `fallback_credit_token`,
2646
2696
  // at any depth, is deleted first (a provider credit token is never
2647
2697
  // emitted). Null (every committed golden) carries nothing. Keyed by turn,
2648
- // so a nested (subagent) response never touches its parent's entry, and
2649
- // only top-level turns close with turn.done.
2698
+ // so a nested (subagent) response never touches its parent's entry; only a
2699
+ // top-level turn.done carries it (a nested terminal carries no
2700
+ // messageMetadata).
2650
2701
  const stopDetails: unknown = m.stop_details;
2651
2702
  if (isJsonObject(stopDetails)) {
2652
2703
  stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
@@ -2691,7 +2742,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2691
2742
  if (resumeReason !== undefined) wrapperMetaRaw["resume_reason"] = resumeReason;
2692
2743
  }
2693
2744
  }
2694
- // X5 (the 2026-09-23 re-cut): the bag mixes two kinds of fact. SPEC
2745
+ // The 2026-09-23 re-cut: the bag mixes two kinds of fact. SPEC
2695
2746
  // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2696
2747
  // round-trip to the provider) and `_meta` host-only side metadata.
2697
2748
  // Every key in HOST_ONLY_WRAPPER_KEYS is a CLI-wrapper fact the Messages
@@ -2732,7 +2783,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2732
2783
  // reasoning block. A listed empty block (display "omitted") gets none.
2733
2784
  // The index is FRAME-local. Never inferred from position, text or turn
2734
2785
  // end; never decoded from the signature; the vendor list itself still
2735
- // rides host-only `_meta` verbatim (X5).
2786
+ // rides host-only `_meta` verbatim.
2736
2787
  const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2737
2788
  if (suppressed && narrationIndexes.size > 0) {
2738
2789
  // STREAMED: the complete frame precedes its blocks' content_block_stop
@@ -2843,6 +2894,21 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2843
2894
  // turn's result frame (which carries the turn's usage) emits it, or
2844
2895
  // `flush()` does if no result ever arrives (see `stashedTurnErrors`).
2845
2896
  if (msg.error !== undefined) {
2897
+ // A reported fix is never silently dropped (SPEC §8.0 item 33). An
2898
+ // error frame's turn can close without a turn.done (the stashed
2899
+ // turn.error, a flush, a nested run), where the turn.done
2900
+ // messageMetadata carry of `stop_details` above never reaches the wire:
2901
+ // the CLI's refusal message (error "invalid_request", stop_reason
2902
+ // "refusal") carries the refusal's category, explanation and
2903
+ // recommended model there. So it rides `message.metadata` on this
2904
+ // still-open message whatever the close, verbatim under its wire name,
2905
+ // less every provider credit token (§13.10), and folds into the
2906
+ // message's `metadata`. A refusal its result closes as turn.done also
2907
+ // carries it on that turn.done's messageMetadata. Null carries nothing.
2908
+ if (isJsonObject(stopDetails)) {
2909
+ const metadata: AgMeta = { stop_details: withoutCreditTokens(JsonValue.parse(stopDetails)) };
2910
+ a.emit({ type: "message.metadata", messageId, metadata });
2911
+ }
2846
2912
  // The API error ended the model's output — nothing can continue this
2847
2913
  // message. Seal it now, so `message.end` still precedes the (deferred)
2848
2914
  // close.
@@ -2850,7 +2916,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2850
2916
  const errCode: NonNullable<SDKAssistantError> = msg.error;
2851
2917
  const retriable = assistantErrorRetriable(errCode);
2852
2918
  if (msg.parent_tool_use_id !== null) {
2853
- // A NESTED error frame (ruling 1, 2026-09-23): the error is
2919
+ // A NESTED error frame (ruled 2026-09-23): the error is
2854
2920
  // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2855
2921
  // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2856
2922
  // parent closes as an error only when its OWN result frame says so.
@@ -2864,13 +2930,18 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2864
2930
  // ("a nested turn has no failure outcome") is an open spec question.
2865
2931
  a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2866
2932
  // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2867
- // frame's close is stashed and released as the nested turn.error when
2868
- // its run closes (see `closeRun`), whatever the Task result reports.
2869
- if (!nestedStashedErrors.has(turnId)) nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2933
+ // frame's close is stashed and released as the nested terminal when
2934
+ // its run closes (turn.done{finishReason refusal} for a refusal frame,
2935
+ // else turn.error; see `closeRun`), whatever the Task result reports.
2936
+ if (!nestedStashedErrors.has(turnId)) {
2937
+ nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2938
+ if (m.stop_reason === "refusal") refusedNestedTurns.add(turnId);
2939
+ }
2870
2940
  } else if (!stashedTurnErrors.has(turnId)) {
2871
2941
  // First error frame wins: a turn already carrying a stashed close keeps
2872
2942
  // it (through 0.6.2, before the stash, the first error frame closed the turn).
2873
2943
  stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
2944
+ if (m.stop_reason === "refusal") refusedTurns.add(turnId);
2874
2945
  }
2875
2946
  }
2876
2947
 
@@ -2878,7 +2949,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2878
2949
  // and this message's seal is deferred (INV-MSG) until nothing can continue it.
2879
2950
 
2880
2951
  // Record this frame's own uuid → the messageId it produced, so a LATER
2881
- // retraction naming this uuid can translate it (Finding #1). The EMITTED
2952
+ // retraction naming this uuid can translate it (§8 item 19). The EMITTED
2882
2953
  // id, so a retraction still names the message that actually exists on the
2883
2954
  // wire when this frame rode a derived carrier.
2884
2955
  registerUuid(msg.uuid, [messageId], turnId);
@@ -2974,10 +3045,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
2974
3045
  // subagent reduce() correctly routes the result.
2975
3046
  const content = msg.message.content;
2976
3047
  if (typeof content !== "string") {
2977
- // Task 8c leg 4: prefer the REAL subagent turnId recorded at
3048
+ // Prefer the REAL subagent turnId recorded at
2978
3049
  // subagent.start time. Fall back to the old synthetic label only when
2979
3050
  // it is unknown (e.g. a result delivered before its subagent.start
2980
- // was ever observed) — defensive; leg 3's never-opened-turn guard now
3051
+ // was ever observed) — defensive; the never-opened-turn guard now
2981
3052
  // parks loudly on that label instead of fabricating a phantom turn.
2982
3053
  // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2983
3054
  // runs make the assembler's last-turn backfill unreliable). With no turn
@@ -3084,7 +3155,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3084
3155
  let toolResultCount = 0;
3085
3156
  for (const b of content) if (b.type === "tool_result") toolResultCount++;
3086
3157
  const applySibling = sibling !== undefined && toolResultCount === 1;
3087
- // Finding #1: this frame's own uuid may later be named by a retraction
3158
+ // Retraction (§8 item 19): this frame's own uuid may later be named by a retraction
3088
3159
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
3089
3160
  // collect every adopted messageId this frame produces below.
3090
3161
  const resultMessageIds: string[] = [];
@@ -3181,7 +3252,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3181
3252
  });
3182
3253
  }
3183
3254
  }
3184
- // Finding #1: record this frame's uuid → the adopted messageId(s) it
3255
+ // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
3185
3256
  // produced, so a later retraction naming this uuid can translate it.
3186
3257
  registerUuid(msg.uuid, resultMessageIds, toolTurnId);
3187
3258
  }
@@ -3235,10 +3306,36 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3235
3306
  // ride `ext.anthropic.result-meta` before the close (no core home on
3236
3307
  // turn.done — see resultMetaPayload's doc). It is emitted on an
3237
3308
  // API-error turn too, before its close like on every other turn.
3238
- const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
3309
+ // A refusal close: the stash came from a refusal frame, or (no frame
3310
+ // decided it) this is_error result itself says stop_reason "refusal".
3311
+ const refusedByFrame = stashedError !== undefined && refusedTurns.delete(turnId);
3312
+ const refusedByResult = stashedError === undefined && apiErrorTurn && msg.stop_reason === "refusal";
3313
+ const refusalClose = refusedByFrame || refusedByResult;
3314
+ const resultMeta = resultMetaPayload(msg, !refusalClose && (stashedError !== undefined || apiErrorTurn));
3239
3315
  if (resultMeta !== undefined) {
3240
3316
  a.emitExt("anthropic", "result-meta", resultMeta);
3241
3317
  }
3318
+ if (refusalClose) {
3319
+ // The refusal close: turn.done, whose finishReason carries the block
3320
+ // signal (SPEC §4) and whose outcome keeps the error the CLI reports
3321
+ // (outcome.type is the facet's choice). The fields are the frame's
3322
+ // stashed ones, or on a result-only refusal this result's own (as its
3323
+ // turn.error close would carry), never an invented code. The closing
3324
+ // response's stop_details rides messageMetadata, as on every turn.done.
3325
+ const fields = stashedError ?? resultErrorFields(msg);
3326
+ const refusalDetails = stopDetailsByTurn.get(turnId);
3327
+ stopDetailsByTurn.delete(turnId);
3328
+ a.closeTurnDone(turnId, {
3329
+ outcome: { type: "error", message: fields.message, code: fields.code, retriable: fields.retriable },
3330
+ finishReason: "refusal",
3331
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
3332
+ safety: [{ category: "refusal", blocked: true }],
3333
+ ...(refusalDetails !== undefined
3334
+ ? { messageId: refusalDetails.messageId, messageMetadata: { stop_details: refusalDetails.value } }
3335
+ : {}),
3336
+ });
3337
+ return;
3338
+ }
3242
3339
  if (stashedError !== undefined) {
3243
3340
  // The assistant error frame decided this close; this frame adds the
3244
3341
  // turn's usage, the same mapping turn.done would have carried (SPEC §4:
@@ -3270,11 +3367,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3270
3367
  // that never happened. `code` is free-form (SPEC :618), so this fills
3271
3368
  // existing fields from the frame's own value; a live API error
3272
3369
  // (terminal_reason "api_error", api-error-auth) is unchanged.
3273
- const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
3370
+ const fields = resultErrorFields(msg);
3274
3371
  a.closeTurnError(turnId, {
3275
- message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
3276
- code,
3277
- retriable: apiErrorStatusRetriable(msg.api_error_status),
3372
+ message: fields.message,
3373
+ code: fields.code,
3374
+ retriable: fields.retriable,
3278
3375
  ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
3279
3376
  });
3280
3377
  return;
@@ -3290,9 +3387,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3290
3387
  // exactly what "paused" names). The result-meta deferredToolUse carry stays.
3291
3388
  // A later invoke that resumes the call opens its own turn, minted from its
3292
3389
  // own frames (INV-XINV). Never keyed on terminal_reason. An is_error result
3293
- // never reaches here: it closed above as turn.error, and so did a
3294
- // turn an API-error frame decided; the deferred tool found unavailable on
3295
- // resume ("tool_deferred_unavailable") is such an is_error close.
3390
+ // never reaches here: it closed above, as turn.error or, for a refusal, as
3391
+ // turn.done, and so did a turn an API-error frame decided; the deferred
3392
+ // tool found unavailable on resume ("tool_deferred_unavailable") is such
3393
+ // an is_error close.
3296
3394
  const deferredCall = readDeferredCall(msg);
3297
3395
  const stop: unknown = msg.stop_reason;
3298
3396
  if (deferredCall !== undefined && stop === "tool_deferred") {
@@ -3332,6 +3430,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3332
3430
  // frame emits it (below). Each turn has its own id now, so an entry can
3333
3431
  // only ever be this turn's.
3334
3432
  const stashedError = takeStashedTurnError(turnId);
3433
+ refusedTurns.delete(turnId);
3335
3434
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
3336
3435
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
3337
3436
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
@@ -3419,7 +3518,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3419
3518
  }
3420
3519
 
3421
3520
  if (msg.type === "system" && msg.subtype === "model_refusal_fallback") {
3422
- // Finding #1 (critical): the end-of-turn authoritative eviction record —
3521
+ // Refusal-fallback retraction: the end-of-turn authoritative eviction record —
3423
3522
  // "the complete audit record for the turn" per the field's own doc.
3424
3523
  // Idempotent with the earlier `supersedes`-triggered eviction above (see
3425
3524
  // `retractUuids`'s doc); also the ONLY retraction path when a consumer
@@ -3430,7 +3529,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3430
3529
  closePendingMessage();
3431
3530
  const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
3432
3531
  retractUuids(uuids);
3433
- // X4 (the 2026-09-23 re-cut): only the retraction has a core home.
3532
+ // The 2026-09-23 re-cut: only the retraction has a core home.
3434
3533
  // A notice yields 0..N `message.remove`s, so there is no single event to
3435
3534
  // hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
3436
3535
  // ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
@@ -3446,10 +3545,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3446
3545
  // whose content that home already conveys, and `message.remove` conveys
3447
3546
  // only the retraction. So the residual fields fall under item 22's
3448
3547
  // no-drop MUST, and the whole frame rides. (A clarifying
3449
- // line for item 22 is queued for the review bar.) `ext.*` is live-only
3548
+ // line for item 22 is queued for review.) `ext.*` is live-only
3450
3549
  // and non-folding, so the second copy of `retracted_message_uuids`
3451
- // cannot double-fold (the M22 hazard). This is the only producer for R&D
3452
- // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
3550
+ // cannot double-fold. This is the only producer for the candidate
3551
+ // `turn.model-switch` event. Synthetic-only (needs a classifier refusal).
3453
3552
  a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
3454
3553
  return;
3455
3554
  }
@@ -3458,8 +3557,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3458
3557
  // Fixture-drift ratchet finding: this standalone LIVE denial notice is
3459
3558
  // the SAME fact the already-handled `SDKResultMessage.permission_denials[]`
3460
3559
  // aggregate turns into a tool.start+tool.done{denied} pair inside the
3461
- // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
3462
- // second pair here (the M22 double-fold hazard). Record this frame's
3560
+ // `<turnId>:denials` carrier (above) — do NOT emit a
3561
+ // second pair here (a double fold). Record this frame's
3463
3562
  // richer diagnostic fields only; the aggregate handler consumes them.
3464
3563
  //
3465
3564
  // `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
@@ -3502,7 +3601,6 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3502
3601
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
3503
3602
  const carriedKind = anthropicFrameKind(msg);
3504
3603
  if (carriedKind !== undefined) {
3505
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3506
3604
  // B-strict: a background sub-run's outcome arrives as task_notification,
3507
3605
  // correlated to its run by tool_use_id (or by task_id through the
3508
3606
  // task_started frame that named it).
@@ -3521,6 +3619,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3521
3619
  }
3522
3620
  }
3523
3621
  }
3622
+ // The carry rides after the home events this frame produced (a correlated
3623
+ // task_notification's nested terminal and subagent.done), SPEC §8.0 item 22.
3624
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3524
3625
  return;
3525
3626
  }
3526
3627
 
@@ -3564,7 +3665,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3564
3665
  flush(): AgEvent[] {
3565
3666
  // INV-MSG: nothing can continue the deferred message now — seal it with
3566
3667
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3567
- // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3668
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3568
3669
  closePendingMessage(true);
3569
3670
  // B-strict: every subagent run still open closes here with its nested
3570
3671
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
@@ -3578,6 +3679,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3578
3679
  a.closeTurnError(turnId, { ...stashed });
3579
3680
  }
3580
3681
  stashedTurnErrors.clear();
3682
+ refusedTurns.clear();
3581
3683
  return a.flush();
3582
3684
  },
3583
3685
  };