@silverprotocol/claude-agent-sdk 0.6.2 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +311 -47
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +353 -43
package/README.md
CHANGED
|
@@ -32,6 +32,7 @@ facet's per-field dispositions, including its disclosed `silently-dropped` gaps)
|
|
|
32
32
|
|
|
33
33
|
| `@anthropic-ai/claude-agent-sdk` | verified | with | evidence |
|
|
34
34
|
| --- | --- | --- | --- |
|
|
35
|
+
| `0.3.280` | 2026-09-23 | 0.6.3 | peer sweep 0.3.272 -> 0.3.280 (SEVEN published versions 0.3.273-0.3.278 and 0.3.280; 0.3.279 has an upstream CHANGELOG entry but was never published to npm; bundled CLI 2.1.272 -> 2.1.280). SDKMessage union UNCHANGED at 39 members and SDKAssistantMessageError unchanged at 13; sdk.d.ts diff 900 lines; agentSdkTypes.d.ts and extractFromBunfs.d.ts byte-identical. claude-opus-5-5 REQUIRES this version: older CLIs still send the id to the API but canonicalise it to claude-opus-5, so they price it at Opus 5 rates, default its effort to high instead of medium and report canonicalModel claude-opus-5. HEADLINE - CL-09, a wrong mapping that predates the cohort, LIVE-CONFIRMED with a deliberately invalid key: query() yielded an assistant frame with error authentication_failed and then a success result with is_error:true and api_error_status 401. Through 0.6.2 that pair produced turn.error AND THEN turn.done{success} on the same turnId, violating the one-close invariant, and reduce() folded the turn as a SUCCESS whose result was 'Failed to authenticate. API Error: 401 API key is invalid.' From 0.6.3 the assistant error frame stashes its close and the result frame emits exactly one turn.error, now carrying the result's usage (so a long agentic turn that fails on round N keeps the cost of its earlier rounds), on either result arm - which also removes a second double close, assistant error followed by an error-subtype result. A success result with is_error:true and NO preceding assistant error frame, which 0.6.2 closed as turn.done{success}, now closes as turn.error {code: api_error_code ?? 'api_error', retriable only for status 429 or >= 500, usage}; a stored 0.6.2 turn of that shape cannot be recovered from the AgJSON alone (its result is the error text). Flush emits a stashed close with no usage if no result arrives; the first error frame wins. Folding the same live frames: 0.6.2 -> [turn.error, turn.done{success}], folded success; 0.6.3 -> [turn.error authentication_failed, retriable false], folded error. CARRIES: usage_report (fixture-only), the undeclared api_error / api_error_params / api_error_code triad, result-meta apiErrorCode and startupFailureReason (retriable false except worktree_unverified), and the undeclared decision_reason_code on permission denials. 0.3.277 changed a carried value without a marker: total_cost_usd and modelUsage now continue across resume and fork (see the SDKResultMessage note). THINKING: with thinking.display unset, CLI 2.1.280 runs its connector_text selector, in which the API returns only between-tool narration and never a thinking summary; at most an empty thinking block carrying only its signature reaches the stream (the same selector exists in CLI 2.1.272, first-party path only). The 0.6.2 refresh of partials-fable51 therefore lost the corpus's only live thinking_delta frames - two EMPTY ones: no capture had ever carried summary text - and three 0.6.3 re-captures confirmed it is systematic, not chance. A new scenario knob (thinkingDisplay) sets thinking {type: adaptive, display: summarized}, and the new thinking-fable51 seed provides streamed summary text for the first time, deterministically: 13 thinking_delta frames, all with summary text, plus a signature_delta. The SDK typed a third display value, 'highlights', but only on setMaxThinkingTokens and its control request, where the API accepts it for Anthropic-hosted sessions only. LIVE at 0.3.280: echo-, partials- and app-update-sonnet5 and echo- and partials-fable51 refreshed; app-update-fable51 DELIBERATELY HELD at its 0.3.272 capture, as the corpus's only live narration_block_indexes evidence (three 0.3.280 re-captures produced no narration); NEW thinking-fable51, echo-, partials- and app-update-opus55, and echo-opus5 (Opus 5 is also a Claude Code 2.1.280 refusal-fallback target: bio and frontier_llm refusals fall back to it, cyber refusals to claude-opus-4-8). Census, after registering init mcp_servers[].source and plugins[], the stream-event cache_creation twins and the claude-opus-5-5 modelUsage family: ZERO drops / ZERO new fields on every claude seed. A replay surface guard now fails a refresh of any of the six single-surface seeds it names (thinking-fable51, app-update-fable51, thinking-gemini38, tool-error-gemini38, echo-gpt6sol/openai, app-spec-structured-result/openai) that drops the surface the seed exists for. Facet tests 168 -> 204. |
|
|
35
36
|
| `0.3.272` | 2026-09-15 | 0.6.2 | peer sweep 0.3.261->0.3.272 (NINE published versions: 0.3.263/265/266/267/268/269/270/271/272; 0.3.262 and 0.3.264 were never published to npm; bundled CLI 2.1.261->2.1.272). 0.3.271->0.3.272 is .d.ts-byte-identical across all four declaration files, so the type audit was derived against 0.3.271 and carries forward unchanged. SDKMessage union UNCHANGED at 39 members (drift-gate-verified); sdk.d.ts diff 610 lines, independently re-derived from both tarballs; agentSdkTypes.d.ts and bridge.d.ts byte-identical. DECLARED stream-scope additions, all three now CARRIED: resume_reason (0.3.268) on SDKAssistantMessage, SDKPartialAssistantMessage and BOTH result arms -> the THIRD leg of the user_message_uuid turn-binding family, which 0.3.269 stamps under ONE rule ('first complete assistant message as well as first stream event when partial messages are on'), so it rides the SAME bag under the SAME once-per-message flag (renamed userMessageUuidCarried -> turnBindingCarried); written outside that guard it would double-emit message.metadata on every streamed lifecycle, and a regression test pins the single emission. result_index (0.3.268, both result arms) -> ext.anthropic.result-meta.resultIndex, guarded typeof==='number' because 0 is the first result of every run; a gap in the sequence is how a consumer detects a LOST result, which is why it is carried rather than allowlisted. local_command (0.3.268, SUCCESS arm only, undocumented upstream) -> result-meta.localCommand, read through the JSON boundary because the union declares no such property; its PRESENCE is the signal (it is the only thing separating a zero-round-trip slash-command success from an empty turn) while its value is deliberately coarse upstream (any user/project/third-party command slugs to 'custom', any MCP command to 'mcp'). SDKAssistantMessageError widened 11 -> 13 members (verification_required, cloud_credential_error): both are correctly NON-retriable (one needs an out-of-band human step, the other is a credential/billing-class failure re-sending cannot clear), so the expression is unchanged, but the decision is now recorded explicitly in the same false-by-omission voice as model_not_found / account_on_hold and pinned by an exhaustive 13-member set-invariance test. UNDECLARED runtime additions, found ONLY by live capture (absent from sdk.d.ts, so no type diff could have seen them): narration_block_indexes on the assistant wrapper -> CARRIED verbatim (it names which of this frame's content blocks are user-facing narration rather than private reasoning, i.e. Anthropic's thinking.display:'updates' progress updates; a rendering decision, so lossless carry over allowlist; a per-frame content fact like `aborted`, so deliberately NOT under the turn-binding flag, and it has no stream-event twin so it cannot double-carry); wire_tool_inputs, the verbatim wire copy of each tool call's input keyed by tool_use_id; and five null-only leaves (event.message.container, event.message.context_management, event.delta.container, usage.iterations[*].model, event.usage.iterations[*].model) allowlisted null-only as stream-event twins of already-allowlisted complete-frame siblings. CENSUS MACHINERY: wire_tool_inputs' keys are per-capture tool ids, so every capture minted a brand-new norm-path and the newFields gate could never be satisfied; normalizePath now collapses the key directly under an explicit ID_KEYED_CONTAINERS list to {id}, the same way it collapses [n] to [*]. The list is explicit, not a key-shape heuristic, precisely so meaningful map keys such as modelUsage.claude-sonnet-5 keep their own registry entries. LIVE at 0.3.272: all six claude seeds refreshed (echo-sonnet5, partials-sonnet5, app-update-sonnet5, echo-fable51, partials-fable51, app-update-fable51) - census ZERO drops / ZERO new fields on all six after triage. Facet tests 147 -> 168. WATCH ITEM CLOSED in part: narration_block_indexes is the first live evidence of the thinking-display 'updates' mode reaching this SDK's wire; the Agent SDK still types display as 'summarized'\|'omitted'. |
|
|
36
37
|
| `0.3.261` | 2026-09-05 | 0.6.1 | peer sweep 0.3.258->0.3.261 (three patches; bundled CLI 2.1.258->2.1.261) - SDKMessage union unchanged (39 members, drift-gate-verified); sdk.d.ts diff 358 lines / 30 hunks, independently re-derived. Stream-scope field additions: user_message_uuids?: string[] on SDKAssistantMessage (first reply frame), SDKPartialAssistantMessage (first non-ping event) and both result arms (0.3.259) -> carried on the SAME three channels as the singular (wrapperMetaRaw first-block providerMetadata / block-less message.metadata; the stream arm's single message.metadata emit; result-meta.userMessageUuids camelCase) under the shared once-per-message flag - a CONSISTENCY carry: the string-prompt capture path supplies no client uuid, so no cassette has ever exercised the singular or the plural; SDKThinkingTokensMessage.user_message_uuid (0.3.260) rides the existing whole-frame carry; SDKResultSuccess first_content_frame_ms / first_stream_post_ms / first_stream_post_ack_ms / first_stream_post_wall_ms (0.3.260, remote-session latency) and SDKAPIRetryMessage.no_response {waited_ms, retry_wait_ms} (0.3.261) are router-plane (allowlisted + registered); the stale ttft_ms allowlist reason corrected (the facet DOES read it off the partial envelope). Control-plane only: permissionPrompts 'none', pluginDelivery 'initialize', reload_output_styles control subtype, initialize plugins/plugins_applied, get_usage skip_behaviors, settings shapes, Artifact tool schema. @anthropic-ai/sdk 0.124.0 is Admin-API/compliance only; the facet devDep ^0.93.0 provably cannot float (only 0.93.0 exists in >=0.93.0 <0.94.0). LIVE at 0.3.261 (CC 2.1.261): echo-sonnet5, partials-sonnet5, echo-fable51, partials-fable51, app-update-fable51 refreshed and the lagging app-update-sonnet5 (0.3.217) refreshed - census ZERO drops / ZERO new fields on all six; agjson byte-identical after regen except capture-time value drift. 8 unit tests added. Watch item: the Agent SDK still types thinking display 'summarized'\|'omitted' while @anthropic-ai/sdk 0.121.0+ types a third 'updates' mode - adoption would change thinking_delta text semantics under Fable's omitted display. |
|
|
37
38
|
| `0.3.258` | 2026-09-02 | 0.5.4 | peer sweep 0.3.233->0.3.258 (20 npm versions; 17 GitHub releases) - SDKMessage union unchanged (39 members, drift-gate-verified) but SIX field-level stream additions the name-only gate cannot see (full d.ts diff, independently re-derived): ModelUsage.costBasis (0.3.246) + ModelUsage.thinkingTokens (0.3.257, subset of outputTokens) -> costBasis joins the per-model identity in ext.anthropic.result-meta, thinkingTokens -> usage.byModel[m].reasoningTokens; usage.output_tokens_details.thinking_tokens (real since the 0.3.257 fix; the old reviewed-any allowlist entry that would have masked it is DELETED) -> usage.reasoningTokens on message.end/turn.done (runtime-guarded; undeclared on the resolved @anthropic-ai/sdk 0.93.0 BetaUsage); user_message_uuid on assistant (first frame), stream_event (first non-ping) and both result arms -> wrapperMetaRaw / message.metadata / result-meta.userMessageUuid; queued_turn_count (both result arms, 0 real) -> result-meta.queuedTurnCount; tool_use_result.resourceLinks (0.3.257, runtime-only) -> tool.done providerMetadata.resourceLinks; SDKAssistantMessageError += account_on_hold (non-retriable, test); system/init effort (router-plane, allowlisted); Task* ambient/is_backgrounded/spawn_depth/resource_links ride the existing whole-frame carry. LIVE CAPTURES at 0.3.258 (Claude Code 2.1.258): echo-sonnet5 + partials-sonnet5 REFRESHED, and the FIRST claude-fable-5-1 seed trio echo-fable51 / partials-fable51 / app-update-fable51 (model GA 2026-09-01; Fable 5.1 requires CC >=2.1.257) - census caught FOUR runtime-only surfaces undeclared in the d.ts: result.subagent_stats (carried whole as result-meta.subagentStats), init.messaging_socket_path (allowlisted), thinking_delta.estimated_tokens (carried on reasoning.delta providerMetadata; core assembler gained the slot), and the first live system/thinking_tokens frames (SDKThinkingTokensMessage promoted router-plane -> carried whole-frame: the only thinking-progress signal under Fable's display:omitted), plus first observation of the typed init.terminal_slash_commands[] (allowlisted). partials-fable51 is the corpus's first live thinking_delta/signature_delta coverage (66 thinking tokens on the result frame, real non-zero reasoningTokens). Out of stream scope: PreModelSwitch/PostModelSwitch hooks, systemPrompt custom/snapshot, perTaskStopAffordance, SDK MCP server timeout, update_settings control, settings shapes, sdk-tools schemas, origin.fromMode/'projects-relay' growth inside the disclosed unread origin. Peer @anthropic-ai/sdk stays >=0.93.0 (facet devDep ^0.93.0 resolves 0.93.0; 0.123.0's BetaFallbackBlock/fallback_credit/output_tokens_details are typed-only additions - a runtime fallback block already lands as provider-raw). Pin + 9 platform-binary exclusions bumped; facet devDep ^0.3.258; 8 unit tests + 3 seeds added; full gate suite green. |
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAGL,KAAK,cAAc,EAQnB,KAAK,UAAU,EAGhB,MAAM,sBAAsB,CAAC;AAO9B,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC;AAE/D,KAAK,YAAY,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAE5C,KAAK,cAAc,GAAG,WAAW,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,CAAC;AAiC/D,iBAAS,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,GAAG,cAAc,CAwB3E;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAGL,KAAK,cAAc,EAQnB,KAAK,UAAU,EAGhB,MAAM,sBAAsB,CAAC;AAO9B,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC;AAE/D,KAAK,YAAY,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAE5C,KAAK,cAAc,GAAG,WAAW,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,CAAC;AAiC/D,iBAAS,aAAa,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,GAAG,cAAc,CAwB3E;AAivBD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CA40CxF;AAED,eAAe,sBAAsB,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -536,6 +536,65 @@ function readNarrationBlockIndexes(v) {
|
|
|
536
536
|
? v
|
|
537
537
|
: undefined;
|
|
538
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
|
+
}
|
|
539
598
|
// ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
|
|
540
599
|
// `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
|
|
541
600
|
// and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
|
|
@@ -629,6 +688,25 @@ function readNarrationBlockIndexes(v) {
|
|
|
629
688
|
// was not given — under the normalized name `localCommand`. Read through the
|
|
630
689
|
// `unknown` boundary because it is declared on the SUCCESS arm ONLY, so the
|
|
631
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.
|
|
632
710
|
function resultMetaPayload(msg) {
|
|
633
711
|
const byModel = {};
|
|
634
712
|
const modelUsage = isJsonObject(msg.modelUsage) ? msg.modelUsage : {};
|
|
@@ -651,6 +729,10 @@ function resultMetaPayload(msg) {
|
|
|
651
729
|
// SUCCESS-arm-only field (0.3.268) — the union carries no such property, so
|
|
652
730
|
// it is read through the same JSON boundary as `subagent_stats`, never cast.
|
|
653
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);
|
|
654
736
|
const payload = {
|
|
655
737
|
...(typeof msg.fast_mode_disabled_reason === "string"
|
|
656
738
|
? { fastModeDisabledReason: msg.fast_mode_disabled_reason }
|
|
@@ -662,6 +744,8 @@ function resultMetaPayload(msg) {
|
|
|
662
744
|
// 0 is the first result of EVERY run — `typeof === "number"`, not truthiness.
|
|
663
745
|
...(typeof msg.result_index === "number" ? { resultIndex: msg.result_index } : {}),
|
|
664
746
|
...(localCommand !== undefined ? { localCommand } : {}),
|
|
747
|
+
...(apiErrorCode !== undefined ? { apiErrorCode } : {}),
|
|
748
|
+
...(startupFailureReason !== undefined ? { startupFailureReason } : {}),
|
|
665
749
|
...(subagentStats !== undefined ? { subagentStats } : {}),
|
|
666
750
|
...(Object.keys(byModel).length > 0 ? { modelUsage: byModel } : {}),
|
|
667
751
|
};
|
|
@@ -694,15 +778,32 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
694
778
|
// `message.remove` — "translated through the facet's uuid→messageId
|
|
695
779
|
// convention" per the adaptation brief.
|
|
696
780
|
const messageIdsByUuid = new Map();
|
|
697
|
-
// Fixture-drift ratchet (SDKPermissionDeniedMessage, "handled" via existing-
|
|
698
|
-
// home mapping): live per-denial diagnostic recorded by the standalone
|
|
699
|
-
// `permission_denied` frame (fires DURING the turn, before the terminal
|
|
700
|
-
// result) — keyed by tool_use_id so the terminal `permission_denials[]`
|
|
701
|
-
// aggregate (the ALREADY-handled W1 `<turnId>:denials` carrier, audit M19)
|
|
702
|
-
// can enrich its tool.done with the actual rejection text + decision-reason
|
|
703
|
-
// context, instead of emitting a SECOND tool.start/tool.done pair for the
|
|
704
|
-
// same denial (the M22 double-fold hazard).
|
|
705
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
|
+
}
|
|
706
807
|
let pending;
|
|
707
808
|
// How many lifecycles each SDK message id has already opened. A same-id frame
|
|
708
809
|
// arriving after its lifecycle closed (a fold-binding frame landed between two
|
|
@@ -1203,6 +1304,20 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1203
1304
|
// wrapper-meta channel's type without an unchecked cast.
|
|
1204
1305
|
wrapperMetaRaw["context_usage"] = JsonValue.parse(msg.context_usage);
|
|
1205
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
|
+
}
|
|
1206
1321
|
// `narration_block_indexes` (0.3.272, first seen live on app-update-fable51):
|
|
1207
1322
|
// the indexes of THIS frame's content blocks that are user-facing narration
|
|
1208
1323
|
// — Anthropic's `thinking.display: "updates"` mode returns progress updates
|
|
@@ -1219,6 +1334,38 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1219
1334
|
if (narrationBlockIndexes !== undefined) {
|
|
1220
1335
|
wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
|
|
1221
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
|
+
}
|
|
1222
1369
|
// `user_message_uuid` (0.3.258) and `user_message_uuids` (0.3.259) join
|
|
1223
1370
|
// the bag below, once `open` is known — their once-per-message flag is
|
|
1224
1371
|
// shared with the stream arm's carry.
|
|
@@ -1353,38 +1500,46 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1353
1500
|
// not — without this merge the join would erase the streamed count.
|
|
1354
1501
|
open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
|
|
1355
1502
|
// If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
|
|
1356
|
-
//
|
|
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`).
|
|
1357
1507
|
if (msg.error !== undefined) {
|
|
1358
|
-
// The
|
|
1359
|
-
// 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.
|
|
1360
1511
|
closePendingMessage();
|
|
1361
1512
|
const errCode = msg.error;
|
|
1362
|
-
a
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
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
|
+
}
|
|
1388
1543
|
}
|
|
1389
1544
|
// `subagent.done` is NOT emitted here: it brackets the MESSAGE, and the
|
|
1390
1545
|
// message's seal is deferred (guuey#26) — `closePendingMessage` emits both,
|
|
@@ -1517,6 +1672,26 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1517
1672
|
// (message.end has always preceded the turn close).
|
|
1518
1673
|
closePendingMessage();
|
|
1519
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;
|
|
1520
1695
|
const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
|
|
1521
1696
|
// structured_output (when a response schema is in effect) overrides the plain
|
|
1522
1697
|
// string result — it is the authoritative typed outcome payload (spec §4).
|
|
@@ -1524,6 +1699,9 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1524
1699
|
// Emit permission_denials as tool.start + tool.done denied pairs, inside a
|
|
1525
1700
|
// dedicated carrier message: the assistant message is already sealed, and
|
|
1526
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.
|
|
1527
1705
|
if (msg.permission_denials.length > 0) {
|
|
1528
1706
|
const denialMsgId = `${turnId}:denials`;
|
|
1529
1707
|
a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: options.threadId ?? msg.session_id });
|
|
@@ -1537,14 +1715,8 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1537
1715
|
// tool.start/tool.done pair is ever emitted for the live frame
|
|
1538
1716
|
// itself (see the dedicated `permission_denied` branch below).
|
|
1539
1717
|
const live = deniedLiveByToolUseId.get(denial.tool_use_id);
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
? AgProviderMeta.parse({
|
|
1543
|
-
...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
|
|
1544
|
-
...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
|
|
1545
|
-
...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
|
|
1546
|
-
})
|
|
1547
|
-
: undefined;
|
|
1718
|
+
const liveFields = liveDenialMeta(live);
|
|
1719
|
+
const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
|
|
1548
1720
|
a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
|
|
1549
1721
|
a.toolDone({
|
|
1550
1722
|
toolCallId: denial.tool_use_id,
|
|
@@ -1557,11 +1729,41 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1557
1729
|
}
|
|
1558
1730
|
// 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
|
|
1559
1731
|
// ride `ext.anthropic.result-meta` before the close (no core home on
|
|
1560
|
-
// 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.
|
|
1561
1734
|
const resultMeta = resultMetaPayload(msg);
|
|
1562
1735
|
if (resultMeta !== undefined) {
|
|
1563
1736
|
a.emitExt("anthropic", "result-meta", resultMeta);
|
|
1564
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
|
+
}
|
|
1565
1767
|
a.closeTurnDone(turnId, {
|
|
1566
1768
|
outcome: { type: "success", result: structuredOutput ?? msg.result },
|
|
1567
1769
|
finishReason: mapStopReason(msg.stop_reason),
|
|
@@ -1575,13 +1777,25 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1575
1777
|
// guuey#26: seal the open assistant message before the turn close.
|
|
1576
1778
|
closePendingMessage();
|
|
1577
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);
|
|
1578
1784
|
// Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
|
|
1579
1785
|
// `typeof v.subtype === "string"` for the result arm — it does NOT validate
|
|
1580
1786
|
// the `errors` array. A malformed message (missing errors, wrong subtype) must
|
|
1581
1787
|
// not throw (Tenet 6: graceful, never throws).
|
|
1582
1788
|
const errors = Array.isArray(msg.errors) ? msg.errors : [];
|
|
1583
1789
|
const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
|
|
1584
|
-
|
|
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";
|
|
1585
1799
|
// 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
|
|
1586
1800
|
// error variant gets the SAME `ext.anthropic.result-meta` carry as the
|
|
1587
1801
|
// success arm above (turn.error carries no metadata slot at all).
|
|
@@ -1589,6 +1803,31 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1589
1803
|
if (resultMeta !== undefined) {
|
|
1590
1804
|
a.emitExt("anthropic", "result-meta", resultMeta);
|
|
1591
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
|
+
}
|
|
1592
1831
|
a.closeTurnError(turnId, {
|
|
1593
1832
|
message: errors.length > 0 ? errors.join("; ") : subtype,
|
|
1594
1833
|
code: subtype,
|
|
@@ -1641,9 +1880,26 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1641
1880
|
// W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
|
|
1642
1881
|
// second pair here (the M22 double-fold hazard). Record this frame's
|
|
1643
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;
|
|
1644
1899
|
deniedLiveByToolUseId.set(msg.tool_use_id, {
|
|
1645
1900
|
message: msg.message,
|
|
1646
1901
|
...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
|
|
1902
|
+
...(decisionReasonCode !== undefined ? { decisionReasonCode } : {}),
|
|
1647
1903
|
...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
|
|
1648
1904
|
...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
|
|
1649
1905
|
});
|
|
@@ -1687,6 +1943,14 @@ export function createClaudeNormalizer(options = {}) {
|
|
|
1687
1943
|
// its real usage (and its subagent bracket) rather than leaving INV-FLUSH
|
|
1688
1944
|
// to synthesize a bare `message.end`.
|
|
1689
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();
|
|
1690
1954
|
return a.flush();
|
|
1691
1955
|
},
|
|
1692
1956
|
};
|