@silverprotocol/claude-agent-sdk 0.6.2 → 0.6.4

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/README.md CHANGED
@@ -32,6 +32,7 @@ facet's per-field dispositions, including its disclosed `silently-dropped` gaps)
32
32
 
33
33
  | `@anthropic-ai/claude-agent-sdk` | verified | with | evidence |
34
34
  | --- | --- | --- | --- |
35
+ | `0.3.280` | 2026-09-23 | 0.6.3 | peer sweep 0.3.272 -> 0.3.280 (SEVEN published versions 0.3.273-0.3.278 and 0.3.280; 0.3.279 has an upstream CHANGELOG entry but was never published to npm; bundled CLI 2.1.272 -> 2.1.280). SDKMessage union UNCHANGED at 39 members and SDKAssistantMessageError unchanged at 13; sdk.d.ts diff 900 lines; agentSdkTypes.d.ts and extractFromBunfs.d.ts byte-identical. claude-opus-5-5 REQUIRES this version: older CLIs still send the id to the API but canonicalise it to claude-opus-5, so they price it at Opus 5 rates, default its effort to high instead of medium and report canonicalModel claude-opus-5. HEADLINE - CL-09, a wrong mapping that predates the cohort, LIVE-CONFIRMED with a deliberately invalid key: query() yielded an assistant frame with error authentication_failed and then a success result with is_error:true and api_error_status 401. Through 0.6.2 that pair produced turn.error AND THEN turn.done{success} on the same turnId, violating the one-close invariant, and reduce() folded the turn as a SUCCESS whose result was 'Failed to authenticate. API Error: 401 API key is invalid.' From 0.6.3 the assistant error frame stashes its close and the result frame emits exactly one turn.error, now carrying the result's usage (so a long agentic turn that fails on round N keeps the cost of its earlier rounds), on either result arm - which also removes a second double close, assistant error followed by an error-subtype result. A success result with is_error:true and NO preceding assistant error frame, which 0.6.2 closed as turn.done{success}, now closes as turn.error {code: api_error_code ?? 'api_error', retriable only for status 429 or >= 500, usage}; a stored 0.6.2 turn of that shape cannot be recovered from the AgJSON alone (its result is the error text). Flush emits a stashed close with no usage if no result arrives; the first error frame wins. Folding the same live frames: 0.6.2 -> [turn.error, turn.done{success}], folded success; 0.6.3 -> [turn.error authentication_failed, retriable false], folded error. CARRIES: usage_report (fixture-only), the undeclared api_error / api_error_params / api_error_code triad, result-meta apiErrorCode and startupFailureReason (retriable false except worktree_unverified), and the undeclared decision_reason_code on permission denials. 0.3.277 changed a carried value without a marker: total_cost_usd and modelUsage now continue across resume and fork (see the SDKResultMessage note). THINKING: with thinking.display unset, CLI 2.1.280 runs its connector_text selector, in which the API returns only between-tool narration and never a thinking summary; at most an empty thinking block carrying only its signature reaches the stream (the same selector exists in CLI 2.1.272, first-party path only). The 0.6.2 refresh of partials-fable51 therefore lost the corpus's only live thinking_delta frames - two EMPTY ones: no capture had ever carried summary text - and three 0.6.3 re-captures confirmed it is systematic, not chance. A new scenario knob (thinkingDisplay) sets thinking {type: adaptive, display: summarized}, and the new thinking-fable51 seed provides streamed summary text for the first time, deterministically: 13 thinking_delta frames, all with summary text, plus a signature_delta. The SDK typed a third display value, 'highlights', but only on setMaxThinkingTokens and its control request, where the API accepts it for Anthropic-hosted sessions only. LIVE at 0.3.280: echo-, partials- and app-update-sonnet5 and echo- and partials-fable51 refreshed; app-update-fable51 DELIBERATELY HELD at its 0.3.272 capture, as the corpus's only live narration_block_indexes evidence (three 0.3.280 re-captures produced no narration); NEW thinking-fable51, echo-, partials- and app-update-opus55, and echo-opus5 (Opus 5 is also a Claude Code 2.1.280 refusal-fallback target: bio and frontier_llm refusals fall back to it, cyber refusals to claude-opus-4-8). Census, after registering init mcp_servers[].source and plugins[], the stream-event cache_creation twins and the claude-opus-5-5 modelUsage family: ZERO drops / ZERO new fields on every claude seed. A replay surface guard now fails a refresh of any of the six single-surface seeds it names (thinking-fable51, app-update-fable51, thinking-gemini38, tool-error-gemini38, echo-gpt6sol/openai, app-spec-structured-result/openai) that drops the surface the seed exists for. Facet tests 168 -> 204. |
35
36
  | `0.3.272` | 2026-09-15 | 0.6.2 | peer sweep 0.3.261->0.3.272 (NINE published versions: 0.3.263/265/266/267/268/269/270/271/272; 0.3.262 and 0.3.264 were never published to npm; bundled CLI 2.1.261->2.1.272). 0.3.271->0.3.272 is .d.ts-byte-identical across all four declaration files, so the type audit was derived against 0.3.271 and carries forward unchanged. SDKMessage union UNCHANGED at 39 members (drift-gate-verified); sdk.d.ts diff 610 lines, independently re-derived from both tarballs; agentSdkTypes.d.ts and bridge.d.ts byte-identical. DECLARED stream-scope additions, all three now CARRIED: resume_reason (0.3.268) on SDKAssistantMessage, SDKPartialAssistantMessage and BOTH result arms -> the THIRD leg of the user_message_uuid turn-binding family, which 0.3.269 stamps under ONE rule ('first complete assistant message as well as first stream event when partial messages are on'), so it rides the SAME bag under the SAME once-per-message flag (renamed userMessageUuidCarried -> turnBindingCarried); written outside that guard it would double-emit message.metadata on every streamed lifecycle, and a regression test pins the single emission. result_index (0.3.268, both result arms) -> ext.anthropic.result-meta.resultIndex, guarded typeof==='number' because 0 is the first result of every run; a gap in the sequence is how a consumer detects a LOST result, which is why it is carried rather than allowlisted. local_command (0.3.268, SUCCESS arm only, undocumented upstream) -> result-meta.localCommand, read through the JSON boundary because the union declares no such property; its PRESENCE is the signal (it is the only thing separating a zero-round-trip slash-command success from an empty turn) while its value is deliberately coarse upstream (any user/project/third-party command slugs to 'custom', any MCP command to 'mcp'). SDKAssistantMessageError widened 11 -> 13 members (verification_required, cloud_credential_error): both are correctly NON-retriable (one needs an out-of-band human step, the other is a credential/billing-class failure re-sending cannot clear), so the expression is unchanged, but the decision is now recorded explicitly in the same false-by-omission voice as model_not_found / account_on_hold and pinned by an exhaustive 13-member set-invariance test. UNDECLARED runtime additions, found ONLY by live capture (absent from sdk.d.ts, so no type diff could have seen them): narration_block_indexes on the assistant wrapper -> CARRIED verbatim (it names which of this frame's content blocks are user-facing narration rather than private reasoning, i.e. Anthropic's thinking.display:'updates' progress updates; a rendering decision, so lossless carry over allowlist; a per-frame content fact like `aborted`, so deliberately NOT under the turn-binding flag, and it has no stream-event twin so it cannot double-carry); wire_tool_inputs, the verbatim wire copy of each tool call's input keyed by tool_use_id; and five null-only leaves (event.message.container, event.message.context_management, event.delta.container, usage.iterations[*].model, event.usage.iterations[*].model) allowlisted null-only as stream-event twins of already-allowlisted complete-frame siblings. CENSUS MACHINERY: wire_tool_inputs' keys are per-capture tool ids, so every capture minted a brand-new norm-path and the newFields gate could never be satisfied; normalizePath now collapses the key directly under an explicit ID_KEYED_CONTAINERS list to {id}, the same way it collapses [n] to [*]. The list is explicit, not a key-shape heuristic, precisely so meaningful map keys such as modelUsage.claude-sonnet-5 keep their own registry entries. LIVE at 0.3.272: all six claude seeds refreshed (echo-sonnet5, partials-sonnet5, app-update-sonnet5, echo-fable51, partials-fable51, app-update-fable51) - census ZERO drops / ZERO new fields on all six after triage. Facet tests 147 -> 168. WATCH ITEM CLOSED in part: narration_block_indexes is the first live evidence of the thinking-display 'updates' mode reaching this SDK's wire; the Agent SDK still types display as 'summarized'\|'omitted'. |
36
37
  | `0.3.261` | 2026-09-05 | 0.6.1 | peer sweep 0.3.258->0.3.261 (three patches; bundled CLI 2.1.258->2.1.261) - SDKMessage union unchanged (39 members, drift-gate-verified); sdk.d.ts diff 358 lines / 30 hunks, independently re-derived. Stream-scope field additions: user_message_uuids?: string[] on SDKAssistantMessage (first reply frame), SDKPartialAssistantMessage (first non-ping event) and both result arms (0.3.259) -> carried on the SAME three channels as the singular (wrapperMetaRaw first-block providerMetadata / block-less message.metadata; the stream arm's single message.metadata emit; result-meta.userMessageUuids camelCase) under the shared once-per-message flag - a CONSISTENCY carry: the string-prompt capture path supplies no client uuid, so no cassette has ever exercised the singular or the plural; SDKThinkingTokensMessage.user_message_uuid (0.3.260) rides the existing whole-frame carry; SDKResultSuccess first_content_frame_ms / first_stream_post_ms / first_stream_post_ack_ms / first_stream_post_wall_ms (0.3.260, remote-session latency) and SDKAPIRetryMessage.no_response {waited_ms, retry_wait_ms} (0.3.261) are router-plane (allowlisted + registered); the stale ttft_ms allowlist reason corrected (the facet DOES read it off the partial envelope). Control-plane only: permissionPrompts 'none', pluginDelivery 'initialize', reload_output_styles control subtype, initialize plugins/plugins_applied, get_usage skip_behaviors, settings shapes, Artifact tool schema. @anthropic-ai/sdk 0.124.0 is Admin-API/compliance only; the facet devDep ^0.93.0 provably cannot float (only 0.93.0 exists in >=0.93.0 <0.94.0). LIVE at 0.3.261 (CC 2.1.261): echo-sonnet5, partials-sonnet5, echo-fable51, partials-fable51, app-update-fable51 refreshed and the lagging app-update-sonnet5 (0.3.217) refreshed - census ZERO drops / ZERO new fields on all six; agjson byte-identical after regen except capture-time value drift. 8 unit tests added. Watch item: the Agent SDK still types thinking display 'summarized'\|'omitted' while @anthropic-ai/sdk 0.121.0+ types a third 'updates' mode - adoption would change thinking_delta text semantics under Fable's omitted display. |
37
38
  | `0.3.258` | 2026-09-02 | 0.5.4 | peer sweep 0.3.233->0.3.258 (20 npm versions; 17 GitHub releases) - SDKMessage union unchanged (39 members, drift-gate-verified) but SIX field-level stream additions the name-only gate cannot see (full d.ts diff, independently re-derived): ModelUsage.costBasis (0.3.246) + ModelUsage.thinkingTokens (0.3.257, subset of outputTokens) -> costBasis joins the per-model identity in ext.anthropic.result-meta, thinkingTokens -> usage.byModel[m].reasoningTokens; usage.output_tokens_details.thinking_tokens (real since the 0.3.257 fix; the old reviewed-any allowlist entry that would have masked it is DELETED) -> usage.reasoningTokens on message.end/turn.done (runtime-guarded; undeclared on the resolved @anthropic-ai/sdk 0.93.0 BetaUsage); user_message_uuid on assistant (first frame), stream_event (first non-ping) and both result arms -> wrapperMetaRaw / message.metadata / result-meta.userMessageUuid; queued_turn_count (both result arms, 0 real) -> result-meta.queuedTurnCount; tool_use_result.resourceLinks (0.3.257, runtime-only) -> tool.done providerMetadata.resourceLinks; SDKAssistantMessageError += account_on_hold (non-retriable, test); system/init effort (router-plane, allowlisted); Task* ambient/is_backgrounded/spawn_depth/resource_links ride the existing whole-frame carry. LIVE CAPTURES at 0.3.258 (Claude Code 2.1.258): echo-sonnet5 + partials-sonnet5 REFRESHED, and the FIRST claude-fable-5-1 seed trio echo-fable51 / partials-fable51 / app-update-fable51 (model GA 2026-09-01; Fable 5.1 requires CC >=2.1.257) - census caught FOUR runtime-only surfaces undeclared in the d.ts: result.subagent_stats (carried whole as result-meta.subagentStats), init.messaging_socket_path (allowlisted), thinking_delta.estimated_tokens (carried on reasoning.delta providerMetadata; core assembler gained the slot), and the first live system/thinking_tokens frames (SDKThinkingTokensMessage promoted router-plane -> carried whole-frame: the only thinking-progress signal under Fable's display:omitted), plus first observation of the typed init.terminal_slash_commands[] (allowlisted). partials-fable51 is the corpus's first live thinking_delta/signature_delta coverage (66 thinking tokens on the result frame, real non-zero reasoningTokens). Out of stream scope: PreModelSwitch/PostModelSwitch hooks, systemPrompt custom/snapshot, perTaskStopAffordance, SDK MCP server timeout, update_settings control, settings shapes, sdk-tools schemas, origin.fromMode/'projects-relay' growth inside the disclosed unread origin. Peer @anthropic-ai/sdk stays >=0.93.0 (facet devDep ^0.93.0 resolves 0.93.0; 0.123.0's BetaFallbackBlock/fallback_credit/output_tokens_details are typed-only additions - a runtime fallback block already lands as provider-raw). Pin + 9 platform-binary exclusions bumped; facet devDep ^0.3.258; 8 unit tests + 3 seeds added; full gate suite green. |
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAGL,KAAK,cAAc,EAQnB,KAAK,UAAU,EAGhB,MAAM,sBAAsB,CAAC;AAO9B,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC;AAE/D,KAAK,YAAY,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAE5C,KAAK,cAAc,GAAG,WAAW,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,CAAC;AAiC/D,iBAAS,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,GAAG,cAAc,CAwB3E;AAypBD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CA8mCxF;AAED,eAAe,sBAAsB,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAGL,KAAK,cAAc,EAQnB,KAAK,UAAU,EAGhB,MAAM,sBAAsB,CAAC;AAO9B,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC;AAE/D,KAAK,YAAY,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAE5C,KAAK,cAAc,GAAG,WAAW,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,CAAC;AAiC/D,iBAAS,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,GAAG,cAAc,CAwB3E;AAuvBD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAu3CxF;AAED,eAAe,sBAAsB,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -450,6 +450,12 @@ function isSDKMessage(v) {
450
450
  // branch + `deniedLiveByToolUseId` in `createClaudeNormalizer()` below; it
451
451
  // is deliberately EXCLUDED from the carried sets here.
452
452
  //
453
+ // SDKModelRefusalFallbackMessage is HALF-mapped: its retraction goes to
454
+ // `message.remove` (§8 item 19) and the rest of the frame has no home. It is
455
+ // NOT in the sets below either. Its dedicated branch does the retraction and
456
+ // then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
457
+ // sp-protocol's item-22 reading for half-mapped frames — see that branch).
458
+ //
453
459
  // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
454
460
  // §12) — not 15 distinct ext keys (ext-vocabulary sprawl, the standing
455
461
  // review Minor this closes). `kind` is the frame's own discriminating
@@ -536,6 +542,65 @@ function readNarrationBlockIndexes(v) {
536
542
  ? v
537
543
  : undefined;
538
544
  }
545
+ // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
546
+ // on both frames that carry it (the API-error assistant frame and the
547
+ // `is_error: true` success result), so it is read through the JSON boundary.
548
+ // The CLI copies the server's error.details.error_code through only when it is
549
+ // an identifier (^[a-z][a-z0-9_]{0,63}$); the facet does not re-validate the
550
+ // producer's invariant, it only refuses a non-string.
551
+ function readApiErrorCode(v) {
552
+ return isJsonObject(v) && typeof v["api_error_code"] === "string" ? v["api_error_code"] : undefined;
553
+ }
554
+ // `startup_failure_reason` (0.3.274) — declared on SDKResultError ONLY, so on
555
+ // the result union it is reachable only through the JSON boundary.
556
+ function readStartupFailureReason(v) {
557
+ return isJsonObject(v) && typeof v["startup_failure_reason"] === "string"
558
+ ? v["startup_failure_reason"]
559
+ : undefined;
560
+ }
561
+ // `turn.error.retriable` for a result that carries `startup_failure_reason`.
562
+ // The type's own lead sentence frames the whole enum as a refusal to start:
563
+ // "Why Claude Code refused to start, so a host can offer the fix instead of a
564
+ // retry." So a PRESENT reason means NOT retriable, except for the values
565
+ // upstream itself EXPLICITLY describes as retriable. At 0.3.280 that set is
566
+ // exactly one value:
567
+ // - `worktree_unverified`: "the session's worktree could not be verified
568
+ // right now; retrying may succeed."
569
+ // Three more values read as if they might clear on their own, but upstream
570
+ // never says a retry helps, so each is a deliberate non-retriable — explicit
571
+ // false-by-omission (the model_not_found / account_on_hold voice in the
572
+ // assistant-error branch), never an oversight:
573
+ // - `org_verify_failed`: "the sign-in's organization could not be verified
574
+ // against the pin (network, or a revoked token)." A revoked token is not
575
+ // transient, and the doc does not tell the two causes apart.
576
+ // - `remote_settings_required_unavailable`: "managed settings the
577
+ // organization requires could not be loaded." No retry guidance; whether
578
+ // the load failure is transient is not stated.
579
+ // - `session_held_by_background`: "the conversation to resume or continue is
580
+ // running as a background session." Nothing says the hold clears, or when.
581
+ // Every other documented value (org_pin_api_key_conflict, org_pin_mismatch,
582
+ // managed_settings_invalid, gateway_signin_required, gateway_access_denied,
583
+ // proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
584
+ // worktree_resume_refused, cli_version_too_old, bypass_root) names a
585
+ // configuration, policy or environment fix, and an unknown future value
586
+ // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
587
+ // reason never reaches this function: the error arm keeps its old rule, so
588
+ // older producers are byte-identical.
589
+ const RETRIABLE_STARTUP_FAILURE_REASONS = new Set(["worktree_unverified"]);
590
+ function startupFailureRetriable(reason) {
591
+ return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
592
+ }
593
+ // `turn.error.retriable` for an API-error turn closed by its result frame:
594
+ // retriable exactly when the HTTP status is a rate limit (429) or a server-
595
+ // side failure (>= 500, which includes 529 overloaded) — the result-frame
596
+ // twin of the assistant-error branch's rate_limit / server_error / overloaded
597
+ // set. A null or absent status is not retriable: it carries no evidence that a
598
+ // re-send would behave differently. Typed `number | null` on the
599
+ // success arm, but the frame is only discriminant-validated, so it is guarded
600
+ // with typeof.
601
+ function apiErrorStatusRetriable(status) {
602
+ return typeof status === "number" && (status === 429 || status >= 500);
603
+ }
539
604
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
540
605
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
541
606
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -629,6 +694,25 @@ function readNarrationBlockIndexes(v) {
629
694
  // was not given — under the normalized name `localCommand`. Read through the
630
695
  // `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
631
696
  // union has no such property to access.
697
+ //
698
+ // 0.3.280 bump — two more result-frame siblings on the SAME carry:
699
+ // - `api_error_code` (SUCCESS arm, CLI 2.1.280, @internal — UNDECLARED in
700
+ // sdk.d.ts, so no typed access exists): "the api_error_code of the API error
701
+ // that ended the turn (see SDKAssistantMessage.api_error_code): the server's
702
+ // error.details.error_code when it is an identifier". It rides the
703
+ // `is_error: true` success result an API-error turn ends with, and it names
704
+ // server gate codes `SDKAssistantMessageError` flattens to 'unknown', so a
705
+ // host can key on a new gate without a Claude Code release. Normalized
706
+ // `apiErrorCode`; the same value is `turn.error.code` when no assistant
707
+ // error frame preceded this result, so the result alone builds the close
708
+ // (see the success branch in `drive()`).
709
+ // - `startup_failure_reason` (ERROR arm only, 0.3.274): set on the zeroed
710
+ // error_during_execution result a stream-json run writes before exiting on
711
+ // a known startup failure — "Why Claude Code refused to start, so a host
712
+ // can offer the fix instead of a retry". Normalized `startupFailureReason`,
713
+ // value verbatim; it also drives `turn.error.retriable` (see
714
+ // `startupFailureRetriable`). Read through the JSON boundary because it is
715
+ // declared on that one arm only.
632
716
  function resultMetaPayload(msg) {
633
717
  const byModel = {};
634
718
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
@@ -651,6 +735,10 @@ function resultMetaPayload(msg) {
651
735
  // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
652
736
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
653
737
  const localCommand = isJsonObject(raw) && typeof raw["local_command"] === "string" ? raw["local_command"] : undefined;
738
+ // 0.3.280 — undeclared on both arms (`api_error_code`) / declared on the
739
+ // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
740
+ const apiErrorCode = readApiErrorCode(msg);
741
+ const startupFailureReason = readStartupFailureReason(msg);
654
742
  const payload = {
655
743
  ...(typeof msg.fast_mode_disabled_reason === "string"
656
744
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -662,6 +750,8 @@ function resultMetaPayload(msg) {
662
750
  // 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
663
751
  ...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
664
752
  ...(localCommand !== undefined ? { localCommand } : {}),
753
+ ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
754
+ ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
665
755
  ...(subagentStats !== undefined ? { subagentStats } : {}),
666
756
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
667
757
  };
@@ -694,15 +784,32 @@ export function createClaudeNormalizer(options = {}) {
694
784
  // `message.remove` — "translated through the facet's uuid→messageId
695
785
  // convention" per the adaptation brief.
696
786
  const messageIdsByUuid = new Map();
697
- // Fixture-drift ratchet (SDKPermissionDeniedMessage, "handled" via existing-
698
- // home mapping): live per-denial diagnostic recorded by the standalone
699
- // `permission_denied` frame (fires DURING the turn, before the terminal
700
- // result) — keyed by tool_use_id so the terminal `permission_denials[]`
701
- // aggregate (the ALREADY-handled W1 `<turnId>:denials` carrier, audit M19)
702
- // can enrich its tool.done with the actual rejection text + decision-reason
703
- // context, instead of emitting a SECOND tool.start/tool.done pair for the
704
- // same denial (the M22 double-fold hazard).
705
787
  const deniedLiveByToolUseId = new Map();
788
+ // The live denial's diagnostic fields, camelCased — the providerMetadata bag
789
+ // on the enriched `<turnId>:denials` tool.done. undefined when the live
790
+ // frame carried none of them (no empty bag).
791
+ function liveDenialMeta(live) {
792
+ if (live === undefined ||
793
+ (live.decisionReasonType === undefined &&
794
+ live.decisionReasonCode === undefined &&
795
+ live.decisionReason === undefined &&
796
+ live.agentId === undefined)) {
797
+ return undefined;
798
+ }
799
+ return {
800
+ ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
801
+ ...(live.decisionReasonCode !== undefined ? { decisionReasonCode: live.decisionReasonCode } : {}),
802
+ ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
803
+ ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
804
+ };
805
+ }
806
+ const stashedTurnErrors = new Map();
807
+ /** Remove and return the stashed error close for `turnId`, if any (CL-09). */
808
+ function takeStashedTurnError(turnId) {
809
+ const stashed = stashedTurnErrors.get(turnId);
810
+ stashedTurnErrors.delete(turnId);
811
+ return stashed;
812
+ }
706
813
  let pending;
707
814
  // How many lifecycles each SDK message id has already opened. A same-id frame
708
815
  // arriving after its lifecycle closed (a fold-binding frame landed between two
@@ -1203,6 +1310,20 @@ export function createClaudeNormalizer(options = {}) {
1203
1310
  // wrapper-meta channel's type without an unchecked cast.
1204
1311
  wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1205
1312
  }
1313
+ // `usage_report` (0.3.273): the structured twin of the /usage report,
1314
+ // riding the synthetic assistant message that delivers its text (session
1315
+ // totals, the plan's usage rows, extra-usage spend) — context_usage's
1316
+ // sibling, same wrapper-level placement per its own doc (never inside
1317
+ // `message.content`, not replayed to the model), so it gets the same carry:
1318
+ // whole and verbatim, wire name kept. Carried whole rather than field by
1319
+ // field because upstream marks SDKUsageReport "Experimental — the shape may
1320
+ // change". A per-frame fact like context_usage, so it sits OUTSIDE the
1321
+ // turn-binding guard. FIXTURE-ONLY: upstream attaches it only "from
1322
+ // claude.ai-subscriber sessions", and the capture harness authenticates
1323
+ // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1324
+ if (msg.usage_report !== undefined) {
1325
+ wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
1326
+ }
1206
1327
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1207
1328
  // the indexes of THIS frame's content blocks that are user-facing narration
1208
1329
  // — Anthropic's `thinking.display: "updates"` mode returns progress updates
@@ -1219,6 +1340,38 @@ export function createClaudeNormalizer(options = {}) {
1219
1340
  if (narrationBlockIndexes !== undefined) {
1220
1341
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1221
1342
  }
1343
+ // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1344
+ // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1345
+ // The CLI stamps them on the synthetic API-error assistant frame, the one
1346
+ // that also carries `error`, which SDKAssistantMessageError flattens to a
1347
+ // 13-value set (a new server gate reads as 'unknown'):
1348
+ // - `api_error`: the typed kind of the error ("for consumers that key on
1349
+ // the cause instead of the message text"), a closed CLI enum of 25
1350
+ // values at CLI 2.1.280 (dlp_request_denied, claude_code_version_too_old,
1351
+ // effort_requires_thinking, provider_credentials, …; "new values are
1352
+ // added over time"). Carried as a string, not enum-gated.
1353
+ // - `api_error_params`: `{effort?, provider?, remedy?}`, "present only
1354
+ // for the kinds that have any" — `remedy` is the fix a host should
1355
+ // offer (refresh_command, refresh_credentials, adc, …). Carried whole.
1356
+ // - `api_error_code`: the server's error.details.error_code, so "a host
1357
+ // can key on a new gate without a Claude Code release".
1358
+ // Per-frame facts of the error frame, like `aborted` / `context_usage`, so
1359
+ // they sit OUTSIDE the turn-binding guard. Wire names verbatim. The frame's
1360
+ // `is_api_error_message: true` flag is deliberately NOT carried: it
1361
+ // restates `error` being set, which already decides the turn's turn.error
1362
+ // close (stashed until the result frame — see `stashedTurnErrors`).
1363
+ if (isJsonObject(rawAssistant)) {
1364
+ const apiError = rawAssistant["api_error"];
1365
+ if (typeof apiError === "string")
1366
+ wrapperMetaRaw["api_error"] = apiError;
1367
+ const apiErrorParams = rawAssistant["api_error_params"];
1368
+ if (isJsonObject(apiErrorParams))
1369
+ wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
1370
+ }
1371
+ const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1372
+ if (assistantApiErrorCode !== undefined) {
1373
+ wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1374
+ }
1222
1375
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1223
1376
  // the bag below, once `open` is known — their once-per-message flag is
1224
1377
  // shared with the stream arm's carry.
@@ -1353,38 +1506,46 @@ export function createClaudeNormalizer(options = {}) {
1353
1506
  // not — without this merge the join would erase the streamed count.
1354
1507
  open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
1355
1508
  // If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
1356
- // emit a turn.error so consumers see the error rather than a silent empty turn.
1509
+ // the turn ends as a turn.error so consumers see the error rather than a
1510
+ // silent empty turn. CL-09: the close is STASHED, not emitted here — the
1511
+ // turn's result frame (which carries the turn's usage) emits it, or
1512
+ // `flush()` does if no result ever arrives (see `stashedTurnErrors`).
1357
1513
  if (msg.error !== undefined) {
1358
- // The turn is over — nothing can continue this message. Seal it first,
1359
- // so `message.end` still precedes the close (unchanged order).
1514
+ // The API error ended the model's output — nothing can continue this
1515
+ // message. Seal it now, so `message.end` still precedes the (deferred)
1516
+ // close.
1360
1517
  closePendingMessage();
1361
1518
  const errCode = msg.error;
1362
- a.closeTurnError(turnId, {
1363
- message: errCode,
1364
- code: errCode,
1365
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1366
- // cousin of rate_limit/server_error) joins the retriable set.
1367
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1368
- // decommissioned model id) is deliberately EXCLUDED: explicit
1369
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1370
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1371
- // deliberate non-retriable: a billing-class code (the account is on
1372
- // hold — a first cousin of `billing_error`, cleared by the account
1373
- // holder, never by re-sending the turn).
1374
- //
1375
- // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1376
- // deliberate non-retriables recorded here for the same reason — an
1377
- // omission must never read as an oversight:
1378
- // - `verification_required`: the request is gated on an out-of-band
1379
- // human step (identity/org verification). Nothing about the turn
1380
- // changes by re-sending it; the block clears only when a person
1381
- // completes the verification.
1382
- // - `cloud_credential_error`: a credential/billing-class failure on
1383
- // the cloud-provider leg (a first cousin of `billing_error` and
1384
- // `account_on_hold`, not of `overloaded`) — a bad, expired or
1385
- // unauthorized credential is exactly as bad on the next attempt.
1386
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1387
- });
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
+ });
1548
+ }
1388
1549
  }
1389
1550
  // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
1390
1551
  // message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
@@ -1397,6 +1558,29 @@ export function createClaudeNormalizer(options = {}) {
1397
1558
  return;
1398
1559
  }
1399
1560
  if (msg.type === "user") {
1561
+ // SDKUserMessageReplay (`isReplay: true`, typed only on that arm; a
1562
+ // runtime `isReplay: false` also exists, so only `=== true` counts) emits
1563
+ // NO core event and does NOT seal the open message (sp-rnd lead,
1564
+ // 2026-09-23). The CLI 2.1.280 replay builders are the host's own-prompt
1565
+ // acks (sent on stdin accept, never held), queued-prompt merges, history
1566
+ // re-sends (filtered to `!toolUseResult`, so no tool_results), and
1567
+ // local-command/bash echo+output. All of them are string or prompt content,
1568
+ // which this branch never mapped (it maps only tool_result blocks), so
1569
+ // skipping loses nothing it used to emit. What the skip fixes:
1570
+ // - REALISTIC: an ack landing mid-stream used to run closePendingMessage()
1571
+ // and split the streaming message (the complete frame then re-opened a
1572
+ // `:cont:` copy). Returning first keeps it a byte-identical no-op.
1573
+ // - DEFENSIVE (fixture-only; no 0.3.280 builder produces it): a replayed
1574
+ // tool_result re-emitted `tool.done`. After its turn's `turn.done` that
1575
+ // parked `reduce()` for the rest of the stream (INV-MSG, SPEC:745); in a
1576
+ // fresh normalizer it carried no turnId and parked from event 0.
1577
+ // DISCLOSED GAP, unchanged by this fix: replayed string content that is the
1578
+ // FIRST delivery (bash `<bash-input>` echo and output, local-command
1579
+ // output) has no AgJSON event. It is a candidate for the item-22 carry
1580
+ // `ext.anthropic.frame{kind:"user"}`. The replay's `tool_use_result`
1581
+ // sibling, read here for live frames, is no longer read on replays.
1582
+ if ("isReplay" in msg && msg.isReplay === true)
1583
+ return;
1400
1584
  // guuey#26: a tool_result binds to the fold — seal the open assistant
1401
1585
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1402
1586
  // adoption below depends on this ordering).
@@ -1517,6 +1701,26 @@ export function createClaudeNormalizer(options = {}) {
1517
1701
  // (message.end has always preceded the turn close).
1518
1702
  closePendingMessage();
1519
1703
  const turnId = turnIdFor(msg.session_id, msg.uuid);
1704
+ // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1705
+ // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1706
+ // the final assistant text in result — or, with is_error true, the error
1707
+ // text when the turn ended on an API error". The CLI sets is_error from
1708
+ // the turn's last assistant frame being its synthetic API-error message
1709
+ // (rate_limit / overloaded after retries ran out, billing_error,
1710
+ // authentication_failed, …). Such a turn closes as an ERROR, never as a
1711
+ // success, and exactly once:
1712
+ // - if that assistant frame reached this facet, it stashed the turn's
1713
+ // error close (`stashedTurnErrors`); this frame emits it, with this
1714
+ // frame's usage — whatever is_error says, since that frame already
1715
+ // decided the turn's outcome;
1716
+ // - otherwise, with is_error true, this frame is the only evidence of
1717
+ // the error, and the close is a turn.error built from the result
1718
+ // itself (see below).
1719
+ // Strict `=== true`: is_error is typed boolean, but the frame is only
1720
+ // discriminant-validated, and false/absent must stay on the success path
1721
+ // byte-for-byte. The stash entry is consumed either way.
1722
+ const stashedError = takeStashedTurnError(turnId);
1723
+ const apiErrorTurn = msg.is_error === true;
1520
1724
  const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1521
1725
  // structured_output (when a response schema is in effect) overrides the plain
1522
1726
  // string result — it is the authoritative typed outcome payload (spec §4).
@@ -1524,6 +1728,9 @@ export function createClaudeNormalizer(options = {}) {
1524
1728
  // Emit permission_denials as tool.start + tool.done denied pairs, inside a
1525
1729
  // dedicated carrier message: the assistant message is already sealed, and
1526
1730
  // INV-MSG (audit M19) forbids attaching to sealed messages / closed turns.
1731
+ // CL-09: an API-error turn's denials take this same carrier, at the same
1732
+ // point — its close is deferred to this frame (below), so the turn is
1733
+ // still open here, like every other turn.
1527
1734
  if (msg.permission_denials.length > 0) {
1528
1735
  const denialMsgId = `${turnId}:denials`;
1529
1736
  a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
@@ -1537,14 +1744,8 @@ export function createClaudeNormalizer(options = {}) {
1537
1744
  // tool.start/tool.done pair is ever emitted for the live frame
1538
1745
  // itself (see the dedicated `permission_denied` branch below).
1539
1746
  const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1540
- const liveMeta = live !== undefined &&
1541
- (live.decisionReasonType !== undefined || live.decisionReason !== undefined || live.agentId !== undefined)
1542
- ? AgProviderMeta.parse({
1543
- ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
1544
- ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
1545
- ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
1546
- })
1547
- : undefined;
1747
+ const liveFields = liveDenialMeta(live);
1748
+ const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1548
1749
  a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1549
1750
  a.toolDone({
1550
1751
  toolCallId: denial.tool_use_id,
@@ -1557,11 +1758,41 @@ export function createClaudeNormalizer(options = {}) {
1557
1758
  }
1558
1759
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1559
1760
  // ride `ext.anthropic.result-meta` before the close (no core home on
1560
- // turn.done — see resultMetaPayload's doc).
1761
+ // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
1762
+ // API-error turn too, before its close like on every other turn.
1561
1763
  const resultMeta = resultMetaPayload(msg);
1562
1764
  if (resultMeta !== undefined) {
1563
1765
  a.emitExt("anthropic", "result-meta", resultMeta);
1564
1766
  }
1767
+ if (stashedError !== undefined) {
1768
+ // The assistant error frame decided this close; this frame adds the
1769
+ // turn's usage, the same mapping turn.done would have carried (SPEC §4:
1770
+ // turn.error `usage` is "accrued billing on the interrupted turn"), so
1771
+ // the fold keeps the cost of every round the turn ran before failing.
1772
+ a.closeTurnError(turnId, {
1773
+ ...stashedError,
1774
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
1775
+ });
1776
+ return;
1777
+ }
1778
+ if (apiErrorTurn) {
1779
+ // No assistant error frame preceded this result (a producer that did
1780
+ // 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";
1788
+ a.closeTurnError(turnId, {
1789
+ message: typeof msg.result === "string" ? msg.result : code,
1790
+ code,
1791
+ retriable: apiErrorStatusRetriable(msg.api_error_status),
1792
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
1793
+ });
1794
+ return;
1795
+ }
1565
1796
  a.closeTurnDone(turnId, {
1566
1797
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1567
1798
  finishReason: mapStopReason(msg.stop_reason),
@@ -1575,13 +1806,25 @@ export function createClaudeNormalizer(options = {}) {
1575
1806
  // guuey#26: seal the open assistant message before the turn close.
1576
1807
  closePendingMessage();
1577
1808
  const turnId = turnIdFor(msg.session_id, msg.uuid);
1809
+ // 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).
1812
+ const stashedError = takeStashedTurnError(turnId);
1578
1813
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1579
1814
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
1580
1815
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
1581
1816
  // not throw (Tenet 6: graceful, never throws).
1582
1817
  const errors = Array.isArray(msg.errors) ? msg.errors : [];
1583
1818
  const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
1584
- const retriable = subtype !== "error_max_turns";
1819
+ // CL-04 (0.3.274): a known startup failure says why the CLI refused to
1820
+ // start, and upstream frames it as "offer the fix instead of a retry" —
1821
+ // so a PRESENT reason decides retriable (false, except the values upstream
1822
+ // itself calls retriable; see `startupFailureRetriable`). An ABSENT reason
1823
+ // keeps the old rule, byte-identical for every older producer.
1824
+ const startupFailureReason = readStartupFailureReason(msg);
1825
+ const retriable = startupFailureReason !== undefined
1826
+ ? startupFailureRetriable(startupFailureReason)
1827
+ : subtype !== "error_max_turns";
1585
1828
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1586
1829
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1587
1830
  // success arm above (turn.error carries no metadata slot at all).
@@ -1589,6 +1832,31 @@ export function createClaudeNormalizer(options = {}) {
1589
1832
  if (resultMeta !== undefined) {
1590
1833
  a.emitExt("anthropic", "result-meta", resultMeta);
1591
1834
  }
1835
+ if (stashedError !== undefined) {
1836
+ // CL-09: an assistant error frame already decided this turn's close —
1837
+ // emit THAT one (the first error that ended the turn), once, never a
1838
+ // second turn.error for the same turnId (INV-TURN), with this frame's
1839
+ // usage (the success arm's mapping). This arm is only
1840
+ // discriminant-validated, so the usage trio is shape-guarded first
1841
+ // (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
1845
+ // 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;
1857
+ a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
1858
+ return;
1859
+ }
1592
1860
  a.closeTurnError(turnId, {
1593
1861
  message: errors.length > 0 ? errors.join("; ") : subtype,
1594
1862
  code: subtype,
@@ -1632,6 +1900,27 @@ export function createClaudeNormalizer(options = {}) {
1632
1900
  closePendingMessage();
1633
1901
  const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
1634
1902
  retractUuids(uuids);
1903
+ // X4 (sp-rnd re-cut, 2026-09-23): only the retraction has a core home.
1904
+ // A notice yields 0..N `message.remove`s, so there is no single event to
1905
+ // hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
1906
+ // ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
1907
+ // `scope` ('session'|'local', absent ⇒ 'session' on older CLIs),
1908
+ // `original_model`/`fallback_model`, `request_id`, `api_refusal_category`
1909
+ // /`_explanation`, `refused_user_message_uuid` (the edit-and-retry target)
1910
+ // and the human-readable `content`. Through 0.6.3 it was dropped. It now
1911
+ // rides the uniform carry beside its `model_refusal_no_fallback` sibling
1912
+ // (SPEC §8 item 22 / §12), the WHOLE frame verbatim, AFTER the removes
1913
+ // (the frame is itself "emitted AFTER the retraction"). Item 22 says a
1914
+ // mapped frame goes to its home "instead" of the bulk carry. sp-protocol
1915
+ // ruled on 2026-09-23 (SPEC blob bef014c) that the clause covers frames
1916
+ // whose content that home already conveys, and `message.remove` conveys
1917
+ // only the retraction. So the residual fields fall under item 22's
1918
+ // no-drop MUST, and the whole frame rides. (sp-protocol's clarifying
1919
+ // line for item 22 is queued for the review bar.) `ext.*` is live-only
1920
+ // and non-folding, so the second copy of `retracted_message_uuids`
1921
+ // cannot double-fold (the M22 hazard). This is the only producer for R&D
1922
+ // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
1923
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
1635
1924
  return;
1636
1925
  }
1637
1926
  if (msg.type === "system" && msg.subtype === "permission_denied") {
@@ -1641,9 +1930,26 @@ export function createClaudeNormalizer(options = {}) {
1641
1930
  // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
1642
1931
  // second pair here (the M22 double-fold hazard). Record this frame's
1643
1932
  // richer diagnostic fields only; the aggregate handler consumes them.
1933
+ //
1934
+ // `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
1935
+ // at 0.3.280, so read through the JSON boundary, never cast): "A
1936
+ // closed-set code for a reason a host can act on, beside
1937
+ // decision_reason_type (whose values are unchanged)":
1938
+ // 'outside_reads_blocked' (permissions.blockReadsOutsideWorkingDirectories
1939
+ // refused the path), 'memory_paused' (/pause-memory has memory paused),
1940
+ // 'classifier_transcript_too_long' (the auto-mode classifier's transcript
1941
+ // exceeded its context window). "Absent for every other reason; new values
1942
+ // are additive" — carried as a string, not enum-gated, camelCased beside
1943
+ // its `decisionReasonType` sibling. Fixture-only: the capture harness
1944
+ // produces no denials.
1945
+ const rawDenied = msg;
1946
+ const decisionReasonCode = isJsonObject(rawDenied) && typeof rawDenied["decision_reason_code"] === "string"
1947
+ ? rawDenied["decision_reason_code"]
1948
+ : undefined;
1644
1949
  deniedLiveByToolUseId.set(msg.tool_use_id, {
1645
1950
  message: msg.message,
1646
1951
  ...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
1952
+ ...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
1647
1953
  ...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
1648
1954
  ...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
1649
1955
  });
@@ -1687,6 +1993,14 @@ export function createClaudeNormalizer(options = {}) {
1687
1993
  // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1688
1994
  // to synthesize a bare `message.end`.
1689
1995
  closePendingMessage();
1996
+ // CL-09: a turn whose assistant error frame stashed its close but whose
1997
+ // result frame never arrived still closes as that turn.error (no usage:
1998
+ // only a result carries the turn's), never as INV-FLUSH's synthesized
1999
+ // turn.abort — the outcome the frame's own close used to produce.
2000
+ for (const [turnId, stashed] of stashedTurnErrors) {
2001
+ a.closeTurnError(turnId, { ...stashed });
2002
+ }
2003
+ stashedTurnErrors.clear();
1690
2004
  return a.flush();
1691
2005
  },
1692
2006
  };