@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/README.md +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +441 -61
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +500 -62
package/dist/index.js
CHANGED
|
@@ -522,6 +522,79 @@ function anthropicFrameKind(msg) {
|
|
|
522
522
|
function readUserMessageUuids(v) {
|
|
523
523
|
return Array.isArray(v) && v.every((s) => typeof s === "string") ? v : undefined;
|
|
524
524
|
}
|
|
525
|
+
// `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
|
|
526
|
+
// user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
|
|
527
|
+
// 0.3.272 (a pass-through of the Messages API field that rides the assistant
|
|
528
|
+
// wrapper), so it is read through the JSON boundary and shape-guarded here, never
|
|
529
|
+
// cast. Integer indexes into `message.content`; an out-of-range or non-integer
|
|
530
|
+
// member means the producer changed shape, so the whole array is refused rather
|
|
531
|
+
// than half-carried.
|
|
532
|
+
function readNarrationBlockIndexes(v) {
|
|
533
|
+
return Array.isArray(v) &&
|
|
534
|
+
v.length > 0 &&
|
|
535
|
+
v.every((n) => typeof n === "number" && Number.isInteger(n) && n >= 0)
|
|
536
|
+
? v
|
|
537
|
+
: undefined;
|
|
538
|
+
}
|
|
539
|
+
// `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
|
|
540
|
+
// on both frames that carry it (the API-error assistant frame and the
|
|
541
|
+
// `is_error: true` success result), so it is read through the JSON boundary.
|
|
542
|
+
// The CLI copies the server's error.details.error_code through only when it is
|
|
543
|
+
// an identifier (^[a-z][a-z0-9_]{0,63}$); the facet does not re-validate the
|
|
544
|
+
// producer's invariant, it only refuses a non-string.
|
|
545
|
+
function readApiErrorCode(v) {
|
|
546
|
+
return isJsonObject(v) && typeof v["api_error_code"] === "string" ? v["api_error_code"] : undefined;
|
|
547
|
+
}
|
|
548
|
+
// `startup_failure_reason` (0.3.274) — declared on SDKResultError ONLY, so on
|
|
549
|
+
// the result union it is reachable only through the JSON boundary.
|
|
550
|
+
function readStartupFailureReason(v) {
|
|
551
|
+
return isJsonObject(v) && typeof v["startup_failure_reason"] === "string"
|
|
552
|
+
? v["startup_failure_reason"]
|
|
553
|
+
: undefined;
|
|
554
|
+
}
|
|
555
|
+
// `turn.error.retriable` for a result that carries `startup_failure_reason`.
|
|
556
|
+
// The type's own lead sentence frames the whole enum as a refusal to start:
|
|
557
|
+
// "Why Claude Code refused to start, so a host can offer the fix instead of a
|
|
558
|
+
// retry." So a PRESENT reason means NOT retriable, except for the values
|
|
559
|
+
// upstream itself EXPLICITLY describes as retriable. At 0.3.280 that set is
|
|
560
|
+
// exactly one value:
|
|
561
|
+
// - `worktree_unverified`: "the session's worktree could not be verified
|
|
562
|
+
// right now; retrying may succeed."
|
|
563
|
+
// Three more values read as if they might clear on their own, but upstream
|
|
564
|
+
// never says a retry helps, so each is a deliberate non-retriable — explicit
|
|
565
|
+
// false-by-omission (the model_not_found / account_on_hold voice in the
|
|
566
|
+
// assistant-error branch), never an oversight:
|
|
567
|
+
// - `org_verify_failed`: "the sign-in's organization could not be verified
|
|
568
|
+
// against the pin (network, or a revoked token)." A revoked token is not
|
|
569
|
+
// transient, and the doc does not tell the two causes apart.
|
|
570
|
+
// - `remote_settings_required_unavailable`: "managed settings the
|
|
571
|
+
// organization requires could not be loaded." No retry guidance; whether
|
|
572
|
+
// the load failure is transient is not stated.
|
|
573
|
+
// - `session_held_by_background`: "the conversation to resume or continue is
|
|
574
|
+
// running as a background session." Nothing says the hold clears, or when.
|
|
575
|
+
// Every other documented value (org_pin_api_key_conflict, org_pin_mismatch,
|
|
576
|
+
// managed_settings_invalid, gateway_signin_required, gateway_access_denied,
|
|
577
|
+
// proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
|
|
578
|
+
// worktree_resume_refused, cli_version_too_old, bypass_root) names a
|
|
579
|
+
// configuration, policy or environment fix, and an unknown future value
|
|
580
|
+
// inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
|
|
581
|
+
// reason never reaches this function: the error arm keeps its old rule, so
|
|
582
|
+
// older producers are byte-identical.
|
|
583
|
+
const RETRIABLE_STARTUP_FAILURE_REASONS = new Set(["worktree_unverified"]);
|
|
584
|
+
function startupFailureRetriable(reason) {
|
|
585
|
+
return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
|
|
586
|
+
}
|
|
587
|
+
// `turn.error.retriable` for an API-error turn closed by its result frame:
|
|
588
|
+
// retriable exactly when the HTTP status is a rate limit (429) or a server-
|
|
589
|
+
// side failure (>= 500, which includes 529 overloaded) — the result-frame
|
|
590
|
+
// twin of the assistant-error branch's rate_limit / server_error / overloaded
|
|
591
|
+
// set. A null or absent status is not retriable: it carries no evidence that a
|
|
592
|
+
// re-send would behave differently. Typed `number | null` on the
|
|
593
|
+
// success arm, but the frame is only discriminant-validated, so it is guarded
|
|
594
|
+
// with typeof.
|
|
595
|
+
function apiErrorStatusRetriable(status) {
|
|
596
|
+
return typeof status === "number" && (status === 429 || status >= 500);
|
|
597
|
+
}
|
|
525
598
|
// ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
|
|
526
599
|
// `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
|
|
527
600
|
// and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
|
|
@@ -575,6 +648,65 @@ function readUserMessageUuids(v) {
|
|
|
575
648
|
// producer's to keep, not the facet's to validate. CONSISTENCY carry: the
|
|
576
649
|
// string-prompt capture path supplies no client uuid, so no cassette has
|
|
577
650
|
// ever exercised either the singular or the plural.
|
|
651
|
+
//
|
|
652
|
+
// 0.3.272 bump — three more result-frame siblings on the SAME carry:
|
|
653
|
+
// - `resume_reason` (BOTH arms, 0.3.268): the result-frame leg of the
|
|
654
|
+
// turn-binding family the assistant/stream arms now carry (see
|
|
655
|
+
// `carryTurnBinding`) — why this turn was the AUTOMATIC re-run of a turn a
|
|
656
|
+
// worker restart interrupted (the host's CLAUDE_CODE_RESUME_REASON:
|
|
657
|
+
// host_draining, checkpoint_restore, container_recreated, …; else
|
|
658
|
+
// 'interrupted_turn'). Its sibling `user_message_uuid` names the INTERRUPTED
|
|
659
|
+
// turn's own last prompt on such a re-run, so a consumer reconciling results
|
|
660
|
+
// by uuid sees the SAME uuid twice; this is the field that says the second
|
|
661
|
+
// one is a re-run and not a duplicate. Normalized `resumeReason`.
|
|
662
|
+
// - `result_index` (BOTH arms, 0.3.268): delivery sequence of this result
|
|
663
|
+
// within the run, from 0, in the order the process writes them. A
|
|
664
|
+
// DELIVERY-INTEGRITY signal, not a counter: "a result whose write fails
|
|
665
|
+
// still consumes its number, so a gap in a stream-json sequence means a
|
|
666
|
+
// result was LOST" — a consumer can detect a dropped result it would
|
|
667
|
+
// otherwise never know about. Direct sibling of `queued_turn_count` (the
|
|
668
|
+
// same "what else is coming" axis), so it lands in the same carrier as
|
|
669
|
+
// `resultIndex`. 0 is a REAL value (every run's first result), so the guard
|
|
670
|
+
// is `typeof === "number"`, never truthiness.
|
|
671
|
+
// - `local_command` (SUCCESS arm only, 0.3.268 — NO upstream doc comment;
|
|
672
|
+
// disposition from a 0.3.272 CLI-bundle read, 2026-09-15): present exactly
|
|
673
|
+
// on the result of a turn that ran a slash command and NEVER entered the
|
|
674
|
+
// model loop. In the bundle it is written only on the `shouldQuery === false`
|
|
675
|
+
// early-return branch of the result builder, from the input processor's
|
|
676
|
+
// `localCommand`, and not at all when the slash command was deferred to the
|
|
677
|
+
// engine (`engineDeferredSlash`). CARRIED, because its PRESENCE is the
|
|
678
|
+
// consumer signal: it is what distinguishes "this turn was a local command,
|
|
679
|
+
// zero model round-trips" from "this turn produced nothing" — a
|
|
680
|
+
// success result with `num_turns: 0` and no assistant frames is otherwise
|
|
681
|
+
// indistinguishable from an empty turn. Its VALUE, however, is deliberately
|
|
682
|
+
// coarse: the CLI passes the command name through the same sanitizer its
|
|
683
|
+
// analytics use (`isMcp ? "mcp" : (isBuiltIn || isBundled || isOfficial ?
|
|
684
|
+
// rawName : "custom")`) and then slugifies it (lowercase, `[^a-z]+`→`_`,
|
|
685
|
+
// trimmed, ≤64 chars, empty ⇒ "custom"), so a user/project/third-party
|
|
686
|
+
// command reports "custom" and any MCP command reports "mcp". Carried
|
|
687
|
+
// verbatim as the producer emits it — the facet never re-derives a name it
|
|
688
|
+
// was not given — under the normalized name `localCommand`. Read through the
|
|
689
|
+
// `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
|
|
690
|
+
// union has no such property to access.
|
|
691
|
+
//
|
|
692
|
+
// 0.3.280 bump — two more result-frame siblings on the SAME carry:
|
|
693
|
+
// - `api_error_code` (SUCCESS arm, CLI 2.1.280, @internal — UNDECLARED in
|
|
694
|
+
// sdk.d.ts, so no typed access exists): "the api_error_code of the API error
|
|
695
|
+
// that ended the turn (see SDKAssistantMessage.api_error_code): the server's
|
|
696
|
+
// error.details.error_code when it is an identifier". It rides the
|
|
697
|
+
// `is_error: true` success result an API-error turn ends with, and it names
|
|
698
|
+
// server gate codes `SDKAssistantMessageError` flattens to 'unknown', so a
|
|
699
|
+
// host can key on a new gate without a Claude Code release. Normalized
|
|
700
|
+
// `apiErrorCode`; the same value is `turn.error.code` when no assistant
|
|
701
|
+
// error frame preceded this result, so the result alone builds the close
|
|
702
|
+
// (see the success branch in `drive()`).
|
|
703
|
+
// - `startup_failure_reason` (ERROR arm only, 0.3.274): set on the zeroed
|
|
704
|
+
// error_during_execution result a stream-json run writes before exiting on
|
|
705
|
+
// a known startup failure — "Why Claude Code refused to start, so a host
|
|
706
|
+
// can offer the fix instead of a retry". Normalized `startupFailureReason`,
|
|
707
|
+
// value verbatim; it also drives `turn.error.retriable` (see
|
|
708
|
+
// `startupFailureRetriable`). Read through the JSON boundary because it is
|
|
709
|
+
// declared on that one arm only.
|
|
578
710
|
function resultMetaPayload(msg) {
|
|
579
711
|
const byModel = {};
|
|
580
712
|
const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
|
|
@@ -594,13 +726,26 @@ function resultMetaPayload(msg) {
|
|
|
594
726
|
const raw = msg;
|
|
595
727
|
const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? JsonValue.parse(raw["subagent_stats"]) : undefined;
|
|
596
728
|
const userMessageUuids = readUserMessageUuids(msg.user_message_uuids);
|
|
729
|
+
// SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
|
|
730
|
+
// it is read through the same JSON boundary as `subagent_stats`, never cast.
|
|
731
|
+
const localCommand = isJsonObject(raw) && typeof raw["local_command"] === "string" ? raw["local_command"] : undefined;
|
|
732
|
+
// 0.3.280 — undeclared on both arms (`api_error_code`) / declared on the
|
|
733
|
+
// ERROR arm only (`startup_failure_reason`): same JSON boundary, never cast.
|
|
734
|
+
const apiErrorCode = readApiErrorCode(msg);
|
|
735
|
+
const startupFailureReason = readStartupFailureReason(msg);
|
|
597
736
|
const payload = {
|
|
598
737
|
...(typeof msg.fast_mode_disabled_reason === "string"
|
|
599
738
|
? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
|
|
600
739
|
: {}),
|
|
601
740
|
...(typeof msg.user_message_uuid === "string" ? { userMessageUuid: msg.user_message_uuid } : {}),
|
|
602
741
|
...(userMessageUuids !== undefined ? { userMessageUuids } : {}),
|
|
742
|
+
...(typeof msg.resume_reason === "string" ? { resumeReason: msg.resume_reason } : {}),
|
|
603
743
|
...(typeof msg.queued_turn_count === "number" ? { queuedTurnCount: msg.queued_turn_count } : {}),
|
|
744
|
+
// 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
|
|
745
|
+
...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
|
|
746
|
+
...(localCommand !== undefined ? { localCommand } : {}),
|
|
747
|
+
...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
|
|
748
|
+
...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
|
|
604
749
|
...(subagentStats !== undefined ? { subagentStats } : {}),
|
|
605
750
|
...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
|
|
606
751
|
};
|
|
@@ -633,15 +778,32 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
633
778
|
// `message.remove` — "translated through the facet's uuid→messageId
|
|
634
779
|
// convention" per the adaptation brief.
|
|
635
780
|
const messageIdsByUuid = new Map();
|
|
636
|
-
// Fixture-drift ratchet (SDKPermissionDeniedMessage, "handled" via existing-
|
|
637
|
-
// home mapping): live per-denial diagnostic recorded by the standalone
|
|
638
|
-
// `permission_denied` frame (fires DURING the turn, before the terminal
|
|
639
|
-
// result) — keyed by tool_use_id so the terminal `permission_denials[]`
|
|
640
|
-
// aggregate (the ALREADY-handled W1 `<turnId>:denials` carrier, audit M19)
|
|
641
|
-
// can enrich its tool.done with the actual rejection text + decision-reason
|
|
642
|
-
// context, instead of emitting a SECOND tool.start/tool.done pair for the
|
|
643
|
-
// same denial (the M22 double-fold hazard).
|
|
644
781
|
const deniedLiveByToolUseId = new Map();
|
|
782
|
+
// The live denial's diagnostic fields, camelCased — the providerMetadata bag
|
|
783
|
+
// on the enriched `<turnId>:denials` tool.done. undefined when the live
|
|
784
|
+
// frame carried none of them (no empty bag).
|
|
785
|
+
function liveDenialMeta(live) {
|
|
786
|
+
if (live === undefined ||
|
|
787
|
+
(live.decisionReasonType === undefined &&
|
|
788
|
+
live.decisionReasonCode === undefined &&
|
|
789
|
+
live.decisionReason === undefined &&
|
|
790
|
+
live.agentId === undefined)) {
|
|
791
|
+
return undefined;
|
|
792
|
+
}
|
|
793
|
+
return {
|
|
794
|
+
...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
|
|
795
|
+
...(live.decisionReasonCode !== undefined ? { decisionReasonCode: live.decisionReasonCode } : {}),
|
|
796
|
+
...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
|
|
797
|
+
...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
const stashedTurnErrors = new Map();
|
|
801
|
+
/** Remove and return the stashed error close for `turnId`, if any (CL-09). */
|
|
802
|
+
function takeStashedTurnError(turnId) {
|
|
803
|
+
const stashed = stashedTurnErrors.get(turnId);
|
|
804
|
+
stashedTurnErrors.delete(turnId);
|
|
805
|
+
return stashed;
|
|
806
|
+
}
|
|
645
807
|
let pending;
|
|
646
808
|
// How many lifecycles each SDK message id has already opened. A same-id frame
|
|
647
809
|
// arriving after its lifecycle closed (a fold-binding frame landed between two
|
|
@@ -686,32 +848,43 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
686
848
|
p.ttftCarried = true;
|
|
687
849
|
a.emit({ type: "message.metadata", messageId: p.emittedId, metadata: { ttft_ms: msg.ttft_ms } });
|
|
688
850
|
}
|
|
689
|
-
//
|
|
690
|
-
//
|
|
691
|
-
//
|
|
692
|
-
// the
|
|
693
|
-
//
|
|
694
|
-
//
|
|
695
|
-
//
|
|
696
|
-
//
|
|
697
|
-
//
|
|
698
|
-
//
|
|
699
|
-
//
|
|
700
|
-
//
|
|
701
|
-
|
|
702
|
-
|
|
851
|
+
// The TURN-BINDING FAMILY on the partial envelope — what binds this reply
|
|
852
|
+
// stream to the send it answers, before the result arrives. Same channel and
|
|
853
|
+
// same once-per-message rule as `ttft_ms` above (message.metadata, wire names
|
|
854
|
+
// verbatim); the flag is shared with the complete arm's wrapper carry so the
|
|
855
|
+
// two channels never double-carry one message.
|
|
856
|
+
// - `user_message_uuid` (0.3.258): the client uuid of the user message this
|
|
857
|
+
// turn answers, stamped on the turn's FIRST non-ping stream event.
|
|
858
|
+
// - `user_message_uuids` (0.3.259): every client uuid of the prompt batch
|
|
859
|
+
// this turn answers, "present exactly when the singular is" — shape-guarded
|
|
860
|
+
// (`readUserMessageUuids`).
|
|
861
|
+
// - `resume_reason` (0.3.268): why this frame's turn is the AUTOMATIC re-run
|
|
862
|
+
// of a turn a worker restart interrupted — the host's
|
|
863
|
+
// CLAUDE_CODE_RESUME_REASON (host_draining, checkpoint_restore,
|
|
864
|
+
// container_recreated, …) or else 'interrupted_turn'. Not a separate
|
|
865
|
+
// concept from the uuids but the third leg of the same binding: on such a
|
|
866
|
+
// re-run `user_message_uuid` names the INTERRUPTED turn's own last prompt,
|
|
867
|
+
// and `resume_reason` is what tells the re-run's first reply apart from the
|
|
868
|
+
// interrupted attempt's. 0.3.269 stamps all three on the SAME frames under
|
|
869
|
+
// ONE rule, so they share ONE guard and ONE emission.
|
|
870
|
+
// Either member alone still triggers the carry — the "exactly when" /
|
|
871
|
+
// "same frames as" invariants are the producer's, not preconditions here.
|
|
872
|
+
function carryTurnBinding(msg, p) {
|
|
873
|
+
if (p.turnBindingCarried)
|
|
703
874
|
return;
|
|
704
875
|
const uuid = typeof msg.user_message_uuid === "string" ? msg.user_message_uuid : undefined;
|
|
705
876
|
const uuids = readUserMessageUuids(msg.user_message_uuids);
|
|
706
|
-
|
|
877
|
+
const resumeReason = typeof msg.resume_reason === "string" ? msg.resume_reason : undefined;
|
|
878
|
+
if (uuid === undefined && uuids === undefined && resumeReason === undefined)
|
|
707
879
|
return;
|
|
708
|
-
p.
|
|
880
|
+
p.turnBindingCarried = true;
|
|
709
881
|
a.emit({
|
|
710
882
|
type: "message.metadata",
|
|
711
883
|
messageId: p.emittedId,
|
|
712
884
|
metadata: {
|
|
713
885
|
...(uuid !== undefined ? { user_message_uuid: uuid } : {}),
|
|
714
886
|
...(uuids !== undefined ? { user_message_uuids: uuids } : {}),
|
|
887
|
+
...(resumeReason !== undefined ? { resume_reason: resumeReason } : {}),
|
|
715
888
|
},
|
|
716
889
|
});
|
|
717
890
|
}
|
|
@@ -791,7 +964,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
791
964
|
if (continued !== undefined) {
|
|
792
965
|
continued.streamed = true;
|
|
793
966
|
carryTtft(msg, continued);
|
|
794
|
-
|
|
967
|
+
carryTurnBinding(msg, continued);
|
|
795
968
|
return;
|
|
796
969
|
}
|
|
797
970
|
closePendingMessage();
|
|
@@ -814,7 +987,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
814
987
|
streamed: true,
|
|
815
988
|
streamBlocks: new Map(),
|
|
816
989
|
ttftCarried: false,
|
|
817
|
-
|
|
990
|
+
turnBindingCarried: false,
|
|
818
991
|
};
|
|
819
992
|
pending = open;
|
|
820
993
|
a.openMessage({
|
|
@@ -828,7 +1001,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
828
1001
|
// (assistant / adopted tool-result frames) — the complete frame that joins
|
|
829
1002
|
// this lifecycle registers its own uuid as before.
|
|
830
1003
|
carryTtft(msg, open);
|
|
831
|
-
|
|
1004
|
+
carryTurnBinding(msg, open);
|
|
832
1005
|
return;
|
|
833
1006
|
}
|
|
834
1007
|
if (ev.type === "message_stop") {
|
|
@@ -842,7 +1015,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
842
1015
|
// either way, never an ext carry.
|
|
843
1016
|
if (pending !== undefined && pending.streamed) {
|
|
844
1017
|
carryTtft(msg, pending);
|
|
845
|
-
|
|
1018
|
+
carryTurnBinding(msg, pending);
|
|
846
1019
|
}
|
|
847
1020
|
return;
|
|
848
1021
|
}
|
|
@@ -856,7 +1029,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
856
1029
|
return;
|
|
857
1030
|
}
|
|
858
1031
|
carryTtft(msg, p);
|
|
859
|
-
|
|
1032
|
+
carryTurnBinding(msg, p);
|
|
860
1033
|
if (ev.type === "content_block_start") {
|
|
861
1034
|
const index = ev.index;
|
|
862
1035
|
const block = ev.content_block;
|
|
@@ -1131,6 +1304,68 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1131
1304
|
// wrapper-meta channel's type without an unchecked cast.
|
|
1132
1305
|
wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
|
|
1133
1306
|
}
|
|
1307
|
+
// `usage_report` (0.3.273): the structured twin of the /usage report,
|
|
1308
|
+
// riding the synthetic assistant message that delivers its text (session
|
|
1309
|
+
// totals, the plan's usage rows, extra-usage spend) — context_usage's
|
|
1310
|
+
// sibling, same wrapper-level placement per its own doc (never inside
|
|
1311
|
+
// `message.content`, not replayed to the model), so it gets the same carry:
|
|
1312
|
+
// whole and verbatim, wire name kept. Carried whole rather than field by
|
|
1313
|
+
// field because upstream marks SDKUsageReport "Experimental — the shape may
|
|
1314
|
+
// change". A per-frame fact like context_usage, so it sits OUTSIDE the
|
|
1315
|
+
// turn-binding guard. FIXTURE-ONLY: upstream attaches it only "from
|
|
1316
|
+
// claude.ai-subscriber sessions", and the capture harness authenticates
|
|
1317
|
+
// with ANTHROPIC_API_KEY, so no live cassette can carry it.
|
|
1318
|
+
if (msg.usage_report !== undefined) {
|
|
1319
|
+
wrapperMetaRaw["usage_report"] = JsonValue.parse(msg.usage_report);
|
|
1320
|
+
}
|
|
1321
|
+
// `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
|
|
1322
|
+
// the indexes of THIS frame's content blocks that are user-facing narration
|
|
1323
|
+
// — Anthropic's `thinking.display: "updates"` mode returns progress updates
|
|
1324
|
+
// between tool calls as thinking blocks, and without this list a consumer
|
|
1325
|
+
// cannot tell a narration block (meant to be shown) from private reasoning
|
|
1326
|
+
// (usually hidden). A rendering decision, so it is carried losslessly rather
|
|
1327
|
+
// than allowlisted. Deliberately OUTSIDE the turn-binding guard: this is a
|
|
1328
|
+
// per-frame content fact like `aborted`, not a member of the
|
|
1329
|
+
// user_message_uuid family, and it appears on the complete assistant frame
|
|
1330
|
+
// only (no stream-event twin), so it cannot double-carry. Wire name verbatim.
|
|
1331
|
+
// Undeclared at 0.3.272 — same JSON boundary as `local_command`, never a cast.
|
|
1332
|
+
const rawAssistant = msg;
|
|
1333
|
+
const narrationBlockIndexes = readNarrationBlockIndexes(isJsonObject(rawAssistant) ? rawAssistant["narration_block_indexes"] : undefined);
|
|
1334
|
+
if (narrationBlockIndexes !== undefined) {
|
|
1335
|
+
wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
|
|
1336
|
+
}
|
|
1337
|
+
// The API-error TRIAD (CLI 2.1.280, all @internal and UNDECLARED in
|
|
1338
|
+
// sdk.d.ts at 0.3.280 — read through the same JSON boundary, never cast).
|
|
1339
|
+
// The CLI stamps them on the synthetic API-error assistant frame, the one
|
|
1340
|
+
// that also carries `error`, which SDKAssistantMessageError flattens to a
|
|
1341
|
+
// 13-value set (a new server gate reads as 'unknown'):
|
|
1342
|
+
// - `api_error`: the typed kind of the error ("for consumers that key on
|
|
1343
|
+
// the cause instead of the message text"), a closed CLI enum of 25
|
|
1344
|
+
// values at CLI 2.1.280 (dlp_request_denied, claude_code_version_too_old,
|
|
1345
|
+
// effort_requires_thinking, provider_credentials, …; "new values are
|
|
1346
|
+
// added over time"). Carried as a string, not enum-gated.
|
|
1347
|
+
// - `api_error_params`: `{effort?, provider?, remedy?}`, "present only
|
|
1348
|
+
// for the kinds that have any" — `remedy` is the fix a host should
|
|
1349
|
+
// offer (refresh_command, refresh_credentials, adc, …). Carried whole.
|
|
1350
|
+
// - `api_error_code`: the server's error.details.error_code, so "a host
|
|
1351
|
+
// can key on a new gate without a Claude Code release".
|
|
1352
|
+
// Per-frame facts of the error frame, like `aborted` / `context_usage`, so
|
|
1353
|
+
// they sit OUTSIDE the turn-binding guard. Wire names verbatim. The frame's
|
|
1354
|
+
// `is_api_error_message: true` flag is deliberately NOT carried: it
|
|
1355
|
+
// restates `error` being set, which already decides the turn's turn.error
|
|
1356
|
+
// close (stashed until the result frame — see `stashedTurnErrors`).
|
|
1357
|
+
if (isJsonObject(rawAssistant)) {
|
|
1358
|
+
const apiError = rawAssistant["api_error"];
|
|
1359
|
+
if (typeof apiError === "string")
|
|
1360
|
+
wrapperMetaRaw["api_error"] = apiError;
|
|
1361
|
+
const apiErrorParams = rawAssistant["api_error_params"];
|
|
1362
|
+
if (isJsonObject(apiErrorParams))
|
|
1363
|
+
wrapperMetaRaw["api_error_params"] = JsonValue.parse(apiErrorParams);
|
|
1364
|
+
}
|
|
1365
|
+
const assistantApiErrorCode = readApiErrorCode(rawAssistant);
|
|
1366
|
+
if (assistantApiErrorCode !== undefined) {
|
|
1367
|
+
wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
|
|
1368
|
+
}
|
|
1134
1369
|
// `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
|
|
1135
1370
|
// the bag below, once `open` is known — their once-per-message flag is
|
|
1136
1371
|
// shared with the stream arm's carry.
|
|
@@ -1167,7 +1402,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1167
1402
|
streamed: false,
|
|
1168
1403
|
streamBlocks: new Map(),
|
|
1169
1404
|
ttftCarried: false,
|
|
1170
|
-
|
|
1405
|
+
turnBindingCarried: false,
|
|
1171
1406
|
};
|
|
1172
1407
|
pending = open;
|
|
1173
1408
|
a.openMessage({
|
|
@@ -1185,7 +1420,7 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1185
1420
|
// `message.content`, not replayed to the model). The join key that
|
|
1186
1421
|
// binds a reply to its send without waiting for the result frame;
|
|
1187
1422
|
// carried verbatim. With partials on, the stamp normally rode the first
|
|
1188
|
-
// non-ping stream event instead (`
|
|
1423
|
+
// non-ping stream event instead (`carryTurnBinding`) — the shared
|
|
1189
1424
|
// once-per-message flag keeps the two channels from double-carrying.
|
|
1190
1425
|
// - `user_message_uuids` (0.3.259): the plural companion — every client
|
|
1191
1426
|
// uuid whose prompt this turn consumed so far, in consumption order
|
|
@@ -1193,15 +1428,31 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1193
1428
|
// LAST member). Same frame, same bag, same flag, wire name verbatim;
|
|
1194
1429
|
// shape-guarded through `readUserMessageUuids`, invariants not
|
|
1195
1430
|
// validated. Either member alone still triggers the (single) carry.
|
|
1196
|
-
|
|
1431
|
+
// - `resume_reason` (0.3.268): the third leg of the SAME turn-binding
|
|
1432
|
+
// family — why this frame's turn is the AUTOMATIC re-run of a turn a
|
|
1433
|
+
// worker restart interrupted (the host's CLAUDE_CODE_RESUME_REASON:
|
|
1434
|
+
// host_draining, checkpoint_restore, container_recreated, …; else
|
|
1435
|
+
// 'interrupted_turn'). On such a re-run `user_message_uuid` names the
|
|
1436
|
+
// INTERRUPTED turn's last prompt, so without this field a consumer
|
|
1437
|
+
// cannot tell the re-run's first reply from the interrupted attempt's.
|
|
1438
|
+
// 0.3.269 stamps all THREE under ONE rule ("first complete assistant
|
|
1439
|
+
// message as well as first stream event when partial messages are
|
|
1440
|
+
// on"), so it MUST ride the same flag: written outside this guard it
|
|
1441
|
+
// would double-emit message.metadata on every streamed lifecycle (the
|
|
1442
|
+
// stream arm carries, then this suppressed complete frame carries
|
|
1443
|
+
// again). Wire name verbatim.
|
|
1444
|
+
if (!open.turnBindingCarried) {
|
|
1197
1445
|
const uuid = typeof msg.user_message_uuid === "string" ? msg.user_message_uuid : undefined;
|
|
1198
1446
|
const uuids = readUserMessageUuids(msg.user_message_uuids);
|
|
1199
|
-
|
|
1200
|
-
|
|
1447
|
+
const resumeReason = typeof msg.resume_reason === "string" ? msg.resume_reason : undefined;
|
|
1448
|
+
if (uuid !== undefined || uuids !== undefined || resumeReason !== undefined) {
|
|
1449
|
+
open.turnBindingCarried = true;
|
|
1201
1450
|
if (uuid !== undefined)
|
|
1202
1451
|
wrapperMetaRaw["user_message_uuid"] = uuid;
|
|
1203
1452
|
if (uuids !== undefined)
|
|
1204
1453
|
wrapperMetaRaw["user_message_uuids"] = uuids;
|
|
1454
|
+
if (resumeReason !== undefined)
|
|
1455
|
+
wrapperMetaRaw["resume_reason"] = resumeReason;
|
|
1205
1456
|
}
|
|
1206
1457
|
}
|
|
1207
1458
|
const wrapperMeta = Object.keys(wrapperMetaRaw).length > 0 ? AgProviderMeta.parse(wrapperMetaRaw) : undefined;
|
|
@@ -1249,26 +1500,46 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1249
1500
|
// not — without this merge the join would erase the streamed count.
|
|
1250
1501
|
open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
|
|
1251
1502
|
// If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
|
|
1252
|
-
//
|
|
1503
|
+
// the turn ends as a turn.error so consumers see the error rather than a
|
|
1504
|
+
// silent empty turn. CL-09: the close is STASHED, not emitted here — the
|
|
1505
|
+
// turn's result frame (which carries the turn's usage) emits it, or
|
|
1506
|
+
// `flush()` does if no result ever arrives (see `stashedTurnErrors`).
|
|
1253
1507
|
if (msg.error !== undefined) {
|
|
1254
|
-
// The
|
|
1255
|
-
// so `message.end` still precedes the
|
|
1508
|
+
// The API error ended the model's output — nothing can continue this
|
|
1509
|
+
// message. Seal it now, so `message.end` still precedes the (deferred)
|
|
1510
|
+
// close.
|
|
1256
1511
|
closePendingMessage();
|
|
1257
1512
|
const errCode = msg.error;
|
|
1258
|
-
a
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1513
|
+
// First error frame wins: a turn already carrying a stashed close keeps
|
|
1514
|
+
// it (before CL-09's stash, the first error frame closed the turn).
|
|
1515
|
+
if (!stashedTurnErrors.has(turnId)) {
|
|
1516
|
+
stashedTurnErrors.set(turnId, {
|
|
1517
|
+
message: errCode,
|
|
1518
|
+
code: errCode,
|
|
1519
|
+
// Finding #2 (minor): `overloaded` (transient capacity error, a first
|
|
1520
|
+
// cousin of rate_limit/server_error) joins the retriable set.
|
|
1521
|
+
// `model_not_found` (a permanent misconfiguration — e.g. a stale/
|
|
1522
|
+
// decommissioned model id) is deliberately EXCLUDED: explicit
|
|
1523
|
+
// false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
|
|
1524
|
+
// adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
|
|
1525
|
+
// deliberate non-retriable: a billing-class code (the account is on
|
|
1526
|
+
// hold — a first cousin of `billing_error`, cleared by the account
|
|
1527
|
+
// holder, never by re-sending the turn).
|
|
1528
|
+
//
|
|
1529
|
+
// 0.3.272 widened `SDKAssistantMessageError` by two more values, both
|
|
1530
|
+
// deliberate non-retriables recorded here for the same reason — an
|
|
1531
|
+
// omission must never read as an oversight:
|
|
1532
|
+
// - `verification_required`: the request is gated on an out-of-band
|
|
1533
|
+
// human step (identity/org verification). Nothing about the turn
|
|
1534
|
+
// changes by re-sending it; the block clears only when a person
|
|
1535
|
+
// completes the verification.
|
|
1536
|
+
// - `cloud_credential_error`: a credential/billing-class failure on
|
|
1537
|
+
// the cloud-provider leg (a first cousin of `billing_error` and
|
|
1538
|
+
// `account_on_hold`, not of `overloaded`) — a bad, expired or
|
|
1539
|
+
// unauthorized credential is exactly as bad on the next attempt.
|
|
1540
|
+
retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1272
1543
|
}
|
|
1273
1544
|
// `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
|
|
1274
1545
|
// message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
|
|
@@ -1401,6 +1672,26 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1401
1672
|
// (message.end has always preceded the turn close).
|
|
1402
1673
|
closePendingMessage();
|
|
1403
1674
|
const turnId = turnIdFor(msg.session_id, msg.uuid);
|
|
1675
|
+
// CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
|
|
1676
|
+
// succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
|
|
1677
|
+
// the final assistant text in result — or, with is_error true, the error
|
|
1678
|
+
// text when the turn ended on an API error". The CLI sets is_error from
|
|
1679
|
+
// the turn's last assistant frame being its synthetic API-error message
|
|
1680
|
+
// (rate_limit / overloaded after retries ran out, billing_error,
|
|
1681
|
+
// authentication_failed, …). Such a turn closes as an ERROR, never as a
|
|
1682
|
+
// success, and exactly once:
|
|
1683
|
+
// - if that assistant frame reached this facet, it stashed the turn's
|
|
1684
|
+
// error close (`stashedTurnErrors`); this frame emits it, with this
|
|
1685
|
+
// frame's usage — whatever is_error says, since that frame already
|
|
1686
|
+
// decided the turn's outcome;
|
|
1687
|
+
// - otherwise, with is_error true, this frame is the only evidence of
|
|
1688
|
+
// the error, and the close is a turn.error built from the result
|
|
1689
|
+
// itself (see below).
|
|
1690
|
+
// Strict `=== true`: is_error is typed boolean, but the frame is only
|
|
1691
|
+
// discriminant-validated, and false/absent must stay on the success path
|
|
1692
|
+
// byte-for-byte. The stash entry is consumed either way.
|
|
1693
|
+
const stashedError = takeStashedTurnError(turnId);
|
|
1694
|
+
const apiErrorTurn = msg.is_error === true;
|
|
1404
1695
|
const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
|
|
1405
1696
|
// structured_output (when a response schema is in effect) overrides the plain
|
|
1406
1697
|
// string result — it is the authoritative typed outcome payload (spec §4).
|
|
@@ -1408,6 +1699,9 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1408
1699
|
// Emit permission_denials as tool.start + tool.done denied pairs, inside a
|
|
1409
1700
|
// dedicated carrier message: the assistant message is already sealed, and
|
|
1410
1701
|
// INV-MSG (audit M19) forbids attaching to sealed messages / closed turns.
|
|
1702
|
+
// CL-09: an API-error turn's denials take this same carrier, at the same
|
|
1703
|
+
// point — its close is deferred to this frame (below), so the turn is
|
|
1704
|
+
// still open here, like every other turn.
|
|
1411
1705
|
if (msg.permission_denials.length > 0) {
|
|
1412
1706
|
const denialMsgId = `${turnId}:denials`;
|
|
1413
1707
|
a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
|
|
@@ -1421,14 +1715,8 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1421
1715
|
// tool.start/tool.done pair is ever emitted for the live frame
|
|
1422
1716
|
// itself (see the dedicated `permission_denied` branch below).
|
|
1423
1717
|
const live = deniedLiveByToolUseId.get(denial.tool_use_id);
|
|
1424
|
-
const
|
|
1425
|
-
|
|
1426
|
-
? AgProviderMeta.parse({
|
|
1427
|
-
...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
|
|
1428
|
-
...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
|
|
1429
|
-
...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
|
|
1430
|
-
})
|
|
1431
|
-
: undefined;
|
|
1718
|
+
const liveFields = liveDenialMeta(live);
|
|
1719
|
+
const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
|
|
1432
1720
|
a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
|
|
1433
1721
|
a.toolDone({
|
|
1434
1722
|
toolCallId: denial.tool_use_id,
|
|
@@ -1441,11 +1729,41 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1441
1729
|
}
|
|
1442
1730
|
// 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
|
|
1443
1731
|
// ride `ext.anthropic.result-meta` before the close (no core home on
|
|
1444
|
-
// turn.done — see resultMetaPayload's doc).
|
|
1732
|
+
// turn.done — see resultMetaPayload's doc). CL-09: it is emitted on an
|
|
1733
|
+
// API-error turn too, before its close like on every other turn.
|
|
1445
1734
|
const resultMeta = resultMetaPayload(msg);
|
|
1446
1735
|
if (resultMeta !== undefined) {
|
|
1447
1736
|
a.emitExt("anthropic", "result-meta", resultMeta);
|
|
1448
1737
|
}
|
|
1738
|
+
if (stashedError !== undefined) {
|
|
1739
|
+
// The assistant error frame decided this close; this frame adds the
|
|
1740
|
+
// turn's usage, the same mapping turn.done would have carried (SPEC §4:
|
|
1741
|
+
// turn.error `usage` is "accrued billing on the interrupted turn"), so
|
|
1742
|
+
// the fold keeps the cost of every round the turn ran before failing.
|
|
1743
|
+
a.closeTurnError(turnId, {
|
|
1744
|
+
...stashedError,
|
|
1745
|
+
usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
|
|
1746
|
+
});
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
if (apiErrorTurn) {
|
|
1750
|
+
// No assistant error frame preceded this result (a producer that did
|
|
1751
|
+
// not yield it, or a normalizer that never saw it), so this result is
|
|
1752
|
+
// the turn's only close. message = the result text, which on this frame
|
|
1753
|
+
// is the API error text; code = the server's api_error_code when the
|
|
1754
|
+
// CLI copied one through, else the generic "api_error"; retriable = the
|
|
1755
|
+
// HTTP status says rate limit or server failure (see
|
|
1756
|
+
// `apiErrorStatusRetriable`); usage = the turn's accrued usage, as
|
|
1757
|
+
// above.
|
|
1758
|
+
const code = readApiErrorCode(msg) ?? "api_error";
|
|
1759
|
+
a.closeTurnError(turnId, {
|
|
1760
|
+
message: typeof msg.result === "string" ? msg.result : code,
|
|
1761
|
+
code,
|
|
1762
|
+
retriable: apiErrorStatusRetriable(msg.api_error_status),
|
|
1763
|
+
usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
|
|
1764
|
+
});
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1449
1767
|
a.closeTurnDone(turnId, {
|
|
1450
1768
|
outcome: { type: "success", result: structuredOutput ?? msg.result },
|
|
1451
1769
|
finishReason: mapStopReason(msg.stop_reason),
|
|
@@ -1459,13 +1777,25 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1459
1777
|
// guuey#26: seal the open assistant message before the turn close.
|
|
1460
1778
|
closePendingMessage();
|
|
1461
1779
|
const turnId = turnIdFor(msg.session_id, msg.uuid);
|
|
1780
|
+
// CL-09: consume any stashed assistant-error close for this turnId — this
|
|
1781
|
+
// frame emits it (below), and it cannot leak into a later turn's result
|
|
1782
|
+
// (every turn of a session shares the turnId).
|
|
1783
|
+
const stashedError = takeStashedTurnError(turnId);
|
|
1462
1784
|
// Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
|
|
1463
1785
|
// `typeof v.subtype === "string"` for the result arm — it does NOT validate
|
|
1464
1786
|
// the `errors` array. A malformed message (missing errors, wrong subtype) must
|
|
1465
1787
|
// not throw (Tenet 6: graceful, never throws).
|
|
1466
1788
|
const errors = Array.isArray(msg.errors) ? msg.errors : [];
|
|
1467
1789
|
const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
|
|
1468
|
-
|
|
1790
|
+
// CL-04 (0.3.274): a known startup failure says why the CLI refused to
|
|
1791
|
+
// start, and upstream frames it as "offer the fix instead of a retry" —
|
|
1792
|
+
// so a PRESENT reason decides retriable (false, except the values upstream
|
|
1793
|
+
// itself calls retriable; see `startupFailureRetriable`). An ABSENT reason
|
|
1794
|
+
// keeps the old rule, byte-identical for every older producer.
|
|
1795
|
+
const startupFailureReason = readStartupFailureReason(msg);
|
|
1796
|
+
const retriable = startupFailureReason !== undefined
|
|
1797
|
+
? startupFailureRetriable(startupFailureReason)
|
|
1798
|
+
: subtype !== "error_max_turns";
|
|
1469
1799
|
// 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
|
|
1470
1800
|
// error variant gets the SAME `ext.anthropic.result-meta` carry as the
|
|
1471
1801
|
// success arm above (turn.error carries no metadata slot at all).
|
|
@@ -1473,6 +1803,31 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1473
1803
|
if (resultMeta !== undefined) {
|
|
1474
1804
|
a.emitExt("anthropic", "result-meta", resultMeta);
|
|
1475
1805
|
}
|
|
1806
|
+
if (stashedError !== undefined) {
|
|
1807
|
+
// CL-09: an assistant error frame already decided this turn's close —
|
|
1808
|
+
// emit THAT one (the first error that ended the turn), once, never a
|
|
1809
|
+
// second turn.error for the same turnId (INV-TURN), with this frame's
|
|
1810
|
+
// usage (the success arm's mapping). This arm is only
|
|
1811
|
+
// discriminant-validated, so the usage trio is shape-guarded first
|
|
1812
|
+
// (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
|
|
1813
|
+
// The guard covers every property `mapTurnUsage` dereferences: the
|
|
1814
|
+
// `server_tool_use` object (null allowed, as typed) and each
|
|
1815
|
+
// `modelUsage` entry — `usage: {}` or a null entry would otherwise
|
|
1816
|
+
// throw here, after the stash was already consumed.
|
|
1817
|
+
const raw = msg;
|
|
1818
|
+
const rawUsage = isJsonObject(raw) ? raw["usage"] : undefined;
|
|
1819
|
+
const rawModelUsage = isJsonObject(raw) ? raw["modelUsage"] : undefined;
|
|
1820
|
+
const usage = isJsonObject(raw) &&
|
|
1821
|
+
isJsonObject(rawUsage) &&
|
|
1822
|
+
(rawUsage["server_tool_use"] === null || isJsonObject(rawUsage["server_tool_use"])) &&
|
|
1823
|
+
isJsonObject(rawModelUsage) &&
|
|
1824
|
+
Object.values(rawModelUsage).every(isJsonObject) &&
|
|
1825
|
+
typeof raw["total_cost_usd"] === "number"
|
|
1826
|
+
? mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage)
|
|
1827
|
+
: undefined;
|
|
1828
|
+
a.closeTurnError(turnId, { ...stashedError, ...(usage !== undefined ? { usage } : {}) });
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1476
1831
|
a.closeTurnError(turnId, {
|
|
1477
1832
|
message: errors.length > 0 ? errors.join("; ") : subtype,
|
|
1478
1833
|
code: subtype,
|
|
@@ -1525,9 +1880,26 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1525
1880
|
// W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
|
|
1526
1881
|
// second pair here (the M22 double-fold hazard). Record this frame's
|
|
1527
1882
|
// richer diagnostic fields only; the aggregate handler consumes them.
|
|
1883
|
+
//
|
|
1884
|
+
// `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
|
|
1885
|
+
// at 0.3.280, so read through the JSON boundary, never cast): "A
|
|
1886
|
+
// closed-set code for a reason a host can act on, beside
|
|
1887
|
+
// decision_reason_type (whose values are unchanged)":
|
|
1888
|
+
// 'outside_reads_blocked' (permissions.blockReadsOutsideWorkingDirectories
|
|
1889
|
+
// refused the path), 'memory_paused' (/pause-memory has memory paused),
|
|
1890
|
+
// 'classifier_transcript_too_long' (the auto-mode classifier's transcript
|
|
1891
|
+
// exceeded its context window). "Absent for every other reason; new values
|
|
1892
|
+
// are additive" — carried as a string, not enum-gated, camelCased beside
|
|
1893
|
+
// its `decisionReasonType` sibling. Fixture-only: the capture harness
|
|
1894
|
+
// produces no denials.
|
|
1895
|
+
const rawDenied = msg;
|
|
1896
|
+
const decisionReasonCode = isJsonObject(rawDenied) && typeof rawDenied["decision_reason_code"] === "string"
|
|
1897
|
+
? rawDenied["decision_reason_code"]
|
|
1898
|
+
: undefined;
|
|
1528
1899
|
deniedLiveByToolUseId.set(msg.tool_use_id, {
|
|
1529
1900
|
message: msg.message,
|
|
1530
1901
|
...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
|
|
1902
|
+
...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
|
|
1531
1903
|
...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
|
|
1532
1904
|
...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
|
|
1533
1905
|
});
|
|
@@ -1571,6 +1943,14 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1571
1943
|
// its real usage (and its subagent bracket) rather than leaving INV-FLUSH
|
|
1572
1944
|
// to synthesize a bare `message.end`.
|
|
1573
1945
|
closePendingMessage();
|
|
1946
|
+
// CL-09: a turn whose assistant error frame stashed its close but whose
|
|
1947
|
+
// result frame never arrived still closes as that turn.error (no usage:
|
|
1948
|
+
// only a result carries the turn's), never as INV-FLUSH's synthesized
|
|
1949
|
+
// turn.abort — the outcome the frame's own close used to produce.
|
|
1950
|
+
for (const [turnId, stashed] of stashedTurnErrors) {
|
|
1951
|
+
a.closeTurnError(turnId, { ...stashed });
|
|
1952
|
+
}
|
|
1953
|
+
stashedTurnErrors.clear();
|
|
1574
1954
|
return a.flush();
|
|
1575
1955
|
},
|
|
1576
1956
|
};
|