@silverprotocol/claude-agent-sdk 0.6.1 → 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
@@ -632,6 +632,84 @@ function readUserMessageUuids(v: unknown): string[] | undefined {
632
632
  return Array.isArray(v) && v.every((s): s is string => typeof s === "string") ? v : undefined;
633
633
  }
634
634
 
635
+ // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
636
+ // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
637
+ // 0.3.272 (a pass-through of the Messages API field that rides the assistant
638
+ // wrapper), so it is read through the JSON boundary and shape-guarded here, never
639
+ // cast. Integer indexes into `message.content`; an out-of-range or non-integer
640
+ // member means the producer changed shape, so the whole array is refused rather
641
+ // than half-carried.
642
+ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
643
+ return Array.isArray(v) &&
644
+ v.length > 0 &&
645
+ v.every((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0)
646
+ ? v
647
+ : undefined;
648
+ }
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
+
635
713
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
636
714
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
637
715
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -685,6 +763,65 @@ function readUserMessageUuids(v: unknown): string[] | undefined {
685
763
  // producer's to keep, not the facet's to validate. CONSISTENCY carry: the
686
764
  // string-prompt capture path supplies no client uuid, so no cassette has
687
765
  // ever exercised either the singular or the plural.
766
+ //
767
+ // 0.3.272 bump — three more result-frame siblings on the SAME carry:
768
+ // - `resume_reason` (BOTH arms, 0.3.268): the result-frame leg of the
769
+ // turn-binding family the assistant/stream arms now carry (see
770
+ // `carryTurnBinding`) — why this turn was the AUTOMATIC re-run of a turn a
771
+ // worker restart interrupted (the host's CLAUDE_CODE_RESUME_REASON:
772
+ // host_draining, checkpoint_restore, container_recreated, …; else
773
+ // 'interrupted_turn'). Its sibling `user_message_uuid` names the INTERRUPTED
774
+ // turn's own last prompt on such a re-run, so a consumer reconciling results
775
+ // by uuid sees the SAME uuid twice; this is the field that says the second
776
+ // one is a re-run and not a duplicate. Normalized `resumeReason`.
777
+ // - `result_index` (BOTH arms, 0.3.268): delivery sequence of this result
778
+ // within the run, from 0, in the order the process writes them. A
779
+ // DELIVERY-INTEGRITY signal, not a counter: "a result whose write fails
780
+ // still consumes its number, so a gap in a stream-json sequence means a
781
+ // result was LOST" — a consumer can detect a dropped result it would
782
+ // otherwise never know about. Direct sibling of `queued_turn_count` (the
783
+ // same "what else is coming" axis), so it lands in the same carrier as
784
+ // `resultIndex`. 0 is a REAL value (every run's first result), so the guard
785
+ // is `typeof === "number"`, never truthiness.
786
+ // - `local_command` (SUCCESS arm only, 0.3.268 — NO upstream doc comment;
787
+ // disposition from a 0.3.272 CLI-bundle read, 2026-09-15): present exactly
788
+ // on the result of a turn that ran a slash command and NEVER entered the
789
+ // model loop. In the bundle it is written only on the `shouldQuery === false`
790
+ // early-return branch of the result builder, from the input processor's
791
+ // `localCommand`, and not at all when the slash command was deferred to the
792
+ // engine (`engineDeferredSlash`). CARRIED, because its PRESENCE is the
793
+ // consumer signal: it is what distinguishes "this turn was a local command,
794
+ // zero model round-trips" from "this turn produced nothing" — a
795
+ // success result with `num_turns: 0` and no assistant frames is otherwise
796
+ // indistinguishable from an empty turn. Its VALUE, however, is deliberately
797
+ // coarse: the CLI passes the command name through the same sanitizer its
798
+ // analytics use (`isMcp ? "mcp" : (isBuiltIn || isBundled || isOfficial ?
799
+ // rawName : "custom")`) and then slugifies it (lowercase, `[^a-z]+`→`_`,
800
+ // trimmed, ≤64 chars, empty ⇒ "custom"), so a user/project/third-party
801
+ // command reports "custom" and any MCP command reports "mcp". Carried
802
+ // verbatim as the producer emits it — the facet never re-derives a name it
803
+ // was not given — under the normalized name `localCommand`. Read through the
804
+ // `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
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.
688
825
  function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | undefined {
689
826
  const byModel: { [k: string]: JsonValue } = {};
690
827
  const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
@@ -703,13 +840,27 @@ function resultMetaPayload(msg: SDKResultMsg): { [k: string]: JsonValue } | unde
703
840
  const subagentStats =
704
841
  isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
705
842
  const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
843
+ // SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
844
+ // it is read through the same JSON boundary as `subagent_stats`, never cast.
845
+ const localCommand =
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);
706
851
  const payload: { [k: string]: JsonValue } = {
707
852
  ...(typeof msg.fast_mode_disabled_reason === "string"
708
853
  ? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
709
854
  : {}),
710
855
  ...(typeof msg.user_message_uuid === "string" ? { userMessageUuid: msg.user_message_uuid } : {}),
711
856
  ...(userMessageUuids !== undefined ? { userMessageUuids } : {}),
857
+ ...(typeof msg.resume_reason === "string" ? { resumeReason: msg.resume_reason } : {}),
712
858
  ...(typeof msg.queued_turn_count === "number" ? { queuedTurnCount: msg.queued_turn_count } : {}),
859
+ // 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
860
+ ...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
861
+ ...(localCommand !== undefined ? { localCommand } : {}),
862
+ ...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
863
+ ...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
713
864
  ...(subagentStats !== undefined ? { subagentStats } : {}),
714
865
  ...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
715
866
  };
@@ -776,10 +927,68 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
776
927
  // can enrich its tool.done with the actual rejection text + decision-reason
777
928
  // context, instead of emitting a SECOND tool.start/tool.done pair for the
778
929
  // same denial (the M22 double-fold hazard).
779
- const deniedLiveByToolUseId = new Map<
780
- string,
781
- { message: string; decisionReasonType?: string; decisionReason?: string; agentId?: string }
782
- >();
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
+ }
783
992
 
784
993
  // guuey#26 — ONE message id ⇒ ONE message lifecycle.
785
994
  //
@@ -830,15 +1039,24 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
830
1039
  /** workspace#7 — `ttft_ms` carried at most once per message (message.metadata). */
831
1040
  ttftCarried: boolean;
832
1041
  /**
833
- * 0.3.258 — `user_message_uuid` carried at most once per message, whichever
1042
+ * The TURN-BINDING FAMILY, carried at most once per message, whichever
834
1043
  * channel delivers it first: the stream arm's message.metadata carry
835
- * (`carryUserMessageUuid`, the first non-ping stream event) or the complete
1044
+ * (`carryTurnBinding`, the first non-ping stream event) or the complete
836
1045
  * arm's first-block wrapper carry (the SDK stamps the turn's FIRST reply
837
1046
  * frame only; with partials the stamp normally rides the stream instead).
838
- * 0.3.261 — the plural `user_message_uuids` (0.3.259) rides the SAME single
839
- * emission under the SAME flag: one carry per message for the whole family.
1047
+ *
1048
+ * 0.3.258 — `user_message_uuid` opened the family.
1049
+ * 0.3.261 — the plural `user_message_uuids` (0.3.259) joined the SAME single
1050
+ * emission under the SAME flag.
1051
+ * 0.3.272 — `resume_reason` (0.3.268) joins it too. The upstream 0.3.269
1052
+ * entry changes all THREE under ONE rule ("stamped on a turn's first
1053
+ * complete assistant message as well as its first stream event when partial
1054
+ * messages are on"), so they are one family with one flag — a field written
1055
+ * outside this guard would double-emit `message.metadata` on a streamed
1056
+ * lifecycle (the stream arm carries, then the content-suppressed complete
1057
+ * frame carries again).
840
1058
  */
841
- userMessageUuidCarried: boolean;
1059
+ turnBindingCarried: boolean;
842
1060
  };
843
1061
  // workspace#7 — per-block accumulation between content_block_start and its
844
1062
  // content_block_stop. `emitted` marks blocks that arrive complete inside the
@@ -896,30 +1114,41 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
896
1114
  a.emit({ type: "message.metadata", messageId: p.emittedId, metadata: { ttft_ms: msg.ttft_ms } });
897
1115
  }
898
1116
 
899
- // 0.3.258: `user_message_uuid` on the partial envelope — the client uuid of
900
- // the user message this turn answers, stamped on the turn's FIRST non-ping
901
- // stream event so a consumer can bind the reply stream to the send before
902
- // the result arrives. Same channel and same once-per-message rule as
903
- // `ttft_ms` above (message.metadata, wire name verbatim); the flag is shared
904
- // with the complete arm's wrapper carry so the two channels never double-
905
- // carry one message.
906
- // 0.3.261: the plural `user_message_uuids` (0.3.259 — every client uuid of
907
- // the prompt batch this turn answers, "present exactly when the singular
908
- // is") joins the SAME single emission, wire name verbatim, shape-guarded
909
- // (`readUserMessageUuids`). Either member alone still triggers the carry —
910
- // the "exactly when" invariant is the producer's, not a precondition here.
911
- function carryUserMessageUuid(msg: SDKPartial, p: PendingMessage): void {
912
- if (p.userMessageUuidCarried) return;
1117
+ // The TURN-BINDING FAMILY on the partial envelope — what binds this reply
1118
+ // stream to the send it answers, before the result arrives. Same channel and
1119
+ // same once-per-message rule as `ttft_ms` above (message.metadata, wire names
1120
+ // verbatim); the flag is shared with the complete arm's wrapper carry so the
1121
+ // two channels never double-carry one message.
1122
+ // - `user_message_uuid` (0.3.258): the client uuid of the user message this
1123
+ // turn answers, stamped on the turn's FIRST non-ping stream event.
1124
+ // - `user_message_uuids` (0.3.259): every client uuid of the prompt batch
1125
+ // this turn answers, "present exactly when the singular is" — shape-guarded
1126
+ // (`readUserMessageUuids`).
1127
+ // - `resume_reason` (0.3.268): why this frame's turn is the AUTOMATIC re-run
1128
+ // of a turn a worker restart interrupted — the host's
1129
+ // CLAUDE_CODE_RESUME_REASON (host_draining, checkpoint_restore,
1130
+ // container_recreated, …) or else 'interrupted_turn'. Not a separate
1131
+ // concept from the uuids but the third leg of the same binding: on such a
1132
+ // re-run `user_message_uuid` names the INTERRUPTED turn's own last prompt,
1133
+ // and `resume_reason` is what tells the re-run's first reply apart from the
1134
+ // interrupted attempt's. 0.3.269 stamps all three on the SAME frames under
1135
+ // ONE rule, so they share ONE guard and ONE emission.
1136
+ // Either member alone still triggers the carry — the "exactly when" /
1137
+ // "same frames as" invariants are the producer's, not preconditions here.
1138
+ function carryTurnBinding(msg: SDKPartial, p: PendingMessage): void {
1139
+ if (p.turnBindingCarried) return;
913
1140
  const uuid = typeof msg.user_message_uuid === "string" ? msg.user_message_uuid : undefined;
914
1141
  const uuids = readUserMessageUuids(msg.user_message_uuids);
915
- if (uuid === undefined && uuids === undefined) return;
916
- p.userMessageUuidCarried = true;
1142
+ const resumeReason = typeof msg.resume_reason === "string" ? msg.resume_reason : undefined;
1143
+ if (uuid === undefined && uuids === undefined && resumeReason === undefined) return;
1144
+ p.turnBindingCarried = true;
917
1145
  a.emit({
918
1146
  type: "message.metadata",
919
1147
  messageId: p.emittedId,
920
1148
  metadata: {
921
1149
  ...(uuid !== undefined ? { user_message_uuid: uuid } : {}),
922
1150
  ...(uuids !== undefined ? { user_message_uuids: uuids } : {}),
1151
+ ...(resumeReason !== undefined ? { resume_reason: resumeReason } : {}),
923
1152
  },
924
1153
  });
925
1154
  }
@@ -1002,7 +1231,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1002
1231
  if (continued !== undefined) {
1003
1232
  continued.streamed = true;
1004
1233
  carryTtft(msg, continued);
1005
- carryUserMessageUuid(msg, continued);
1234
+ carryTurnBinding(msg, continued);
1006
1235
  return;
1007
1236
  }
1008
1237
  closePendingMessage();
@@ -1025,7 +1254,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1025
1254
  streamed: true,
1026
1255
  streamBlocks: new Map(),
1027
1256
  ttftCarried: false,
1028
- userMessageUuidCarried: false,
1257
+ turnBindingCarried: false,
1029
1258
  };
1030
1259
  pending = open;
1031
1260
  a.openMessage({
@@ -1039,7 +1268,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1039
1268
  // (assistant / adopted tool-result frames) — the complete frame that joins
1040
1269
  // this lifecycle registers its own uuid as before.
1041
1270
  carryTtft(msg, open);
1042
- carryUserMessageUuid(msg, open);
1271
+ carryTurnBinding(msg, open);
1043
1272
  return;
1044
1273
  }
1045
1274
 
@@ -1054,7 +1283,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1054
1283
  // either way, never an ext carry.
1055
1284
  if (pending !== undefined && pending.streamed) {
1056
1285
  carryTtft(msg, pending);
1057
- carryUserMessageUuid(msg, pending);
1286
+ carryTurnBinding(msg, pending);
1058
1287
  }
1059
1288
  return;
1060
1289
  }
@@ -1069,7 +1298,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1069
1298
  return;
1070
1299
  }
1071
1300
  carryTtft(msg, p);
1072
- carryUserMessageUuid(msg, p);
1301
+ carryTurnBinding(msg, p);
1073
1302
 
1074
1303
  if (ev.type === "content_block_start") {
1075
1304
  const index = ev.index;
@@ -1350,6 +1579,68 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1350
1579
  // wrapper-meta channel's type without an unchecked cast.
1351
1580
  wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
1352
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
+ }
1596
+ // `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
1597
+ // the indexes of THIS frame's content blocks that are user-facing narration
1598
+ // — Anthropic's `thinking.display: "updates"` mode returns progress updates
1599
+ // between tool calls as thinking blocks, and without this list a consumer
1600
+ // cannot tell a narration block (meant to be shown) from private reasoning
1601
+ // (usually hidden). A rendering decision, so it is carried losslessly rather
1602
+ // than allowlisted. Deliberately OUTSIDE the turn-binding guard: this is a
1603
+ // per-frame content fact like `aborted`, not a member of the
1604
+ // user_message_uuid family, and it appears on the complete assistant frame
1605
+ // only (no stream-event twin), so it cannot double-carry. Wire name verbatim.
1606
+ // Undeclared at 0.3.272 — same JSON boundary as `local_command`, never a cast.
1607
+ const rawAssistant: unknown = msg;
1608
+ const narrationBlockIndexes = readNarrationBlockIndexes(
1609
+ isJsonObject(rawAssistant) ? rawAssistant["narration_block_indexes"] : undefined,
1610
+ );
1611
+ if (narrationBlockIndexes !== undefined) {
1612
+ wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
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
+ }
1353
1644
  // `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
1354
1645
  // the bag below, once `open` is known — their once-per-message flag is
1355
1646
  // shared with the stream arm's carry.
@@ -1387,7 +1678,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1387
1678
  streamed: false,
1388
1679
  streamBlocks: new Map(),
1389
1680
  ttftCarried: false,
1390
- userMessageUuidCarried: false,
1681
+ turnBindingCarried: false,
1391
1682
  };
1392
1683
  pending = open;
1393
1684
  a.openMessage({
@@ -1405,7 +1696,7 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1405
1696
  // `message.content`, not replayed to the model). The join key that
1406
1697
  // binds a reply to its send without waiting for the result frame;
1407
1698
  // carried verbatim. With partials on, the stamp normally rode the first
1408
- // non-ping stream event instead (`carryUserMessageUuid`) — the shared
1699
+ // non-ping stream event instead (`carryTurnBinding`) — the shared
1409
1700
  // once-per-message flag keeps the two channels from double-carrying.
1410
1701
  // - `user_message_uuids` (0.3.259): the plural companion — every client
1411
1702
  // uuid whose prompt this turn consumed so far, in consumption order
@@ -1413,13 +1704,28 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1413
1704
  // LAST member). Same frame, same bag, same flag, wire name verbatim;
1414
1705
  // shape-guarded through `readUserMessageUuids`, invariants not
1415
1706
  // validated. Either member alone still triggers the (single) carry.
1416
- if (!open.userMessageUuidCarried) {
1707
+ // - `resume_reason` (0.3.268): the third leg of the SAME turn-binding
1708
+ // family — why this frame's turn is the AUTOMATIC re-run of a turn a
1709
+ // worker restart interrupted (the host's CLAUDE_CODE_RESUME_REASON:
1710
+ // host_draining, checkpoint_restore, container_recreated, …; else
1711
+ // 'interrupted_turn'). On such a re-run `user_message_uuid` names the
1712
+ // INTERRUPTED turn's last prompt, so without this field a consumer
1713
+ // cannot tell the re-run's first reply from the interrupted attempt's.
1714
+ // 0.3.269 stamps all THREE under ONE rule ("first complete assistant
1715
+ // message as well as first stream event when partial messages are
1716
+ // on"), so it MUST ride the same flag: written outside this guard it
1717
+ // would double-emit message.metadata on every streamed lifecycle (the
1718
+ // stream arm carries, then this suppressed complete frame carries
1719
+ // again). Wire name verbatim.
1720
+ if (!open.turnBindingCarried) {
1417
1721
  const uuid = typeof msg.user_message_uuid === "string" ? msg.user_message_uuid : undefined;
1418
1722
  const uuids = readUserMessageUuids(msg.user_message_uuids);
1419
- if (uuid !== undefined || uuids !== undefined) {
1420
- open.userMessageUuidCarried = true;
1723
+ const resumeReason = typeof msg.resume_reason === "string" ? msg.resume_reason : undefined;
1724
+ if (uuid !== undefined || uuids !== undefined || resumeReason !== undefined) {
1725
+ open.turnBindingCarried = true;
1421
1726
  if (uuid !== undefined) wrapperMetaRaw["user_message_uuid"] = uuid;
1422
1727
  if (uuids !== undefined) wrapperMetaRaw["user_message_uuids"] = uuids;
1728
+ if (resumeReason !== undefined) wrapperMetaRaw["resume_reason"] = resumeReason;
1423
1729
  }
1424
1730
  }
1425
1731
  const wrapperMeta: AgProviderMeta | undefined =
@@ -1468,26 +1774,46 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1468
1774
  open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
1469
1775
 
1470
1776
  // If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
1471
- // 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`).
1472
1781
  if (msg.error !== undefined) {
1473
- // The turn is over — nothing can continue this message. Seal it first,
1474
- // 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.
1475
1785
  closePendingMessage();
1476
1786
  const errCode: NonNullable<SDKAssistantError> = msg.error;
1477
- a.closeTurnError(turnId, {
1478
- message: errCode,
1479
- code: errCode,
1480
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
1481
- // cousin of rate_limit/server_error) joins the retriable set.
1482
- // `model_not_found` (a permanent misconfiguration — e.g. a stale/
1483
- // decommissioned model id) is deliberately EXCLUDED: explicit
1484
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
1485
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
1486
- // deliberate non-retriable: a billing-class code (the account is on
1487
- // hold — a first cousin of `billing_error`, cleared by the account
1488
- // holder, never by re-sending the turn).
1489
- retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
1490
- });
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
+ }
1491
1817
  }
1492
1818
 
1493
1819
  // `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
@@ -1629,6 +1955,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1629
1955
  // (message.end has always preceded the turn close).
1630
1956
  closePendingMessage();
1631
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;
1632
1978
  const safety: AgSafety[] | undefined =
1633
1979
  msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
1634
1980
  // structured_output (when a response schema is in effect) overrides the plain
@@ -1638,6 +1984,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1638
1984
  // Emit permission_denials as tool.start + tool.done denied pairs, inside a
1639
1985
  // dedicated carrier message: the assistant message is already sealed, and
1640
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.
1641
1990
  if (msg.permission_denials.length > 0) {
1642
1991
  const denialMsgId = `${turnId}:denials`;
1643
1992
  a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
@@ -1651,15 +2000,9 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1651
2000
  // tool.start/tool.done pair is ever emitted for the live frame
1652
2001
  // itself (see the dedicated `permission_denied` branch below).
1653
2002
  const live = deniedLiveByToolUseId.get(denial.tool_use_id);
2003
+ const liveFields = liveDenialMeta(live);
1654
2004
  const liveMeta: AgProviderMeta | undefined =
1655
- live !== undefined &&
1656
- (live.decisionReasonType !== undefined || live.decisionReason !== undefined || live.agentId !== undefined)
1657
- ? AgProviderMeta.parse({
1658
- ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
1659
- ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
1660
- ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
1661
- })
1662
- : undefined;
2005
+ liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1663
2006
  a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1664
2007
  a.toolDone({
1665
2008
  toolCallId: denial.tool_use_id,
@@ -1672,11 +2015,41 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1672
2015
  }
1673
2016
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
1674
2017
  // ride `ext.anthropic.result-meta` before the close (no core home on
1675
- // 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.
1676
2020
  const resultMeta = resultMetaPayload(msg);
1677
2021
  if (resultMeta !== undefined) {
1678
2022
  a.emitExt("anthropic", "result-meta", resultMeta);
1679
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
+ }
1680
2053
  a.closeTurnDone(turnId, {
1681
2054
  outcome: { type: "success", result: structuredOutput ?? msg.result },
1682
2055
  finishReason: mapStopReason(msg.stop_reason),
@@ -1691,13 +2064,26 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1691
2064
  // guuey#26: seal the open assistant message before the turn close.
1692
2065
  closePendingMessage();
1693
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);
1694
2071
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
1695
2072
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
1696
2073
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
1697
2074
  // not throw (Tenet 6: graceful, never throws).
1698
2075
  const errors = Array.isArray(msg.errors) ? msg.errors : [];
1699
2076
  const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
1700
- 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";
1701
2087
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
1702
2088
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
1703
2089
  // success arm above (turn.error carries no metadata slot at all).
@@ -1705,6 +2091,32 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1705
2091
  if (resultMeta !== undefined) {
1706
2092
  a.emitExt("anthropic", "result-meta", resultMeta);
1707
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
+ }
1708
2120
  a.closeTurnError(turnId, {
1709
2121
  message: errors.length > 0 ? errors.join("; ") : subtype,
1710
2122
  code: subtype,
@@ -1760,9 +2172,27 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1760
2172
  // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
1761
2173
  // second pair here (the M22 double-fold hazard). Record this frame's
1762
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;
1763
2192
  deniedLiveByToolUseId.set(msg.tool_use_id, {
1764
2193
  message: msg.message,
1765
2194
  ...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
2195
+ ...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
1766
2196
  ...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
1767
2197
  ...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
1768
2198
  });
@@ -1810,6 +2240,14 @@ export function createClaudeNormalizer(options: ClaudeNormalizerOptions = {}): N
1810
2240
  // its real usage (and its subagent bracket) rather than leaving INV-FLUSH
1811
2241
  // to synthesize a bare `message.end`.
1812
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();
1813
2251
  return a.flush();
1814
2252
  },
1815
2253
  };