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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1087,6 +1087,38 @@ function closeCauseTerminalReason(v: unknown): string | undefined {
1087
1087
  return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
1088
1088
  }
1089
1089
 
1090
+ // SPEC §8.0 item 17: a result frame that says the turn was interrupted. The
1091
+ // turn closes as one turn.abort{reason:"cancelled"}, never as turn.error or a
1092
+ // success turn.done, whichever result arm carries the signal. The signal is
1093
+ // any one of:
1094
+ // - `terminal_reason` "aborted_streaming" (the interrupt came while the
1095
+ // model was streaming) or "aborted_tools" (it came while a tool ran). The
1096
+ // CLI sends a client interrupt (Query.interrupt()) on the ERROR arm
1097
+ // (error_during_execution, is_error true) with one of these two, then
1098
+ // exits 1. That is captured at 0.3.319 for a text, a thinking, a tool and
1099
+ // a subagent run.
1100
+ // - `stopped_by_permission_check: true`, the turn stopped by the CLI's
1101
+ // permission check after repeated refusals.
1102
+ // - `interrupted_by_shutdown: true`, the turn interrupted when its host
1103
+ // worker shut down.
1104
+ // No capture has shown either flag yet, so their arm is unknown: the check
1105
+ // reads both arms. Both are runtime-only (absent from sdk.d.ts at 0.3.319),
1106
+ // so the frame is read through the JSON boundary, and only a literal `true`
1107
+ // counts. The key is never the result's `errors` text.
1108
+ const INTERRUPTION_TERMINAL_REASONS = new Set<string>(["aborted_streaming", "aborted_tools"]);
1109
+ // The CLI's top-level interrupt marker after a tool call a Stop cut off (see
1110
+ // `heldStopToolDones`); a CLI constant at 0.3.319.
1111
+ const INTERRUPT_FOR_TOOL_USE_MARKER = "[Request interrupted by user for tool use]";
1112
+ function resultSignalsInterruption(msg: unknown): boolean {
1113
+ if (!isJsonObject(msg)) return false;
1114
+ const terminalReason = msg["terminal_reason"];
1115
+ return (
1116
+ (typeof terminalReason === "string" && INTERRUPTION_TERMINAL_REASONS.has(terminalReason)) ||
1117
+ msg["stopped_by_permission_check"] === true ||
1118
+ msg["interrupted_by_shutdown"] === true
1119
+ );
1120
+ }
1121
+
1090
1122
  // `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
1091
1123
  // on both frames that carry it (the API-error assistant frame and the
1092
1124
  // `is_error: true` success result), so it is read through the JSON boundary.
@@ -1335,9 +1367,10 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
1335
1367
  // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1336
1368
  const apiErrorStatus =
1337
1369
  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;
1370
+ // `stop_reason` on a result that closes as turn.error, or as turn.abort for
1371
+ // an interruption: neither has a finishReason slot (and finishReasonRaw is
1372
+ // turn.done-only), so the native value would otherwise be dropped. Carried
1373
+ // verbatim ONLY on such a close;
1341
1374
  // a success close keeps it on finishReason / finishReasonRaw (no duplicate).
1342
1375
  const stopReason =
1343
1376
  closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
@@ -1754,6 +1787,119 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1754
1787
  // tool.done{denied} for a call already closed is a duplicate start and a second
1755
1788
  // final tool.done (INV-BLOCK: the reducer parks it as a double fold).
1756
1789
  const closedToolCallIds = new Set<string>();
1790
+ // A tool call that a client Stop cut off WHILE IT RAN. At 0.3.319 the CLI
1791
+ // stamps its tool_result `non_execution_kind: "user-rejected"`, the stamp a
1792
+ // refusal at the permission prompt also gets, and writes the refusal text
1793
+ // with a correction appended ("this call was stopped while running, not
1794
+ // refused before it ran"). Such a call ran and may have had effects, so it
1795
+ // records `outcome: "error"` with `isError`, not "denied". "denied" stays
1796
+ // for a call kept from running. The detector reads structural signals only,
1797
+ // never the correction text:
1798
+ // - the trigger: the CLI's top-level interrupt marker, a user frame whose
1799
+ // one text block is "[Request interrupted by user for tool use]",
1800
+ // arrives after the tool_result before any frame that continues the
1801
+ // turn (`continuesTopLevelTurn`);
1802
+ // - the decider: the turn's result signals an interruption
1803
+ // (`resultSignalsInterruption`; a Stop during a tool says
1804
+ // terminal_reason "aborted_tools"), and its `permission_denials`, which
1805
+ // the SDK calls the authoritative record of refusals, does not list the
1806
+ // call.
1807
+ // A refusal whose turn stops (a canUseTool deny with interrupt) also gets
1808
+ // the marker and an interrupted result, but its call is in
1809
+ // permission_denials, so it stays "denied". So the tool.done of a top-level
1810
+ // "user-rejected" result is HELD instead of emitted. The next frame that
1811
+ // continues the turn, other than the marker, releases it unchanged
1812
+ // ("denied"), so a turn that goes on after a refusal keeps its order. Other
1813
+ // frames (system notices, a subagent's frames, the rest of a stream already
1814
+ // open) leave it held, in either window, before or after the marker. After the marker, the turn's result
1815
+ // decides, and the tool.done is emitted from that result's push(), before
1816
+ // the denials carrier and the turn close. The "error" record keeps the
1817
+ // native content and the `_meta` toolResultMeta entry (the stamp)
1818
+ // verbatim, and takes the marker's text as `errorText`, with no
1819
+ // `errorCode`. A stream that ends while a tool.done is held emits no
1820
+ // tool.done, because a flush emits none (INV-FLUSH (3)). Instead the held
1821
+ // tool_result frame rides the `kind: "user"` frame carry, verbatim, before
1822
+ // the flush's closes, so the delivered frame is not lost. Nested results
1823
+ // are not held: they keep the stamp's outcome.
1824
+ const heldStopToolDones: Array<{ readonly fields: Parameters<StreamAssembler["toolDone"]>[0]; readonly frame: unknown }> = [];
1825
+ let heldStopMarker: string | undefined;
1826
+ function interruptForToolUseMarker(frame: unknown): string | undefined {
1827
+ if (!isJsonObject(frame) || frame["type"] !== "user" || frame["parent_tool_use_id"] !== null) return undefined;
1828
+ const message = frame["message"];
1829
+ const content = isJsonObject(message) ? message["content"] : undefined;
1830
+ if (!Array.isArray(content) || content.length !== 1) return undefined;
1831
+ const only: unknown = content[0];
1832
+ return isJsonObject(only) && only["type"] === "text" && only["text"] === INTERRUPT_FOR_TOOL_USE_MARKER
1833
+ ? INTERRUPT_FOR_TOOL_USE_MARKER
1834
+ : undefined;
1835
+ }
1836
+ // Whether `frame` continues the top-level turn: a top-level assistant
1837
+ // frame, a top-level stream_event that starts a new message
1838
+ // (`message_start`), or a top-level user frame. Such a frame releases a
1839
+ // held tool.done unchanged. Every other frame leaves it held for the turn's
1840
+ // result: a system frame, a subagent's frame, a command_lifecycle frame,
1841
+ // any other type, and the rest of a stream already open (content_block_*,
1842
+ // message_delta, message_stop), since a draining stream starts nothing. The CLI writes background-task notices (task_updated,
1843
+ // task_notification, background_tasks_changed) to the output as they
1844
+ // happen, and the Stop that cuts off a tool call also stops running
1845
+ // background tasks. So those notices can land before or after the marker,
1846
+ // and before the result.
1847
+ // Two kinds of top-level user frame do not continue it either: a replay
1848
+ // ack (`isReplay: true`, which the user branch skips), and a frame whose
1849
+ // every block is a tool_result stamped "user-rejected" with is_error. A Stop
1850
+ // that cuts off parallel calls stamps each call's result in its own frame,
1851
+ // so such a frame joins the hold (the user branch holds its tool.done too).
1852
+ // DISCLOSED: a frame mixing such a tool_result with another block releases
1853
+ // (no CLI path writes one: each cut-off call gets its own frame).
1854
+ function continuesTopLevelTurn(frame: unknown): boolean {
1855
+ if (!isJsonObject(frame)) return false;
1856
+ const type = frame["type"];
1857
+ if (type !== "assistant" && type !== "stream_event" && type !== "user") return false;
1858
+ const parent = frame["parent_tool_use_id"];
1859
+ if (parent !== null && parent !== undefined) return false;
1860
+ if (type === "stream_event") {
1861
+ const event = frame["event"];
1862
+ return isJsonObject(event) && event["type"] === "message_start";
1863
+ }
1864
+ if (type !== "user") return true;
1865
+ if (frame["isReplay"] === true) return false;
1866
+ // The user branch holds only a frame whose parent_tool_use_id is null.
1867
+ if (parent !== null) return true;
1868
+ const message = frame["message"];
1869
+ const content = isJsonObject(message) ? message["content"] : undefined;
1870
+ if (!Array.isArray(content) || content.length === 0) return true;
1871
+ const kinds = readNonExecutionKinds(frame);
1872
+ for (const block of content) {
1873
+ if (!isJsonObject(block) || block["type"] !== "tool_result" || block["is_error"] !== true) return true;
1874
+ const id = block["tool_use_id"];
1875
+ if (typeof id !== "string" || kinds.get(id) !== "user-rejected") return true;
1876
+ }
1877
+ return false;
1878
+ }
1879
+ // Release every held tool.done: as an interrupted call when the marker was
1880
+ // seen and `result` (the turn's result frame, either arm) signals an
1881
+ // interruption without listing the call in permission_denials; otherwise
1882
+ // unchanged.
1883
+ function releaseHeldToolDones(result?: unknown): void {
1884
+ if (heldStopToolDones.length === 0) return;
1885
+ const held = heldStopToolDones.splice(0);
1886
+ const marker = heldStopMarker;
1887
+ heldStopMarker = undefined;
1888
+ // The marker's text when this result decides "stopped while running".
1889
+ const stopMarker = result !== undefined && resultSignalsInterruption(result) ? marker : undefined;
1890
+ const listed = new Set<string>();
1891
+ const denials = isJsonObject(result) ? result["permission_denials"] : undefined;
1892
+ if (Array.isArray(denials)) {
1893
+ for (const d of denials) if (isJsonObject(d) && typeof d["tool_use_id"] === "string") listed.add(d["tool_use_id"]);
1894
+ }
1895
+ for (const { fields } of held) {
1896
+ if (stopMarker !== undefined && !listed.has(fields.toolCallId)) {
1897
+ a.toolDone({ ...fields, outcome: "error", isError: true, errorText: stopMarker });
1898
+ } else {
1899
+ a.toolDone(fields);
1900
+ }
1901
+ }
1902
+ }
1757
1903
  // SDK message id → the `diagnostics` value already carried for it (see the
1758
1904
  // assistant branch): one carry per response, not one per frame.
1759
1905
  const diagnosticsCarried = new Map<string, string>();
@@ -1824,6 +1970,40 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
1824
1970
  return stashed;
1825
1971
  }
1826
1972
 
1973
+ // The close of a turn whose result frame signals an interruption (SPEC §8.0
1974
+ // item 17; see `resultSignalsInterruption`), on either result arm. First the
1975
+ // result-meta carry, as before every close. turn.abort has no finishReason
1976
+ // slot, so it is built as for an error close and stop_reason rides it. Then
1977
+ // exactly one turn.abort{reason:"cancelled"}: "cancelled" is the value the
1978
+ // ADK client-abort close uses (§8.0 item 35) and the state the CLI's own
1979
+ // command_lifecycle frame reports for the interrupted command. The flag
1980
+ // branches use the same value: they have no captured emission yet, and one
1981
+ // value keeps one consumer branch for "the turn was stopped before it
1982
+ // finished".
1983
+ //
1984
+ // turn.abort has no code or message, so the cause rides result-meta, on this
1985
+ // close only: `terminalReason` (the result's terminal_reason, a string,
1986
+ // verbatim), plus `stoppedByPermissionCheck` / `interruptedByShutdown` when the
1987
+ // result carries them as booleans, verbatim. Every other close's result-meta
1988
+ // is unchanged. The `errors` text an error-arm result carries (through
1989
+ // 0.12.11 / 1.0.0-rc.7 it was turn.error's message) is not carried.
1990
+ function closeInterruptedTurn(turnId: string, msg: SDKResultMsg): void {
1991
+ const raw: unknown = msg;
1992
+ const terminalReason = isJsonObject(raw) ? raw["terminal_reason"] : undefined;
1993
+ const byPermission = isJsonObject(raw) ? raw["stopped_by_permission_check"] : undefined;
1994
+ const byShutdown = isJsonObject(raw) ? raw["interrupted_by_shutdown"] : undefined;
1995
+ const resultMeta: { [k: string]: JsonValue } = {
1996
+ ...resultMetaPayload(msg, true),
1997
+ ...(typeof terminalReason === "string" ? { terminalReason } : {}),
1998
+ ...(typeof byPermission === "boolean" ? { stoppedByPermissionCheck: byPermission } : {}),
1999
+ ...(typeof byShutdown === "boolean" ? { interruptedByShutdown: byShutdown } : {}),
2000
+ };
2001
+ if (Object.keys(resultMeta).length > 0) {
2002
+ a.emitExt("anthropic", "result-meta", resultMeta);
2003
+ }
2004
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
2005
+ }
2006
+
1827
2007
  // INV-MSG — ONE message id ⇒ ONE message lifecycle.
1828
2008
  //
1829
2009
  // The Claude Agent SDK splits ONE API assistant message across MULTIPLE
@@ -3142,7 +3322,23 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3142
3322
  const run = openRuns.get(parentToolUseId);
3143
3323
  if (run !== undefined) {
3144
3324
  toolTurnId = run.turnId;
3145
- } else {
3325
+ } else if (opensWithToolResult || !closedRuns.has(parentToolUseId)) {
3326
+ // A run that already CLOSED reopens only for a frame that carries a
3327
+ // tool_result, because that frame's tool.done needs a nested turn to
3328
+ // land in. A closed run's nested frame with no tool_result emits
3329
+ // nothing into a nested turn (it rides the `kind: "user"` carry
3330
+ // above), so it reopens nothing. The live case: after a client
3331
+ // interrupt the CLI sends a stopped subagent's "[Request interrupted
3332
+ // by user]" text frame, carrying its parent_tool_use_id, after
3333
+ // task_updated / task_notification has already closed that run as
3334
+ // turn.abort{stopped}. Through 0.12.11 / 1.0.0-rc.7 that frame
3335
+ // opened an empty second run, which flush then closed as
3336
+ // turn.abort{stream-truncated}. A run this invoke never opened still
3337
+ // opens on any nested user frame: a subagent's first frame is its
3338
+ // prompt, a text-only user frame, and a run that fails before any
3339
+ // assistant frame (subagent-fail-sonnet5) has no other opener for
3340
+ // its turn.error.
3341
+ //
3146
3342
  // A run that CLOSED, or one this invoke never opened (the stream
3147
3343
  // started mid-run: a background agent spanning invokes, a resume):
3148
3344
  // open a fresh run named by this frame, so its tool.done lands in a
@@ -3263,7 +3459,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3263
3459
  // always before this tool_result) rides here instead, the same
3264
3460
  // `_meta` record the carrier gives it, so D drops nothing.
3265
3461
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
3266
- a.toolDone({
3462
+ const doneFields: Parameters<StreamAssembler["toolDone"]>[0] = {
3267
3463
  toolCallId: block.tool_use_id,
3268
3464
  content: toolContent,
3269
3465
  outcome,
@@ -3310,7 +3506,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3310
3506
  });
3311
3507
  return merged !== undefined ? { _meta: merged } : {};
3312
3508
  })(),
3313
- });
3509
+ };
3510
+ // A top-level "user-rejected" result may be a call a client Stop cut
3511
+ // off while it ran, not a refusal: held until a frame that
3512
+ // continues the turn, or the turn's result, shows which (see
3513
+ // `heldStopToolDones`).
3514
+ if (denied && kind === "user-rejected" && msg.parent_tool_use_id === null) {
3515
+ heldStopToolDones.push({ fields: doneFields, frame: msg });
3516
+ } else {
3517
+ a.toolDone(doneFields);
3518
+ }
3314
3519
  }
3315
3520
  }
3316
3521
  // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
@@ -3328,6 +3533,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3328
3533
  // is NOT closed by its parent's result; it closes when the framework
3329
3534
  // reports it, or at flush.
3330
3535
  const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
3536
+ // A held Stop candidate's tool.done, decided by this result (see
3537
+ // `heldStopToolDones`), while the turn is still open.
3538
+ releaseHeldToolDones(msg);
3331
3539
  // Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
3332
3540
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
3333
3541
  // the final assistant text in result — or, with is_error true, the error
@@ -3363,6 +3571,21 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3363
3571
  // point — its close is deferred to this frame (below), so the turn is
3364
3572
  // still open here, like every other turn.
3365
3573
  emitDenialsCarrier(turnId, msg.permission_denials, msg.session_id);
3574
+ if (resultSignalsInterruption(msg)) {
3575
+ // SPEC §8.0 item 17 (see `resultSignalsInterruption`), checked before
3576
+ // every other close on this arm: the turn was interrupted, so it closes
3577
+ // with one turn.abort, whatever is_error, a stashed error frame, a
3578
+ // refusal or a parked call would otherwise decide. The stash, refusal
3579
+ // and stop_details entries are consumed (and so dropped). turn.abort has
3580
+ // no finishReason slot, so stop_reason rides result-meta, as on an error
3581
+ // close. turn.abort carries no usage either. The last round's usage
3582
+ // stays on its message.end, as item 17 allows; the result's turn total
3583
+ // is not carried.
3584
+ refusedTurns.delete(turnId);
3585
+ stopDetailsByTurn.delete(turnId);
3586
+ closeInterruptedTurn(turnId, msg);
3587
+ return;
3588
+ }
3366
3589
  // 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
3367
3590
  // ride `ext.anthropic.result-meta` before the close (no core home on
3368
3591
  // turn.done — see resultMetaPayload's doc). It is emitted on an
@@ -3487,6 +3710,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3487
3710
  // INV-MSG: seal the open assistant message before the turn close.
3488
3711
  closePendingMessage();
3489
3712
  const turnId = closingTopTurnId(msg.uuid, msg.session_id);
3713
+ releaseHeldToolDones(msg);
3490
3714
  // Consume any stashed assistant-error close for this turnId — this
3491
3715
  // frame emits it (below). Each turn has its own id now, so an entry can
3492
3716
  // only ever be this turn's.
@@ -3520,6 +3744,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3520
3744
  )
3521
3745
  : [];
3522
3746
  emitDenialsCarrier(turnId, denials, msg.session_id);
3747
+ if (resultSignalsInterruption(msg)) {
3748
+ // SPEC §8.0 item 17, checked before the retriable rule and the stashed
3749
+ // close (both consumed above): the turn closes with one turn.abort, not
3750
+ // turn.error. This is the arm a client interrupt reaches:
3751
+ // error_during_execution with terminal_reason "aborted_streaming" or
3752
+ // "aborted_tools". Through 0.12.11 / 1.0.0-rc.7 it closed as
3753
+ // turn.error{retriable: true}.
3754
+ closeInterruptedTurn(turnId, msg);
3755
+ return;
3756
+ }
3523
3757
  // 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
3524
3758
  // error variant gets the SAME `ext.anthropic.result-meta` carry as the
3525
3759
  // success arm above (turn.error carries no metadata slot at all).
@@ -3706,6 +3940,15 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3706
3940
  // ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
3707
3941
  // frame is the same reference, anything else its JSON form).
3708
3942
  const frame = native;
3943
+ // A held Stop candidate (see `heldStopToolDones`): the marker frame keeps
3944
+ // it held for the turn's result to decide. A frame that continues the
3945
+ // turn releases it unchanged before that frame is handled; a result
3946
+ // decides it, and any other frame leaves it held.
3947
+ if (heldStopToolDones.length > 0) {
3948
+ const marker = heldStopMarker === undefined ? interruptForToolUseMarker(frame) : undefined;
3949
+ if (marker !== undefined) heldStopMarker = marker;
3950
+ else if (continuesTopLevelTurn(frame)) releaseHeldToolDones();
3951
+ }
3709
3952
  if (!isSDKMessage(frame)) {
3710
3953
  // Graceful guard (SPEC §8.0): route the raw payload through the lossless
3711
3954
  // vendor channel rather than throwing. Nest under `native` so a payload
@@ -3728,6 +3971,17 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
3728
3971
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3729
3972
  // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3730
3973
  closePendingMessage(true);
3974
+ // A tool.done still held (see `heldStopToolDones`) is not emitted: a
3975
+ // flush emits no tool.done. Its tool_result frame rides the `kind:
3976
+ // "user"` frame carry instead, verbatim, before every close below
3977
+ // (INV-FLUSH (3) allows the graceful-degradation carries there).
3978
+ const carriedHeldFrames = new Set<unknown>();
3979
+ for (const { frame } of heldStopToolDones.splice(0)) {
3980
+ if (carriedHeldFrames.has(frame)) continue;
3981
+ carriedHeldFrames.add(frame);
3982
+ a.emitExt("anthropic", "frame", { kind: "user", frame: carryVerbatim(frame) });
3983
+ }
3984
+ heldStopMarker = undefined;
3731
3985
  // B-strict: every subagent run still open closes here with its nested
3732
3986
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
3733
3987
  // its subagent.done, innermost first.