@silverprotocol/claude-agent-sdk 1.0.0-rc.7 → 1.0.0-rc.9

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,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.332` | 2026-11-28 | 1.0.0-rc.9 | @anthropic-ai/claude-agent-sdk 0.3.319 -> 0.3.332 (bundled CLI 2.1.319 -> 2.1.332; 0.3.320 was never published to npm). SDKMessage stays at 40 arms; no union arm was added or removed. Members added inside arms: SDKResultError.invalid_config_file (0.3.324), not carried; system/init plugins[].managed_lock (0.3.324), not carried, since init emits nothing; SDKMessageOrigin.subkind 'external-event' (0.3.330), carried verbatim with the origin; tool_result_meta[].rewritten_by_plugin (0.3.332), riding the existing tool_result_meta carry. SDKStartupFailureReason adds managed_settings_not_delivered (0.3.323), initialize_fields_not_delivered (0.3.327) and sideload_flags_disabled (0.3.331). All three close turn.error as non-retriable: upstream says the fix for the first two is in the host or a wrapper script, not a retry, and gives no retry guidance for the third. An undeclared system subtype now rides ext.anthropic.frame whole, with kind set to the subtype, like an undeclared top-level type; through 1.0.0-rc.8 such a frame emitted nothing. The CLI's schemas at 2.1.332 hold system subtypes with no d.ts entry, and the README's "Unmapped frames" section says what such a frame can hold. Runtime-only keys in the 2.1.332 CLI schema that no d.ts declares: api_error_type (the error.type of the API response body, copied only when it is an identifier), which rides the assistant API-error frame and the result beside api_error_origin (both seen in a live bad-key run at 0.3.332; no committed cassette holds them), and the result key begun_message_ids (the msg_* ids of the responses that began streaming in the turn; with partials on), seen in partials-sonnet5, partials-fable52, thinking-fable52 and partials-sonnet55. Both are registered as reviewed drops on this line, as is api_error_origin (since CLI 2.1.299). Option changes the capture agent meets: 0.3.326 adds mcpServersDelivery: 'initialize' and deprecates the command-line default; the capture agent now sets 'initialize', so the mock MCP servers' Authorization header stays off the CLI's argv. 0.3.327 refuses options that cannot be sent to Claude Code and requires hook values to be arrays; the agent's hooks are arrays, and every capture booted. 0.3.325: sandboxed Bash is no longer auto-approved; the agent sets no sandbox, so this does not reach it. 0.3.321: resume and continue read initialize during boot; the defer resume legs captured green. Behaviour changes the facet already handles, with no code change: 0.3.323: a tool permission check that fails after a PreToolUse allow goes to canUseTool, or is refused; a refusal closes as it always did. 0.3.327: a woken background subagent's task_started has no prompt, and 0.3.331: task_notification.output_file names a foreground subagent's output file too; the task_* frames ride the whole-frame carry, so each is carried as sent. 0.3.329: when the macOS Keychain cannot save a refreshed login, the assistant error is invalid_request (it was authentication_failed), with api_error_status null; both are non-retriable, so the close is unchanged. 0.3.323: a periodic tool_progress heartbeat while a turn waits on long-running hooks, with tool_use_id beginning hook-; tool_progress stays router-plane and emits nothing. system/informational gains the tags settings_not_in_effect (0.3.330), managed_hooks_not_loaded (0.3.329), managed_mcp_arrived (0.3.326) and hook_no_verdict (0.3.325), plus an untagged tool-list warning (0.3.326); informational keeps its dedicated branch, which does not carry the tag. 0.3.328 adds CLAUDE_CODE_DISABLE_DEFERRED_TOOL_RESUME, which stops resume and continue from running a tool call a hook deferred; the agent does not set it. Thinking display: CLI 2.1.332 sends display 'updates' with the beta thinking-display-updates-2026-08-18 on every main-thread request that leaves display unset, while the Agent SDK still types display as 'summarized' \| 'omitted'. The stream reports it as thinking_display: 'updates' on the display-unset partials seeds (partials-sonnet5, partials-fable52, partials-sonnet55) and 'summarized' on thinking-fable52; narration_block_indexes was not seen on any display-unset seed. Live: echo-fable52, partials-fable52, thinking-fable52 and app-update-fable52 (claude-fable-5-2) and partials-sonnet55 (claude-sonnet-5-5), the first captures of those seeds, captured green at 0.3.332; fable-5-2 streamed no thinking under display 'summarized' (thinking-fable52 has no thinking block, and reasoningTokens 0). Refreshed: echo-sonnet55 (claude-sonnet-5-5), echo-haiku55 and multi-result-haiku55 (claude-haiku-5-5), and defer-tool-sonnet5 and partials-sonnet5 (claude-sonnet-5) keep the event-type sequences of their earlier cassettes; the defer resume legs (claude-sonnet-5) resume and close as before, the model taking a shorter path this time (no reasoning block on the allow leg, one denied attempt on the deny leg). Census: no drops and no new fields after registering the new models' usage entries as their earlier models' are, a hook attachment frame's members as transforms to its whole-frame carry, the streamed usage speed, and the runtime-only keys served_by_anthropic and sandbox_enabled (init), first_request_cache_read_input_tokens (result) and thinking_display (stream) as drops. |
35
36
  | `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
37
  | `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. |
37
38
  | `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. |
@@ -82,6 +83,18 @@ events.push(...n.flush()); // seal anything still open at end-of-stream
82
83
  Malformed input never throws — it routes through the lossless
83
84
  `ext.anthropic.unparsed` channel instead.
84
85
 
86
+ ### Unmapped frames
87
+
88
+ A `system` frame whose subtype the facet neither maps nor has reviewed as
89
+ carrying no turn content rides `ext.anthropic.frame` whole, with `kind` set to
90
+ the subtype (`"system"` when the subtype is not a string). A top-level frame
91
+ type the SDK does not declare rides the same way, with `kind` set to that type.
92
+ The CLI adds subtypes without a type entry, so such a frame can hold local
93
+ paths, the git branch, hook command lines and free text. Apart from
94
+ `__proto__` members, only `fallback_credit_token` keys are removed, at any
95
+ depth. A host that relays ext events to another party should filter them by
96
+ `kind`.
97
+
85
98
  ### Thread id
86
99
 
87
100
  Pass the host's own thread id as `createClaudeNormalizer({ threadId })`. The
@@ -196,6 +209,46 @@ do not set it, so a refusal there still closes as `turn.error`.
196
209
  - A stream that ends before the result closes the turn as `turn.error`, and so
197
210
  does a subagent's refusal whose run is still open at the end of the stream.
198
211
 
212
+ ### Interrupted turns
213
+
214
+ A result that reports an interruption closes the turn with one
215
+ `turn.abort { reason: "cancelled" }`, never with `turn.error` or `turn.done`
216
+ (SPEC §8.0 item 17). An interruption is any of: `terminal_reason`
217
+ `"aborted_streaming"` or `"aborted_tools"`, `stopped_by_permission_check: true`,
218
+ or `interrupted_by_shutdown: true`. Either result arm counts, and the check
219
+ comes before every other close the result would make. A client Stop
220
+ (`Query.interrupt()`) ends the turn this way: the CLI sends an
221
+ `error_during_execution` result with one of those two `terminal_reason`
222
+ values. `turn.abort` carries no usage: each round's usage stays on its
223
+ `message.end`, and the result's turn total is not carried. The result's
224
+ `stop_reason` rides `ext.anthropic.result-meta`, as on an error close. On
225
+ this close only, result-meta also carries the cause: `terminalReason` (the
226
+ result's `terminal_reason`) and, when the result carries them,
227
+ `stoppedByPermissionCheck` and `interruptedByShutdown`. The result's
228
+ `errors` text is not carried. A subagent run the CLI stops closes its
229
+ nested turn with `turn.abort { reason: "stopped" }`.
230
+
231
+ A tool call the Stop cut off while it ran records `tool.done` with
232
+ `outcome: "error"`, `isError: true` and `errorText` set to the CLI's
233
+ interrupt marker, `"[Request interrupted by user for tool use]"`; its content
234
+ and its `non_execution_kind: "user-rejected"` stamp (in `_meta`) stay
235
+ verbatim. The CLI stamps such a call the way it stamps a refusal, so the
236
+ facet holds that `tool.done` until a frame that continues the turn arrives:
237
+ a top-level assistant frame, a top-level `message_start` stream event, or a
238
+ top-level user frame other than the interrupt marker. The turn's result
239
+ decides it too. System frames, a subagent's frames, replay acks and the rest
240
+ of a stream already open leave it held: the CLI writes background-task
241
+ notices as they happen, so they can land on either side of the marker. A
242
+ top-level frame whose every `tool_result` is an `is_error` result stamped the
243
+ same way joins the hold: a Stop that cuts off parallel calls stamps each
244
+ call's result in its own frame. When the interrupt marker arrives first and
245
+ the turn's result reports an interruption without listing the call in
246
+ `permission_denials`, the call ran and was stopped. Otherwise it
247
+ was refused, and stays `outcome: "denied"`. A stream that ends while the
248
+ `tool.done` is held emits no `tool.done`, because a flush emits none; the
249
+ held tool_result frame rides `ext.anthropic.frame` (`kind: "user"`)
250
+ verbatim instead, before the turn closes.
251
+
199
252
  ### Turn trigger
200
253
 
201
254
  When the frame that opens a top-level turn is an assistant message, a streamed
@@ -218,4 +271,4 @@ and subagent turns never carry it.
218
271
 
219
272
  Spec: [silverprotocol.io/AgJSON](https://silverprotocol.io/AgJSON) — canonical
220
273
  in [silverprotocol/AgJSON](https://github.com/silverprotocol/AgJSON); wire
221
- version `1.0.0-rc.3`.
274
+ version `1.0.0-rc.4`.
@@ -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;AAyyCD,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;AAo3CD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AA+8ED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAIxF;eAEc,sBAAsB;AACrC,OAAO,EAAE,aAAa,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -334,10 +334,24 @@ function mcpToolResultContentToAgBlocks(content) {
334
334
  // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
335
335
  // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
336
336
  // not carry the tool's own execution output (user-rejected / permission-rule /
337
- // automode-* / interrupted / cancelled); absent means the tool ran to
338
- // completion" (the CLI's own schema doc). Read through the JSON boundary; a
339
- // malformed entry is skipped. The entry itself is NOT carried here (that carry
340
- // is package 15's); only the kind decides the outcome below.
337
+ // automode-* / interrupted / cancelled); absent usually means that the tool ran
338
+ // to completion, but see call_ended" (the CLI's own schema doc, from CLI
339
+ // 2.1.332; earlier: "absent means the tool ran to completion"). Read through the
340
+ // JSON boundary; a malformed entry is skipped. The entry itself is NOT carried
341
+ // here (`readToolResultMetaEntries` carries it); only the kind decides the
342
+ // outcome below.
343
+ //
344
+ // `call_ended` (CLI 2.1.332, same entry) says how a call ended where the kind
345
+ // does not. Its one value, "not_started", marks a call that a replacement
346
+ // process closed without running it, after a permission prompt on an earlier
347
+ // call of the same message was answered or a new message closed it: "nobody
348
+ // stopped or refused this call, so a host shows it as not run". The CLI writes
349
+ // that result with is_error:true and a kind of "cancelled" (after a deny or a
350
+ // new message) or no kind (after an allow). It is not read here: neither case
351
+ // is a refusal, so the call records outcome "error" with isError, by the same
352
+ // rule as every other non-denial kind, and never "denied", which records a
353
+ // refusal that kept a call from running. The entry, call_ended included, rides
354
+ // the tool.done's `_meta` verbatim, so a host can show the call as not run.
341
355
  function readNonExecutionKinds(frame) {
342
356
  const out = new Map();
343
357
  if (!isJsonObject(frame))
@@ -592,8 +606,9 @@ function isSDKMessage(v) {
592
606
  const ev = v.event;
593
607
  return isJsonObject(ev) && typeof ev.type === "string";
594
608
  }
595
- // system / status / … — structurally valid SDKMessage arms that carry no
596
- // AgJSON-relevant content. Accept (the normalizer no-ops on them).
609
+ // system / status / … — structurally valid SDKMessage arms. Accept: drive()
610
+ // maps them, carries them on ext.anthropic.frame, or (the studied uncarried
611
+ // subtypes and arms) emits nothing.
597
612
  return typeof t === "string";
598
613
  }
599
614
  // ─── uniform lossless carry: 17 claude arms — the fixture-drift ratchet's
@@ -695,6 +710,27 @@ const CARRIED_SYSTEM_SUBTYPES = new Set([
695
710
  // reasoning-progress event is a draft.3 spec candidate) → whole-frame carry.
696
711
  "thinking_tokens",
697
712
  ]);
713
+ // The system subtypes the facet studied and left uncarried: each SDK member
714
+ // disposed `router-plane` in sdk-surface.json (SDKSystemMessage = init,
715
+ // SDKCompactBoundaryMessage, SDKAPIRetryMessage, SDKControlRequestProgressMessage,
716
+ // SDKHookStartedMessage, SDKPluginInstallMessage, SDKSessionStateChangedMessage,
717
+ // SDKWorkerShuttingDownMessage, SDKCommandsChangedMessage,
718
+ // SDKElicitationCompleteMessage). They emit nothing, as before. Every OTHER
719
+ // subtype without its own branch, declared or not, rides
720
+ // `ext.anthropic.frame{kind: <subtype>, frame}` at the end of `drive()`.
721
+ // Through 0.12.12 / 1.0.0-rc.8 an undeclared subtype was dropped silently.
722
+ const STUDIED_UNCARRIED_SYSTEM_SUBTYPES = new Set([
723
+ "init",
724
+ "compact_boundary",
725
+ "api_retry",
726
+ "control_request_progress",
727
+ "hook_started",
728
+ "plugin_install",
729
+ "session_state_changed",
730
+ "worker_shutting_down",
731
+ "commands_changed",
732
+ "elicitation_complete",
733
+ ]);
698
734
  const CARRIED_STANDALONE_TYPES = new Set([
699
735
  "auth_status",
700
736
  "tool_use_summary",
@@ -939,6 +975,36 @@ function readDeferredCall(v) {
939
975
  function closeCauseTerminalReason(v) {
940
976
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
941
977
  }
978
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
979
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
980
+ // success turn.done, whichever result arm carries the signal. The signal is
981
+ // any one of:
982
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
983
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
984
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
985
+ // (error_during_execution, is_error true) with one of these two, then
986
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
987
+ // a subagent run.
988
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
989
+ // permission check after repeated refusals.
990
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
991
+ // worker shut down.
992
+ // No capture has shown either flag yet, so their arm is unknown: the check
993
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
994
+ // so the frame is read through the JSON boundary, and only a literal `true`
995
+ // counts. The key is never the result's `errors` text.
996
+ const INTERRUPTION_TERMINAL_REASONS = new Set(["aborted_streaming", "aborted_tools"]);
997
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
998
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
999
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
1000
+ function resultSignalsInterruption(msg) {
1001
+ if (!isJsonObject(msg))
1002
+ return false;
1003
+ const terminalReason = msg["terminal_reason"];
1004
+ return ((typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
1005
+ msg["stopped_by_permission_check"] === true ||
1006
+ msg["interrupted_by_shutdown"] === true);
1007
+ }
942
1008
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
943
1009
  // on both frames that carry it (the API-error assistant frame and the
944
1010
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -959,7 +1025,7 @@ function readStartupFailureReason(v) {
959
1025
  // The type's own lead sentence frames the whole enum as a refusal to start:
960
1026
  // "Why Claude Code refused to start, so a host can offer the fix instead of a
961
1027
  // retry." So a PRESENT reason means NOT retriable, except for the values
962
- // upstream itself EXPLICITLY describes as retriable. Through 0.3.319 that set is
1028
+ // upstream itself EXPLICITLY describes as retriable. Through 0.3.332 that set is
963
1029
  // exactly two values:
964
1030
  // - `worktree_unverified`: "the session's worktree could not be verified
965
1031
  // right now; retrying may succeed."
@@ -985,9 +1051,15 @@ function readStartupFailureReason(v) {
985
1051
  // org_config_refused: "signing in again or an admin's change is the fix, not a
986
1052
  // retry", 0.3.314's sandbox_required_unavailable: "make the sandbox
987
1053
  // available or have the requirement changed", 0.3.317's initialize_not_first:
988
- // "the fix is in the host or the wrapper script, not a retry", and 0.3.318's
989
- // config_file_invalid: "a retry alone does not help") names a configuration,
990
- // policy or environment fix, and an unknown future value
1054
+ // "the fix is in the host or the wrapper script, not a retry", 0.3.318's
1055
+ // config_file_invalid: "a retry alone does not help", 0.3.323's
1056
+ // managed_settings_not_delivered: "the fix is in the host or in a wrapper
1057
+ // script between it and Claude Code, not a retry", 0.3.327's
1058
+ // initialize_fields_not_delivered, described as the same failure for
1059
+ // --initialize-fields, and 0.3.331's sideload_flags_disabled: managed
1060
+ // settings refuse the launch's own plugins, agents or MCP servers, with no
1061
+ // retry guidance) names a configuration, policy or environment fix, and an
1062
+ // unknown future value
991
1063
  // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
992
1064
  // reason never reaches this function: the error arm keeps its old rule, so
993
1065
  // older producers are byte-identical.
@@ -1180,9 +1252,10 @@ function resultMetaPayload(msg, closesAsError) {
1180
1252
  // the census allowlist's "carry candidate the first time an error seed
1181
1253
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1182
1254
  const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1183
- // `stop_reason` on a result that closes as turn.error: turn.error has no
1184
- // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1185
- // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1255
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1256
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1257
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1258
+ // verbatim ONLY on such a close;
1186
1259
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1187
1260
  const stopReason = closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
1188
1261
  const modelUsageSinceLastResult = isJsonObject(raw)
@@ -1497,6 +1570,134 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1497
1570
  // tool.done{denied} for a call already closed is a duplicate start and a second
1498
1571
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1499
1572
  const closedToolCallIds = new Set();
1573
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1574
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1575
+ // refusal at the permission prompt also gets, and writes the refusal text
1576
+ // with a correction appended ("this call was stopped while running, not
1577
+ // refused before it ran"). Such a call ran and may have had effects, so it
1578
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1579
+ // for a call kept from running. The detector reads structural signals only,
1580
+ // never the correction text:
1581
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1582
+ // one text block is "[Request interrupted by user for tool use]",
1583
+ // arrives after the tool_result before any frame that continues the
1584
+ // turn (`continuesTopLevelTurn`);
1585
+ // - the decider: the turn's result signals an interruption
1586
+ // (`resultSignalsInterruption`; a Stop during a tool says
1587
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1588
+ // the SDK calls the authoritative record of refusals, does not list the
1589
+ // call.
1590
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1591
+ // the marker and an interrupted result, but its call is in
1592
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1593
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1594
+ // continues the turn, other than the marker, releases it unchanged
1595
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1596
+ // frames (system notices, a subagent's frames, the rest of a stream already
1597
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1598
+ // decides, and the tool.done is emitted from that result's push(), before
1599
+ // the denials carrier and the turn close. The "error" record keeps the
1600
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1601
+ // verbatim, and takes the marker's text as `errorText`, with no
1602
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1603
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1604
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1605
+ // the flush's closes, so the delivered frame is not lost. Nested results
1606
+ // are not held: they keep the stamp's outcome.
1607
+ const heldStopToolDones = [];
1608
+ let heldStopMarker;
1609
+ function interruptForToolUseMarker(frame) {
1610
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null)
1611
+ return undefined;
1612
+ const message = frame["message"];
1613
+ const content = isJsonObject(message) ? message["content"] : undefined;
1614
+ if (!Array.isArray(content) || content.length !== 1)
1615
+ return undefined;
1616
+ const only = content[0];
1617
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1618
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1619
+ : undefined;
1620
+ }
1621
+ // Whether `frame` continues the top-level turn: a top-level assistant
1622
+ // frame, a top-level stream_event that starts a new message
1623
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1624
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1625
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1626
+ // any other type, and the rest of a stream already open (content_block_*,
1627
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1628
+ // task_notification, background_tasks_changed) to the output as they
1629
+ // happen, and the Stop that cuts off a tool call also stops running
1630
+ // background tasks. So those notices can land before or after the marker,
1631
+ // and before the result.
1632
+ // Two kinds of top-level user frame do not continue it either: a replay
1633
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1634
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1635
+ // that cuts off parallel calls stamps each call's result in its own frame,
1636
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1637
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1638
+ // (no CLI path writes one: each cut-off call gets its own frame).
1639
+ function continuesTopLevelTurn(frame) {
1640
+ if (!isJsonObject(frame))
1641
+ return false;
1642
+ const type = frame["type"];
1643
+ if (type !== "assistant" && type !== "stream_event" && type !== "user")
1644
+ return false;
1645
+ const parent = frame["parent_tool_use_id"];
1646
+ if (parent !== null && parent !== undefined)
1647
+ return false;
1648
+ if (type === "stream_event") {
1649
+ const event = frame["event"];
1650
+ return isJsonObject(event) && event["type"] === "message_start";
1651
+ }
1652
+ if (type !== "user")
1653
+ return true;
1654
+ if (frame["isReplay"] === true)
1655
+ return false;
1656
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1657
+ if (parent !== null)
1658
+ return true;
1659
+ const message = frame["message"];
1660
+ const content = isJsonObject(message) ? message["content"] : undefined;
1661
+ if (!Array.isArray(content) || content.length === 0)
1662
+ return true;
1663
+ const kinds = readNonExecutionKinds(frame);
1664
+ for (const block of content) {
1665
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true)
1666
+ return true;
1667
+ const id = block["tool_use_id"];
1668
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected")
1669
+ return true;
1670
+ }
1671
+ return false;
1672
+ }
1673
+ // Release every held tool.done: as an interrupted call when the marker was
1674
+ // seen and `result` (the turn's result frame, either arm) signals an
1675
+ // interruption without listing the call in permission_denials; otherwise
1676
+ // unchanged.
1677
+ function releaseHeldToolDones(result) {
1678
+ if (heldStopToolDones.length === 0)
1679
+ return;
1680
+ const held = heldStopToolDones.splice(0);
1681
+ const marker = heldStopMarker;
1682
+ heldStopMarker = undefined;
1683
+ // The marker's text when this result decides "stopped while running".
1684
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1685
+ const listed = new Set();
1686
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1687
+ if (Array.isArray(denials)) {
1688
+ for (const d of denials)
1689
+ if (isJsonObject(d) && typeof d["tool_use_id"] === "string")
1690
+ listed.add(d["tool_use_id"]);
1691
+ }
1692
+ for (const { fields } of held) {
1693
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1694
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1695
+ }
1696
+ else {
1697
+ a.toolDone(fields);
1698
+ }
1699
+ }
1700
+ }
1500
1701
  // SDK message id → the `diagnostics` value already carried for it (see the
1501
1702
  // assistant branch): one carry per response, not one per frame.
1502
1703
  const diagnosticsCarried = new Map();
@@ -1537,6 +1738,39 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1537
1738
  stashedTurnErrors.delete(turnId);
1538
1739
  return stashed;
1539
1740
  }
1741
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
1742
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
1743
+ // result-meta carry, as before every close. turn.abort has no finishReason
1744
+ // slot, so it is built as for an error close and stop_reason rides it. Then
1745
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
1746
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
1747
+ // command_lifecycle frame reports for the interrupted command. The flag
1748
+ // branches use the same value: they have no captured emission yet, and one
1749
+ // value keeps one consumer branch for "the turn was stopped before it
1750
+ // finished".
1751
+ //
1752
+ // turn.abort has no code or message, so the cause rides result-meta, on this
1753
+ // close only: `terminalReason` (the result's terminal_reason, a string,
1754
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
1755
+ // result carries them as booleans, verbatim. Every other close's result-meta
1756
+ // is unchanged. The `errors` text an error-arm result carries (through
1757
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
1758
+ function closeInterruptedTurn(turnId, msg) {
1759
+ const raw = msg;
1760
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
1761
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
1762
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
1763
+ const resultMeta = {
1764
+ ...resultMetaPayload(msg, true),
1765
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
1766
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
1767
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
1768
+ };
1769
+ if (Object.keys(resultMeta).length > 0) {
1770
+ a.emitExt("anthropic", "result-meta", resultMeta);
1771
+ }
1772
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
1773
+ }
1540
1774
  let pending;
1541
1775
  // How many lifecycles each SDK message id has already opened. A same-id frame
1542
1776
  // arriving after its lifecycle closed (a fold-binding frame landed between two
@@ -2742,7 +2976,23 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2742
2976
  if (run !== undefined) {
2743
2977
  toolTurnId = run.turnId;
2744
2978
  }
2745
- else {
2979
+ else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
2980
+ // A run that already CLOSED reopens only for a frame that carries a
2981
+ // tool_result, because that frame's tool.done needs a nested turn to
2982
+ // land in. A closed run's nested frame with no tool_result emits
2983
+ // nothing into a nested turn (it rides the `kind: "user"` carry
2984
+ // above), so it reopens nothing. The live case: after a client
2985
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
2986
+ // by user]" text frame, carrying its parent_tool_use_id, after
2987
+ // task_updated / task_notification has already closed that run as
2988
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
2989
+ // opened an empty second run, which flush then closed as
2990
+ // turn.abort{stream-truncated}. A run this invoke never opened still
2991
+ // opens on any nested user frame: a subagent's first frame is its
2992
+ // prompt, a text-only user frame, and a run that fails before any
2993
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
2994
+ // its turn.error.
2995
+ //
2746
2996
  // A run that CLOSED, or one this invoke never opened (the stream
2747
2997
  // started mid-run: a background agent spanning invokes, a resume):
2748
2998
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -2858,7 +3108,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2858
3108
  // always before this tool_result) rides here instead, the same
2859
3109
  // `_meta` record the carrier gives it, so D drops nothing.
2860
3110
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2861
- a.toolDone({
3111
+ const doneFields = {
2862
3112
  toolCallId: block.tool_use_id,
2863
3113
  content: toolContent,
2864
3114
  outcome,
@@ -2905,7 +3155,17 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2905
3155
  });
2906
3156
  return merged !== undefined ? { _meta: merged } : {};
2907
3157
  })(),
2908
- });
3158
+ };
3159
+ // A top-level "user-rejected" result may be a call a client Stop cut
3160
+ // off while it ran, not a refusal: held until a frame that
3161
+ // continues the turn, or the turn's result, shows which (see
3162
+ // `heldStopToolDones`).
3163
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3164
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3165
+ }
3166
+ else {
3167
+ a.toolDone(doneFields);
3168
+ }
2909
3169
  }
2910
3170
  }
2911
3171
  // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
@@ -2922,6 +3182,9 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2922
3182
  // is NOT closed by its parent's result; it closes when the framework
2923
3183
  // reports it, or at flush.
2924
3184
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3185
+ // A held Stop candidate's tool.done, decided by this result (see
3186
+ // `heldStopToolDones`), while the turn is still open.
3187
+ releaseHeldToolDones(msg);
2925
3188
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
2926
3189
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
2927
3190
  // the final assistant text in result — or, with is_error true, the error
@@ -2955,6 +3218,21 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2955
3218
  // point — its close is deferred to this frame (below), so the turn is
2956
3219
  // still open here, like every other turn.
2957
3220
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3221
+ if (resultSignalsInterruption(msg)) {
3222
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3223
+ // every other close on this arm: the turn was interrupted, so it closes
3224
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3225
+ // refusal or a parked call would otherwise decide. The stash, refusal
3226
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3227
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3228
+ // close. turn.abort carries no usage either. The last round's usage
3229
+ // stays on its message.end, as item 17 allows; the result's turn total
3230
+ // is not carried.
3231
+ refusedTurns.delete(turnId);
3232
+ stopDetailsByTurn.delete(turnId);
3233
+ closeInterruptedTurn(turnId, msg);
3234
+ return;
3235
+ }
2958
3236
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
2959
3237
  // ride `ext.anthropic.result-meta` before the close (no core home on
2960
3238
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -3078,6 +3356,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3078
3356
  // INV-MSG: seal the open assistant message before the turn close.
3079
3357
  closePendingMessage();
3080
3358
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3359
+ releaseHeldToolDones(msg);
3081
3360
  // Consume any stashed assistant-error close for this turnId — this
3082
3361
  // frame emits it (below). Each turn has its own id now, so an entry can
3083
3362
  // only ever be this turn's.
@@ -3108,6 +3387,16 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3108
3387
  : [])
3109
3388
  : [];
3110
3389
  emitDenialsCarrier(turnId, denials, msg.session_id);
3390
+ if (resultSignalsInterruption(msg)) {
3391
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3392
+ // close (both consumed above): the turn closes with one turn.abort, not
3393
+ // turn.error. This is the arm a client interrupt reaches:
3394
+ // error_during_execution with terminal_reason "aborted_streaming" or
3395
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3396
+ // turn.error{retriable: true}.
3397
+ closeInterruptedTurn(turnId, msg);
3398
+ return;
3399
+ }
3111
3400
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
3112
3401
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
3113
3402
  // success arm above (turn.error carries no metadata slot at all).
@@ -3279,8 +3568,25 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3279
3568
  a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
3280
3569
  return;
3281
3570
  }
3282
- // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
3283
- // content on this seam → no events.
3571
+ // A `system` frame whose subtype has no branch above and is not one the
3572
+ // facet studied and left uncarried (see STUDIED_UNCARRIED_SYSTEM_SUBTYPES):
3573
+ // carried whole, never silently dropped (SPEC §8.0 "MUST NOT silently drop
3574
+ // a native event it cannot map"; §8 item 22 names the subtype as the frame
3575
+ // kind). The CLI adds subtypes without a d.ts entry, so the next one is
3576
+ // carried the day it ships. A subtype that is not a string rides as kind
3577
+ // "system".
3578
+ if (msg.type === "system") {
3579
+ const raw = msg;
3580
+ const subtype = isJsonObject(raw) ? raw["subtype"] : undefined;
3581
+ const kind = typeof subtype === "string" ? subtype : "system";
3582
+ if (!STUDIED_UNCARRIED_SYSTEM_SUBTYPES.has(kind)) {
3583
+ a.emitExt("anthropic", "frame", { kind, frame: carryVerbatim(msg) });
3584
+ return;
3585
+ }
3586
+ }
3587
+ // The studied uncarried variants (the system subtypes above, tool_progress,
3588
+ // rate_limit_event) carry no AgJSON-relevant content on this seam → no
3589
+ // events.
3284
3590
  }
3285
3591
  return {
3286
3592
  push(native) {
@@ -3289,6 +3595,17 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3289
3595
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3290
3596
  // frame is the same reference, anything else its JSON form).
3291
3597
  const frame = native;
3598
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
3599
+ // it held for the turn's result to decide. A frame that continues the
3600
+ // turn releases it unchanged before that frame is handled; a result
3601
+ // decides it, and any other frame leaves it held.
3602
+ if (heldStopToolDones.length > 0) {
3603
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
3604
+ if (marker !== undefined)
3605
+ heldStopMarker = marker;
3606
+ else if (continuesTopLevelTurn(frame))
3607
+ releaseHeldToolDones();
3608
+ }
3292
3609
  if (!isSDKMessage(frame)) {
3293
3610
  // Graceful guard (SPEC §8.0): route the raw payload through the lossless
3294
3611
  // vendor channel rather than throwing. Nest under `native` so a payload
@@ -3311,6 +3628,18 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3311
3628
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3312
3629
  // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3313
3630
  closePendingMessage(true);
3631
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
3632
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
3633
+ // "user"` frame carry instead, verbatim, before every close below
3634
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
3635
+ const carriedHeldFrames = new Set();
3636
+ for (const { frame } of heldStopToolDones.splice(0)) {
3637
+ if (carriedHeldFrames.has(frame))
3638
+ continue;
3639
+ carriedHeldFrames.add(frame);
3640
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
3641
+ }
3642
+ heldStopMarker = undefined;
3314
3643
  // B-strict: every subagent run still open closes here with its nested
3315
3644
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3316
3645
  // its subagent.done, innermost first.