@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/src/index.ts CHANGED
@@ -437,10 +437,24 @@ function mcpToolResultContentToAgBlocks(content: McpToolResultContent): AgBlock[
437
437
  // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
438
438
  // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
439
439
  // not carry the tool's own execution output (user-rejected / permission-rule /
440
- // automode-* / interrupted / cancelled); absent means the tool ran to
441
- // completion" (the CLI's own schema doc). Read through the JSON boundary; a
442
- // malformed entry is skipped. The entry itself is NOT carried here (that carry
443
- // is package 15's); only the kind decides the outcome below.
440
+ // automode-* / interrupted / cancelled); absent usually means that the tool ran
441
+ // to completion, but see call_ended" (the CLI's own schema doc, from CLI
442
+ // 2.1.332; earlier: "absent means the tool ran to completion"). Read through the
443
+ // JSON boundary; a malformed entry is skipped. The entry itself is NOT carried
444
+ // here (`readToolResultMetaEntries` carries it); only the kind decides the
445
+ // outcome below.
446
+ //
447
+ // `call_ended` (CLI 2.1.332, same entry) says how a call ended where the kind
448
+ // does not. Its one value, "not_started", marks a call that a replacement
449
+ // process closed without running it, after a permission prompt on an earlier
450
+ // call of the same message was answered or a new message closed it: "nobody
451
+ // stopped or refused this call, so a host shows it as not run". The CLI writes
452
+ // that result with is_error:true and a kind of "cancelled" (after a deny or a
453
+ // new message) or no kind (after an allow). It is not read here: neither case
454
+ // is a refusal, so the call records outcome "error" with isError, by the same
455
+ // rule as every other non-denial kind, and never "denied", which records a
456
+ // refusal that kept a call from running. The entry, call_ended included, rides
457
+ // the tool.done's `_meta` verbatim, so a host can show the call as not run.
444
458
  function readNonExecutionKinds(frame: unknown): Map<string, string> {
445
459
  const out = new Map<string, string>();
446
460
  if (!isJsonObject(frame)) return out;
@@ -733,8 +747,9 @@ function isSDKMessage(v: unknown): v is SDKMessage {
733
747
  const ev = v.event;
734
748
  return isJsonObject(ev) && typeof ev.type === "string";
735
749
  }
736
- // system / status / … — structurally valid SDKMessage arms that carry no
737
- // AgJSON-relevant content. Accept (the normalizer no-ops on them).
750
+ // system / status / … — structurally valid SDKMessage arms. Accept: drive()
751
+ // maps them, carries them on ext.anthropic.frame, or (the studied uncarried
752
+ // subtypes and arms) emits nothing.
738
753
  return typeof t === "string";
739
754
  }
740
755
 
@@ -837,6 +852,27 @@ const CARRIED_SYSTEM_SUBTYPES = new Set<string>([
837
852
  // reasoning-progress event is a draft.3 spec candidate) → whole-frame carry.
838
853
  "thinking_tokens",
839
854
  ]);
855
+ // The system subtypes the facet studied and left uncarried: each SDK member
856
+ // disposed `router-plane` in sdk-surface.json (SDKSystemMessage = init,
857
+ // SDKCompactBoundaryMessage, SDKAPIRetryMessage, SDKControlRequestProgressMessage,
858
+ // SDKHookStartedMessage, SDKPluginInstallMessage, SDKSessionStateChangedMessage,
859
+ // SDKWorkerShuttingDownMessage, SDKCommandsChangedMessage,
860
+ // SDKElicitationCompleteMessage). They emit nothing, as before. Every OTHER
861
+ // subtype without its own branch, declared or not, rides
862
+ // `ext.anthropic.frame{kind: <subtype>, frame}` at the end of `drive()`.
863
+ // Through 0.12.12 / 1.0.0-rc.8 an undeclared subtype was dropped silently.
864
+ const STUDIED_UNCARRIED_SYSTEM_SUBTYPES: ReadonlySet<string> = new Set([
865
+ "init",
866
+ "compact_boundary",
867
+ "api_retry",
868
+ "control_request_progress",
869
+ "hook_started",
870
+ "plugin_install",
871
+ "session_state_changed",
872
+ "worker_shutting_down",
873
+ "commands_changed",
874
+ "elicitation_complete",
875
+ ]);
840
876
  const CARRIED_STANDALONE_TYPES = new Set<string>([
841
877
  "auth_status",
842
878
  "tool_use_summary",
@@ -1087,6 +1123,38 @@ function closeCauseTerminalReason(v: unknown): string | undefined {
1087
1123
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
1088
1124
  }
1089
1125
 
1126
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
1127
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
1128
+ // success turn.done, whichever result arm carries the signal. The signal is
1129
+ // any one of:
1130
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
1131
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
1132
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
1133
+ // (error_during_execution, is_error true) with one of these two, then
1134
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
1135
+ // a subagent run.
1136
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
1137
+ // permission check after repeated refusals.
1138
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
1139
+ // worker shut down.
1140
+ // No capture has shown either flag yet, so their arm is unknown: the check
1141
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
1142
+ // so the frame is read through the JSON boundary, and only a literal `true`
1143
+ // counts. The key is never the result's `errors` text.
1144
+ const INTERRUPTION_TERMINAL_REASONS = new Set<string>(["aborted_streaming", "aborted_tools"]);
1145
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
1146
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
1147
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
1148
+ function resultSignalsInterruption(msg: unknown): boolean {
1149
+ if (!isJsonObject(msg)) return false;
1150
+ const terminalReason = msg["terminal_reason"];
1151
+ return (
1152
+ (typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
1153
+ msg["stopped_by_permission_check"] === true ||
1154
+ msg["interrupted_by_shutdown"] === true
1155
+ );
1156
+ }
1157
+
1090
1158
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
1091
1159
  // on both frames that carry it (the API-error assistant frame and the
1092
1160
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -1109,7 +1177,7 @@ function readStartupFailureReason(v: unknown): string | undefined {
1109
1177
  // The type's own lead sentence frames the whole enum as a refusal to start:
1110
1178
  // "Why Claude Code refused to start, so a host can offer the fix instead of a
1111
1179
  // retry." So a PRESENT reason means NOT retriable, except for the values
1112
- // upstream itself EXPLICITLY describes as retriable. Through 0.3.319 that set is
1180
+ // upstream itself EXPLICITLY describes as retriable. Through 0.3.332 that set is
1113
1181
  // exactly two values:
1114
1182
  // - `worktree_unverified`: "the session's worktree could not be verified
1115
1183
  // right now; retrying may succeed."
@@ -1135,9 +1203,15 @@ function readStartupFailureReason(v: unknown): string | undefined {
1135
1203
  // org_config_refused: "signing in again or an admin's change is the fix, not a
1136
1204
  // retry", 0.3.314's sandbox_required_unavailable: "make the sandbox
1137
1205
  // available or have the requirement changed", 0.3.317's initialize_not_first:
1138
- // "the fix is in the host or the wrapper script, not a retry", and 0.3.318's
1139
- // config_file_invalid: "a retry alone does not help") names a configuration,
1140
- // policy or environment fix, and an unknown future value
1206
+ // "the fix is in the host or the wrapper script, not a retry", 0.3.318's
1207
+ // config_file_invalid: "a retry alone does not help", 0.3.323's
1208
+ // managed_settings_not_delivered: "the fix is in the host or in a wrapper
1209
+ // script between it and Claude Code, not a retry", 0.3.327's
1210
+ // initialize_fields_not_delivered, described as the same failure for
1211
+ // --initialize-fields, and 0.3.331's sideload_flags_disabled: managed
1212
+ // settings refuse the launch's own plugins, agents or MCP servers, with no
1213
+ // retry guidance) names a configuration, policy or environment fix, and an
1214
+ // unknown future value
1141
1215
  // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
1142
1216
  // reason never reaches this function: the error arm keeps its old rule, so
1143
1217
  // older producers are byte-identical.
@@ -1335,9 +1409,10 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
1335
1409
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1336
1410
  const apiErrorStatus =
1337
1411
  isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1338
- // `stop_reason` on a result that closes as turn.error: turn.error has no
1339
- // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1340
- // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1412
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1413
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1414
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1415
+ // verbatim ONLY on such a close;
1341
1416
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1342
1417
  const stopReason =
1343
1418
  closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
@@ -1754,6 +1829,119 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1754
1829
  // tool.done{denied} for a call already closed is a duplicate start and a second
1755
1830
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1756
1831
  const closedToolCallIds = new Set<string>();
1832
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1833
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1834
+ // refusal at the permission prompt also gets, and writes the refusal text
1835
+ // with a correction appended ("this call was stopped while running, not
1836
+ // refused before it ran"). Such a call ran and may have had effects, so it
1837
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1838
+ // for a call kept from running. The detector reads structural signals only,
1839
+ // never the correction text:
1840
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1841
+ // one text block is "[Request interrupted by user for tool use]",
1842
+ // arrives after the tool_result before any frame that continues the
1843
+ // turn (`continuesTopLevelTurn`);
1844
+ // - the decider: the turn's result signals an interruption
1845
+ // (`resultSignalsInterruption`; a Stop during a tool says
1846
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1847
+ // the SDK calls the authoritative record of refusals, does not list the
1848
+ // call.
1849
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1850
+ // the marker and an interrupted result, but its call is in
1851
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1852
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1853
+ // continues the turn, other than the marker, releases it unchanged
1854
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1855
+ // frames (system notices, a subagent's frames, the rest of a stream already
1856
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1857
+ // decides, and the tool.done is emitted from that result's push(), before
1858
+ // the denials carrier and the turn close. The "error" record keeps the
1859
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1860
+ // verbatim, and takes the marker's text as `errorText`, with no
1861
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1862
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1863
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1864
+ // the flush's closes, so the delivered frame is not lost. Nested results
1865
+ // are not held: they keep the stamp's outcome.
1866
+ const heldStopToolDones: Array<{ readonly fields: Parameters<StreamAssembler["toolDone"]>[0]; readonly frame: unknown }> = [];
1867
+ let heldStopMarker: string | undefined;
1868
+ function interruptForToolUseMarker(frame: unknown): string | undefined {
1869
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null) return undefined;
1870
+ const message = frame["message"];
1871
+ const content = isJsonObject(message) ? message["content"] : undefined;
1872
+ if (!Array.isArray(content) || content.length !== 1) return undefined;
1873
+ const only: unknown = content[0];
1874
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1875
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1876
+ : undefined;
1877
+ }
1878
+ // Whether `frame` continues the top-level turn: a top-level assistant
1879
+ // frame, a top-level stream_event that starts a new message
1880
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1881
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1882
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1883
+ // any other type, and the rest of a stream already open (content_block_*,
1884
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1885
+ // task_notification, background_tasks_changed) to the output as they
1886
+ // happen, and the Stop that cuts off a tool call also stops running
1887
+ // background tasks. So those notices can land before or after the marker,
1888
+ // and before the result.
1889
+ // Two kinds of top-level user frame do not continue it either: a replay
1890
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1891
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1892
+ // that cuts off parallel calls stamps each call's result in its own frame,
1893
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1894
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1895
+ // (no CLI path writes one: each cut-off call gets its own frame).
1896
+ function continuesTopLevelTurn(frame: unknown): boolean {
1897
+ if (!isJsonObject(frame)) return false;
1898
+ const type = frame["type"];
1899
+ if (type !== "assistant" && type !== "stream_event" && type !== "user") return false;
1900
+ const parent = frame["parent_tool_use_id"];
1901
+ if (parent !== null && parent !== undefined) return false;
1902
+ if (type === "stream_event") {
1903
+ const event = frame["event"];
1904
+ return isJsonObject(event) && event["type"] === "message_start";
1905
+ }
1906
+ if (type !== "user") return true;
1907
+ if (frame["isReplay"] === true) return false;
1908
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1909
+ if (parent !== null) return true;
1910
+ const message = frame["message"];
1911
+ const content = isJsonObject(message) ? message["content"] : undefined;
1912
+ if (!Array.isArray(content) || content.length === 0) return true;
1913
+ const kinds = readNonExecutionKinds(frame);
1914
+ for (const block of content) {
1915
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true) return true;
1916
+ const id = block["tool_use_id"];
1917
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected") return true;
1918
+ }
1919
+ return false;
1920
+ }
1921
+ // Release every held tool.done: as an interrupted call when the marker was
1922
+ // seen and `result` (the turn's result frame, either arm) signals an
1923
+ // interruption without listing the call in permission_denials; otherwise
1924
+ // unchanged.
1925
+ function releaseHeldToolDones(result?: unknown): void {
1926
+ if (heldStopToolDones.length === 0) return;
1927
+ const held = heldStopToolDones.splice(0);
1928
+ const marker = heldStopMarker;
1929
+ heldStopMarker = undefined;
1930
+ // The marker's text when this result decides "stopped while running".
1931
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1932
+ const listed = new Set<string>();
1933
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1934
+ if (Array.isArray(denials)) {
1935
+ for (const d of denials) if (isJsonObject(d) && typeof d["tool_use_id"] === "string") listed.add(d["tool_use_id"]);
1936
+ }
1937
+ for (const { fields } of held) {
1938
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1939
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1940
+ } else {
1941
+ a.toolDone(fields);
1942
+ }
1943
+ }
1944
+ }
1757
1945
  // SDK message id → the `diagnostics` value already carried for it (see the
1758
1946
  // assistant branch): one carry per response, not one per frame.
1759
1947
  const diagnosticsCarried = new Map<string, string>();
@@ -1824,6 +2012,40 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1824
2012
  return stashed;
1825
2013
  }
1826
2014
 
2015
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
2016
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
2017
+ // result-meta carry, as before every close. turn.abort has no finishReason
2018
+ // slot, so it is built as for an error close and stop_reason rides it. Then
2019
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
2020
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
2021
+ // command_lifecycle frame reports for the interrupted command. The flag
2022
+ // branches use the same value: they have no captured emission yet, and one
2023
+ // value keeps one consumer branch for "the turn was stopped before it
2024
+ // finished".
2025
+ //
2026
+ // turn.abort has no code or message, so the cause rides result-meta, on this
2027
+ // close only: `terminalReason` (the result's terminal_reason, a string,
2028
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
2029
+ // result carries them as booleans, verbatim. Every other close's result-meta
2030
+ // is unchanged. The `errors` text an error-arm result carries (through
2031
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
2032
+ function closeInterruptedTurn(turnId: string, msg: SDKResultMsg): void {
2033
+ const raw: unknown = msg;
2034
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
2035
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
2036
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
2037
+ const resultMeta: { [k: string]: JsonValue } = {
2038
+ ...resultMetaPayload(msg, true),
2039
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
2040
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
2041
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
2042
+ };
2043
+ if (Object.keys(resultMeta).length > 0) {
2044
+ a.emitExt("anthropic", "result-meta", resultMeta);
2045
+ }
2046
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
2047
+ }
2048
+
1827
2049
  // INV-MSG — ONE message id ⇒ ONE message lifecycle.
1828
2050
  //
1829
2051
  // The Claude Agent SDK splits ONE API assistant message across MULTIPLE
@@ -3142,7 +3364,23 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3142
3364
  const run = openRuns.get(parentToolUseId);
3143
3365
  if (run !== undefined) {
3144
3366
  toolTurnId = run.turnId;
3145
- } else {
3367
+ } else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
3368
+ // A run that already CLOSED reopens only for a frame that carries a
3369
+ // tool_result, because that frame's tool.done needs a nested turn to
3370
+ // land in. A closed run's nested frame with no tool_result emits
3371
+ // nothing into a nested turn (it rides the `kind: "user"` carry
3372
+ // above), so it reopens nothing. The live case: after a client
3373
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
3374
+ // by user]" text frame, carrying its parent_tool_use_id, after
3375
+ // task_updated / task_notification has already closed that run as
3376
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
3377
+ // opened an empty second run, which flush then closed as
3378
+ // turn.abort{stream-truncated}. A run this invoke never opened still
3379
+ // opens on any nested user frame: a subagent's first frame is its
3380
+ // prompt, a text-only user frame, and a run that fails before any
3381
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
3382
+ // its turn.error.
3383
+ //
3146
3384
  // A run that CLOSED, or one this invoke never opened (the stream
3147
3385
  // started mid-run: a background agent spanning invokes, a resume):
3148
3386
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -3263,7 +3501,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3263
3501
  // always before this tool_result) rides here instead, the same
3264
3502
  // `_meta` record the carrier gives it, so D drops nothing.
3265
3503
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
3266
- a.toolDone({
3504
+ const doneFields: Parameters<StreamAssembler["toolDone"]>[0] = {
3267
3505
  toolCallId: block.tool_use_id,
3268
3506
  content: toolContent,
3269
3507
  outcome,
@@ -3310,7 +3548,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3310
3548
  });
3311
3549
  return merged !== undefined ? { _meta: merged } : {};
3312
3550
  })(),
3313
- });
3551
+ };
3552
+ // A top-level "user-rejected" result may be a call a client Stop cut
3553
+ // off while it ran, not a refusal: held until a frame that
3554
+ // continues the turn, or the turn's result, shows which (see
3555
+ // `heldStopToolDones`).
3556
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3557
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3558
+ } else {
3559
+ a.toolDone(doneFields);
3560
+ }
3314
3561
  }
3315
3562
  }
3316
3563
  // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
@@ -3328,6 +3575,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3328
3575
  // is NOT closed by its parent's result; it closes when the framework
3329
3576
  // reports it, or at flush.
3330
3577
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3578
+ // A held Stop candidate's tool.done, decided by this result (see
3579
+ // `heldStopToolDones`), while the turn is still open.
3580
+ releaseHeldToolDones(msg);
3331
3581
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
3332
3582
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
3333
3583
  // the final assistant text in result — or, with is_error true, the error
@@ -3363,6 +3613,21 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3363
3613
  // point — its close is deferred to this frame (below), so the turn is
3364
3614
  // still open here, like every other turn.
3365
3615
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3616
+ if (resultSignalsInterruption(msg)) {
3617
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3618
+ // every other close on this arm: the turn was interrupted, so it closes
3619
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3620
+ // refusal or a parked call would otherwise decide. The stash, refusal
3621
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3622
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3623
+ // close. turn.abort carries no usage either. The last round's usage
3624
+ // stays on its message.end, as item 17 allows; the result's turn total
3625
+ // is not carried.
3626
+ refusedTurns.delete(turnId);
3627
+ stopDetailsByTurn.delete(turnId);
3628
+ closeInterruptedTurn(turnId, msg);
3629
+ return;
3630
+ }
3366
3631
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
3367
3632
  // ride `ext.anthropic.result-meta` before the close (no core home on
3368
3633
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -3487,6 +3752,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3487
3752
  // INV-MSG: seal the open assistant message before the turn close.
3488
3753
  closePendingMessage();
3489
3754
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3755
+ releaseHeldToolDones(msg);
3490
3756
  // Consume any stashed assistant-error close for this turnId — this
3491
3757
  // frame emits it (below). Each turn has its own id now, so an entry can
3492
3758
  // only ever be this turn's.
@@ -3520,6 +3786,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3520
3786
  )
3521
3787
  : [];
3522
3788
  emitDenialsCarrier(turnId, denials, msg.session_id);
3789
+ if (resultSignalsInterruption(msg)) {
3790
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3791
+ // close (both consumed above): the turn closes with one turn.abort, not
3792
+ // turn.error. This is the arm a client interrupt reaches:
3793
+ // error_during_execution with terminal_reason "aborted_streaming" or
3794
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3795
+ // turn.error{retriable: true}.
3796
+ closeInterruptedTurn(turnId, msg);
3797
+ return;
3798
+ }
3523
3799
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
3524
3800
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
3525
3801
  // success arm above (turn.error carries no metadata slot at all).
@@ -3695,8 +3971,26 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3695
3971
  return;
3696
3972
  }
3697
3973
 
3698
- // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
3699
- // content on this seam → no events.
3974
+ // A `system` frame whose subtype has no branch above and is not one the
3975
+ // facet studied and left uncarried (see STUDIED_UNCARRIED_SYSTEM_SUBTYPES):
3976
+ // carried whole, never silently dropped (SPEC §8.0 "MUST NOT silently drop
3977
+ // a native event it cannot map"; §8 item 22 names the subtype as the frame
3978
+ // kind). The CLI adds subtypes without a d.ts entry, so the next one is
3979
+ // carried the day it ships. A subtype that is not a string rides as kind
3980
+ // "system".
3981
+ if (msg.type === "system") {
3982
+ const raw: unknown = msg;
3983
+ const subtype = isJsonObject(raw) ? raw["subtype"] : undefined;
3984
+ const kind = typeof subtype === "string" ? subtype : "system";
3985
+ if (!STUDIED_UNCARRIED_SYSTEM_SUBTYPES.has(kind)) {
3986
+ a.emitExt("anthropic", "frame", { kind, frame: carryVerbatim(msg) });
3987
+ return;
3988
+ }
3989
+ }
3990
+
3991
+ // The studied uncarried variants (the system subtypes above, tool_progress,
3992
+ // rate_limit_event) carry no AgJSON-relevant content on this seam → no
3993
+ // events.
3700
3994
  }
3701
3995
 
3702
3996
  return {
@@ -3706,6 +4000,15 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3706
4000
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3707
4001
  // frame is the same reference, anything else its JSON form).
3708
4002
  const frame = native;
4003
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
4004
+ // it held for the turn's result to decide. A frame that continues the
4005
+ // turn releases it unchanged before that frame is handled; a result
4006
+ // decides it, and any other frame leaves it held.
4007
+ if (heldStopToolDones.length > 0) {
4008
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
4009
+ if (marker !== undefined) heldStopMarker = marker;
4010
+ else if (continuesTopLevelTurn(frame)) releaseHeldToolDones();
4011
+ }
3709
4012
  if (!isSDKMessage(frame)) {
3710
4013
  // Graceful guard (SPEC §8.0): route the raw payload through the lossless
3711
4014
  // vendor channel rather than throwing. Nest under `native` so a payload
@@ -3728,6 +4031,17 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3728
4031
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3729
4032
  // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3730
4033
  closePendingMessage(true);
4034
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
4035
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
4036
+ // "user"` frame carry instead, verbatim, before every close below
4037
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
4038
+ const carriedHeldFrames = new Set<unknown>();
4039
+ for (const { frame } of heldStopToolDones.splice(0)) {
4040
+ if (carriedHeldFrames.has(frame)) continue;
4041
+ carriedHeldFrames.add(frame);
4042
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
4043
+ }
4044
+ heldStopMarker = undefined;
3731
4045
  // B-strict: every subagent run still open closes here with its nested
3732
4046
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3733
4047
  // its subagent.done, innermost first.