@silverprotocol/claude-agent-sdk 0.6.2 → 0.6.3

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
@@ -647,6 +647,69 @@ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
647
647
  : undefined;
648
648
  }
649
649
 
650
+ // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
651
+ // on both frames that carry it (the API-error assistant frame and the
652
+ // `is_error: true` success result), so it is read through the JSON boundary.
653
+ // The CLI copies the server's error.details.error_code through only when it is
654
+ // an identifier (^[a-z][a-z0-9_]{0,63}$); the facet does not re-validate the
655
+ // producer's invariant, it only refuses a non-string.
656
+ function readApiErrorCode(v: unknown): string | undefined {
657
+ return isJsonObject(v) && typeof v["api_error_code"] === "string" ? v["api_error_code"] : undefined;
658
+ }
659
+
660
+ // `startup_failure_reason` (0.3.274) — declared on SDKResultError ONLY, so on
661
+ // the result union it is reachable only through the JSON boundary.
662
+ function readStartupFailureReason(v: unknown): string | undefined {
663
+ return isJsonObject(v) && typeof v["startup_failure_reason"] === "string"
664
+ ? v["startup_failure_reason"]
665
+ : undefined;
666
+ }
667
+
668
+ // `turn.error.retriable` for a result that carries `startup_failure_reason`.
669
+ // The type's own lead sentence frames the whole enum as a refusal to start:
670
+ // "Why Claude Code refused to start, so a host can offer the fix instead of a
671
+ // retry." So a PRESENT reason means NOT retriable, except for the values
672
+ // upstream itself EXPLICITLY describes as retriable. At 0.3.280 that set is
673
+ // exactly one value:
674
+ // - `worktree_unverified`: "the session's worktree could not be verified
675
+ // right now; retrying may succeed."
676
+ // Three more values read as if they might clear on their own, but upstream
677
+ // never says a retry helps, so each is a deliberate non-retriable — explicit
678
+ // false-by-omission (the model_not_found / account_on_hold voice in the
679
+ // assistant-error branch), never an oversight:
680
+ // - `org_verify_failed`: "the sign-in's organization could not be verified
681
+ // against the pin (network, or a revoked token)." A revoked token is not
682
+ // transient, and the doc does not tell the two causes apart.
683
+ // - `remote_settings_required_unavailable`: "managed settings the
684
+ // organization requires could not be loaded." No retry guidance; whether
685
+ // the load failure is transient is not stated.
686
+ // - `session_held_by_background`: "the conversation to resume or continue is
687
+ // running as a background session." Nothing says the hold clears, or when.
688
+ // Every other documented value (org_pin_api_key_conflict, org_pin_mismatch,
689
+ // managed_settings_invalid, gateway_signin_required, gateway_access_denied,
690
+ // proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
691
+ // worktree_resume_refused, cli_version_too_old, bypass_root) names a
692
+ // configuration, policy or environment fix, and an unknown future value
693
+ // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
694
+ // reason never reaches this function: the error arm keeps its old rule, so
695
+ // older producers are byte-identical.
696
+ const RETRIABLE_STARTUP_FAILURE_REASONS = new Set<string>(["worktree_unverified"]);
697
+ function startupFailureRetriable(reason: string): boolean {
698
+ return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
699
+ }
700
+
701
+ // `turn.error.retriable` for an API-error turn closed by its result frame:
702
+ // retriable exactly when the HTTP status is a rate limit (429) or a server-
703
+ // side failure (>= 500, which includes 529 overloaded) — the result-frame
704
+ // twin of the assistant-error branch's rate_limit / server_error / overloaded
705
+ // set. A null or absent status is not retriable: it carries no evidence that a
706
+ // re-send would behave differently. Typed `number | null` on the
707
+ // success arm, but the frame is only discriminant-validated, so it is guarded
708
+ // with typeof.
709
+ function apiErrorStatusRetriable(status: unknown): boolean {
710
+ return typeof status === "number" && (status === 429 || status >= 500);
711
+ }
712
+
650
713
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
651
714
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
652
715
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -740,6 +803,25 @@ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
740
803
  // was not given — under the normalized name `localCommand`. Read through the
741
804
  // `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
742
805
  // union has no such property to access.
806
+ //
807
+ // 0.3.280 bump — two more result-frame siblings on the SAME carry:
808
+ // - `api_error_code` (SUCCESS arm, CLI 2.1.280, @internal — UNDECLARED in
809
+ // sdk.d.ts, so no typed access exists): "the api_error_code of the API error
810
+ // that ended the turn (see SDKAssistantMessage.api_error_code): the server's
811
+ // error.details.error_code when it is an identifier". It rides the
812
+ // `is_error: true` success result an API-error turn ends with, and it names
813
+ // server gate codes `SDKAssistantMessageError` flattens to 'unknown', so a
814
+ // host can key on a new gate without a Claude Code release. Normalized
815
+ // `apiErrorCode`; the same value is `turn.error.code` when no assistant
816
+ // error frame preceded this result, so the result alone builds the close
817
+ // (see the success branch in `drive()`).
818
+ // - `startup_failure_reason` (ERROR arm only, 0.3.274): set on the zeroed
819
+ // error_during_execution result a stream-json run writes before exiting on
820
+ // a known startup failure — "Why Claude Code refused to start, so a host
821
+ // can offer the fix instead of a retry". Normalized `startupFailureReason`,
822
+ // value verbatim; it also drives `turn.error.retriable` (see
823
+ // `startupFailureRetriable`). Read through the JSON boundary because it is
824
+ // declared on that one arm only.
743
825
  function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | undefined {
744
826
  const byModel: { [k: string]: JsonValue } = {};
745
827
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
@@ -762,6 +844,10 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
762
844
  // it is read through the same JSON boundary as `subagent_stats`, never cast.
763
845
  const localCommand =
764
846
  isJsonObject(raw) && typeof raw["local_command"] === "string" ? raw["local_command"] : undefined;
847
+ // 0.3.280 — undeclared on both arms (`api_error_code`) / declared on the
848
+ // ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
849
+ const apiErrorCode = readApiErrorCode(msg);
850
+ const startupFailureReason = readStartupFailureReason(msg);
765
851
  const payload: { [k: string]: JsonValue } = {
766
852
  ...(typeof msg.fast_mode_disabled_reason === "string"
767
853
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
@@ -773,6 +859,8 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
773
859
  // 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
774
860
  ...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
775
861
  ...(localCommand !== undefined ? { localCommand } : {}),
862
+ ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
863
+ ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
776
864
  ...(subagentStats !== undefined ? { subagentStats } : {}),
777
865
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
778
866
  };
@@ -839,10 +927,68 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
839
927
  // can enrich its tool.done with the actual rejection text + decision-reason
840
928
  // context, instead of emitting a SECOND tool.start/tool.done pair for the
841
929
  // same denial (the M22 double-fold hazard).
842
- const deniedLiveByToolUseId = new Map<
843
- string,
844
- { message: string; decisionReasonType?: string; decisionReason?: string; agentId?: string }
845
- >();
930
+ type LiveDenial = {
931
+ message: string;
932
+ decisionReasonType?: string;
933
+ decisionReasonCode?: string;
934
+ decisionReason?: string;
935
+ agentId?: string;
936
+ };
937
+ const deniedLiveByToolUseId = new Map<string, LiveDenial>();
938
+
939
+ // The live denial's diagnostic fields, camelCased — the providerMetadata bag
940
+ // on the enriched `<turnId>:denials` tool.done. undefined when the live
941
+ // frame carried none of them (no empty bag).
942
+ function liveDenialMeta(live: LiveDenial | undefined): { [k: string]: JsonValue } | undefined {
943
+ if (
944
+ live === undefined ||
945
+ (live.decisionReasonType === undefined &&
946
+ live.decisionReasonCode === undefined &&
947
+ live.decisionReason === undefined &&
948
+ live.agentId === undefined)
949
+ ) {
950
+ return undefined;
951
+ }
952
+ return {
953
+ ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
954
+ ...(live.decisionReasonCode !== undefined ? { decisionReasonCode: live.decisionReasonCode } : {}),
955
+ ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
956
+ ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
957
+ };
958
+ }
959
+
960
+ // CL-09 (0.3.280 sweep): the turn.error close an API-error assistant frame
961
+ // (`error` set) decided for its turn, STASHED until the turn's result frame
962
+ // (the vercel facet's `stashedError` pattern). An API-error turn reaches this
963
+ // facet as TWO frames: the synthetic assistant message carrying `error`, and
964
+ // then the turn's result, `subtype: "success"` with `is_error: true` ("with
965
+ // is_error true, the error text when the turn ended on an API error").
966
+ // Closing at the assistant frame lost the turn's usage: only the result
967
+ // carries `usage` / `total_cost_usd` / `modelUsage`, so a long agentic turn
968
+ // failing on its Nth round dropped the cost of every earlier round from the
969
+ // fold. So the assistant branch stashes {message, code, retriable} here, and
970
+ // the turn is closed exactly ONCE (INV-TURN):
971
+ // - by its result frame, EITHER arm, as turn.error with the stashed fields
972
+ // plus the usage mapped from that result (`mapTurnUsage`, the success
973
+ // close's mapping) — never as a turn.done (reduce() keeps the LAST
974
+ // outcome, so the old turn.error → turn.done pair folded an API-error turn
975
+ // as a success), never as a second turn.error;
976
+ // - or, if the stream ends before any result frame, by `flush()`, with the
977
+ // stashed fields and no usage — never degraded to INV-FLUSH's
978
+ // engine-synthesized turn.abort.
979
+ // The FIRST error frame's fields win: a later error frame on the same turn
980
+ // leaves the stash alone. EVERY result frame consumes the entry, whichever
981
+ // arm it is, because every turn of a session shares one turnId (`turnIdFor`)
982
+ // and a stale entry must never leak into the next turn's result.
983
+ type StashedTurnError = { readonly message: string; readonly code: string; readonly retriable: boolean };
984
+ const stashedTurnErrors = new Map<string, StashedTurnError>();
985
+
986
+ /** Remove and return the stashed error close for `turnId`, if any (CL-09). */
987
+ function takeStashedTurnError(turnId: string): StashedTurnError | undefined {
988
+ const stashed = stashedTurnErrors.get(turnId);
989
+ stashedTurnErrors.delete(turnId);
990
+ return stashed;
991
+ }
846
992
 
847
993
  // guuey#26 — ONE message id ⇒ ONE message lifecycle.
848
994
  //
@@ -1433,6 +1579,20 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1433
1579
  // wrapper-meta channel's type without an unchecked cast.
1434
1580
  wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1435
1581
  }
1582
+ // `usage_report` (0.3.273): the structured twin of the /usage report,
1583
+ // riding the synthetic assistant message that delivers its text (session
1584
+ // totals, the plan's usage rows, extra-usage spend) — context_usage's
1585
+ // sibling, same wrapper-level placement per its own doc (never inside
1586
+ // `message.content`, not replayed to the model), so it gets the same carry:
1587
+ // whole and verbatim, wire name kept. Carried whole rather than field by
1588
+ // field because upstream marks SDKUsageReport "Experimental — the shape may
1589
+ // change". A per-frame fact like context_usage, so it sits OUTSIDE the
1590
+ // turn-binding guard. FIXTURE-ONLY: upstream attaches it only "from
1591
+ // claude.ai-subscriber sessions", and the capture harness authenticates
1592
+ // with ANTHROPIC_API_KEY, so no live cassette can carry it.
1593
+ if (msg.usage_report !== undefined) {
1594
+ wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
1595
+ }
1436
1596
  // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1437
1597
  // the indexes of THIS frame's content blocks that are user-facing narration
1438
1598
  // — Anthropic's `thinking.display: "updates"` mode returns progress updates
@@ -1451,6 +1611,36 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1451
1611
  if (narrationBlockIndexes !== undefined) {
1452
1612
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1453
1613
  }
1614
+ // The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
1615
+ // sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
1616
+ // The CLI stamps them on the synthetic API-error assistant frame, the one
1617
+ // that also carries `error`, which SDKAssistantMessageError flattens to a
1618
+ // 13-value set (a new server gate reads as 'unknown'):
1619
+ // - `api_error`: the typed kind of the error ("for consumers that key on
1620
+ // the cause instead of the message text"), a closed CLI enum of 25
1621
+ // values at CLI 2.1.280 (dlp_request_denied, claude_code_version_too_old,
1622
+ // effort_requires_thinking, provider_credentials, …; "new values are
1623
+ // added over time"). Carried as a string, not enum-gated.
1624
+ // - `api_error_params`: `{effort?, provider?, remedy?}`, "present only
1625
+ // for the kinds that have any" — `remedy` is the fix a host should
1626
+ // offer (refresh_command, refresh_credentials, adc, …). Carried whole.
1627
+ // - `api_error_code`: the server's error.details.error_code, so "a host
1628
+ // can key on a new gate without a Claude Code release".
1629
+ // Per-frame facts of the error frame, like `aborted` / `context_usage`, so
1630
+ // they sit OUTSIDE the turn-binding guard. Wire names verbatim. The frame's
1631
+ // `is_api_error_message: true` flag is deliberately NOT carried: it
1632
+ // restates `error` being set, which already decides the turn's turn.error
1633
+ // close (stashed until the result frame — see `stashedTurnErrors`).
1634
+ if (isJsonObject(rawAssistant)) {
1635
+ const apiError = rawAssistant["api_error"];
1636
+ if (typeof apiError === "string") wrapperMetaRaw["api_error"] = apiError;
1637
+ const apiErrorParams = rawAssistant["api_error_params"];
1638
+ if (isJsonObject(apiErrorParams)) wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
1639
+ }
1640
+ const assistantApiErrorCode = readApiErrorCode(rawAssistant);
1641
+ if (assistantApiErrorCode !== undefined) {
1642
+ wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1643
+ }
1454
1644
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1455
1645
  // the bag below, once `open` is known — their once-per-message flag is
1456
1646
  // shared with the stream arm's carry.
@@ -1584,38 +1774,46 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1584
1774
  open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
1585
1775
 
1586
1776
  // 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.
1777
+ // the turn ends as a turn.error so consumers see the error rather than a
1778
+ // silent empty turn. CL-09: the close is STASHED, not emitted here — the
1779
+ // turn's result frame (which carries the turn's usage) emits it, or
1780
+ // `flush()` does if no result ever arrives (see `stashedTurnErrors`).
1588
1781
  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).
1782
+ // The API error ended the model's output — nothing can continue this
1783
+ // message. Seal it now, so `message.end` still precedes the (deferred)
1784
+ // close.
1591
1785
  closePendingMessage();
1592
1786
  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
- });
1787
+ // First error frame wins: a turn already carrying a stashed close keeps
1788
+ // it (before CL-09's stash, the first error frame closed the turn).
1789
+ if (!stashedTurnErrors.has(turnId)) {
1790
+ stashedTurnErrors.set(turnId, {
1791
+ message: errCode,
1792
+ code: errCode,
1793
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
1794
+ // cousin of rate_limit/server_error) joins the retriable set.
1795
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1796
+ // decommissioned model id) is deliberately EXCLUDED: explicit
1797
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1798
+ // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1799
+ // deliberate non-retriable: a billing-class code (the account is on
1800
+ // hold — a first cousin of `billing_error`, cleared by the account
1801
+ // holder, never by re-sending the turn).
1802
+ //
1803
+ // 0.3.272 widened `SDKAssistantMessageError` by two more values, both
1804
+ // deliberate non-retriables recorded here for the same reason — an
1805
+ // omission must never read as an oversight:
1806
+ // - `verification_required`: the request is gated on an out-of-band
1807
+ // human step (identity/org verification). Nothing about the turn
1808
+ // changes by re-sending it; the block clears only when a person
1809
+ // completes the verification.
1810
+ // - `cloud_credential_error`: a credential/billing-class failure on
1811
+ // the cloud-provider leg (a first cousin of `billing_error` and
1812
+ // `account_on_hold`, not of `overloaded`) — a bad, expired or
1813
+ // unauthorized credential is exactly as bad on the next attempt.
1814
+ retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1815
+ });
1816
+ }
1619
1817
  }
1620
1818
 
1621
1819
  // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
@@ -1757,6 +1955,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1757
1955
  // (message.end has always preceded the turn close).
1758
1956
  closePendingMessage();
1759
1957
  const turnId = turnIdFor(msg.session_id, msg.uuid);
1958
+ // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
1959
+ // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
1960
+ // the final assistant text in result — or, with is_error true, the error
1961
+ // text when the turn ended on an API error". The CLI sets is_error from
1962
+ // the turn's last assistant frame being its synthetic API-error message
1963
+ // (rate_limit / overloaded after retries ran out, billing_error,
1964
+ // authentication_failed, …). Such a turn closes as an ERROR, never as a
1965
+ // success, and exactly once:
1966
+ // - if that assistant frame reached this facet, it stashed the turn's
1967
+ // error close (`stashedTurnErrors`); this frame emits it, with this
1968
+ // frame's usage — whatever is_error says, since that frame already
1969
+ // decided the turn's outcome;
1970
+ // - otherwise, with is_error true, this frame is the only evidence of
1971
+ // the error, and the close is a turn.error built from the result
1972
+ // itself (see below).
1973
+ // Strict `=== true`: is_error is typed boolean, but the frame is only
1974
+ // discriminant-validated, and false/absent must stay on the success path
1975
+ // byte-for-byte. The stash entry is consumed either way.
1976
+ const stashedError = takeStashedTurnError(turnId);
1977
+ const apiErrorTurn = msg.is_error === true;
1760
1978
  const safety: AgSafety[] | undefined =
1761
1979
  msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1762
1980
  // structured_output (when a response schema is in effect) overrides the plain
@@ -1766,6 +1984,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1766
1984
  // Emit permission_denials as tool.start + tool.done denied pairs, inside a
1767
1985
  // dedicated carrier message: the assistant message is already sealed, and
1768
1986
  // INV-MSG (audit M19) forbids attaching to sealed messages / closed turns.
1987
+ // CL-09: an API-error turn's denials take this same carrier, at the same
1988
+ // point — its close is deferred to this frame (below), so the turn is
1989
+ // still open here, like every other turn.
1769
1990
  if (msg.permission_denials.length > 0) {
1770
1991
  const denialMsgId = `${turnId}:denials`;
1771
1992
  a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
@@ -1779,15 +2000,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1779
2000
  // tool.start/tool.done pair is ever emitted for the live frame
1780
2001
  // itself (see the dedicated `permission_denied` branch below).
1781
2002
  const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2003
+ const liveFields = liveDenialMeta(live);
1782
2004
  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;
2005
+ liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1791
2006
  a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1792
2007
  a.toolDone({
1793
2008
  toolCallId: denial.tool_use_id,
@@ -1800,11 +2015,41 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1800
2015
  }
1801
2016
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1802
2017
  // ride `ext.anthropic.result-meta` before the close (no core home on
1803
- // turn.done — see resultMetaPayload's doc).
2018
+ // turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
2019
+ // API-error turn too, before its close like on every other turn.
1804
2020
  const resultMeta = resultMetaPayload(msg);
1805
2021
  if (resultMeta !== undefined) {
1806
2022
  a.emitExt("anthropic", "result-meta", resultMeta);
1807
2023
  }
2024
+ if (stashedError !== undefined) {
2025
+ // The assistant error frame decided this close; this frame adds the
2026
+ // turn's usage, the same mapping turn.done would have carried (SPEC §4:
2027
+ // turn.error `usage` is "accrued billing on the interrupted turn"), so
2028
+ // the fold keeps the cost of every round the turn ran before failing.
2029
+ a.closeTurnError(turnId, {
2030
+ ...stashedError,
2031
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2032
+ });
2033
+ return;
2034
+ }
2035
+ if (apiErrorTurn) {
2036
+ // No assistant error frame preceded this result (a producer that did
2037
+ // not yield it, or a normalizer that never saw it), so this result is
2038
+ // the turn's only close. message = the result text, which on this frame
2039
+ // is the API error text; code = the server's api_error_code when the
2040
+ // CLI copied one through, else the generic "api_error"; retriable = the
2041
+ // HTTP status says rate limit or server failure (see
2042
+ // `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
2043
+ // above.
2044
+ const code = readApiErrorCode(msg) ?? "api_error";
2045
+ a.closeTurnError(turnId, {
2046
+ message: typeof msg.result === "string" ? msg.result : code,
2047
+ code,
2048
+ retriable: apiErrorStatusRetriable(msg.api_error_status),
2049
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
2050
+ });
2051
+ return;
2052
+ }
1808
2053
  a.closeTurnDone(turnId, {
1809
2054
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1810
2055
  finishReason: mapStopReason(msg.stop_reason),
@@ -1819,13 +2064,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1819
2064
  // guuey#26: seal the open assistant message before the turn close.
1820
2065
  closePendingMessage();
1821
2066
  const turnId = turnIdFor(msg.session_id, msg.uuid);
2067
+ // CL-09: consume any stashed assistant-error close for this turnId — this
2068
+ // frame emits it (below), and it cannot leak into a later turn's result
2069
+ // (every turn of a session shares the turnId).
2070
+ const stashedError = takeStashedTurnError(turnId);
1822
2071
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1823
2072
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
1824
2073
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
1825
2074
  // not throw (Tenet 6: graceful, never throws).
1826
2075
  const errors = Array.isArray(msg.errors) ? msg.errors : [];
1827
2076
  const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
1828
- const retriable = subtype !== "error_max_turns";
2077
+ // CL-04 (0.3.274): a known startup failure says why the CLI refused to
2078
+ // start, and upstream frames it as "offer the fix instead of a retry" —
2079
+ // so a PRESENT reason decides retriable (false, except the values upstream
2080
+ // itself calls retriable; see `startupFailureRetriable`). An ABSENT reason
2081
+ // keeps the old rule, byte-identical for every older producer.
2082
+ const startupFailureReason = readStartupFailureReason(msg);
2083
+ const retriable =
2084
+ startupFailureReason !== undefined
2085
+ ? startupFailureRetriable(startupFailureReason)
2086
+ : subtype !== "error_max_turns";
1829
2087
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1830
2088
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1831
2089
  // success arm above (turn.error carries no metadata slot at all).
@@ -1833,6 +2091,32 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1833
2091
  if (resultMeta !== undefined) {
1834
2092
  a.emitExt("anthropic", "result-meta", resultMeta);
1835
2093
  }
2094
+ if (stashedError !== undefined) {
2095
+ // CL-09: an assistant error frame already decided this turn's close —
2096
+ // emit THAT one (the first error that ended the turn), once, never a
2097
+ // second turn.error for the same turnId (INV-TURN), with this frame's
2098
+ // usage (the success arm's mapping). This arm is only
2099
+ // discriminant-validated, so the usage trio is shape-guarded first
2100
+ // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
2101
+ // The guard covers every property `mapTurnUsage` dereferences: the
2102
+ // `server_tool_use` object (null allowed, as typed) and each
2103
+ // `modelUsage` entry — `usage: {}` or a null entry would otherwise
2104
+ // throw here, after the stash was already consumed.
2105
+ const raw: unknown = msg;
2106
+ const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
2107
+ const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
2108
+ const usage =
2109
+ isJsonObject(raw) &&
2110
+ isJsonObject(rawUsage) &&
2111
+ (rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
2112
+ isJsonObject(rawModelUsage) &&
2113
+ Object.values(rawModelUsage).every(isJsonObject) &&
2114
+ typeof raw["total_cost_usd"] === "number"
2115
+ ? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
2116
+ : undefined;
2117
+ a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
2118
+ return;
2119
+ }
1836
2120
  a.closeTurnError(turnId, {
1837
2121
  message: errors.length > 0 ? errors.join("; ") : subtype,
1838
2122
  code: subtype,
@@ -1888,9 +2172,27 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1888
2172
  // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
1889
2173
  // second pair here (the M22 double-fold hazard). Record this frame's
1890
2174
  // richer diagnostic fields only; the aggregate handler consumes them.
2175
+ //
2176
+ // `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
2177
+ // at 0.3.280, so read through the JSON boundary, never cast): "A
2178
+ // closed-set code for a reason a host can act on, beside
2179
+ // decision_reason_type (whose values are unchanged)":
2180
+ // 'outside_reads_blocked' (permissions.blockReadsOutsideWorkingDirectories
2181
+ // refused the path), 'memory_paused' (/pause-memory has memory paused),
2182
+ // 'classifier_transcript_too_long' (the auto-mode classifier's transcript
2183
+ // exceeded its context window). "Absent for every other reason; new values
2184
+ // are additive" — carried as a string, not enum-gated, camelCased beside
2185
+ // its `decisionReasonType` sibling. Fixture-only: the capture harness
2186
+ // produces no denials.
2187
+ const rawDenied: unknown = msg;
2188
+ const decisionReasonCode =
2189
+ isJsonObject(rawDenied) && typeof rawDenied["decision_reason_code"] === "string"
2190
+ ? rawDenied["decision_reason_code"]
2191
+ : undefined;
1891
2192
  deniedLiveByToolUseId.set(msg.tool_use_id, {
1892
2193
  message: msg.message,
1893
2194
  ...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
2195
+ ...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
1894
2196
  ...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
1895
2197
  ...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
1896
2198
  });
@@ -1938,6 +2240,14 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1938
2240
  // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1939
2241
  // to synthesize a bare `message.end`.
1940
2242
  closePendingMessage();
2243
+ // CL-09: a turn whose assistant error frame stashed its close but whose
2244
+ // result frame never arrived still closes as that turn.error (no usage:
2245
+ // only a result carries the turn's), never as INV-FLUSH's synthesized
2246
+ // turn.abort — the outcome the frame's own close used to produce.
2247
+ for (const [turnId, stashed] of stashedTurnErrors) {
2248
+ a.closeTurnError(turnId, { ...stashed });
2249
+ }
2250
+ stashedTurnErrors.clear();
1941
2251
  return a.flush();
1942
2252
  },
1943
2253
  };