@silverprotocol/claude-agent-sdk 1.0.0-rc.6 → 1.0.0-rc.8

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 CHANGED
@@ -32,6 +32,8 @@ 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.319` | 2026-11-09 | 1.0.0-rc.6 | @anthropic-ai/claude-agent-sdk 0.3.314 -> 0.3.319. SDKMessage grows from 39 to 40 arms with SDKSessionWritesLostMessage (0.3.317), system/session_writes_lost {error_code ENOSPC or EDQUOT, lost[], transcript_session_ids?}, sent once as the CLI exits with status 0 after the last result; the facet carries it as ext.anthropic.frame (fixture only: no capture fills a disk). SDKStartupFailureReason adds initialize_not_first (0.3.317) and config_file_invalid (0.3.318); both close turn.error as non-retriable. From 0.3.318 the config_file_invalid, org_config_required_unavailable and org_config_refused results are written on every stream-json run, without CLAUDE_CODE_STARTUP_FAILURE_RESULTS. Both result arms add credential_expires_at (0.3.318), present only for a claude.ai login, and the CLI's result schema adds the runtime-only stopped_by_permission_check, set only when an auto-mode permission check aborts the turn; the facet reads neither, and neither appears in the API-key captures. system/init gains two runtime-only composer hints, ultrathink_available and ultrathink_typed_raises (false in both captures), registered as drops. The four @anthropic-ai/sdk type imports are unchanged; the rest is initialize-response, hook, control-request, settings, bridge and tool-text surface the facet does not read. Live: echo-haiku55 and multi-result-haiku55 (claude-haiku-5-5) captured green at 0.3.319 with the event-type sequences of their 0.3.314 cassettes; on multi-result-haiku55, result 2's model_usage_since_last_result still equals modelUsage2 - modelUsage1 on every token counter. Census: no drops and no new fields after those two entries. |
36
+ | `0.3.314` | 2026-11-03 | 1.0.0-rc.6 | @anthropic-ai/claude-agent-sdk 0.3.310 -> 0.3.314. SDKMessage keeps its 39 arms and the four @anthropic-ai/sdk type imports are unchanged. 0.3.311 adds ModelUsage.cacheCreationEphemeral5mInputTokens and cacheCreationEphemeral1hInputTokens, the per-TTL split of the cache writes already counted inside cacheCreationInputTokens, on every result's modelUsage and model_usage_since_last_result entries; the facet reads named counters only, so usage.byModel and modelUsageSinceLastResult are unchanged, and the four leaves are registered as drops with no AgUsage home. 0.3.314 adds the startup-failure reason sandbox_required_unavailable, which closes as non-retriable. The rest is settings and capability text the facet does not read. The CLI's result schema gains eleven runtime-only keys (shell and process timing and stream counts, three of them only on remote hosts) and two system subtypes (inherited_asks_settled, ui_placed); none appears in the live captures. Live: echo-haiku55 and multi-result-haiku55 (claude-haiku-5-5) captured green at 0.3.314; on multi-result-haiku55, result 2's model_usage_since_last_result still equals modelUsage2 - modelUsage1 on every counter, the per-TTL split included. Census: no drops and no new fields after those four entries; both fresh cassettes are committed. |
35
37
  | `0.3.310` | 2026-10-25 | 1.0.0-rc.3 | @anthropic-ai/claude-agent-sdk 0.3.304 -> 0.3.310. The d.ts adds no message type and no init key; 0.3.307's runtime-only wakeup_source and scheduled_for on command_lifecycle ride the whole-frame carry. A key diff per event type of a live echo-haiku55 against the 0.3.304 capture: system/init 27 -> 27, assistant 9 -> 9, user 8 -> 8, result/success 26 -> 27. The new runtime-only result key model_usage_since_last_result is the per-result delta of modelUsage (the running total the facet carries as usage.byModel with cumulative:true): on a new two-result seed, multi-result-haiku55, result 1's map equals its modelUsage and result 2's equals modelUsage2 - modelUsage1 for every counter; its leaves are registered as derivable drops until a carry lands. first_request_input_tokens (multi-result runs only) is the cache-inclusive input of the result's first API request, which the facet already emits as that message's usage.inputTokens. Live: echo-haiku55 and multi-result-haiku55 (claude-haiku-5-5) captured green at 0.3.310, with replay and census green after those entries; both fresh cassettes are committed. |
36
38
  | `0.3.304` | 2026-10-20 | 1.0.0-rc.3 | @anthropic-ai/claude-agent-sdk 0.3.296 -> 0.3.304, with @anthropic-ai/sdk ^0.133.0 -> ^0.135.0. The d.ts changes no message type: the SDKMessage union and SDKStartupFailureReason are unchanged. Runtime changes the facet folds unchanged: 0.3.301 sends api_error_status null (was 401) on a full-disk login failure, which folds retriable:false as before; 0.3.302 closes a refused structured output as an error result with no payload, down the existing is_error + refusal close; 0.3.302 turns fork subagents on by default (the subagent seeds were not re-captured). Two runtime-only fields the facet never reads, registered with the census: system/init `original_cwd`, a local path that captures now redact at source beside `cwd`, and `tool_use_meta[*].tool_name`, the tool's unprefixed name beside display_name and server_display_name. Live: echo-haiku55 (claude-haiku-5-5) captured green at 0.3.304 with the same event-type sequence as the 0.3.296 golden; the fresh cassette is committed and, regenerated against the real guards, has no drops and no new leaves after those two entries. A third new init key, additional_directories, was empty in this capture; it is now redacted at source and registered too. |
37
39
  | `0.3.296` | 2026-10-13 | 1.0.0-rc.1 | @anthropic-ai/claude-agent-sdk 0.3.292 -> 0.3.296 (CLI 2.1.296). 0.3.296 adds two SDKStartupFailureReason values: org_config_required_unavailable, which upstream documents as possibly succeeding on retry, joins the facet's retriable set, and org_config_refused stays non-retriable (the facet change landed before this pin). 0.3.293's subagent_type rides the existing whole-frame carry unchanged; 0.3.295's overageEnabled sits on the router-plane rate_limit_event the facet does not emit. A runtime-only field the d.ts does not declare: a tool_result's tool_result_meta entries now carry permission_decision {decision, source, reason_type}, which the facet already carries verbatim on tool.done _meta["anthropic/toolResultMeta"]; the three paths are registered with the census. modelUsage per-model inputTokens is carried derived, folded into the cache-inclusive usage.byModel inputTokens, so the value-matching census now allowlists it. Live: echo-haiku55 (claude-haiku-5-5) captured green at 0.3.296 with replay and census green after those two entries; the committed cassette was kept. modelUsage costBasis for claude-haiku-5-5 now reads "list" ("unknown" at 0.3.292). |
@@ -194,6 +196,46 @@ do not set it, so a refusal there still closes as `turn.error`.
194
196
  - A stream that ends before the result closes the turn as `turn.error`, and so
195
197
  does a subagent's refusal whose run is still open at the end of the stream.
196
198
 
199
+ ### Interrupted turns
200
+
201
+ A result that reports an interruption closes the turn with one
202
+ `turn.abort { reason: "cancelled" }`, never with `turn.error` or `turn.done`
203
+ (SPEC §8.0 item 17). An interruption is any of: `terminal_reason`
204
+ `"aborted_streaming"` or `"aborted_tools"`, `stopped_by_permission_check: true`,
205
+ or `interrupted_by_shutdown: true`. Either result arm counts, and the check
206
+ comes before every other close the result would make. A client Stop
207
+ (`Query.interrupt()`) ends the turn this way: the CLI sends an
208
+ `error_during_execution` result with one of those two `terminal_reason`
209
+ values. `turn.abort` carries no usage: each round's usage stays on its
210
+ `message.end`, and the result's turn total is not carried. The result's
211
+ `stop_reason` rides `ext.anthropic.result-meta`, as on an error close. On
212
+ this close only, result-meta also carries the cause: `terminalReason` (the
213
+ result's `terminal_reason`) and, when the result carries them,
214
+ `stoppedByPermissionCheck` and `interruptedByShutdown`. The result's
215
+ `errors` text is not carried. A subagent run the CLI stops closes its
216
+ nested turn with `turn.abort { reason: "stopped" }`.
217
+
218
+ A tool call the Stop cut off while it ran records `tool.done` with
219
+ `outcome: "error"`, `isError: true` and `errorText` set to the CLI's
220
+ interrupt marker, `"[Request interrupted by user for tool use]"`; its content
221
+ and its `non_execution_kind: "user-rejected"` stamp (in `_meta`) stay
222
+ verbatim. The CLI stamps such a call the way it stamps a refusal, so the
223
+ facet holds that `tool.done` until a frame that continues the turn arrives:
224
+ a top-level assistant frame, a top-level `message_start` stream event, or a
225
+ top-level user frame other than the interrupt marker. The turn's result
226
+ decides it too. System frames, a subagent's frames, replay acks and the rest
227
+ of a stream already open leave it held: the CLI writes background-task
228
+ notices as they happen, so they can land on either side of the marker. A
229
+ top-level frame whose every `tool_result` is an `is_error` result stamped the
230
+ same way joins the hold: a Stop that cuts off parallel calls stamps each
231
+ call's result in its own frame. When the interrupt marker arrives first and
232
+ the turn's result reports an interruption without listing the call in
233
+ `permission_denials`, the call ran and was stopped. Otherwise it
234
+ was refused, and stays `outcome: "denied"`. A stream that ends while the
235
+ `tool.done` is held emits no `tool.done`, because a flush emits none; the
236
+ held tool_result frame rides `ext.anthropic.frame` (`kind: "user"`)
237
+ verbatim instead, before the turn closes.
238
+
197
239
  ### Turn trigger
198
240
 
199
241
  When the frame that opens a top-level turn is an assistant message, a streamed
package/dist/index.d.ts CHANGED
@@ -30,7 +30,7 @@
30
30
  *
31
31
  * `push(native)` structurally guards `native` → `SDKMessage`; on a guard failure it
32
32
  * routes the raw payload through the lossless `ext.anthropic.unparsed` channel and
33
- * returns — graceful, never throws (Tenet 6). Stable ids derive from the SDK ids
33
+ * returns — graceful, never throws (SPEC §8.0). Stable ids derive from the SDK ids
34
34
  * (`message.id`, block `id`, `tool_use_id`).
35
35
  */
36
36
  import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
@@ -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,EASnB,KAAK,UAAU,EAKhB,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;AA6xCD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAguED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAIxF;eAEc,sBAAsB;AACrC,OAAO,EAAE,aAAa,EAAE,CAAC"}
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,EASnB,KAAK,UAAU,EAKhB,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;AA00CD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AA67ED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAIxF;eAEc,sBAAsB;AACrC,OAAO,EAAE,aAAa,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -150,7 +150,7 @@ function mapModelUsage(mu) {
150
150
  // but a result frame is discriminant-validated only, so a leaner producer (a
151
151
  // proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
152
152
  // member passed the `!== null` check and threw a TypeError out of push()
153
- // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found while writing §10.23),
153
+ // (SPEC §8.0 "MUST NOT throw"; found while writing §10.23),
154
154
  // and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
155
155
  // anything else ⇒ absent.
156
156
  function serverToolRequestCount(usage) {
@@ -561,7 +561,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
561
561
  // yields well-formed `SDKMessage`s, but this is the deserialization boundary so we
562
562
  // confirm the discriminant + the per-arm load-bearing nested shape before driving
563
563
  // the engine. A user-defined type guard (not a cast) narrows on success; a failure
564
- // routes the raw payload to `ext.anthropic.unparsed` and returns (graceful, Tenet 6).
564
+ // routes the raw payload to `ext.anthropic.unparsed` and returns (graceful, SPEC §8.0).
565
565
  function isJsonObject(v) {
566
566
  return typeof v === "object" && v !== null && !Array.isArray(v);
567
567
  }
@@ -668,6 +668,14 @@ const CARRIED_SYSTEM_SUBTYPES = new Set([
668
668
  "files_persisted",
669
669
  "memory_recall",
670
670
  "mirror_error",
671
+ // 0.3.317: system/session_writes_lost {error_code, lost[],
672
+ // transcript_session_ids?}, sent at most once, as the CLI exits with status
673
+ // 0 after the last result, when the disk was full or over quota and lines of a session
674
+ // transcript or changes to ~/.claude.json were not saved. Upstream calls it
675
+ // safe to ignore, but a host that resumes one of the listed sessions may
676
+ // find part of its conversation missing, and no AgJSON event says so. A
677
+ // persistence-failure diagnostic like mirror_error above: whole-frame carry.
678
+ "session_writes_lost",
671
679
  // workspace#7 census-caught (2026-08-07, corpus/partials-sonnet5): the
672
680
  // system/status ping — status:'compacting'|'requesting'|null (+ optional
673
681
  // compact_result/compact_error). GENUINE consumer-facing agent-state signal
@@ -699,7 +707,7 @@ const CARRIED_STANDALONE_TYPES = new Set([
699
707
  // thread-rotation mapping is a future spec decision, not a mechanical carry.
700
708
  "conversation_reset",
701
709
  ]);
702
- // The top-level `type` literals the SDKMessage union declares (0.3.280: 39
710
+ // The top-level `type` literals the SDKMessage union declares (0.3.319: 40
703
711
  // members over these 11 types). A frame whose `type` is NOT among them is
704
712
  // RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
705
713
  // frame type). The first one observed: `command_lifecycle`
@@ -736,7 +744,7 @@ function anthropicFrameKind(msg) {
736
744
  // arrived through `JsonValue.parse` and `isSDKMessage` validates only the
737
745
  // discriminants, so the typed `string[]` is nominal — guard the shape at
738
746
  // runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
739
- // carry it verbatim. A malformed list is ignored, never thrown on (Tenet 6);
747
+ // carry it verbatim. A malformed list is ignored, never thrown on (SPEC §8.0);
740
748
  // `string[]` is itself a JsonValue, so no cast is needed downstream.
741
749
  // A COPY, never the frame's own array: the value is emitted unparsed
742
750
  // (result-meta, message.metadata), core's StreamAssembler does not copy, and
@@ -931,6 +939,36 @@ function readDeferredCall(v) {
931
939
  function closeCauseTerminalReason(v) {
932
940
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
933
941
  }
942
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
943
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
944
+ // success turn.done, whichever result arm carries the signal. The signal is
945
+ // any one of:
946
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
947
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
948
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
949
+ // (error_during_execution, is_error true) with one of these two, then
950
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
951
+ // a subagent run.
952
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
953
+ // permission check after repeated refusals.
954
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
955
+ // worker shut down.
956
+ // No capture has shown either flag yet, so their arm is unknown: the check
957
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
958
+ // so the frame is read through the JSON boundary, and only a literal `true`
959
+ // counts. The key is never the result's `errors` text.
960
+ const INTERRUPTION_TERMINAL_REASONS = new Set(["aborted_streaming", "aborted_tools"]);
961
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
962
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
963
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
964
+ function resultSignalsInterruption(msg) {
965
+ if (!isJsonObject(msg))
966
+ return false;
967
+ const terminalReason = msg["terminal_reason"];
968
+ return ((typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
969
+ msg["stopped_by_permission_check"] === true ||
970
+ msg["interrupted_by_shutdown"] === true);
971
+ }
934
972
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
935
973
  // on both frames that carry it (the API-error assistant frame and the
936
974
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -951,7 +989,7 @@ function readStartupFailureReason(v) {
951
989
  // The type's own lead sentence frames the whole enum as a refusal to start:
952
990
  // "Why Claude Code refused to start, so a host can offer the fix instead of a
953
991
  // retry." So a PRESENT reason means NOT retriable, except for the values
954
- // upstream itself EXPLICITLY describes as retriable. Through 0.3.304 that set is
992
+ // upstream itself EXPLICITLY describes as retriable. Through 0.3.319 that set is
955
993
  // exactly two values:
956
994
  // - `worktree_unverified`: "the session's worktree could not be verified
957
995
  // right now; retrying may succeed."
@@ -975,7 +1013,11 @@ function readStartupFailureReason(v) {
975
1013
  // gateway_access_denied, proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
976
1014
  // worktree_resume_refused, cli_version_too_old, bypass_root, and 0.3.296's
977
1015
  // org_config_refused: "signing in again or an admin's change is the fix, not a
978
- // retry") names a configuration, policy or environment fix, and an unknown future value
1016
+ // retry", 0.3.314's sandbox_required_unavailable: "make the sandbox
1017
+ // available or have the requirement changed", 0.3.317's initialize_not_first:
1018
+ // "the fix is in the host or the wrapper script, not a retry", and 0.3.318's
1019
+ // config_file_invalid: "a retry alone does not help") names a configuration,
1020
+ // policy or environment fix, and an unknown future value
979
1021
  // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
980
1022
  // reason never reaches this function: the error arm keeps its old rule, so
981
1023
  // older producers are byte-identical.
@@ -1024,7 +1066,7 @@ function resultErrorFields(msg) {
1024
1066
  // Absent fields ⇒ undefined (never an empty bag; pre-0.3.220 wire is
1025
1067
  // byte-identical). Nested access is runtime-guarded like the error arm's
1026
1068
  // `errors` guard: `isSDKMessage` validates only `subtype` on a result frame,
1027
- // and a malformed frame must not throw (Tenet 6).
1069
+ // and a malformed frame must not throw (SPEC §8.0).
1028
1070
  //
1029
1071
  // 0.3.258 bump — three more result-frame siblings join the SAME carry (one
1030
1072
  // carrier per concept, §0.6; nothing new on the ext vocabulary):
@@ -1168,9 +1210,10 @@ function resultMetaPayload(msg, closesAsError) {
1168
1210
  // the census allowlist's "carry candidate the first time an error seed
1169
1211
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1170
1212
  const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1171
- // `stop_reason` on a result that closes as turn.error: turn.error has no
1172
- // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1173
- // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1213
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1214
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1215
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1216
+ // verbatim ONLY on such a close;
1174
1217
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1175
1218
  const stopReason = closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
1176
1219
  const modelUsageSinceLastResult = isJsonObject(raw)
@@ -1248,7 +1291,7 @@ function readModelUsageSinceLastResult(v) {
1248
1291
  }
1249
1292
  // A result frame's turn usage, or undefined when the frame's usage trio is not
1250
1293
  // the shape `mapTurnUsage` dereferences. Both result arms are
1251
- // discriminant-validated only, so every call goes through this guard (Tenet 6:
1294
+ // discriminant-validated only, so every call goes through this guard (SPEC §8.0:
1252
1295
  // a malformed frame must not throw out of push()); absent ⇒ no usage key.
1253
1296
  // The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
1254
1297
  // object and its minimal real shape (numeric input/output token counts, so an
@@ -1485,6 +1528,134 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1485
1528
  // tool.done{denied} for a call already closed is a duplicate start and a second
1486
1529
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1487
1530
  const closedToolCallIds = new Set();
1531
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1532
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1533
+ // refusal at the permission prompt also gets, and writes the refusal text
1534
+ // with a correction appended ("this call was stopped while running, not
1535
+ // refused before it ran"). Such a call ran and may have had effects, so it
1536
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1537
+ // for a call kept from running. The detector reads structural signals only,
1538
+ // never the correction text:
1539
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1540
+ // one text block is "[Request interrupted by user for tool use]",
1541
+ // arrives after the tool_result before any frame that continues the
1542
+ // turn (`continuesTopLevelTurn`);
1543
+ // - the decider: the turn's result signals an interruption
1544
+ // (`resultSignalsInterruption`; a Stop during a tool says
1545
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1546
+ // the SDK calls the authoritative record of refusals, does not list the
1547
+ // call.
1548
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1549
+ // the marker and an interrupted result, but its call is in
1550
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1551
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1552
+ // continues the turn, other than the marker, releases it unchanged
1553
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1554
+ // frames (system notices, a subagent's frames, the rest of a stream already
1555
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1556
+ // decides, and the tool.done is emitted from that result's push(), before
1557
+ // the denials carrier and the turn close. The "error" record keeps the
1558
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1559
+ // verbatim, and takes the marker's text as `errorText`, with no
1560
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1561
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1562
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1563
+ // the flush's closes, so the delivered frame is not lost. Nested results
1564
+ // are not held: they keep the stamp's outcome.
1565
+ const heldStopToolDones = [];
1566
+ let heldStopMarker;
1567
+ function interruptForToolUseMarker(frame) {
1568
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null)
1569
+ return undefined;
1570
+ const message = frame["message"];
1571
+ const content = isJsonObject(message) ? message["content"] : undefined;
1572
+ if (!Array.isArray(content) || content.length !== 1)
1573
+ return undefined;
1574
+ const only = content[0];
1575
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1576
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1577
+ : undefined;
1578
+ }
1579
+ // Whether `frame` continues the top-level turn: a top-level assistant
1580
+ // frame, a top-level stream_event that starts a new message
1581
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1582
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1583
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1584
+ // any other type, and the rest of a stream already open (content_block_*,
1585
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1586
+ // task_notification, background_tasks_changed) to the output as they
1587
+ // happen, and the Stop that cuts off a tool call also stops running
1588
+ // background tasks. So those notices can land before or after the marker,
1589
+ // and before the result.
1590
+ // Two kinds of top-level user frame do not continue it either: a replay
1591
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1592
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1593
+ // that cuts off parallel calls stamps each call's result in its own frame,
1594
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1595
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1596
+ // (no CLI path writes one: each cut-off call gets its own frame).
1597
+ function continuesTopLevelTurn(frame) {
1598
+ if (!isJsonObject(frame))
1599
+ return false;
1600
+ const type = frame["type"];
1601
+ if (type !== "assistant" && type !== "stream_event" && type !== "user")
1602
+ return false;
1603
+ const parent = frame["parent_tool_use_id"];
1604
+ if (parent !== null && parent !== undefined)
1605
+ return false;
1606
+ if (type === "stream_event") {
1607
+ const event = frame["event"];
1608
+ return isJsonObject(event) && event["type"] === "message_start";
1609
+ }
1610
+ if (type !== "user")
1611
+ return true;
1612
+ if (frame["isReplay"] === true)
1613
+ return false;
1614
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1615
+ if (parent !== null)
1616
+ return true;
1617
+ const message = frame["message"];
1618
+ const content = isJsonObject(message) ? message["content"] : undefined;
1619
+ if (!Array.isArray(content) || content.length === 0)
1620
+ return true;
1621
+ const kinds = readNonExecutionKinds(frame);
1622
+ for (const block of content) {
1623
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true)
1624
+ return true;
1625
+ const id = block["tool_use_id"];
1626
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected")
1627
+ return true;
1628
+ }
1629
+ return false;
1630
+ }
1631
+ // Release every held tool.done: as an interrupted call when the marker was
1632
+ // seen and `result` (the turn's result frame, either arm) signals an
1633
+ // interruption without listing the call in permission_denials; otherwise
1634
+ // unchanged.
1635
+ function releaseHeldToolDones(result) {
1636
+ if (heldStopToolDones.length === 0)
1637
+ return;
1638
+ const held = heldStopToolDones.splice(0);
1639
+ const marker = heldStopMarker;
1640
+ heldStopMarker = undefined;
1641
+ // The marker's text when this result decides "stopped while running".
1642
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1643
+ const listed = new Set();
1644
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1645
+ if (Array.isArray(denials)) {
1646
+ for (const d of denials)
1647
+ if (isJsonObject(d) && typeof d["tool_use_id"] === "string")
1648
+ listed.add(d["tool_use_id"]);
1649
+ }
1650
+ for (const { fields } of held) {
1651
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1652
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1653
+ }
1654
+ else {
1655
+ a.toolDone(fields);
1656
+ }
1657
+ }
1658
+ }
1488
1659
  // SDK message id → the `diagnostics` value already carried for it (see the
1489
1660
  // assistant branch): one carry per response, not one per frame.
1490
1661
  const diagnosticsCarried = new Map();
@@ -1525,6 +1696,39 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1525
1696
  stashedTurnErrors.delete(turnId);
1526
1697
  return stashed;
1527
1698
  }
1699
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
1700
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
1701
+ // result-meta carry, as before every close. turn.abort has no finishReason
1702
+ // slot, so it is built as for an error close and stop_reason rides it. Then
1703
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
1704
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
1705
+ // command_lifecycle frame reports for the interrupted command. The flag
1706
+ // branches use the same value: they have no captured emission yet, and one
1707
+ // value keeps one consumer branch for "the turn was stopped before it
1708
+ // finished".
1709
+ //
1710
+ // turn.abort has no code or message, so the cause rides result-meta, on this
1711
+ // close only: `terminalReason` (the result's terminal_reason, a string,
1712
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
1713
+ // result carries them as booleans, verbatim. Every other close's result-meta
1714
+ // is unchanged. The `errors` text an error-arm result carries (through
1715
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
1716
+ function closeInterruptedTurn(turnId, msg) {
1717
+ const raw = msg;
1718
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
1719
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
1720
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
1721
+ const resultMeta = {
1722
+ ...resultMetaPayload(msg, true),
1723
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
1724
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
1725
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
1726
+ };
1727
+ if (Object.keys(resultMeta).length > 0) {
1728
+ a.emitExt("anthropic", "result-meta", resultMeta);
1729
+ }
1730
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
1731
+ }
1528
1732
  let pending;
1529
1733
  // How many lifecycles each SDK message id has already opened. A same-id frame
1530
1734
  // arriving after its lifecycle closed (a fold-binding frame landed between two
@@ -2028,7 +2232,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2028
2232
  messageIdsByUuid.set(uuid, [...ids]);
2029
2233
  }
2030
2234
  // Evict every messageId ever produced for each uuid in `uuids`. An uuid this
2031
- // facet never observed is skipped (Tenet 6: nothing is fabricated — the fold
2235
+ // facet never observed is skipped (no remove is fabricated — the fold
2032
2236
  // has nothing live under an unknown id anyway; `reduce()`'s `#removeMessage`
2033
2237
  // is a documented no-op on an unknown id regardless). Safe to call from BOTH
2034
2238
  // retraction sources without double-effect: `supersedes` fires "on arrival"
@@ -2730,7 +2934,23 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2730
2934
  if (run !== undefined) {
2731
2935
  toolTurnId = run.turnId;
2732
2936
  }
2733
- else {
2937
+ else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
2938
+ // A run that already CLOSED reopens only for a frame that carries a
2939
+ // tool_result, because that frame's tool.done needs a nested turn to
2940
+ // land in. A closed run's nested frame with no tool_result emits
2941
+ // nothing into a nested turn (it rides the `kind: "user"` carry
2942
+ // above), so it reopens nothing. The live case: after a client
2943
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
2944
+ // by user]" text frame, carrying its parent_tool_use_id, after
2945
+ // task_updated / task_notification has already closed that run as
2946
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
2947
+ // opened an empty second run, which flush then closed as
2948
+ // turn.abort{stream-truncated}. A run this invoke never opened still
2949
+ // opens on any nested user frame: a subagent's first frame is its
2950
+ // prompt, a text-only user frame, and a run that fails before any
2951
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
2952
+ // its turn.error.
2953
+ //
2734
2954
  // A run that CLOSED, or one this invoke never opened (the stream
2735
2955
  // started mid-run: a background agent spanning invokes, a resume):
2736
2956
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -2846,7 +3066,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2846
3066
  // always before this tool_result) rides here instead, the same
2847
3067
  // `_meta` record the carrier gives it, so D drops nothing.
2848
3068
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2849
- a.toolDone({
3069
+ const doneFields = {
2850
3070
  toolCallId: block.tool_use_id,
2851
3071
  content: toolContent,
2852
3072
  outcome,
@@ -2893,7 +3113,17 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2893
3113
  });
2894
3114
  return merged !== undefined ? { _meta: merged } : {};
2895
3115
  })(),
2896
- });
3116
+ };
3117
+ // A top-level "user-rejected" result may be a call a client Stop cut
3118
+ // off while it ran, not a refusal: held until a frame that
3119
+ // continues the turn, or the turn's result, shows which (see
3120
+ // `heldStopToolDones`).
3121
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3122
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3123
+ }
3124
+ else {
3125
+ a.toolDone(doneFields);
3126
+ }
2897
3127
  }
2898
3128
  }
2899
3129
  // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
@@ -2910,6 +3140,9 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2910
3140
  // is NOT closed by its parent's result; it closes when the framework
2911
3141
  // reports it, or at flush.
2912
3142
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3143
+ // A held Stop candidate's tool.done, decided by this result (see
3144
+ // `heldStopToolDones`), while the turn is still open.
3145
+ releaseHeldToolDones(msg);
2913
3146
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
2914
3147
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
2915
3148
  // the final assistant text in result — or, with is_error true, the error
@@ -2929,7 +3162,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2929
3162
  // discriminant-validated, and false/absent must stay on the success path
2930
3163
  // byte-for-byte. The stash entry is consumed either way.
2931
3164
  const stashedError = takeStashedTurnError(turnId);
2932
- // Shape-guarded once for every close below (Tenet 6; see guardedTurnUsage).
3165
+ // Shape-guarded once for every close below (SPEC §8.0; see guardedTurnUsage).
2933
3166
  const turnUsage = guardedTurnUsage(msg);
2934
3167
  const apiErrorTurn = msg.is_error === true;
2935
3168
  const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
@@ -2943,6 +3176,21 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2943
3176
  // point — its close is deferred to this frame (below), so the turn is
2944
3177
  // still open here, like every other turn.
2945
3178
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3179
+ if (resultSignalsInterruption(msg)) {
3180
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3181
+ // every other close on this arm: the turn was interrupted, so it closes
3182
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3183
+ // refusal or a parked call would otherwise decide. The stash, refusal
3184
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3185
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3186
+ // close. turn.abort carries no usage either. The last round's usage
3187
+ // stays on its message.end, as item 17 allows; the result's turn total
3188
+ // is not carried.
3189
+ refusedTurns.delete(turnId);
3190
+ stopDetailsByTurn.delete(turnId);
3191
+ closeInterruptedTurn(turnId, msg);
3192
+ return;
3193
+ }
2946
3194
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
2947
3195
  // ride `ext.anthropic.result-meta` before the close (no core home on
2948
3196
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -3066,6 +3314,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3066
3314
  // INV-MSG: seal the open assistant message before the turn close.
3067
3315
  closePendingMessage();
3068
3316
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3317
+ releaseHeldToolDones(msg);
3069
3318
  // Consume any stashed assistant-error close for this turnId — this
3070
3319
  // frame emits it (below). Each turn has its own id now, so an entry can
3071
3320
  // only ever be this turn's.
@@ -3074,7 +3323,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3074
3323
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
3075
3324
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
3076
3325
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
3077
- // not throw (Tenet 6: graceful, never throws).
3326
+ // not throw (SPEC §8.0: graceful, never throws).
3078
3327
  const errors = Array.isArray(msg.errors) ? msg.errors : [];
3079
3328
  const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
3080
3329
  // Since claude-agent-sdk 0.3.274: a known startup failure says why the CLI refused to
@@ -3088,7 +3337,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3088
3337
  : subtype !== "error_max_turns";
3089
3338
  // Denials ride the SAME carrier as on the success arm, at the same point.
3090
3339
  // This arm is discriminant-validated only, so the array is shape-guarded
3091
- // (a malformed entry is skipped; Tenet 6: never throw).
3340
+ // (a malformed entry is skipped; SPEC §8.0: never throw).
3092
3341
  const rawDenials = isJsonObject(msg) ? msg["permission_denials"] : undefined;
3093
3342
  const denials = Array.isArray(rawDenials)
3094
3343
  ? rawDenials.flatMap((d) => isJsonObject(d) && typeof d["tool_name"] === "string" && typeof d["tool_use_id"] === "string"
@@ -3096,6 +3345,16 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3096
3345
  : [])
3097
3346
  : [];
3098
3347
  emitDenialsCarrier(turnId, denials, msg.session_id);
3348
+ if (resultSignalsInterruption(msg)) {
3349
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3350
+ // close (both consumed above): the turn closes with one turn.abort, not
3351
+ // turn.error. This is the arm a client interrupt reaches:
3352
+ // error_during_execution with terminal_reason "aborted_streaming" or
3353
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3354
+ // turn.error{retriable: true}.
3355
+ closeInterruptedTurn(turnId, msg);
3356
+ return;
3357
+ }
3099
3358
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
3100
3359
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
3101
3360
  // success arm above (turn.error carries no metadata slot at all).
@@ -3109,7 +3368,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3109
3368
  // second turn.error for the same turnId (INV-TURN), with this frame's
3110
3369
  // usage (the success arm's mapping). This arm is only
3111
3370
  // discriminant-validated, so the usage trio is shape-guarded first
3112
- // (Tenet 6: a malformed frame must not throw); absent ⇒ no usage key.
3371
+ // (SPEC §8.0: a malformed frame must not throw); absent ⇒ no usage key.
3113
3372
  // The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
3114
3373
  // dereferences — `usage: {}` or a null modelUsage entry would otherwise
3115
3374
  // throw here, after the stash was already consumed.
@@ -3226,8 +3485,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3226
3485
  driveStreamEvent(msg);
3227
3486
  return;
3228
3487
  }
3229
- // Fixture-drift ratchet (2026-07-03 follow-up; +2 on the 0.3.207 bump):
3230
- // 17 carried arms with genuine consumer-facing content and no existing
3488
+ // Fixture-drift ratchet (2026-07-03 follow-up; 20 arms as of 0.3.319):
3489
+ // the carried arms with genuine consumer-facing content and no existing
3231
3490
  // AgJSON home — uniform lossless carry (see `anthropicFrameKind` doc
3232
3491
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
3233
3492
  const carriedKind = anthropicFrameKind(msg);
@@ -3277,8 +3536,19 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3277
3536
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3278
3537
  // frame is the same reference, anything else its JSON form).
3279
3538
  const frame = native;
3539
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
3540
+ // it held for the turn's result to decide. A frame that continues the
3541
+ // turn releases it unchanged before that frame is handled; a result
3542
+ // decides it, and any other frame leaves it held.
3543
+ if (heldStopToolDones.length > 0) {
3544
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
3545
+ if (marker !== undefined)
3546
+ heldStopMarker = marker;
3547
+ else if (continuesTopLevelTurn(frame))
3548
+ releaseHeldToolDones();
3549
+ }
3280
3550
  if (!isSDKMessage(frame)) {
3281
- // Graceful guard (Tenet 6): route the raw payload through the lossless
3551
+ // Graceful guard (SPEC §8.0): route the raw payload through the lossless
3282
3552
  // vendor channel rather than throwing. Nest under `native` so a payload
3283
3553
  // that carries its own `type` key (the common malformed-SDKMessage shape
3284
3554
  // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
@@ -3299,6 +3569,18 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3299
3569
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3300
3570
  // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3301
3571
  closePendingMessage(true);
3572
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
3573
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
3574
+ // "user"` frame carry instead, verbatim, before every close below
3575
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
3576
+ const carriedHeldFrames = new Set();
3577
+ for (const { frame } of heldStopToolDones.splice(0)) {
3578
+ if (carriedHeldFrames.has(frame))
3579
+ continue;
3580
+ carriedHeldFrames.add(frame);
3581
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
3582
+ }
3583
+ heldStopMarker = undefined;
3302
3584
  // B-strict: every subagent run still open closes here with its nested
3303
3585
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3304
3586
  // its subagent.done, innermost first.