@silverprotocol/claude-agent-sdk 0.12.11 → 0.12.13

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
@@ -77,6 +77,17 @@ events.push(...n.flush()); // seal anything still open at end-of-stream
77
77
  Malformed input never throws — it routes through the lossless
78
78
  `ext.anthropic.unparsed` channel instead.
79
79
 
80
+ ### Unmapped frames
81
+
82
+ A `system` frame whose subtype the facet neither maps nor has reviewed as
83
+ carrying no turn content rides `ext.anthropic.frame` whole, with `kind` set to
84
+ the subtype (`"system"` when the subtype is not a string). A top-level frame
85
+ type the SDK does not declare rides the same way, with `kind` set to that type.
86
+ The CLI adds subtypes without a type entry, so such a frame can hold local
87
+ paths, the git branch, hook command lines and free text. Only
88
+ `fallback_credit_token` keys are removed, at any depth. A host that relays ext
89
+ events to another party should filter them by `kind`.
90
+
80
91
  ### Thread id
81
92
 
82
93
  Pass the host's own thread id as `createClaudeNormalizer({ threadId })`. The
@@ -161,6 +172,46 @@ Usage follows the AgJSON draft.5 accounting rules (spec §4):
161
172
  its usage only when an API-error assistant message had already ended the
162
173
  turn; otherwise its `turn.error` carries none.
163
174
 
175
+ ### Interrupted turns
176
+
177
+ A result that reports an interruption closes the turn with one
178
+ `turn.abort { reason: "cancelled" }`, never with `turn.error` or `turn.done`
179
+ (SPEC §8.0 item 17). An interruption is any of: `terminal_reason`
180
+ `"aborted_streaming"` or `"aborted_tools"`, `stopped_by_permission_check: true`,
181
+ or `interrupted_by_shutdown: true`. Either result arm counts, and the check
182
+ comes before every other close the result would make. A client Stop
183
+ (`Query.interrupt()`) ends the turn this way: the CLI sends an
184
+ `error_during_execution` result with one of those two `terminal_reason`
185
+ values. `turn.abort` carries no usage: each round's usage stays on its
186
+ `message.end`, and the result's turn total is not carried. The result's
187
+ `stop_reason` rides `ext.anthropic.result-meta`, as on an error close. On
188
+ this close only, result-meta also carries the cause: `terminalReason` (the
189
+ result's `terminal_reason`) and, when the result carries them,
190
+ `stoppedByPermissionCheck` and `interruptedByShutdown`. The result's
191
+ `errors` text is not carried. A subagent run the CLI stops closes its
192
+ nested turn with `turn.abort { reason: "stopped" }`.
193
+
194
+ A tool call the Stop cut off while it ran records `tool.done` with
195
+ `outcome: "error"`, `isError: true` and `errorText` set to the CLI's
196
+ interrupt marker, `"[Request interrupted by user for tool use]"`; its content
197
+ and its `non_execution_kind: "user-rejected"` stamp (in `_meta`) stay
198
+ verbatim. The CLI stamps such a call the way it stamps a refusal, so the
199
+ facet holds that `tool.done` until a frame that continues the turn arrives:
200
+ a top-level assistant frame, a top-level `message_start` stream event, or a
201
+ top-level user frame other than the interrupt marker. The turn's result
202
+ decides it too. System frames, a subagent's frames, replay acks and the rest
203
+ of a stream already open leave it held: the CLI writes background-task
204
+ notices as they happen, so they can land on either side of the marker. A
205
+ top-level frame whose every `tool_result` is an `is_error` result stamped the
206
+ same way joins the hold: a Stop that cuts off parallel calls stamps each
207
+ call's result in its own frame. When the interrupt marker arrives first and
208
+ the turn's result reports an interruption without listing the call in
209
+ `permission_denials`, the call ran and was stopped. Otherwise it
210
+ was refused, and stays `outcome: "denied"`. A stream that ends while the
211
+ `tool.done` is held emits no `tool.done`, because a flush emits none; the
212
+ held tool_result frame rides `ext.anthropic.frame` (`kind: "user"`)
213
+ verbatim instead, before the turn closes.
214
+
164
215
  ### Turn trigger
165
216
 
166
217
  When the frame that opens a top-level turn is an assistant message, a streamed
@@ -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;AAstCD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAqpED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAIxF;AAED,eAAe,sBAAsB,CAAC;AACtC,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;AA6wCD,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAm4ED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CAIxF;AAED,eAAe,sBAAsB,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -592,8 +592,9 @@ function isSDKMessage(v) {
592
592
  const ev = v.event;
593
593
  return isJsonObject(ev) && typeof ev.type === "string";
594
594
  }
595
- // system / status / … — structurally valid SDKMessage arms that carry no
596
- // AgJSON-relevant content. Accept (the normalizer no-ops on them).
595
+ // system / status / … — structurally valid SDKMessage arms. Accept: drive()
596
+ // maps them, carries them on ext.anthropic.frame, or (the studied uncarried
597
+ // subtypes and arms) emits nothing.
597
598
  return typeof t === "string";
598
599
  }
599
600
  // ─── uniform lossless carry: 17 claude arms — the fixture-drift ratchet's
@@ -685,6 +686,27 @@ const CARRIED_SYSTEM_SUBTYPES = new Set([
685
686
  // reasoning-progress event is a draft.3 spec candidate) → whole-frame carry.
686
687
  "thinking_tokens",
687
688
  ]);
689
+ // The system subtypes the facet studied and left uncarried: each SDK member
690
+ // disposed `router-plane` in sdk-surface.json (SDKSystemMessage = init,
691
+ // SDKCompactBoundaryMessage, SDKAPIRetryMessage, SDKControlRequestProgressMessage,
692
+ // SDKHookStartedMessage, SDKPluginInstallMessage, SDKSessionStateChangedMessage,
693
+ // SDKWorkerShuttingDownMessage, SDKCommandsChangedMessage,
694
+ // SDKElicitationCompleteMessage). They emit nothing, as before. Every OTHER
695
+ // subtype without its own branch, declared or not, rides
696
+ // `ext.anthropic.frame{kind: <subtype>, frame}` at the end of `drive()`.
697
+ // Through 0.12.12 an undeclared subtype was dropped silently.
698
+ const STUDIED_UNCARRIED_SYSTEM_SUBTYPES = new Set([
699
+ "init",
700
+ "compact_boundary",
701
+ "api_retry",
702
+ "control_request_progress",
703
+ "hook_started",
704
+ "plugin_install",
705
+ "session_state_changed",
706
+ "worker_shutting_down",
707
+ "commands_changed",
708
+ "elicitation_complete",
709
+ ]);
688
710
  const CARRIED_STANDALONE_TYPES = new Set([
689
711
  "auth_status",
690
712
  "tool_use_summary",
@@ -929,6 +951,36 @@ function readDeferredCall(v) {
929
951
  function closeCauseTerminalReason(v) {
930
952
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
931
953
  }
954
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
955
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
956
+ // success turn.done, whichever result arm carries the signal. The signal is
957
+ // any one of:
958
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
959
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
960
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
961
+ // (error_during_execution, is_error true) with one of these two, then
962
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
963
+ // a subagent run.
964
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
965
+ // permission check after repeated refusals.
966
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
967
+ // worker shut down.
968
+ // No capture has shown either flag yet, so their arm is unknown: the check
969
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
970
+ // so the frame is read through the JSON boundary, and only a literal `true`
971
+ // counts. The key is never the result's `errors` text.
972
+ const INTERRUPTION_TERMINAL_REASONS = new Set(["aborted_streaming", "aborted_tools"]);
973
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
974
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
975
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
976
+ function resultSignalsInterruption(msg) {
977
+ if (!isJsonObject(msg))
978
+ return false;
979
+ const terminalReason = msg["terminal_reason"];
980
+ return ((typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
981
+ msg["stopped_by_permission_check"] === true ||
982
+ msg["interrupted_by_shutdown"] === true);
983
+ }
932
984
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
933
985
  // on both frames that carry it (the API-error assistant frame and the
934
986
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -1147,9 +1199,10 @@ function resultMetaPayload(msg, closesAsError) {
1147
1199
  // the census allowlist's "carry candidate the first time an error seed
1148
1200
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1149
1201
  const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1150
- // `stop_reason` on a result that closes as turn.error: turn.error has no
1151
- // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1152
- // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1202
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1203
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1204
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1205
+ // verbatim ONLY on such a close;
1153
1206
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1154
1207
  const stopReason = closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
1155
1208
  const payload = {
@@ -1397,6 +1450,134 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1397
1450
  // tool.done{denied} for a call already closed is a duplicate start and a second
1398
1451
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1399
1452
  const closedToolCallIds = new Set();
1453
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1454
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1455
+ // refusal at the permission prompt also gets, and writes the refusal text
1456
+ // with a correction appended ("this call was stopped while running, not
1457
+ // refused before it ran"). Such a call ran and may have had effects, so it
1458
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1459
+ // for a call kept from running. The detector reads structural signals only,
1460
+ // never the correction text:
1461
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1462
+ // one text block is "[Request interrupted by user for tool use]",
1463
+ // arrives after the tool_result before any frame that continues the
1464
+ // turn (`continuesTopLevelTurn`);
1465
+ // - the decider: the turn's result signals an interruption
1466
+ // (`resultSignalsInterruption`; a Stop during a tool says
1467
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1468
+ // the SDK calls the authoritative record of refusals, does not list the
1469
+ // call.
1470
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1471
+ // the marker and an interrupted result, but its call is in
1472
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1473
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1474
+ // continues the turn, other than the marker, releases it unchanged
1475
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1476
+ // frames (system notices, a subagent's frames, the rest of a stream already
1477
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1478
+ // decides, and the tool.done is emitted from that result's push(), before
1479
+ // the denials carrier and the turn close. The "error" record keeps the
1480
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1481
+ // verbatim, and takes the marker's text as `errorText`, with no
1482
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1483
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1484
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1485
+ // the flush's closes, so the delivered frame is not lost. Nested results
1486
+ // are not held: they keep the stamp's outcome.
1487
+ const heldStopToolDones = [];
1488
+ let heldStopMarker;
1489
+ function interruptForToolUseMarker(frame) {
1490
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null)
1491
+ return undefined;
1492
+ const message = frame["message"];
1493
+ const content = isJsonObject(message) ? message["content"] : undefined;
1494
+ if (!Array.isArray(content) || content.length !== 1)
1495
+ return undefined;
1496
+ const only = content[0];
1497
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1498
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1499
+ : undefined;
1500
+ }
1501
+ // Whether `frame` continues the top-level turn: a top-level assistant
1502
+ // frame, a top-level stream_event that starts a new message
1503
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1504
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1505
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1506
+ // any other type, and the rest of a stream already open (content_block_*,
1507
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1508
+ // task_notification, background_tasks_changed) to the output as they
1509
+ // happen, and the Stop that cuts off a tool call also stops running
1510
+ // background tasks. So those notices can land before or after the marker,
1511
+ // and before the result.
1512
+ // Two kinds of top-level user frame do not continue it either: a replay
1513
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1514
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1515
+ // that cuts off parallel calls stamps each call's result in its own frame,
1516
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1517
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1518
+ // (no CLI path writes one: each cut-off call gets its own frame).
1519
+ function continuesTopLevelTurn(frame) {
1520
+ if (!isJsonObject(frame))
1521
+ return false;
1522
+ const type = frame["type"];
1523
+ if (type !== "assistant" && type !== "stream_event" && type !== "user")
1524
+ return false;
1525
+ const parent = frame["parent_tool_use_id"];
1526
+ if (parent !== null && parent !== undefined)
1527
+ return false;
1528
+ if (type === "stream_event") {
1529
+ const event = frame["event"];
1530
+ return isJsonObject(event) && event["type"] === "message_start";
1531
+ }
1532
+ if (type !== "user")
1533
+ return true;
1534
+ if (frame["isReplay"] === true)
1535
+ return false;
1536
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1537
+ if (parent !== null)
1538
+ return true;
1539
+ const message = frame["message"];
1540
+ const content = isJsonObject(message) ? message["content"] : undefined;
1541
+ if (!Array.isArray(content) || content.length === 0)
1542
+ return true;
1543
+ const kinds = readNonExecutionKinds(frame);
1544
+ for (const block of content) {
1545
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true)
1546
+ return true;
1547
+ const id = block["tool_use_id"];
1548
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected")
1549
+ return true;
1550
+ }
1551
+ return false;
1552
+ }
1553
+ // Release every held tool.done: as an interrupted call when the marker was
1554
+ // seen and `result` (the turn's result frame, either arm) signals an
1555
+ // interruption without listing the call in permission_denials; otherwise
1556
+ // unchanged.
1557
+ function releaseHeldToolDones(result) {
1558
+ if (heldStopToolDones.length === 0)
1559
+ return;
1560
+ const held = heldStopToolDones.splice(0);
1561
+ const marker = heldStopMarker;
1562
+ heldStopMarker = undefined;
1563
+ // The marker's text when this result decides "stopped while running".
1564
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1565
+ const listed = new Set();
1566
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1567
+ if (Array.isArray(denials)) {
1568
+ for (const d of denials)
1569
+ if (isJsonObject(d) && typeof d["tool_use_id"] === "string")
1570
+ listed.add(d["tool_use_id"]);
1571
+ }
1572
+ for (const { fields } of held) {
1573
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1574
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1575
+ }
1576
+ else {
1577
+ a.toolDone(fields);
1578
+ }
1579
+ }
1580
+ }
1400
1581
  // SDK message id → the `diagnostics` value already carried for it (see the
1401
1582
  // assistant branch): one carry per response, not one per frame.
1402
1583
  const diagnosticsCarried = new Map();
@@ -1429,6 +1610,39 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1429
1610
  stashedTurnErrors.delete(turnId);
1430
1611
  return stashed;
1431
1612
  }
1613
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
1614
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
1615
+ // result-meta carry, as before every close. turn.abort has no finishReason
1616
+ // slot, so it is built as for an error close and stop_reason rides it. Then
1617
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
1618
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
1619
+ // command_lifecycle frame reports for the interrupted command. The flag
1620
+ // branches use the same value: they have no captured emission yet, and one
1621
+ // value keeps one consumer branch for "the turn was stopped before it
1622
+ // finished".
1623
+ //
1624
+ // turn.abort has no code or message, so the cause rides result-meta, on this
1625
+ // close only: `terminalReason` (the result's terminal_reason, a string,
1626
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
1627
+ // result carries them as booleans, verbatim. Every other close's result-meta
1628
+ // is unchanged. The `errors` text an error-arm result carries (through
1629
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
1630
+ function closeInterruptedTurn(turnId, msg) {
1631
+ const raw = msg;
1632
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
1633
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
1634
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
1635
+ const resultMeta = {
1636
+ ...resultMetaPayload(msg, true),
1637
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
1638
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
1639
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
1640
+ };
1641
+ if (Object.keys(resultMeta).length > 0) {
1642
+ a.emitExt("anthropic", "result-meta", resultMeta);
1643
+ }
1644
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
1645
+ }
1432
1646
  let pending;
1433
1647
  // How many lifecycles each SDK message id has already opened. A same-id frame
1434
1648
  // arriving after its lifecycle closed (a fold-binding frame landed between two
@@ -2612,7 +2826,23 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2612
2826
  if (run !== undefined) {
2613
2827
  toolTurnId = run.turnId;
2614
2828
  }
2615
- else {
2829
+ else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
2830
+ // A run that already CLOSED reopens only for a frame that carries a
2831
+ // tool_result, because that frame's tool.done needs a nested turn to
2832
+ // land in. A closed run's nested frame with no tool_result emits
2833
+ // nothing into a nested turn (it rides the `kind: "user"` carry
2834
+ // above), so it reopens nothing. The live case: after a client
2835
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
2836
+ // by user]" text frame, carrying its parent_tool_use_id, after
2837
+ // task_updated / task_notification has already closed that run as
2838
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
2839
+ // opened an empty second run, which flush then closed as
2840
+ // turn.abort{stream-truncated}. A run this invoke never opened still
2841
+ // opens on any nested user frame: a subagent's first frame is its
2842
+ // prompt, a text-only user frame, and a run that fails before any
2843
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
2844
+ // its turn.error.
2845
+ //
2616
2846
  // A run that CLOSED, or one this invoke never opened (the stream
2617
2847
  // started mid-run: a background agent spanning invokes, a resume):
2618
2848
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -2728,7 +2958,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2728
2958
  // always before this tool_result) rides here instead, the same
2729
2959
  // `_meta` record the carrier gives it, so D drops nothing.
2730
2960
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2731
- a.toolDone({
2961
+ const doneFields = {
2732
2962
  toolCallId: block.tool_use_id,
2733
2963
  content: toolContent,
2734
2964
  outcome,
@@ -2775,7 +3005,17 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2775
3005
  });
2776
3006
  return merged !== undefined ? { _meta: merged } : {};
2777
3007
  })(),
2778
- });
3008
+ };
3009
+ // A top-level "user-rejected" result may be a call a client Stop cut
3010
+ // off while it ran, not a refusal: held until a frame that
3011
+ // continues the turn, or the turn's result, shows which (see
3012
+ // `heldStopToolDones`).
3013
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3014
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3015
+ }
3016
+ else {
3017
+ a.toolDone(doneFields);
3018
+ }
2779
3019
  }
2780
3020
  }
2781
3021
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
@@ -2792,6 +3032,9 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2792
3032
  // is NOT closed by its parent's result; it closes when the framework
2793
3033
  // reports it, or at flush.
2794
3034
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3035
+ // A held Stop candidate's tool.done, decided by this result (see
3036
+ // `heldStopToolDones`), while the turn is still open.
3037
+ releaseHeldToolDones(msg);
2795
3038
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
2796
3039
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
2797
3040
  // the final assistant text in result — or, with is_error true, the error
@@ -2825,6 +3068,20 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2825
3068
  // point — its close is deferred to this frame (below), so the turn is
2826
3069
  // still open here, like every other turn.
2827
3070
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3071
+ if (resultSignalsInterruption(msg)) {
3072
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3073
+ // every other close on this arm: the turn was interrupted, so it closes
3074
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3075
+ // refusal or a parked call would otherwise decide. The stash, refusal
3076
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3077
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3078
+ // close. turn.abort carries no usage either. The last round's usage
3079
+ // stays on its message.end, as item 17 allows; the result's turn total
3080
+ // is not carried.
3081
+ stopDetailsByTurn.delete(turnId);
3082
+ closeInterruptedTurn(turnId, msg);
3083
+ return;
3084
+ }
2828
3085
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
2829
3086
  // ride `ext.anthropic.result-meta` before the close (no core home on
2830
3087
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -2921,6 +3178,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2921
3178
  // INV-MSG: seal the open assistant message before the turn close.
2922
3179
  closePendingMessage();
2923
3180
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3181
+ releaseHeldToolDones(msg);
2924
3182
  // Consume any stashed assistant-error close for this turnId — this
2925
3183
  // frame emits it (below). Each turn has its own id now, so an entry can
2926
3184
  // only ever be this turn's.
@@ -2950,6 +3208,16 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2950
3208
  : [])
2951
3209
  : [];
2952
3210
  emitDenialsCarrier(turnId, denials, msg.session_id);
3211
+ if (resultSignalsInterruption(msg)) {
3212
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3213
+ // close (both consumed above): the turn closes with one turn.abort, not
3214
+ // turn.error. This is the arm a client interrupt reaches:
3215
+ // error_during_execution with terminal_reason "aborted_streaming" or
3216
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3217
+ // turn.error{retriable: true}.
3218
+ closeInterruptedTurn(turnId, msg);
3219
+ return;
3220
+ }
2953
3221
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
2954
3222
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
2955
3223
  // success arm above (turn.error carries no metadata slot at all).
@@ -3119,8 +3387,25 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3119
3387
  a.emitExt("anthropic", "frame", { kind: topLevelType, frame: carryVerbatim(msg) });
3120
3388
  return;
3121
3389
  }
3122
- // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
3123
- // content on this seam → no events.
3390
+ // A `system` frame whose subtype has no branch above and is not one the
3391
+ // facet studied and left uncarried (see STUDIED_UNCARRIED_SYSTEM_SUBTYPES):
3392
+ // carried whole, never silently dropped (SPEC §8.0 "MUST NOT silently drop
3393
+ // a native event it cannot map"; §8 item 22 names the subtype as the frame
3394
+ // kind). The CLI adds subtypes without a d.ts entry, so the next one is
3395
+ // carried the day it ships. A subtype that is not a string rides as kind
3396
+ // "system".
3397
+ if (msg.type === "system") {
3398
+ const raw = msg;
3399
+ const subtype = isJsonObject(raw) ? raw["subtype"] : undefined;
3400
+ const kind = typeof subtype === "string" ? subtype : "system";
3401
+ if (!STUDIED_UNCARRIED_SYSTEM_SUBTYPES.has(kind)) {
3402
+ a.emitExt("anthropic", "frame", { kind, frame: carryVerbatim(msg) });
3403
+ return;
3404
+ }
3405
+ }
3406
+ // The studied uncarried variants (the system subtypes above, tool_progress,
3407
+ // rate_limit_event) carry no AgJSON-relevant content on this seam → no
3408
+ // events.
3124
3409
  }
3125
3410
  return {
3126
3411
  push(native) {
@@ -3129,6 +3414,17 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3129
3414
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3130
3415
  // frame is the same reference, anything else its JSON form).
3131
3416
  const frame = native;
3417
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
3418
+ // it held for the turn's result to decide. A frame that continues the
3419
+ // turn releases it unchanged before that frame is handled; a result
3420
+ // decides it, and any other frame leaves it held.
3421
+ if (heldStopToolDones.length > 0) {
3422
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
3423
+ if (marker !== undefined)
3424
+ heldStopMarker = marker;
3425
+ else if (continuesTopLevelTurn(frame))
3426
+ releaseHeldToolDones();
3427
+ }
3132
3428
  if (!isSDKMessage(frame)) {
3133
3429
  // Graceful guard (Tenet 6): route the raw payload through the lossless
3134
3430
  // vendor channel rather than throwing. Nest under `native` so a payload
@@ -3151,6 +3447,18 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3151
3447
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3152
3448
  // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3153
3449
  closePendingMessage(true);
3450
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
3451
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
3452
+ // "user"` frame carry instead, verbatim, before every close below
3453
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
3454
+ const carriedHeldFrames = new Set();
3455
+ for (const { frame } of heldStopToolDones.splice(0)) {
3456
+ if (carriedHeldFrames.has(frame))
3457
+ continue;
3458
+ carriedHeldFrames.add(frame);
3459
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
3460
+ }
3461
+ heldStopMarker = undefined;
3154
3462
  // B-strict: every subagent run still open closes here with its nested
3155
3463
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3156
3464
  // its subagent.done, innermost first.