@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/src/index.ts CHANGED
@@ -557,6 +557,12 @@ function isSDKMessage(v: unknown): v is SDKMessage {
557
557
  // branch + `deniedLiveByToolUseId` in `createClaudeNormalizer()` below; it
558
558
  // is deliberately EXCLUDED from the carried sets here.
559
559
  //
560
+ // SDKModelRefusalFallbackMessage is HALF-mapped: its retraction goes to
561
+ // `message.remove` (§8 item 19) and the rest of the frame has no home. It is
562
+ // NOT in the sets below either. Its dedicated branch does the retraction and
563
+ // then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
564
+ // sp-protocol's item-22 reading for half-mapped frames — see that branch).
565
+ //
560
566
  // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
561
567
  // §12) — not 15 distinct ext keys (ext-vocabulary sprawl, the standing
562
568
  // review Minor this closes). `kind` is the frame's own discriminating
@@ -647,6 +653,69 @@ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
647
653
  : undefined;
648
654
  }
649
655
 
656
+ // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
657
+ // on both frames that carry it (the API-error assistant frame and the
658
+ // `is_error: true` success result), so it is read through the JSON boundary.
659
+ // The CLI copies the server's error.details.error_code through only when it is
660
+ // an identifier (^[a-z][a-z0-9_]{0,63}$); the facet does not re-validate the
661
+ // producer's invariant, it only refuses a non-string.
662
+ function readApiErrorCode(v: unknown): string | undefined {
663
+ return isJsonObject(v) && typeof v["api_error_code"] === "string" ? v["api_error_code"] : undefined;
664
+ }
665
+
666
+ // `startup_failure_reason` (0.3.274) — declared on SDKResultError ONLY, so on
667
+ // the result union it is reachable only through the JSON boundary.
668
+ function readStartupFailureReason(v: unknown): string | undefined {
669
+ return isJsonObject(v) && typeof v["startup_failure_reason"] === "string"
670
+ ? v["startup_failure_reason"]
671
+ : undefined;
672
+ }
673
+
674
+ // `turn.error.retriable` for a result that carries `startup_failure_reason`.
675
+ // The type's own lead sentence frames the whole enum as a refusal to start:
676
+ // "Why Claude Code refused to start, so a host can offer the fix instead of a
677
+ // retry." So a PRESENT reason means NOT retriable, except for the values
678
+ // upstream itself EXPLICITLY describes as retriable. At 0.3.280 that set is
679
+ // exactly one value:
680
+ // - `worktree_unverified`: "the session's worktree could not be verified
681
+ // right now; retrying may succeed."
682
+ // Three more values read as if they might clear on their own, but upstream
683
+ // never says a retry helps, so each is a deliberate non-retriable — explicit
684
+ // false-by-omission (the model_not_found / account_on_hold voice in the
685
+ // assistant-error branch), never an oversight:
686
+ // - `org_verify_failed`: "the sign-in's organization could not be verified
687
+ // against the pin (network, or a revoked token)." A revoked token is not
688
+ // transient, and the doc does not tell the two causes apart.
689
+ // - `remote_settings_required_unavailable`: "managed settings the
690
+ // organization requires could not be loaded." No retry guidance; whether
691
+ // the load failure is transient is not stated.
692
+ // - `session_held_by_background`: "the conversation to resume or continue is
693
+ // running as a background session." Nothing says the hold clears, or when.
694
+ // Every other documented value (org_pin_api_key_conflict, org_pin_mismatch,
695
+ // managed_settings_invalid, gateway_signin_required, gateway_access_denied,
696
+ // proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
697
+ // worktree_resume_refused, cli_version_too_old, bypass_root) names a
698
+ // configuration, policy or environment fix, and an unknown future value
699
+ // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
700
+ // reason never reaches this function: the error arm keeps its old rule, so
701
+ // older producers are byte-identical.
702
+ const RETRIABLE_STARTUP_FAILURE_REASONS = new Set<string>(["worktree_unverified"]);
703
+ function startupFailureRetriable(reason: string): boolean {
704
+ return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
705
+ }
706
+
707
+ // `turn.error.retriable` for an API-error turn closed by its result frame:
708
+ // retriable exactly when the HTTP status is a rate limit (429) or a server-
709
+ // side failure (>= 500, which includes 529 overloaded) — the result-frame
710
+ // twin of the assistant-error branch's rate_limit / server_error / overloaded
711
+ // set. A null or absent status is not retriable: it carries no evidence that a
712
+ // re-send would behave differently. Typed `number | null` on the
713
+ // success arm, but the frame is only discriminant-validated, so it is guarded
714
+ // with typeof.
715
+ function apiErrorStatusRetriable(status: unknown): boolean {
716
+ return typeof status === "number" && (status === 429 || status >= 500);
717
+ }
718
+
650
719
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
651
720
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
652
721
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -740,6 +809,25 @@ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
740
809
  // was not given — under the normalized name `localCommand`. Read through the
741
810
  // `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
742
811
  // union has no such property to access.
812
+ //
813
+ // 0.3.280 bump — two more result-frame siblings on the SAME carry:
814
+ // - `api_error_code` (SUCCESS arm, CLI 2.1.280, @internal — UNDECLARED in
815
+ // sdk.d.ts, so no typed access exists): "the api_error_code of the API error
816
+ // that ended the turn (see SDKAssistantMessage.api_error_code): the server's
817
+ // error.details.error_code when it is an identifier". It rides the
818
+ // `is_error: true` success result an API-error turn ends with, and it names
819
+ // server gate codes `SDKAssistantMessageError` flattens to 'unknown', so a
820
+ // host can key on a new gate without a Claude Code release. Normalized
821
+ // `apiErrorCode`; the same value is `turn.error.code` when no assistant
822
+ // error frame preceded this result, so the result alone builds the close
823
+ // (see the success branch in `drive()`).
824
+ // - `startup_failure_reason` (ERROR arm only, 0.3.274): set on the zeroed
825
+ // error_during_execution result a stream-json run writes before exiting on
826
+ // a known startup failure — "Why Claude Code refused to start, so a host
827
+ // can offer the fix instead of a retry". Normalized `startupFailureReason`,
828
+ // value verbatim; it also drives `turn.error.retriable` (see
829
+ // `startupFailureRetriable`). Read through the JSON boundary because it is
830
+ // declared on that one arm only.
743
831
  function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | undefined {
744
832
  const byModel: { [k: string]: JsonValue } = {};
745
833
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
@@ -762,6 +850,10 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
762
850
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
763
851
  const localCommand =
764
852
  isJsonObject(raw) && typeof raw["local_command"] === "string" ? raw["local_command"] : undefined;
853
+ // 0.3.280 — undeclared on both arms (`api_error_code`) / declared on the
854
+ // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
855
+ const apiErrorCode = readApiErrorCode(msg);
856
+ const startupFailureReason = readStartupFailureReason(msg);
765
857
  const payload: { [k: string]: JsonValue } = {
766
858
  ...(typeof msg.fast_mode_disabled_reason === "string"
767
859
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -773,6 +865,8 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
773
865
  // 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
774
866
  ...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
775
867
  ...(localCommand !== undefined ? { localCommand } : {}),
868
+ ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
869
+ ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
776
870
  ...(subagentStats !== undefined ? { subagentStats } : {}),
777
871
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
778
872
  };
@@ -839,10 +933,68 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
839
933
  // can enrich its tool.done with the actual rejection text + decision-reason
840
934
  // context, instead of emitting a SECOND tool.start/tool.done pair for the
841
935
  // same denial (the M22 double-fold hazard).
842
- const deniedLiveByToolUseId = new Map<
843
- string,
844
- { message: string; decisionReasonType?: string; decisionReason?: string; agentId?: string }
845
- >();
936
+ type LiveDenial = {
937
+ message: string;
938
+ decisionReasonType?: string;
939
+ decisionReasonCode?: string;
940
+ decisionReason?: string;
941
+ agentId?: string;
942
+ };
943
+ const deniedLiveByToolUseId = new Map<string, LiveDenial>();
944
+
945
+ // The live denial's diagnostic fields, camelCased — the providerMetadata bag
946
+ // on the enriched `<turnId>:denials` tool.done. undefined when the live
947
+ // frame carried none of them (no empty bag).
948
+ function liveDenialMeta(live: LiveDenial | undefined): { [k: string]: JsonValue } | undefined {
949
+ if (
950
+ live === undefined ||
951
+ (live.decisionReasonType === undefined &&
952
+ live.decisionReasonCode === undefined &&
953
+ live.decisionReason === undefined &&
954
+ live.agentId === undefined)
955
+ ) {
956
+ return undefined;
957
+ }
958
+ return {
959
+ ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
960
+ ...(live.decisionReasonCode !== undefined ? { decisionReasonCode: live.decisionReasonCode } : {}),
961
+ ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
962
+ ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
963
+ };
964
+ }
965
+
966
+ // CL-09 (0.3.280 sweep): the turn.error close an API-error assistant frame
967
+ // (`error` set) decided for its turn, STASHED until the turn's result frame
968
+ // (the vercel facet's `stashedError` pattern). An API-error turn reaches this
969
+ // facet as TWO frames: the synthetic assistant message carrying `error`, and
970
+ // then the turn's result, `subtype: "success"` with `is_error: true` ("with
971
+ // is_error true, the error text when the turn ended on an API error").
972
+ // Closing at the assistant frame lost the turn's usage: only the result
973
+ // carries `usage` / `total_cost_usd` / `modelUsage`, so a long agentic turn
974
+ // failing on its Nth round dropped the cost of every earlier round from the
975
+ // fold. So the assistant branch stashes {message, code, retriable} here, and
976
+ // the turn is closed exactly ONCE (INV-TURN):
977
+ // - by its result frame, EITHER arm, as turn.error with the stashed fields
978
+ // plus the usage mapped from that result (`mapTurnUsage`, the success
979
+ // close's mapping) — never as a turn.done (reduce() keeps the LAST
980
+ // outcome, so the old turn.error → turn.done pair folded an API-error turn
981
+ // as a success), never as a second turn.error;
982
+ // - or, if the stream ends before any result frame, by `flush()`, with the
983
+ // stashed fields and no usage — never degraded to INV-FLUSH's
984
+ // engine-synthesized turn.abort.
985
+ // The FIRST error frame's fields win: a later error frame on the same turn
986
+ // leaves the stash alone. EVERY result frame consumes the entry, whichever
987
+ // arm it is, because every turn of a session shares one turnId (`turnIdFor`)
988
+ // and a stale entry must never leak into the next turn's result.
989
+ type StashedTurnError = { readonly message: string; readonly code: string; readonly retriable: boolean };
990
+ const stashedTurnErrors = new Map<string, StashedTurnError>();
991
+
992
+ /** Remove and return the stashed error close for `turnId`, if any (CL-09). */
993
+ function takeStashedTurnError(turnId: string): StashedTurnError | undefined {
994
+ const stashed = stashedTurnErrors.get(turnId);
995
+ stashedTurnErrors.delete(turnId);
996
+ return stashed;
997
+ }
846
998
 
847
999
  // guuey#26 — ONE message id ⇒ ONE message lifecycle.
848
1000
  //
@@ -1433,6 +1585,20 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1433
1585
  // wrapper-meta channel's type without an unchecked cast.
1434
1586
  wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1435
1587
  }
1588
+ // `usage_report` (0.3.273): the structured twin of the /usage report,
1589
+ // riding the synthetic assistant message that delivers its text (session
1590
+ // totals, the plan's usage rows, extra-usage spend) — context_usage's
1591
+ // sibling, same wrapper-level placement per its own doc (never inside
1592
+ // `message.content`, not replayed to the model), so it gets the same carry:
1593
+ // whole and verbatim, wire name kept. Carried whole rather than field by
1594
+ // field because upstream marks SDKUsageReport "Experimental — the shape may
1595
+ // change". A per-frame fact like context_usage, so it sits OUTSIDE the
1596
+ // turn-binding guard. FIXTURE-ONLY: upstream attaches it only "from
1597
+ // claude.ai-subscriber sessions", and the capture harness authenticates
1598
+ // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1599
+ if (msg.usage_report !== undefined) {
1600
+ wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
1601
+ }
1436
1602
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1437
1603
  // the indexes of THIS frame's content blocks that are user-facing narration
1438
1604
  // — Anthropic's `thinking.display: "updates"` mode returns progress updates
@@ -1451,6 +1617,36 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1451
1617
  if (narrationBlockIndexes !== undefined) {
1452
1618
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1453
1619
  }
1620
+ // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1621
+ // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1622
+ // The CLI stamps them on the synthetic API-error assistant frame, the one
1623
+ // that also carries `error`, which SDKAssistantMessageError flattens to a
1624
+ // 13-value set (a new server gate reads as 'unknown'):
1625
+ // - `api_error`: the typed kind of the error ("for consumers that key on
1626
+ // the cause instead of the message text"), a closed CLI enum of 25
1627
+ // values at CLI 2.1.280 (dlp_request_denied, claude_code_version_too_old,
1628
+ // effort_requires_thinking, provider_credentials, …; "new values are
1629
+ // added over time"). Carried as a string, not enum-gated.
1630
+ // - `api_error_params`: `{effort?, provider?, remedy?}`, "present only
1631
+ // for the kinds that have any" — `remedy` is the fix a host should
1632
+ // offer (refresh_command, refresh_credentials, adc, …). Carried whole.
1633
+ // - `api_error_code`: the server's error.details.error_code, so "a host
1634
+ // can key on a new gate without a Claude Code release".
1635
+ // Per-frame facts of the error frame, like `aborted` / `context_usage`, so
1636
+ // they sit OUTSIDE the turn-binding guard. Wire names verbatim. The frame's
1637
+ // `is_api_error_message: true` flag is deliberately NOT carried: it
1638
+ // restates `error` being set, which already decides the turn's turn.error
1639
+ // close (stashed until the result frame — see `stashedTurnErrors`).
1640
+ if (isJsonObject(rawAssistant)) {
1641
+ const apiError = rawAssistant["api_error"];
1642
+ if (typeof apiError === "string") wrapperMetaRaw["api_error"] = apiError;
1643
+ const apiErrorParams = rawAssistant["api_error_params"];
1644
+ if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
1645
+ }
1646
+ const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1647
+ if (assistantApiErrorCode !== undefined) {
1648
+ wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1649
+ }
1454
1650
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1455
1651
  // the bag below, once `open` is known — their once-per-message flag is
1456
1652
  // shared with the stream arm's carry.
@@ -1584,38 +1780,46 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1584
1780
  open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
1585
1781
 
1586
1782
  // If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
1587
- // emit a turn.error so consumers see the error rather than a silent empty turn.
1783
+ // the turn ends as a turn.error so consumers see the error rather than a
1784
+ // silent empty turn. CL-09: the close is STASHED, not emitted here — the
1785
+ // turn's result frame (which carries the turn's usage) emits it, or
1786
+ // `flush()` does if no result ever arrives (see `stashedTurnErrors`).
1588
1787
  if (msg.error !== undefined) {
1589
- // The turn is over — nothing can continue this message. Seal it first,
1590
- // so `message.end` still precedes the close (unchanged order).
1788
+ // The API error ended the model's output — nothing can continue this
1789
+ // message. Seal it now, so `message.end` still precedes the (deferred)
1790
+ // close.
1591
1791
  closePendingMessage();
1592
1792
  const errCode: NonNullable<SDKAssistantError> = msg.error;
1593
- a.closeTurnError(turnId, {
1594
- message: errCode,
1595
- code: errCode,
1596
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1597
- // cousin of rate_limit/server_error) joins the retriable set.
1598
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1599
- // decommissioned model id) is deliberately EXCLUDED: explicit
1600
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1601
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1602
- // deliberate non-retriable: a billing-class code (the account is on
1603
- // hold — a first cousin of `billing_error`, cleared by the account
1604
- // holder, never by re-sending the turn).
1605
- //
1606
- // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1607
- // deliberate non-retriables recorded here for the same reason — an
1608
- // omission must never read as an oversight:
1609
- // - `verification_required`: the request is gated on an out-of-band
1610
- // human step (identity/org verification). Nothing about the turn
1611
- // changes by re-sending it; the block clears only when a person
1612
- // completes the verification.
1613
- // - `cloud_credential_error`: a credential/billing-class failure on
1614
- // the cloud-provider leg (a first cousin of `billing_error` and
1615
- // `account_on_hold`, not of `overloaded`) — a bad, expired or
1616
- // unauthorized credential is exactly as bad on the next attempt.
1617
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1618
- });
1793
+ // First error frame wins: a turn already carrying a stashed close keeps
1794
+ // it (before CL-09's stash, the first error frame closed the turn).
1795
+ if (!stashedTurnErrors.has(turnId)) {
1796
+ stashedTurnErrors.set(turnId, {
1797
+ message: errCode,
1798
+ code: errCode,
1799
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
1800
+ // cousin of rate_limit/server_error) joins the retriable set.
1801
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1802
+ // decommissioned model id) is deliberately EXCLUDED: explicit
1803
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1804
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1805
+ // deliberate non-retriable: a billing-class code (the account is on
1806
+ // hold — a first cousin of `billing_error`, cleared by the account
1807
+ // holder, never by re-sending the turn).
1808
+ //
1809
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1810
+ // deliberate non-retriables recorded here for the same reason — an
1811
+ // omission must never read as an oversight:
1812
+ // - `verification_required`: the request is gated on an out-of-band
1813
+ // human step (identity/org verification). Nothing about the turn
1814
+ // changes by re-sending it; the block clears only when a person
1815
+ // completes the verification.
1816
+ // - `cloud_credential_error`: a credential/billing-class failure on
1817
+ // the cloud-provider leg (a first cousin of `billing_error` and
1818
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
1819
+ // unauthorized credential is exactly as bad on the next attempt.
1820
+ retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1821
+ });
1822
+ }
1619
1823
  }
1620
1824
 
1621
1825
  // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
@@ -1631,6 +1835,28 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1631
1835
  }
1632
1836
 
1633
1837
  if (msg.type === "user") {
1838
+ // SDKUserMessageReplay (`isReplay: true`, typed only on that arm; a
1839
+ // runtime `isReplay: false` also exists, so only `=== true` counts) emits
1840
+ // NO core event and does NOT seal the open message (sp-rnd lead,
1841
+ // 2026-09-23). The CLI 2.1.280 replay builders are the host's own-prompt
1842
+ // acks (sent on stdin accept, never held), queued-prompt merges, history
1843
+ // re-sends (filtered to `!toolUseResult`, so no tool_results), and
1844
+ // local-command/bash echo+output. All of them are string or prompt content,
1845
+ // which this branch never mapped (it maps only tool_result blocks), so
1846
+ // skipping loses nothing it used to emit. What the skip fixes:
1847
+ // - REALISTIC: an ack landing mid-stream used to run closePendingMessage()
1848
+ // and split the streaming message (the complete frame then re-opened a
1849
+ // `:cont:` copy). Returning first keeps it a byte-identical no-op.
1850
+ // - DEFENSIVE (fixture-only; no 0.3.280 builder produces it): a replayed
1851
+ // tool_result re-emitted `tool.done`. After its turn's `turn.done` that
1852
+ // parked `reduce()` for the rest of the stream (INV-MSG, SPEC:745); in a
1853
+ // fresh normalizer it carried no turnId and parked from event 0.
1854
+ // DISCLOSED GAP, unchanged by this fix: replayed string content that is the
1855
+ // FIRST delivery (bash `<bash-input>` echo and output, local-command
1856
+ // output) has no AgJSON event. It is a candidate for the item-22 carry
1857
+ // `ext.anthropic.frame{kind:"user"}`. The replay's `tool_use_result`
1858
+ // sibling, read here for live frames, is no longer read on replays.
1859
+ if ("isReplay" in msg && msg.isReplay === true) return;
1634
1860
  // guuey#26: a tool_result binds to the fold — seal the open assistant
1635
1861
  // message first, exactly as the per-frame close used to (spec §5 tool.done
1636
1862
  // adoption below depends on this ordering).
@@ -1757,6 +1983,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1757
1983
  // (message.end has always preceded the turn close).
1758
1984
  closePendingMessage();
1759
1985
  const turnId = turnIdFor(msg.session_id, msg.uuid);
1986
+ // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1987
+ // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1988
+ // the final assistant text in result — or, with is_error true, the error
1989
+ // text when the turn ended on an API error". The CLI sets is_error from
1990
+ // the turn's last assistant frame being its synthetic API-error message
1991
+ // (rate_limit / overloaded after retries ran out, billing_error,
1992
+ // authentication_failed, …). Such a turn closes as an ERROR, never as a
1993
+ // success, and exactly once:
1994
+ // - if that assistant frame reached this facet, it stashed the turn's
1995
+ // error close (`stashedTurnErrors`); this frame emits it, with this
1996
+ // frame's usage — whatever is_error says, since that frame already
1997
+ // decided the turn's outcome;
1998
+ // - otherwise, with is_error true, this frame is the only evidence of
1999
+ // the error, and the close is a turn.error built from the result
2000
+ // itself (see below).
2001
+ // Strict `=== true`: is_error is typed boolean, but the frame is only
2002
+ // discriminant-validated, and false/absent must stay on the success path
2003
+ // byte-for-byte. The stash entry is consumed either way.
2004
+ const stashedError = takeStashedTurnError(turnId);
2005
+ const apiErrorTurn = msg.is_error === true;
1760
2006
  const safety: AgSafety[] | undefined =
1761
2007
  msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1762
2008
  // structured_output (when a response schema is in effect) overrides the plain
@@ -1766,6 +2012,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1766
2012
  // Emit permission_denials as tool.start + tool.done denied pairs, inside a
1767
2013
  // dedicated carrier message: the assistant message is already sealed, and
1768
2014
  // INV-MSG (audit M19) forbids attaching to sealed messages / closed turns.
2015
+ // CL-09: an API-error turn's denials take this same carrier, at the same
2016
+ // point — its close is deferred to this frame (below), so the turn is
2017
+ // still open here, like every other turn.
1769
2018
  if (msg.permission_denials.length > 0) {
1770
2019
  const denialMsgId = `${turnId}:denials`;
1771
2020
  a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
@@ -1779,15 +2028,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1779
2028
  // tool.start/tool.done pair is ever emitted for the live frame
1780
2029
  // itself (see the dedicated `permission_denied` branch below).
1781
2030
  const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2031
+ const liveFields = liveDenialMeta(live);
1782
2032
  const liveMeta: AgProviderMeta | undefined =
1783
- live !== undefined &&
1784
- (live.decisionReasonType !== undefined || live.decisionReason !== undefined || live.agentId !== undefined)
1785
- ? AgProviderMeta.parse({
1786
- ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
1787
- ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
1788
- ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
1789
- })
1790
- : undefined;
2033
+ liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1791
2034
  a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1792
2035
  a.toolDone({
1793
2036
  toolCallId: denial.tool_use_id,
@@ -1800,11 +2043,41 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1800
2043
  }
1801
2044
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1802
2045
  // ride `ext.anthropic.result-meta` before the close (no core home on
1803
- // turn.done — see resultMetaPayload's doc).
2046
+ // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
2047
+ // API-error turn too, before its close like on every other turn.
1804
2048
  const resultMeta = resultMetaPayload(msg);
1805
2049
  if (resultMeta !== undefined) {
1806
2050
  a.emitExt("anthropic", "result-meta", resultMeta);
1807
2051
  }
2052
+ if (stashedError !== undefined) {
2053
+ // The assistant error frame decided this close; this frame adds the
2054
+ // turn's usage, the same mapping turn.done would have carried (SPEC §4:
2055
+ // turn.error `usage` is "accrued billing on the interrupted turn"), so
2056
+ // the fold keeps the cost of every round the turn ran before failing.
2057
+ a.closeTurnError(turnId, {
2058
+ ...stashedError,
2059
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2060
+ });
2061
+ return;
2062
+ }
2063
+ if (apiErrorTurn) {
2064
+ // No assistant error frame preceded this result (a producer that did
2065
+ // not yield it, or a normalizer that never saw it), so this result is
2066
+ // the turn's only close. message = the result text, which on this frame
2067
+ // is the API error text; code = the server's api_error_code when the
2068
+ // CLI copied one through, else the generic "api_error"; retriable = the
2069
+ // HTTP status says rate limit or server failure (see
2070
+ // `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
2071
+ // above.
2072
+ const code = readApiErrorCode(msg) ?? "api_error";
2073
+ a.closeTurnError(turnId, {
2074
+ message: typeof msg.result === "string" ? msg.result : code,
2075
+ code,
2076
+ retriable: apiErrorStatusRetriable(msg.api_error_status),
2077
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2078
+ });
2079
+ return;
2080
+ }
1808
2081
  a.closeTurnDone(turnId, {
1809
2082
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1810
2083
  finishReason: mapStopReason(msg.stop_reason),
@@ -1819,13 +2092,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1819
2092
  // guuey#26: seal the open assistant message before the turn close.
1820
2093
  closePendingMessage();
1821
2094
  const turnId = turnIdFor(msg.session_id, msg.uuid);
2095
+ // CL-09: consume any stashed assistant-error close for this turnId — this
2096
+ // frame emits it (below), and it cannot leak into a later turn's result
2097
+ // (every turn of a session shares the turnId).
2098
+ const stashedError = takeStashedTurnError(turnId);
1822
2099
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1823
2100
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
1824
2101
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
1825
2102
  // not throw (Tenet 6: graceful, never throws).
1826
2103
  const errors = Array.isArray(msg.errors) ? msg.errors : [];
1827
2104
  const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
1828
- const retriable = subtype !== "error_max_turns";
2105
+ // CL-04 (0.3.274): a known startup failure says why the CLI refused to
2106
+ // start, and upstream frames it as "offer the fix instead of a retry" —
2107
+ // so a PRESENT reason decides retriable (false, except the values upstream
2108
+ // itself calls retriable; see `startupFailureRetriable`). An ABSENT reason
2109
+ // keeps the old rule, byte-identical for every older producer.
2110
+ const startupFailureReason = readStartupFailureReason(msg);
2111
+ const retriable =
2112
+ startupFailureReason !== undefined
2113
+ ? startupFailureRetriable(startupFailureReason)
2114
+ : subtype !== "error_max_turns";
1829
2115
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1830
2116
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1831
2117
  // success arm above (turn.error carries no metadata slot at all).
@@ -1833,6 +2119,32 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1833
2119
  if (resultMeta !== undefined) {
1834
2120
  a.emitExt("anthropic", "result-meta", resultMeta);
1835
2121
  }
2122
+ if (stashedError !== undefined) {
2123
+ // CL-09: an assistant error frame already decided this turn's close —
2124
+ // emit THAT one (the first error that ended the turn), once, never a
2125
+ // second turn.error for the same turnId (INV-TURN), with this frame's
2126
+ // usage (the success arm's mapping). This arm is only
2127
+ // discriminant-validated, so the usage trio is shape-guarded first
2128
+ // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
2129
+ // The guard covers every property `mapTurnUsage` dereferences: the
2130
+ // `server_tool_use` object (null allowed, as typed) and each
2131
+ // `modelUsage` entry — `usage: {}` or a null entry would otherwise
2132
+ // throw here, after the stash was already consumed.
2133
+ const raw: unknown = msg;
2134
+ const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
2135
+ const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
2136
+ const usage =
2137
+ isJsonObject(raw) &&
2138
+ isJsonObject(rawUsage) &&
2139
+ (rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
2140
+ isJsonObject(rawModelUsage) &&
2141
+ Object.values(rawModelUsage).every(isJsonObject) &&
2142
+ typeof raw["total_cost_usd"] === "number"
2143
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
2144
+ : undefined;
2145
+ a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
2146
+ return;
2147
+ }
1836
2148
  a.closeTurnError(turnId, {
1837
2149
  message: errors.length > 0 ? errors.join("; ") : subtype,
1838
2150
  code: subtype,
@@ -1878,6 +2190,27 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1878
2190
  closePendingMessage();
1879
2191
  const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
1880
2192
  retractUuids(uuids);
2193
+ // X4 (sp-rnd re-cut, 2026-09-23): only the retraction has a core home.
2194
+ // A notice yields 0..N `message.remove`s, so there is no single event to
2195
+ // hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
2196
+ // ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
2197
+ // `scope` ('session'|'local', absent ⇒ 'session' on older CLIs),
2198
+ // `original_model`/`fallback_model`, `request_id`, `api_refusal_category`
2199
+ // /`_explanation`, `refused_user_message_uuid` (the edit-and-retry target)
2200
+ // and the human-readable `content`. Through 0.6.3 it was dropped. It now
2201
+ // rides the uniform carry beside its `model_refusal_no_fallback` sibling
2202
+ // (SPEC §8 item 22 / §12), the WHOLE frame verbatim, AFTER the removes
2203
+ // (the frame is itself "emitted AFTER the retraction"). Item 22 says a
2204
+ // mapped frame goes to its home "instead" of the bulk carry. sp-protocol
2205
+ // ruled on 2026-09-23 (SPEC blob bef014c) that the clause covers frames
2206
+ // whose content that home already conveys, and `message.remove` conveys
2207
+ // only the retraction. So the residual fields fall under item 22's
2208
+ // no-drop MUST, and the whole frame rides. (sp-protocol's clarifying
2209
+ // line for item 22 is queued for the review bar.) `ext.*` is live-only
2210
+ // and non-folding, so the second copy of `retracted_message_uuids`
2211
+ // cannot double-fold (the M22 hazard). This is the only producer for R&D
2212
+ // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
2213
+ a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: JsonValue.parse(msg) });
1881
2214
  return;
1882
2215
  }
1883
2216
 
@@ -1888,9 +2221,27 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1888
2221
  // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
1889
2222
  // second pair here (the M22 double-fold hazard). Record this frame's
1890
2223
  // richer diagnostic fields only; the aggregate handler consumes them.
2224
+ //
2225
+ // `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
2226
+ // at 0.3.280, so read through the JSON boundary, never cast): "A
2227
+ // closed-set code for a reason a host can act on, beside
2228
+ // decision_reason_type (whose values are unchanged)":
2229
+ // 'outside_reads_blocked' (permissions.blockReadsOutsideWorkingDirectories
2230
+ // refused the path), 'memory_paused' (/pause-memory has memory paused),
2231
+ // 'classifier_transcript_too_long' (the auto-mode classifier's transcript
2232
+ // exceeded its context window). "Absent for every other reason; new values
2233
+ // are additive" — carried as a string, not enum-gated, camelCased beside
2234
+ // its `decisionReasonType` sibling. Fixture-only: the capture harness
2235
+ // produces no denials.
2236
+ const rawDenied: unknown = msg;
2237
+ const decisionReasonCode =
2238
+ isJsonObject(rawDenied) && typeof rawDenied["decision_reason_code"] === "string"
2239
+ ? rawDenied["decision_reason_code"]
2240
+ : undefined;
1891
2241
  deniedLiveByToolUseId.set(msg.tool_use_id, {
1892
2242
  message: msg.message,
1893
2243
  ...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
2244
+ ...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
1894
2245
  ...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
1895
2246
  ...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
1896
2247
  });
@@ -1938,6 +2289,14 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1938
2289
  // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1939
2290
  // to synthesize a bare `message.end`.
1940
2291
  closePendingMessage();
2292
+ // CL-09: a turn whose assistant error frame stashed its close but whose
2293
+ // result frame never arrived still closes as that turn.error (no usage:
2294
+ // only a result carries the turn's), never as INV-FLUSH's synthesized
2295
+ // turn.abort — the outcome the frame's own close used to produce.
2296
+ for (const [turnId, stashed] of stashedTurnErrors) {
2297
+ a.closeTurnError(turnId, { ...stashed });
2298
+ }
2299
+ stashedTurnErrors.clear();
1941
2300
  return a.flush();
1942
2301
  },
1943
2302
  };