@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/src/index.ts CHANGED
@@ -733,8 +733,9 @@ function isSDKMessage(v: unknown): v is SDKMessage {
733
733
  const ev = v.event;
734
734
  return isJsonObject(ev) && typeof ev.type === "string";
735
735
  }
736
- // system / status / … — structurally valid SDKMessage arms that carry no
737
- // AgJSON-relevant content. Accept (the normalizer no-ops on them).
736
+ // system / status / … — structurally valid SDKMessage arms. Accept: drive()
737
+ // maps them, carries them on ext.anthropic.frame, or (the studied uncarried
738
+ // subtypes and arms) emits nothing.
738
739
  return typeof t === "string";
739
740
  }
740
741
 
@@ -827,6 +828,27 @@ const CARRIED_SYSTEM_SUBTYPES = new Set<string>([
827
828
  // reasoning-progress event is a draft.3 spec candidate) → whole-frame carry.
828
829
  "thinking_tokens",
829
830
  ]);
831
+ // The system subtypes the facet studied and left uncarried: each SDK member
832
+ // disposed `router-plane` in sdk-surface.json (SDKSystemMessage = init,
833
+ // SDKCompactBoundaryMessage, SDKAPIRetryMessage, SDKControlRequestProgressMessage,
834
+ // SDKHookStartedMessage, SDKPluginInstallMessage, SDKSessionStateChangedMessage,
835
+ // SDKWorkerShuttingDownMessage, SDKCommandsChangedMessage,
836
+ // SDKElicitationCompleteMessage). They emit nothing, as before. Every OTHER
837
+ // subtype without its own branch, declared or not, rides
838
+ // `ext.anthropic.frame{kind: <subtype>, frame}` at the end of `drive()`.
839
+ // Through 0.12.12 an undeclared subtype was dropped silently.
840
+ const STUDIED_UNCARRIED_SYSTEM_SUBTYPES: ReadonlySet<string> = new Set([
841
+ "init",
842
+ "compact_boundary",
843
+ "api_retry",
844
+ "control_request_progress",
845
+ "hook_started",
846
+ "plugin_install",
847
+ "session_state_changed",
848
+ "worker_shutting_down",
849
+ "commands_changed",
850
+ "elicitation_complete",
851
+ ]);
830
852
  const CARRIED_STANDALONE_TYPES = new Set<string>([
831
853
  "auth_status",
832
854
  "tool_use_summary",
@@ -1077,6 +1099,38 @@ function closeCauseTerminalReason(v: unknown): string | undefined {
1077
1099
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
1078
1100
  }
1079
1101
 
1102
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
1103
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
1104
+ // success turn.done, whichever result arm carries the signal. The signal is
1105
+ // any one of:
1106
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
1107
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
1108
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
1109
+ // (error_during_execution, is_error true) with one of these two, then
1110
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
1111
+ // a subagent run.
1112
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
1113
+ // permission check after repeated refusals.
1114
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
1115
+ // worker shut down.
1116
+ // No capture has shown either flag yet, so their arm is unknown: the check
1117
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
1118
+ // so the frame is read through the JSON boundary, and only a literal `true`
1119
+ // counts. The key is never the result's `errors` text.
1120
+ const INTERRUPTION_TERMINAL_REASONS = new Set<string>(["aborted_streaming", "aborted_tools"]);
1121
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
1122
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
1123
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
1124
+ function resultSignalsInterruption(msg: unknown): boolean {
1125
+ if (!isJsonObject(msg)) return false;
1126
+ const terminalReason = msg["terminal_reason"];
1127
+ return (
1128
+ (typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
1129
+ msg["stopped_by_permission_check"] === true ||
1130
+ msg["interrupted_by_shutdown"] === true
1131
+ );
1132
+ }
1133
+
1080
1134
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
1081
1135
  // on both frames that carry it (the API-error assistant frame and the
1082
1136
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -1301,9 +1355,10 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
1301
1355
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1302
1356
  const apiErrorStatus =
1303
1357
  isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1304
- // `stop_reason` on a result that closes as turn.error: turn.error has no
1305
- // finishReason slot (and finishReasonRaw is turn.done-only), so the native
1306
- // value would otherwise be dropped. Carried verbatim ONLY on an error close;
1358
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1359
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1360
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1361
+ // verbatim ONLY on such a close;
1307
1362
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1308
1363
  const stopReason =
1309
1364
  closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
@@ -1656,6 +1711,119 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1656
1711
  // tool.done{denied} for a call already closed is a duplicate start and a second
1657
1712
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1658
1713
  const closedToolCallIds = new Set<string>();
1714
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1715
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1716
+ // refusal at the permission prompt also gets, and writes the refusal text
1717
+ // with a correction appended ("this call was stopped while running, not
1718
+ // refused before it ran"). Such a call ran and may have had effects, so it
1719
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1720
+ // for a call kept from running. The detector reads structural signals only,
1721
+ // never the correction text:
1722
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1723
+ // one text block is "[Request interrupted by user for tool use]",
1724
+ // arrives after the tool_result before any frame that continues the
1725
+ // turn (`continuesTopLevelTurn`);
1726
+ // - the decider: the turn's result signals an interruption
1727
+ // (`resultSignalsInterruption`; a Stop during a tool says
1728
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1729
+ // the SDK calls the authoritative record of refusals, does not list the
1730
+ // call.
1731
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1732
+ // the marker and an interrupted result, but its call is in
1733
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1734
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1735
+ // continues the turn, other than the marker, releases it unchanged
1736
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1737
+ // frames (system notices, a subagent's frames, the rest of a stream already
1738
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1739
+ // decides, and the tool.done is emitted from that result's push(), before
1740
+ // the denials carrier and the turn close. The "error" record keeps the
1741
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1742
+ // verbatim, and takes the marker's text as `errorText`, with no
1743
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1744
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1745
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1746
+ // the flush's closes, so the delivered frame is not lost. Nested results
1747
+ // are not held: they keep the stamp's outcome.
1748
+ const heldStopToolDones: Array<{ readonly fields: Parameters<StreamAssembler["toolDone"]>[0]; readonly frame: unknown }> = [];
1749
+ let heldStopMarker: string | undefined;
1750
+ function interruptForToolUseMarker(frame: unknown): string | undefined {
1751
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null) return undefined;
1752
+ const message = frame["message"];
1753
+ const content = isJsonObject(message) ? message["content"] : undefined;
1754
+ if (!Array.isArray(content) || content.length !== 1) return undefined;
1755
+ const only: unknown = content[0];
1756
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1757
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1758
+ : undefined;
1759
+ }
1760
+ // Whether `frame` continues the top-level turn: a top-level assistant
1761
+ // frame, a top-level stream_event that starts a new message
1762
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1763
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1764
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1765
+ // any other type, and the rest of a stream already open (content_block_*,
1766
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1767
+ // task_notification, background_tasks_changed) to the output as they
1768
+ // happen, and the Stop that cuts off a tool call also stops running
1769
+ // background tasks. So those notices can land before or after the marker,
1770
+ // and before the result.
1771
+ // Two kinds of top-level user frame do not continue it either: a replay
1772
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1773
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1774
+ // that cuts off parallel calls stamps each call's result in its own frame,
1775
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1776
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1777
+ // (no CLI path writes one: each cut-off call gets its own frame).
1778
+ function continuesTopLevelTurn(frame: unknown): boolean {
1779
+ if (!isJsonObject(frame)) return false;
1780
+ const type = frame["type"];
1781
+ if (type !== "assistant" && type !== "stream_event" && type !== "user") return false;
1782
+ const parent = frame["parent_tool_use_id"];
1783
+ if (parent !== null && parent !== undefined) return false;
1784
+ if (type === "stream_event") {
1785
+ const event = frame["event"];
1786
+ return isJsonObject(event) && event["type"] === "message_start";
1787
+ }
1788
+ if (type !== "user") return true;
1789
+ if (frame["isReplay"] === true) return false;
1790
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1791
+ if (parent !== null) return true;
1792
+ const message = frame["message"];
1793
+ const content = isJsonObject(message) ? message["content"] : undefined;
1794
+ if (!Array.isArray(content) || content.length === 0) return true;
1795
+ const kinds = readNonExecutionKinds(frame);
1796
+ for (const block of content) {
1797
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true) return true;
1798
+ const id = block["tool_use_id"];
1799
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected") return true;
1800
+ }
1801
+ return false;
1802
+ }
1803
+ // Release every held tool.done: as an interrupted call when the marker was
1804
+ // seen and `result` (the turn's result frame, either arm) signals an
1805
+ // interruption without listing the call in permission_denials; otherwise
1806
+ // unchanged.
1807
+ function releaseHeldToolDones(result?: unknown): void {
1808
+ if (heldStopToolDones.length === 0) return;
1809
+ const held = heldStopToolDones.splice(0);
1810
+ const marker = heldStopMarker;
1811
+ heldStopMarker = undefined;
1812
+ // The marker's text when this result decides "stopped while running".
1813
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1814
+ const listed = new Set<string>();
1815
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1816
+ if (Array.isArray(denials)) {
1817
+ for (const d of denials) if (isJsonObject(d) && typeof d["tool_use_id"] === "string") listed.add(d["tool_use_id"]);
1818
+ }
1819
+ for (const { fields } of held) {
1820
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1821
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1822
+ } else {
1823
+ a.toolDone(fields);
1824
+ }
1825
+ }
1826
+ }
1659
1827
  // SDK message id → the `diagnostics` value already carried for it (see the
1660
1828
  // assistant branch): one carry per response, not one per frame.
1661
1829
  const diagnosticsCarried = new Map<string, string>();
@@ -1718,6 +1886,40 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1718
1886
  return stashed;
1719
1887
  }
1720
1888
 
1889
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
1890
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
1891
+ // result-meta carry, as before every close. turn.abort has no finishReason
1892
+ // slot, so it is built as for an error close and stop_reason rides it. Then
1893
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
1894
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
1895
+ // command_lifecycle frame reports for the interrupted command. The flag
1896
+ // branches use the same value: they have no captured emission yet, and one
1897
+ // value keeps one consumer branch for "the turn was stopped before it
1898
+ // finished".
1899
+ //
1900
+ // turn.abort has no code or message, so the cause rides result-meta, on this
1901
+ // close only: `terminalReason` (the result's terminal_reason, a string,
1902
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
1903
+ // result carries them as booleans, verbatim. Every other close's result-meta
1904
+ // is unchanged. The `errors` text an error-arm result carries (through
1905
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
1906
+ function closeInterruptedTurn(turnId: string, msg: SDKResultMsg): void {
1907
+ const raw: unknown = msg;
1908
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
1909
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
1910
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
1911
+ const resultMeta: { [k: string]: JsonValue } = {
1912
+ ...resultMetaPayload(msg, true),
1913
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
1914
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
1915
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
1916
+ };
1917
+ if (Object.keys(resultMeta).length > 0) {
1918
+ a.emitExt("anthropic", "result-meta", resultMeta);
1919
+ }
1920
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
1921
+ }
1922
+
1721
1923
  // INV-MSG — ONE message id ⇒ ONE message lifecycle.
1722
1924
  //
1723
1925
  // The Claude Agent SDK splits ONE API assistant message across MULTIPLE
@@ -3015,7 +3217,23 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3015
3217
  const run = openRuns.get(parentToolUseId);
3016
3218
  if (run !== undefined) {
3017
3219
  toolTurnId = run.turnId;
3018
- } else {
3220
+ } else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
3221
+ // A run that already CLOSED reopens only for a frame that carries a
3222
+ // tool_result, because that frame's tool.done needs a nested turn to
3223
+ // land in. A closed run's nested frame with no tool_result emits
3224
+ // nothing into a nested turn (it rides the `kind: "user"` carry
3225
+ // above), so it reopens nothing. The live case: after a client
3226
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
3227
+ // by user]" text frame, carrying its parent_tool_use_id, after
3228
+ // task_updated / task_notification has already closed that run as
3229
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
3230
+ // opened an empty second run, which flush then closed as
3231
+ // turn.abort{stream-truncated}. A run this invoke never opened still
3232
+ // opens on any nested user frame: a subagent's first frame is its
3233
+ // prompt, a text-only user frame, and a run that fails before any
3234
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
3235
+ // its turn.error.
3236
+ //
3019
3237
  // A run that CLOSED, or one this invoke never opened (the stream
3020
3238
  // started mid-run: a background agent spanning invokes, a resume):
3021
3239
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -3136,7 +3354,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3136
3354
  // always before this tool_result) rides here instead, the same
3137
3355
  // `_meta` record the carrier gives it, so D drops nothing.
3138
3356
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
3139
- a.toolDone({
3357
+ const doneFields: Parameters<StreamAssembler["toolDone"]>[0] = {
3140
3358
  toolCallId: block.tool_use_id,
3141
3359
  content: toolContent,
3142
3360
  outcome,
@@ -3183,7 +3401,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3183
3401
  });
3184
3402
  return merged !== undefined ? { _meta: merged } : {};
3185
3403
  })(),
3186
- });
3404
+ };
3405
+ // A top-level "user-rejected" result may be a call a client Stop cut
3406
+ // off while it ran, not a refusal: held until a frame that
3407
+ // continues the turn, or the turn's result, shows which (see
3408
+ // `heldStopToolDones`).
3409
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3410
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3411
+ } else {
3412
+ a.toolDone(doneFields);
3413
+ }
3187
3414
  }
3188
3415
  }
3189
3416
  // Finding #1: record this frame's uuid → the adopted messageId(s) it
@@ -3201,6 +3428,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3201
3428
  // is NOT closed by its parent's result; it closes when the framework
3202
3429
  // reports it, or at flush.
3203
3430
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3431
+ // A held Stop candidate's tool.done, decided by this result (see
3432
+ // `heldStopToolDones`), while the turn is still open.
3433
+ releaseHeldToolDones(msg);
3204
3434
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
3205
3435
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
3206
3436
  // the final assistant text in result — or, with is_error true, the error
@@ -3236,6 +3466,20 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3236
3466
  // point — its close is deferred to this frame (below), so the turn is
3237
3467
  // still open here, like every other turn.
3238
3468
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3469
+ if (resultSignalsInterruption(msg)) {
3470
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3471
+ // every other close on this arm: the turn was interrupted, so it closes
3472
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3473
+ // refusal or a parked call would otherwise decide. The stash, refusal
3474
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3475
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3476
+ // close. turn.abort carries no usage either. The last round's usage
3477
+ // stays on its message.end, as item 17 allows; the result's turn total
3478
+ // is not carried.
3479
+ stopDetailsByTurn.delete(turnId);
3480
+ closeInterruptedTurn(turnId, msg);
3481
+ return;
3482
+ }
3239
3483
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
3240
3484
  // ride `ext.anthropic.result-meta` before the close (no core home on
3241
3485
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -3333,6 +3577,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3333
3577
  // INV-MSG: seal the open assistant message before the turn close.
3334
3578
  closePendingMessage();
3335
3579
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3580
+ releaseHeldToolDones(msg);
3336
3581
  // Consume any stashed assistant-error close for this turnId — this
3337
3582
  // frame emits it (below). Each turn has its own id now, so an entry can
3338
3583
  // only ever be this turn's.
@@ -3365,6 +3610,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3365
3610
  )
3366
3611
  : [];
3367
3612
  emitDenialsCarrier(turnId, denials, msg.session_id);
3613
+ if (resultSignalsInterruption(msg)) {
3614
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3615
+ // close (both consumed above): the turn closes with one turn.abort, not
3616
+ // turn.error. This is the arm a client interrupt reaches:
3617
+ // error_during_execution with terminal_reason "aborted_streaming" or
3618
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3619
+ // turn.error{retriable: true}.
3620
+ closeInterruptedTurn(turnId, msg);
3621
+ return;
3622
+ }
3368
3623
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
3369
3624
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
3370
3625
  // success arm above (turn.error carries no metadata slot at all).
@@ -3538,8 +3793,26 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3538
3793
  return;
3539
3794
  }
3540
3795
 
3541
- // Other SDKMessage variants (system, status, …) carry no AgJSON-relevant
3542
- // content on this seam → no events.
3796
+ // A `system` frame whose subtype has no branch above and is not one the
3797
+ // facet studied and left uncarried (see STUDIED_UNCARRIED_SYSTEM_SUBTYPES):
3798
+ // carried whole, never silently dropped (SPEC §8.0 "MUST NOT silently drop
3799
+ // a native event it cannot map"; §8 item 22 names the subtype as the frame
3800
+ // kind). The CLI adds subtypes without a d.ts entry, so the next one is
3801
+ // carried the day it ships. A subtype that is not a string rides as kind
3802
+ // "system".
3803
+ if (msg.type === "system") {
3804
+ const raw: unknown = msg;
3805
+ const subtype = isJsonObject(raw) ? raw["subtype"] : undefined;
3806
+ const kind = typeof subtype === "string" ? subtype : "system";
3807
+ if (!STUDIED_UNCARRIED_SYSTEM_SUBTYPES.has(kind)) {
3808
+ a.emitExt("anthropic", "frame", { kind, frame: carryVerbatim(msg) });
3809
+ return;
3810
+ }
3811
+ }
3812
+
3813
+ // The studied uncarried variants (the system subtypes above, tool_progress,
3814
+ // rate_limit_event) carry no AgJSON-relevant content on this seam → no
3815
+ // events.
3543
3816
  }
3544
3817
 
3545
3818
  return {
@@ -3549,6 +3822,15 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3549
3822
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3550
3823
  // frame is the same reference, anything else its JSON form).
3551
3824
  const frame = native;
3825
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
3826
+ // it held for the turn's result to decide. A frame that continues the
3827
+ // turn releases it unchanged before that frame is handled; a result
3828
+ // decides it, and any other frame leaves it held.
3829
+ if (heldStopToolDones.length > 0) {
3830
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
3831
+ if (marker !== undefined) heldStopMarker = marker;
3832
+ else if (continuesTopLevelTurn(frame)) releaseHeldToolDones();
3833
+ }
3552
3834
  if (!isSDKMessage(frame)) {
3553
3835
  // Graceful guard (Tenet 6): route the raw payload through the lossless
3554
3836
  // vendor channel rather than throwing. Nest under `native` so a payload
@@ -3571,6 +3853,17 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3571
3853
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3572
3854
  // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3573
3855
  closePendingMessage(true);
3856
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
3857
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
3858
+ // "user"` frame carry instead, verbatim, before every close below
3859
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
3860
+ const carriedHeldFrames = new Set<unknown>();
3861
+ for (const { frame } of heldStopToolDones.splice(0)) {
3862
+ if (carriedHeldFrames.has(frame)) continue;
3863
+ carriedHeldFrames.add(frame);
3864
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
3865
+ }
3866
+ heldStopMarker = undefined;
3574
3867
  // B-strict: every subagent run still open closes here with its nested
3575
3868
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3576
3869
  // its subagent.done, innermost first.