@silverprotocol/claude-agent-sdk 1.0.0-rc.6 → 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/README.md +42 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +304 -22
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +289 -23
package/src/index.ts
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
*
|
|
31
31
|
* `push(native)` structurally guards `native` → `SDKMessage`; on a guard failure it
|
|
32
32
|
* routes the raw payload through the lossless `ext.anthropic.unparsed` channel and
|
|
33
|
-
* returns — graceful, never throws (
|
|
33
|
+
* returns — graceful, never throws (SPEC §8.0). Stable ids derive from the SDK ids
|
|
34
34
|
* (`message.id`, block `id`, `tool_use_id`).
|
|
35
35
|
*/
|
|
36
36
|
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
|
@@ -253,7 +253,7 @@ function mapModelUsage(mu: SDKModelUsage): AgUsage {
|
|
|
253
253
|
// but a result frame is discriminant-validated only, so a leaner producer (a
|
|
254
254
|
// proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
|
|
255
255
|
// member passed the `!== null` check and threw a TypeError out of push()
|
|
256
|
-
// (
|
|
256
|
+
// (SPEC §8.0 "MUST NOT throw"; found while writing §10.23),
|
|
257
257
|
// and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
|
|
258
258
|
// anything else ⇒ absent.
|
|
259
259
|
function serverToolRequestCount(usage: unknown): number | undefined {
|
|
@@ -703,7 +703,7 @@ function emitAssistantBlock(
|
|
|
703
703
|
// yields well-formed `SDKMessage`s, but this is the deserialization boundary so we
|
|
704
704
|
// confirm the discriminant + the per-arm load-bearing nested shape before driving
|
|
705
705
|
// the engine. A user-defined type guard (not a cast) narrows on success; a failure
|
|
706
|
-
// routes the raw payload to `ext.anthropic.unparsed` and returns (graceful,
|
|
706
|
+
// routes the raw payload to `ext.anthropic.unparsed` and returns (graceful, SPEC §8.0).
|
|
707
707
|
function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
|
|
708
708
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
709
709
|
}
|
|
@@ -810,6 +810,14 @@ const CARRIED_SYSTEM_SUBTYPES = new Set<string>([
|
|
|
810
810
|
"files_persisted",
|
|
811
811
|
"memory_recall",
|
|
812
812
|
"mirror_error",
|
|
813
|
+
// 0.3.317: system/session_writes_lost {error_code, lost[],
|
|
814
|
+
// transcript_session_ids?}, sent at most once, as the CLI exits with status
|
|
815
|
+
// 0 after the last result, when the disk was full or over quota and lines of a session
|
|
816
|
+
// transcript or changes to ~/.claude.json were not saved. Upstream calls it
|
|
817
|
+
// safe to ignore, but a host that resumes one of the listed sessions may
|
|
818
|
+
// find part of its conversation missing, and no AgJSON event says so. A
|
|
819
|
+
// persistence-failure diagnostic like mirror_error above: whole-frame carry.
|
|
820
|
+
"session_writes_lost",
|
|
813
821
|
// workspace#7 census-caught (2026-08-07, corpus/partials-sonnet5): the
|
|
814
822
|
// system/status ping — status:'compacting'|'requesting'|null (+ optional
|
|
815
823
|
// compact_result/compact_error). GENUINE consumer-facing agent-state signal
|
|
@@ -842,7 +850,7 @@ const CARRIED_STANDALONE_TYPES = new Set<string>([
|
|
|
842
850
|
"conversation_reset",
|
|
843
851
|
]);
|
|
844
852
|
|
|
845
|
-
// The top-level `type` literals the SDKMessage union declares (0.3.
|
|
853
|
+
// The top-level `type` literals the SDKMessage union declares (0.3.319: 40
|
|
846
854
|
// members over these 11 types). A frame whose `type` is NOT among them is
|
|
847
855
|
// RUNTIME-ONLY: no d.ts diff shows it (the 0.3.272 lesson, now for a whole
|
|
848
856
|
// frame type). The first one observed: `command_lifecycle`
|
|
@@ -881,7 +889,7 @@ function anthropicFrameKind(msg: SDKMessage): string | undefined {
|
|
|
881
889
|
// arrived through `JsonValue.parse` and `isSDKMessage` validates only the
|
|
882
890
|
// discriminants, so the typed `string[]` is nominal — guard the shape at
|
|
883
891
|
// runtime (Array.isArray + every-string, the `resourceLinks` precedent) and
|
|
884
|
-
// carry it verbatim. A malformed list is ignored, never thrown on (
|
|
892
|
+
// carry it verbatim. A malformed list is ignored, never thrown on (SPEC §8.0);
|
|
885
893
|
// `string[]` is itself a JsonValue, so no cast is needed downstream.
|
|
886
894
|
// A COPY, never the frame's own array: the value is emitted unparsed
|
|
887
895
|
// (result-meta, message.metadata), core's StreamAssembler does not copy, and
|
|
@@ -1079,6 +1087,38 @@ function closeCauseTerminalReason(v: unknown): string | undefined {
|
|
|
1079
1087
|
return typeof v === "string" && v !== "" && v !== "completed" ? v : undefined;
|
|
1080
1088
|
}
|
|
1081
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
|
+
|
|
1082
1122
|
// `api_error_code` (CLI 2.1.280, @internal) — UNDECLARED in sdk.d.ts at 0.3.280
|
|
1083
1123
|
// on both frames that carry it (the API-error assistant frame and the
|
|
1084
1124
|
// `is_error: true` success result), so it is read through the JSON boundary.
|
|
@@ -1101,7 +1141,7 @@ function readStartupFailureReason(v: unknown): string | undefined {
|
|
|
1101
1141
|
// The type's own lead sentence frames the whole enum as a refusal to start:
|
|
1102
1142
|
// "Why Claude Code refused to start, so a host can offer the fix instead of a
|
|
1103
1143
|
// retry." So a PRESENT reason means NOT retriable, except for the values
|
|
1104
|
-
// upstream itself EXPLICITLY describes as retriable. Through 0.3.
|
|
1144
|
+
// upstream itself EXPLICITLY describes as retriable. Through 0.3.319 that set is
|
|
1105
1145
|
// exactly two values:
|
|
1106
1146
|
// - `worktree_unverified`: "the session's worktree could not be verified
|
|
1107
1147
|
// right now; retrying may succeed."
|
|
@@ -1125,7 +1165,11 @@ function readStartupFailureReason(v: unknown): string | undefined {
|
|
|
1125
1165
|
// gateway_access_denied, proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
|
|
1126
1166
|
// worktree_resume_refused, cli_version_too_old, bypass_root, and 0.3.296's
|
|
1127
1167
|
// org_config_refused: "signing in again or an admin's change is the fix, not a
|
|
1128
|
-
// retry"
|
|
1168
|
+
// retry", 0.3.314's sandbox_required_unavailable: "make the sandbox
|
|
1169
|
+
// available or have the requirement changed", 0.3.317's initialize_not_first:
|
|
1170
|
+
// "the fix is in the host or the wrapper script, not a retry", and 0.3.318's
|
|
1171
|
+
// config_file_invalid: "a retry alone does not help") names a configuration,
|
|
1172
|
+
// policy or environment fix, and an unknown future value
|
|
1129
1173
|
// inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
|
|
1130
1174
|
// reason never reaches this function: the error arm keeps its old rule, so
|
|
1131
1175
|
// older producers are byte-identical.
|
|
@@ -1177,7 +1221,7 @@ function resultErrorFields(msg: SDKResultSuccessMsg): { readonly message: string
|
|
|
1177
1221
|
// Absent fields ⇒ undefined (never an empty bag; pre-0.3.220 wire is
|
|
1178
1222
|
// byte-identical). Nested access is runtime-guarded like the error arm's
|
|
1179
1223
|
// `errors` guard: `isSDKMessage` validates only `subtype` on a result frame,
|
|
1180
|
-
// and a malformed frame must not throw (
|
|
1224
|
+
// and a malformed frame must not throw (SPEC §8.0).
|
|
1181
1225
|
//
|
|
1182
1226
|
// 0.3.258 bump — three more result-frame siblings join the SAME carry (one
|
|
1183
1227
|
// carrier per concept, §0.6; nothing new on the ext vocabulary):
|
|
@@ -1323,9 +1367,10 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
|
|
|
1323
1367
|
// surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
|
|
1324
1368
|
const apiErrorStatus =
|
|
1325
1369
|
isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
|
|
1326
|
-
// `stop_reason` on a result that closes as turn.error
|
|
1327
|
-
// finishReason slot (and finishReasonRaw is
|
|
1328
|
-
// value would otherwise be dropped. Carried
|
|
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;
|
|
1329
1374
|
// a success close keeps it on finishReason / finishReasonRaw (no duplicate).
|
|
1330
1375
|
const stopReason =
|
|
1331
1376
|
closesAsError && isJsonObject(raw) && typeof raw["stop_reason"] === "string" ? raw["stop_reason"] : undefined;
|
|
@@ -1403,7 +1448,7 @@ function readModelUsageSinceLastResult(v: unknown): { [k: string]: JsonValue } |
|
|
|
1403
1448
|
|
|
1404
1449
|
// A result frame's turn usage, or undefined when the frame's usage trio is not
|
|
1405
1450
|
// the shape `mapTurnUsage` dereferences. Both result arms are
|
|
1406
|
-
// discriminant-validated only, so every call goes through this guard (
|
|
1451
|
+
// discriminant-validated only, so every call goes through this guard (SPEC §8.0:
|
|
1407
1452
|
// a malformed frame must not throw out of push()); absent ⇒ no usage key.
|
|
1408
1453
|
// The guard covers each property `mapTurnUsage` reads unguarded: the `usage`
|
|
1409
1454
|
// object and its minimal real shape (numeric input/output token counts, so an
|
|
@@ -1742,6 +1787,119 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1742
1787
|
// tool.done{denied} for a call already closed is a duplicate start and a second
|
|
1743
1788
|
// final tool.done (INV-BLOCK: the reducer parks it as a double fold).
|
|
1744
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
|
+
}
|
|
1745
1903
|
// SDK message id → the `diagnostics` value already carried for it (see the
|
|
1746
1904
|
// assistant branch): one carry per response, not one per frame.
|
|
1747
1905
|
const diagnosticsCarried = new Map<string, string>();
|
|
@@ -1812,6 +1970,40 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1812
1970
|
return stashed;
|
|
1813
1971
|
}
|
|
1814
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
|
+
|
|
1815
2007
|
// INV-MSG — ONE message id ⇒ ONE message lifecycle.
|
|
1816
2008
|
//
|
|
1817
2009
|
// The Claude Agent SDK splits ONE API assistant message across MULTIPLE
|
|
@@ -2431,7 +2623,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2431
2623
|
}
|
|
2432
2624
|
|
|
2433
2625
|
// Evict every messageId ever produced for each uuid in `uuids`. An uuid this
|
|
2434
|
-
// facet never observed is skipped (
|
|
2626
|
+
// facet never observed is skipped (no remove is fabricated — the fold
|
|
2435
2627
|
// has nothing live under an unknown id anyway; `reduce()`'s `#removeMessage`
|
|
2436
2628
|
// is a documented no-op on an unknown id regardless). Safe to call from BOTH
|
|
2437
2629
|
// retraction sources without double-effect: `supersedes` fires "on arrival"
|
|
@@ -3130,7 +3322,23 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3130
3322
|
const run = openRuns.get(parentToolUseId);
|
|
3131
3323
|
if (run !== undefined) {
|
|
3132
3324
|
toolTurnId = run.turnId;
|
|
3133
|
-
} 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
|
+
//
|
|
3134
3342
|
// A run that CLOSED, or one this invoke never opened (the stream
|
|
3135
3343
|
// started mid-run: a background agent spanning invokes, a resume):
|
|
3136
3344
|
// open a fresh run named by this frame, so its tool.done lands in a
|
|
@@ -3251,7 +3459,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3251
3459
|
// always before this tool_result) rides here instead, the same
|
|
3252
3460
|
// `_meta` record the carrier gives it, so D drops nothing.
|
|
3253
3461
|
const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
|
|
3254
|
-
|
|
3462
|
+
const doneFields: Parameters<StreamAssembler["toolDone"]>[0] = {
|
|
3255
3463
|
toolCallId: block.tool_use_id,
|
|
3256
3464
|
content: toolContent,
|
|
3257
3465
|
outcome,
|
|
@@ -3298,7 +3506,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3298
3506
|
});
|
|
3299
3507
|
return merged !== undefined ? { _meta: merged } : {};
|
|
3300
3508
|
})(),
|
|
3301
|
-
}
|
|
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
|
+
}
|
|
3302
3519
|
}
|
|
3303
3520
|
}
|
|
3304
3521
|
// Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
|
|
@@ -3316,6 +3533,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3316
3533
|
// is NOT closed by its parent's result; it closes when the framework
|
|
3317
3534
|
// reports it, or at flush.
|
|
3318
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);
|
|
3319
3539
|
// Since 0.6.3 (claude-agent-sdk 0.3.280): `subtype: "success"` does NOT mean the turn
|
|
3320
3540
|
// succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
|
|
3321
3541
|
// the final assistant text in result — or, with is_error true, the error
|
|
@@ -3335,7 +3555,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3335
3555
|
// discriminant-validated, and false/absent must stay on the success path
|
|
3336
3556
|
// byte-for-byte. The stash entry is consumed either way.
|
|
3337
3557
|
const stashedError = takeStashedTurnError(turnId);
|
|
3338
|
-
// Shape-guarded once for every close below (
|
|
3558
|
+
// Shape-guarded once for every close below (SPEC §8.0; see guardedTurnUsage).
|
|
3339
3559
|
const turnUsage = guardedTurnUsage(msg);
|
|
3340
3560
|
const apiErrorTurn = msg.is_error === true;
|
|
3341
3561
|
const safety: AgSafety[] | undefined =
|
|
@@ -3351,6 +3571,21 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3351
3571
|
// point — its close is deferred to this frame (below), so the turn is
|
|
3352
3572
|
// still open here, like every other turn.
|
|
3353
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
|
+
}
|
|
3354
3589
|
// 0.3.220: fast_mode_disabled_reason + per-model canonicalModel/provider
|
|
3355
3590
|
// ride `ext.anthropic.result-meta` before the close (no core home on
|
|
3356
3591
|
// turn.done — see resultMetaPayload's doc). It is emitted on an
|
|
@@ -3475,6 +3710,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3475
3710
|
// INV-MSG: seal the open assistant message before the turn close.
|
|
3476
3711
|
closePendingMessage();
|
|
3477
3712
|
const turnId = closingTopTurnId(msg.uuid, msg.session_id);
|
|
3713
|
+
releaseHeldToolDones(msg);
|
|
3478
3714
|
// Consume any stashed assistant-error close for this turnId — this
|
|
3479
3715
|
// frame emits it (below). Each turn has its own id now, so an entry can
|
|
3480
3716
|
// only ever be this turn's.
|
|
@@ -3483,7 +3719,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3483
3719
|
// Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
|
|
3484
3720
|
// `typeof v.subtype === "string"` for the result arm — it does NOT validate
|
|
3485
3721
|
// the `errors` array. A malformed message (missing errors, wrong subtype) must
|
|
3486
|
-
// not throw (
|
|
3722
|
+
// not throw (SPEC §8.0: graceful, never throws).
|
|
3487
3723
|
const errors = Array.isArray(msg.errors) ? msg.errors : [];
|
|
3488
3724
|
const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
|
|
3489
3725
|
// Since claude-agent-sdk 0.3.274: a known startup failure says why the CLI refused to
|
|
@@ -3498,7 +3734,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3498
3734
|
: subtype !== "error_max_turns";
|
|
3499
3735
|
// Denials ride the SAME carrier as on the success arm, at the same point.
|
|
3500
3736
|
// This arm is discriminant-validated only, so the array is shape-guarded
|
|
3501
|
-
// (a malformed entry is skipped;
|
|
3737
|
+
// (a malformed entry is skipped; SPEC §8.0: never throw).
|
|
3502
3738
|
const rawDenials: unknown = isJsonObject(msg) ? msg["permission_denials"] : undefined;
|
|
3503
3739
|
const denials = Array.isArray(rawDenials)
|
|
3504
3740
|
? rawDenials.flatMap((d: unknown) =>
|
|
@@ -3508,6 +3744,16 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3508
3744
|
)
|
|
3509
3745
|
: [];
|
|
3510
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
|
+
}
|
|
3511
3757
|
// 0.3.220: fast_mode_disabled_reason exists on BOTH result arms — the
|
|
3512
3758
|
// error variant gets the SAME `ext.anthropic.result-meta` carry as the
|
|
3513
3759
|
// success arm above (turn.error carries no metadata slot at all).
|
|
@@ -3521,7 +3767,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3521
3767
|
// second turn.error for the same turnId (INV-TURN), with this frame's
|
|
3522
3768
|
// usage (the success arm's mapping). This arm is only
|
|
3523
3769
|
// discriminant-validated, so the usage trio is shape-guarded first
|
|
3524
|
-
// (
|
|
3770
|
+
// (SPEC §8.0: a malformed frame must not throw); absent ⇒ no usage key.
|
|
3525
3771
|
// The guard (`guardedTurnUsage`) covers every property `mapTurnUsage`
|
|
3526
3772
|
// dereferences — `usage: {}` or a null modelUsage entry would otherwise
|
|
3527
3773
|
// throw here, after the stash was already consumed.
|
|
@@ -3644,8 +3890,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3644
3890
|
return;
|
|
3645
3891
|
}
|
|
3646
3892
|
|
|
3647
|
-
// Fixture-drift ratchet (2026-07-03 follow-up;
|
|
3648
|
-
//
|
|
3893
|
+
// Fixture-drift ratchet (2026-07-03 follow-up; 20 arms as of 0.3.319):
|
|
3894
|
+
// the carried arms with genuine consumer-facing content and no existing
|
|
3649
3895
|
// AgJSON home — uniform lossless carry (see `anthropicFrameKind` doc
|
|
3650
3896
|
// comment above for the full per-arm reasoning, SPEC §8 item 22).
|
|
3651
3897
|
const carriedKind = anthropicFrameKind(msg);
|
|
@@ -3694,8 +3940,17 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3694
3940
|
// ran core's toJsonValueSafe on it before this push (SPEC:933; a JSON
|
|
3695
3941
|
// frame is the same reference, anything else its JSON form).
|
|
3696
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
|
+
}
|
|
3697
3952
|
if (!isSDKMessage(frame)) {
|
|
3698
|
-
// Graceful guard (
|
|
3953
|
+
// Graceful guard (SPEC §8.0): route the raw payload through the lossless
|
|
3699
3954
|
// vendor channel rather than throwing. Nest under `native` so a payload
|
|
3700
3955
|
// that carries its own `type` key (the common malformed-SDKMessage shape
|
|
3701
3956
|
// that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
|
|
@@ -3716,6 +3971,17 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3716
3971
|
// its real usage rather than leaving INV-FLUSH to synthesize a bare
|
|
3717
3972
|
// `message.end`. At flush: no content is minted (INV-FLUSH (3)).
|
|
3718
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;
|
|
3719
3985
|
// B-strict: every subagent run still open closes here with its nested
|
|
3720
3986
|
// terminal (turn.abort{stream-truncated}, or its stashed API error) and
|
|
3721
3987
|
// its subagent.done, innermost first.
|