@silverprotocol/claude-agent-sdk 0.7.2 → 0.9.0
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 +86 -5
- package/dist/index.d.ts +9 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +317 -113
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +351 -128
package/src/index.ts
CHANGED
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
AgProviderMeta,
|
|
43
43
|
type AgSafety,
|
|
44
44
|
type AgSource,
|
|
45
|
+
type AgTrigger,
|
|
45
46
|
type AgUsage,
|
|
46
47
|
type AgEvent,
|
|
47
48
|
JsonValue,
|
|
@@ -136,7 +137,7 @@ function stopReasonRaw(stop: BetaStopReason | string | null): string | undefined
|
|
|
136
137
|
// invoke the second turn's message.start and content landed on T AFTER
|
|
137
138
|
// turn.done(T) (the assembler's seen-turn set suppressed a second
|
|
138
139
|
// turn.start), breaking INV-TURN (SPEC:743), and reduce() merged every turn
|
|
139
|
-
// of a session into one AgTurnRecord (
|
|
140
|
+
// of a session into one AgTurnRecord (2026-09-23).
|
|
140
141
|
|
|
141
142
|
// ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
|
|
142
143
|
function imageSource(source: ImageBlockSource): AgSource {
|
|
@@ -181,15 +182,61 @@ function readThinkingTokens(usage: unknown): number | undefined {
|
|
|
181
182
|
return typeof thinking === "number" ? thinking : undefined;
|
|
182
183
|
}
|
|
183
184
|
|
|
185
|
+
// draft.5 §4 (input side): `inputTokens` counts EVERY input token the provider
|
|
186
|
+
// processed, cache reads and writes included, and `cacheReadTokens` /
|
|
187
|
+
// `cacheWriteTokens` are its breakdowns. Anthropic's `input_tokens` EXCLUDES
|
|
188
|
+
// cache tokens, so the facet ADDS the two cache counters in, on every AgUsage
|
|
189
|
+
// it emits (turn, message and `byModel` entries alike), the provider's own
|
|
190
|
+
// definition of total input. On a running-total object the sum of three
|
|
191
|
+
// co-scoped running totals is itself the running total, so nothing is
|
|
192
|
+
// de-cumulated. A cache counter that is absent (or null) counts 0, so with
|
|
193
|
+
// both absent the input counter is carried as is and no cache key is
|
|
194
|
+
// invented. A non-numeric input counter yields no `inputTokens` (a malformed
|
|
195
|
+
// frame never makes NaN). The facet never subtracts a cache counter out.
|
|
196
|
+
function inclusiveInput(input: unknown, cacheRead: unknown, cacheWrite: unknown): number | undefined {
|
|
197
|
+
if (typeof input !== "number") return undefined;
|
|
198
|
+
return input + (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// The cache breakdown keys of an AgUsage: each present only when its native
|
|
202
|
+
// counter is a number, so an absent (or null) counter invents no key, on the
|
|
203
|
+
// wire or in memory (draft.5 §4: both absent ⇒ no cache key).
|
|
204
|
+
function cacheBreakdown(cacheRead: unknown, cacheWrite: unknown): { cacheReadTokens?: number; cacheWriteTokens?: number } {
|
|
205
|
+
return {
|
|
206
|
+
...(typeof cacheRead === "number" ? { cacheReadTokens: cacheRead } : {}),
|
|
207
|
+
...(typeof cacheWrite === "number" ? { cacheWriteTokens: cacheWrite } : {}),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// A message's native input trio merged field-wise with a newer usage object
|
|
212
|
+
// (only numeric counters overwrite), for the cache-inclusive `inputTokens` of a
|
|
213
|
+
// message whose usage arrives in parts (see PendingMessage.rawInput).
|
|
214
|
+
function nativeInput(
|
|
215
|
+
prev: { input?: number; cacheRead?: number; cacheWrite?: number },
|
|
216
|
+
usage: unknown,
|
|
217
|
+
): { input?: number; cacheRead?: number; cacheWrite?: number } {
|
|
218
|
+
if (!isJsonObject(usage)) return prev;
|
|
219
|
+
const input = usage["input_tokens"];
|
|
220
|
+
const cacheRead = usage["cache_read_input_tokens"];
|
|
221
|
+
const cacheWrite = usage["cache_creation_input_tokens"];
|
|
222
|
+
return {
|
|
223
|
+
...prev,
|
|
224
|
+
...(typeof input === "number" ? { input } : {}),
|
|
225
|
+
...(typeof cacheRead === "number" ? { cacheRead } : {}),
|
|
226
|
+
...(typeof cacheWrite === "number" ? { cacheWrite } : {}),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
184
230
|
// `thinkingTokens` (0.3.257) → `reasoningTokens`: the per-model twin of
|
|
185
231
|
// `readThinkingTokens` above — same subset-of-outputTokens semantics (the SDK's
|
|
186
232
|
// own doc: "already counted inside outputTokens"), same absent ⇒ no key rule.
|
|
233
|
+
// A `modelUsage` entry is the SDK's per-model RUNNING TOTAL over the query, so
|
|
234
|
+
// it keeps `cumulative: true` (the flag binds the object it sits on).
|
|
187
235
|
function mapModelUsage(mu: SDKModelUsage): AgUsage {
|
|
188
236
|
return {
|
|
189
|
-
inputTokens: mu.inputTokens,
|
|
237
|
+
inputTokens: inclusiveInput(mu.inputTokens, mu.cacheReadInputTokens, mu.cacheCreationInputTokens),
|
|
190
238
|
outputTokens: mu.outputTokens,
|
|
191
|
-
|
|
192
|
-
cacheWriteTokens: mu.cacheCreationInputTokens,
|
|
239
|
+
...cacheBreakdown(mu.cacheReadInputTokens, mu.cacheCreationInputTokens),
|
|
193
240
|
...(mu.thinkingTokens !== undefined ? { reasoningTokens: mu.thinkingTokens } : {}),
|
|
194
241
|
costUsd: mu.costUSD,
|
|
195
242
|
serverToolRequests: mu.webSearchRequests,
|
|
@@ -201,7 +248,7 @@ function mapModelUsage(mu: SDKModelUsage): AgUsage {
|
|
|
201
248
|
// but a result frame is discriminant-validated only, so a leaner producer (a
|
|
202
249
|
// proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
|
|
203
250
|
// member passed the `!== null` check and threw a TypeError out of push()
|
|
204
|
-
// (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found
|
|
251
|
+
// (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found while writing §10.23),
|
|
205
252
|
// and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
|
|
206
253
|
// anything else ⇒ absent.
|
|
207
254
|
function serverToolRequestCount(usage: unknown): number | undefined {
|
|
@@ -213,6 +260,17 @@ function serverToolRequestCount(usage: unknown): number | undefined {
|
|
|
213
260
|
return typeof search === "number" && typeof fetch === "number" ? search + fetch : undefined;
|
|
214
261
|
}
|
|
215
262
|
|
|
263
|
+
// A result frame's usage → the turn terminal's usage. Its token counters are
|
|
264
|
+
// PER TURN (a streaming-input invoke's second result reports that turn alone),
|
|
265
|
+
// so the object is flagged `cumulative: false` (draft.5 §8.0 item 4; through
|
|
266
|
+
// 0.7.x it read `true`, and a "running total" that went down from one terminal
|
|
267
|
+
// to the next was the tell). `total_cost_usd` is different: the SDK's running
|
|
268
|
+
// cost over the `query()` call, which continues from restored state on a
|
|
269
|
+
// resumed or forked session and restarts on its reset commands. Its scope is
|
|
270
|
+
// not the object's, so it carries `costScope: "query"` (§4): a consumer takes
|
|
271
|
+
// the latest per scope, may subtract adjacent snapshots, and never sums them.
|
|
272
|
+
// `byModel` entries are the SDK's per-model running totals and keep their own
|
|
273
|
+
// `cumulative: true`.
|
|
216
274
|
function mapTurnUsage(
|
|
217
275
|
usage: SDKResultSuccessMsg["usage"],
|
|
218
276
|
totalCostUsd: number,
|
|
@@ -224,30 +282,40 @@ function mapTurnUsage(
|
|
|
224
282
|
}
|
|
225
283
|
const reasoningTokens = readThinkingTokens(usage);
|
|
226
284
|
return {
|
|
227
|
-
inputTokens: usage.input_tokens,
|
|
285
|
+
inputTokens: inclusiveInput(usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
|
|
228
286
|
outputTokens: usage.output_tokens,
|
|
229
|
-
|
|
230
|
-
cacheWriteTokens: usage.cache_creation_input_tokens,
|
|
287
|
+
...cacheBreakdown(usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
|
|
231
288
|
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
|
|
232
289
|
serverToolRequests: serverToolRequestCount(usage),
|
|
233
290
|
costUsd: totalCostUsd,
|
|
234
|
-
|
|
291
|
+
// The scope labels the cost, so it rides only beside a numeric costUsd.
|
|
292
|
+
...(typeof totalCostUsd === "number" ? { costScope: "query" } : {}),
|
|
293
|
+
cumulative: false,
|
|
235
294
|
...(Object.keys(byModel).length > 0 ? { byModel } : {}),
|
|
236
295
|
};
|
|
237
296
|
}
|
|
238
297
|
|
|
298
|
+
// Message-level usage: the Anthropic message stream's RUNNING TOTALS, so
|
|
299
|
+
// `cumulative: true`, with the cache-inclusive input add.
|
|
239
300
|
function mapMessageUsage(usage: BetaMessageT["usage"]): AgUsage {
|
|
240
301
|
const reasoningTokens = readThinkingTokens(usage);
|
|
241
302
|
return {
|
|
242
|
-
inputTokens: usage.input_tokens,
|
|
303
|
+
inputTokens: inclusiveInput(usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
|
|
243
304
|
outputTokens: usage.output_tokens,
|
|
244
|
-
|
|
245
|
-
cacheWriteTokens: usage.cache_creation_input_tokens ?? undefined,
|
|
305
|
+
...cacheBreakdown(usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
|
|
246
306
|
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
|
|
247
307
|
cumulative: true,
|
|
248
308
|
};
|
|
249
309
|
}
|
|
250
310
|
|
|
311
|
+
// A message usage without its `outputTokens` (the no-partials seal; see
|
|
312
|
+
// PendingMessage.usageDelta). A copy: the pending usage is not mutated.
|
|
313
|
+
function withoutOutputTokens(usage: AgUsage): AgUsage {
|
|
314
|
+
const out: AgUsage = {};
|
|
315
|
+
for (const [k, v] of Object.entries(usage)) if (k !== "outputTokens") Object.assign(out, { [k]: v });
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
|
|
251
319
|
// ─── citation mapping helpers ─────────────────────────────────────────────────
|
|
252
320
|
function mapCitations(citations: BetaTextCitationT[]): AgCitation[] {
|
|
253
321
|
const result: AgCitation[] = [];
|
|
@@ -358,7 +426,7 @@ function mcpToolResultContentToAgBlocks(content: McpToolResultContent): AgBlock[
|
|
|
358
426
|
return out;
|
|
359
427
|
}
|
|
360
428
|
|
|
361
|
-
// `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on
|
|
429
|
+
// `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on the
|
|
362
430
|
// defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
|
|
363
431
|
// `non_execution_kind` is "the harness-stamped reason an is_error:true result did
|
|
364
432
|
// not carry the tool's own execution output (user-rejected / permission-rule /
|
|
@@ -379,25 +447,28 @@ function readNonExecutionKinds(frame: unknown): Map<string, string> {
|
|
|
379
447
|
return out;
|
|
380
448
|
}
|
|
381
449
|
|
|
382
|
-
// rd-15 (
|
|
450
|
+
// rd-15 (ruling of 2026-09-24, fix the carries): each `tool_result_meta`
|
|
383
451
|
// entry, keyed by its `id` (the tool_use_id), verbatim: {id, non_execution_kind?,
|
|
384
452
|
// user_feedback?, remedy?} per the CLI's schema ("@internal Display metadata for
|
|
385
453
|
// this message's tool_result blocks"). Read through the JSON boundary; an entry
|
|
386
|
-
// without a string id is skipped. It rides the matching tool.done's `_meta
|
|
454
|
+
// without a string id is skipped. It rides the matching tool.done's `_meta`,
|
|
455
|
+
// through `carryVerbatim`: a CLI-authored subtree like the other wrapper
|
|
456
|
+
// carries, so a `fallback_credit_token` at any depth (a `remedy` can hold one)
|
|
457
|
+
// is deleted before it is emitted.
|
|
387
458
|
function readToolResultMetaEntries(frame: unknown): Map<string, JsonValue> {
|
|
388
459
|
const out = new Map<string, JsonValue>();
|
|
389
460
|
if (!isJsonObject(frame)) return out;
|
|
390
461
|
const list = frame["tool_result_meta"];
|
|
391
462
|
if (!Array.isArray(list)) return out;
|
|
392
463
|
for (const entry of list) {
|
|
393
|
-
if (isJsonObject(entry) && typeof entry["id"] === "string") out.set(entry["id"],
|
|
464
|
+
if (isJsonObject(entry) && typeof entry["id"] === "string") out.set(entry["id"], carryVerbatim(entry));
|
|
394
465
|
}
|
|
395
466
|
return out;
|
|
396
467
|
}
|
|
397
468
|
|
|
398
469
|
// The non_execution_kinds that mean the call was NOT PERMITTED to run →
|
|
399
470
|
// `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
|
|
400
|
-
// item 15 routes Claude's permission denials to it;
|
|
471
|
+
// item 15 routes Claude's permission denials to it; 2026-09-23).
|
|
401
472
|
// `interrupted`, `cancelled`, absent and any unknown value are not denials and
|
|
402
473
|
// keep "error" (no guessing).
|
|
403
474
|
function isDenialKind(kind: string | undefined): boolean {
|
|
@@ -436,9 +507,8 @@ function assistantErrorRetriable(errCode: NonNullable<SDKAssistantError>): boole
|
|
|
436
507
|
// open message named by `messageId`. The caller passes the frame's wrapper
|
|
437
508
|
// carry ONLY for blockIndex 0, mirroring the "signature on first block"
|
|
438
509
|
// precedent (§8 item 8, Gemini thoughtSignature), in two bags:
|
|
439
|
-
// - `blockProviderMetadata`: the REPLAY-side wrapper facts (
|
|
440
|
-
// `resumed_from_incomplete_thinking
|
|
441
|
-
// `usage_report`, the turn-binding family). `text` / `thinking` /
|
|
510
|
+
// - `blockProviderMetadata`: the REPLAY-side wrapper facts (since draft.5,
|
|
511
|
+
// only `resumed_from_incomplete_thinking`). `text` / `thinking` /
|
|
442
512
|
// `redacted_thinking` and the `tool_use` family land it on their *.start
|
|
443
513
|
// event. The rarer block-0 shapes (mcp_tool_result / compaction / the
|
|
444
514
|
// default content.block) never apply it, so those facts drop there (a
|
|
@@ -706,7 +776,7 @@ function isSDKMessage(v: unknown): v is SDKMessage {
|
|
|
706
776
|
// `message.remove` (§8 item 19) and the rest of the frame has no home. It is
|
|
707
777
|
// NOT in the sets below either. Its dedicated branch does the retraction and
|
|
708
778
|
// then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
|
|
709
|
-
//
|
|
779
|
+
// the item-22 reading for half-mapped frames — see that branch).
|
|
710
780
|
//
|
|
711
781
|
// ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
|
|
712
782
|
// §12) — not 15 distinct ext keys (ext-vocabulary sprawl, the standing
|
|
@@ -822,11 +892,27 @@ const HOST_ONLY_WRAPPER_KEYS: ReadonlySet<string> = new Set([
|
|
|
822
892
|
"api_error",
|
|
823
893
|
"api_error_params",
|
|
824
894
|
"api_error_code",
|
|
825
|
-
// rd-15 (
|
|
895
|
+
// rd-15 (defer the field, fix the carries): three more @internal
|
|
826
896
|
// CLI assistant-wrapper strings, carried where the host can read them.
|
|
827
897
|
"error_details",
|
|
828
898
|
"advisor_model",
|
|
829
899
|
"attribution_agent",
|
|
900
|
+
// draft.5 (§10 item 45; §8.0 item 19 for `supersedes`): the rest of the
|
|
901
|
+
// wrapper bag. Each is host-only by its own sdk.d.ts doc (never inside
|
|
902
|
+
// `message.content`, not replayed to the model): the /context and /usage
|
|
903
|
+
// twins, the turn-binding family, the interrupt-truncation flag, and the
|
|
904
|
+
// refusal-fallback supersede list, whose eviction already runs as
|
|
905
|
+
// `message.remove` (the list is an audit copy). Through 0.7.x they rode
|
|
906
|
+
// `providerMetadata`. `resumed_from_incomplete_thinking` is the one wrapper
|
|
907
|
+
// key NOT here: its doc makes it a flag a history replayed through the
|
|
908
|
+
// bridge must carry back, so it stays replay-side.
|
|
909
|
+
"context_usage",
|
|
910
|
+
"usage_report",
|
|
911
|
+
"user_message_uuid",
|
|
912
|
+
"user_message_uuids",
|
|
913
|
+
"resume_reason",
|
|
914
|
+
"aborted",
|
|
915
|
+
"supersedes",
|
|
830
916
|
]);
|
|
831
917
|
|
|
832
918
|
// `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
|
|
@@ -852,7 +938,8 @@ function readNarrationBlockIndexes(v: unknown): number[] | undefined {
|
|
|
852
938
|
// depth (withoutCreditTokens). Every verbatim carrier of this facet goes
|
|
853
939
|
// through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
|
|
854
940
|
// carries, provider-raw blocks, and the CLI/API wrapper subtrees
|
|
855
|
-
// (context_usage, usage_report, diagnostics, api_error_params, subagent_stats
|
|
941
|
+
// (context_usage, usage_report, diagnostics, api_error_params, subagent_stats,
|
|
942
|
+
// the `tool_result_meta` entries).
|
|
856
943
|
// Model- or tool-authored payloads (tool input, a deferred tool call, MCP
|
|
857
944
|
// structuredContent / _meta / resourceLinks, structured_output) are NOT
|
|
858
945
|
// stripped: a key there is user content, and the wire already carries the same
|
|
@@ -861,7 +948,7 @@ function carryVerbatim(v: unknown): JsonValue {
|
|
|
861
948
|
return withoutCreditTokens(JsonValue.parse(v));
|
|
862
949
|
}
|
|
863
950
|
|
|
864
|
-
// rd-15 / SPEC §13.
|
|
951
|
+
// rd-15 / SPEC §13.10: a provider credit or bearer token is never
|
|
865
952
|
// emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
|
|
866
953
|
// (top level and per fallback), so every key of that name is deleted at any
|
|
867
954
|
// depth; everything else is kept verbatim.
|
|
@@ -887,15 +974,25 @@ function toolResultText(content: unknown): string | undefined {
|
|
|
887
974
|
}
|
|
888
975
|
|
|
889
976
|
// The namespace of the facet's own harness keys on a tool.done `_meta` (the
|
|
890
|
-
// subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta"
|
|
977
|
+
// subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta",
|
|
978
|
+
// and since draft.5 the two host records below). SPEC §2.1 *Host records*: a
|
|
979
|
+
// producer carries such a record under a key in a namespace it owns.
|
|
891
980
|
const HARNESS_META_PREFIX = "anthropic/";
|
|
981
|
+
// draft.5 (§2.1 Host records, §10 item 45): the SDK's verbatim
|
|
982
|
+
// `tool_use_result.resourceLinks` list (through 0.7.x on the tool.done's
|
|
983
|
+
// `providerMetadata.resourceLinks`).
|
|
984
|
+
const RESOURCE_LINKS_META_KEY = `${HARNESS_META_PREFIX}resourceLinks`;
|
|
985
|
+
// draft.5 (§10 item 45): the live `permission_denied` notice's decision context
|
|
986
|
+
// ({decisionReasonType?, decisionReasonCode?, decisionReason?, agentId?}; through
|
|
987
|
+
// 0.7.x those four rode the denied call's tool.done `providerMetadata` flat).
|
|
988
|
+
const PERMISSION_DENIED_META_KEY = `${HARNESS_META_PREFIX}permissionDenied`;
|
|
892
989
|
|
|
893
990
|
// A tool.done's host-only `_meta`: the tool-authored MCP sibling `_meta` merged
|
|
894
991
|
// with the facet's own harness keys. The harness namespace is RESERVED: every
|
|
895
992
|
// sibling key under "anthropic/" is dropped before the harness keys are
|
|
896
993
|
// written, so a tool (a malicious MCP server) can never present a forged
|
|
897
994
|
// harness fact, such as an agent report or a remedy pointing a host at its URL,
|
|
898
|
-
// even for a call the facet writes no harness key for (
|
|
995
|
+
// even for a call the facet writes no harness key for (a review of the
|
|
899
996
|
// rd-15 carry; the CLI itself strips its own reserved `com.anthropic/` prefix
|
|
900
997
|
// from server `_meta`). Every other sibling key is kept verbatim. undefined
|
|
901
998
|
// when nothing remains.
|
|
@@ -909,7 +1006,7 @@ function mergeHarnessMeta(sibling: AgMeta | undefined, harness: { [k: string]: J
|
|
|
909
1006
|
}
|
|
910
1007
|
|
|
911
1008
|
// `wire_tool_inputs` (CLI 2.1.280, @internal, undeclared in sdk.d.ts; first seen
|
|
912
|
-
// on
|
|
1009
|
+
// on the subagent captures): "tool_use.input exactly as the API produced
|
|
913
1010
|
// it, keyed by tool_use id, for a message whose message.content carries the
|
|
914
1011
|
// client-normalized input. Round-tripped so a replayed history echoes each
|
|
915
1012
|
// earlier tool call back to the API as the API emitted it" (the CLI's own
|
|
@@ -957,6 +1054,13 @@ function jsonEqual(x: unknown, y: unknown): boolean {
|
|
|
957
1054
|
return false;
|
|
958
1055
|
}
|
|
959
1056
|
|
|
1057
|
+
// The id of the tool call a result's `deferred_tool_use` parked, when it names
|
|
1058
|
+
// one (a string `id`); undefined otherwise. Read through the JSON boundary.
|
|
1059
|
+
function readDeferredCall(v: unknown): string | undefined {
|
|
1060
|
+
const deferred = isJsonObject(v) ? v["deferred_tool_use"] : undefined;
|
|
1061
|
+
return isJsonObject(deferred) && typeof deferred["id"] === "string" ? deferred["id"] : undefined;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
960
1064
|
// A result's `terminal_reason` when it names why the turn ended other than a
|
|
961
1065
|
// normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
|
|
962
1066
|
// live API error's own value is "api_error", which is also the generic code, so
|
|
@@ -1158,7 +1262,7 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
|
|
|
1158
1262
|
const raw: unknown = msg;
|
|
1159
1263
|
// `origin` (SDKMessageOrigin, on the result arms): set on the result of a turn
|
|
1160
1264
|
// the framework WOKE, not the user, e.g. {kind: "task-notification"} after a
|
|
1161
|
-
// background subagent reported (
|
|
1265
|
+
// background subagent reported (the background capture). turn.start's
|
|
1162
1266
|
// `trigger` is a frozen enum, so it rides here verbatim.
|
|
1163
1267
|
const origin = isJsonObject(raw) && isJsonObject(raw["origin"]) ? carryVerbatim(raw["origin"]) : undefined;
|
|
1164
1268
|
const subagentStats =
|
|
@@ -1175,18 +1279,18 @@ function resultMetaPayload(msg: SDKResultMsg, closesAsError: boolean): { [k: str
|
|
|
1175
1279
|
// `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
|
|
1176
1280
|
// input}`): the tool call a host's PreToolUse `defer` decision parked, which
|
|
1177
1281
|
// the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
|
|
1178
|
-
// the host needs it to act on the parked call.
|
|
1179
|
-
//
|
|
1180
|
-
//
|
|
1181
|
-
//
|
|
1182
|
-
//
|
|
1282
|
+
// the host needs it to act on the parked call. Carried WHOLE and verbatim
|
|
1283
|
+
// here (the `subagent_stats` precedent), and on a deferred close
|
|
1284
|
+
// (stop_reason "tool_deferred") the turn ALSO closes paused with an approval
|
|
1285
|
+
// ask for it (see the success arm, draft.5 §8.0 item 32). The live capture is
|
|
1286
|
+
// defer-tool-sonnet5.
|
|
1183
1287
|
const deferredToolUse =
|
|
1184
1288
|
isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
|
|
1185
1289
|
// `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
|
|
1186
1290
|
// API error that ended the turn. It already decides `retriable` on an
|
|
1187
1291
|
// is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
|
|
1188
1292
|
// the census allowlist's "carry candidate the first time an error seed
|
|
1189
|
-
// surfaces it" (
|
|
1293
|
+
// surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
|
|
1190
1294
|
const apiErrorStatus =
|
|
1191
1295
|
isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
|
|
1192
1296
|
// `stop_reason` on a result that closes as turn.error: turn.error has no
|
|
@@ -1249,12 +1353,13 @@ function guardedTurnUsage(msg: SDKResultMsg): AgUsage | undefined {
|
|
|
1249
1353
|
export interface ClaudeNormalizerOptions {
|
|
1250
1354
|
/**
|
|
1251
1355
|
* The partition-root `threadId` stamped on every entity this normalizer
|
|
1252
|
-
* emits (SPEC §
|
|
1253
|
-
*
|
|
1254
|
-
* partition root). The Claude Agent SDK
|
|
1255
|
-
* `session_id` — so with this option ABSENT
|
|
1256
|
-
* `session_id` as the threadId, a
|
|
1257
|
-
*
|
|
1356
|
+
* emits (SPEC §1.2, the partition root, and §8.0 host obligation 6: the root
|
|
1357
|
+
* each unit carries so a key-value persistence layer can write it knowing
|
|
1358
|
+
* only its own id, its parent, and the partition root). The Claude Agent SDK
|
|
1359
|
+
* wire has no thread concept — only `session_id` — so with this option ABSENT
|
|
1360
|
+
* the adapter relabels `session_id` as the threadId (or, on a leading
|
|
1361
|
+
* tool_result frame that carries none, the turn's own id), a placeholder in
|
|
1362
|
+
* the same spirit as the openai/vercel facets' fixed labels. That placeholder is fine for
|
|
1258
1363
|
* self-contained streams but LEAKS into any consumer that persists
|
|
1259
1364
|
* events verbatim under its own thread identity (guuey#415: mid-stream
|
|
1260
1365
|
* events carried the session id while the runtime's session records
|
|
@@ -1270,7 +1375,7 @@ export interface ClaudeNormalizerOptions {
|
|
|
1270
1375
|
* turn by its SDK message id or frame uuid, unique by construction). A host
|
|
1271
1376
|
* folds every invoke of a conversation into ONE Reducer, so a stem that
|
|
1272
1377
|
* restarted with each invoke repeated those ids across invokes (DC-10, from
|
|
1273
|
-
*
|
|
1378
|
+
* the D3 review). Absent, each normalizer draws a random
|
|
1274
1379
|
* `claude_<16 hex>` stem at most once, lazily (only when a fallback id is
|
|
1275
1380
|
* first needed, so the common path draws no randomness), and holds it
|
|
1276
1381
|
* OUTSIDE the atomic-push rebuild, so a rebuild reproduces it. Pass a fixed
|
|
@@ -1310,7 +1415,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1310
1415
|
// tool_result (same non-null parent_tool_use_id) can route to it instead.
|
|
1311
1416
|
const subagentTurnByParentToolUseId = new Map<string, string>();
|
|
1312
1417
|
|
|
1313
|
-
// INV-TURN (SPEC:743;
|
|
1418
|
+
// INV-TURN (SPEC:743; ruling B, 2026-09-23): ONE turnId names
|
|
1314
1419
|
// exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
|
|
1315
1420
|
// OPENS it: the first assistant message's id (`m.id`, from a complete frame
|
|
1316
1421
|
// or a stream `message_start`) in the ordinary case, or the frame's own
|
|
@@ -1353,20 +1458,40 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1353
1458
|
}
|
|
1354
1459
|
return openTopTurnId;
|
|
1355
1460
|
}
|
|
1461
|
+
// The turn's trigger (AgTrigger, folded onto AgTurnRecord.trigger): the CLI's
|
|
1462
|
+
// `user_message_uuid` echo, read ONLY from the frame that OPENS a top-level
|
|
1463
|
+
// turn. The three stamped openers are a stream `message_start`, a complete
|
|
1464
|
+
// assistant frame and a success result that opens a result-only turn; each
|
|
1465
|
+
// caller checks `openTopTurnId === undefined` and `parent_tool_use_id === null`
|
|
1466
|
+
// before it mints the turn id, and passes the result to `a.openTurn` BEFORE
|
|
1467
|
+
// anything else of the turn is emitted, so the turn's one turn.start carries
|
|
1468
|
+
// it. turn.start is never re-sent to add one: a turn opened by a notice, a
|
|
1469
|
+
// tool_result or an error result, and a turn whose uuid first appears on a
|
|
1470
|
+
// later frame, carry no trigger. An error result is never an opener here,
|
|
1471
|
+
// because its echo can be a client-minted queue key (sdk.d.ts 0.3.280, the
|
|
1472
|
+
// delivery-failure case). `kind: "user"` means a user-role send the host
|
|
1473
|
+
// submitted with that uuid, not human authorship; `user_message_uuids` and
|
|
1474
|
+
// thinking_tokens frames are never read for it.
|
|
1475
|
+
function openerTrigger(uuid: unknown): { trigger: AgTrigger } | undefined {
|
|
1476
|
+
return typeof uuid === "string" && uuid.length > 0 ? { trigger: { kind: "user", ref: uuid } } : undefined;
|
|
1477
|
+
}
|
|
1356
1478
|
// The result frame closes the open turn (or, for a result-only turn, the one
|
|
1357
1479
|
// it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
|
|
1358
1480
|
// notice or stream opened it: the CL-09 result-only API-error path, a
|
|
1359
1481
|
// startup-failure result, a local-command result) is OPENED here with an
|
|
1360
1482
|
// explicit turn.start before anything else the result emits (INV-TURN,
|
|
1361
1483
|
// SPEC:743: every turn is opened by exactly one turn.start and closed by
|
|
1362
|
-
// exactly one terminal;
|
|
1484
|
+
// exactly one terminal; 2026-09-23). Through the B commit such a
|
|
1363
1485
|
// turn was only closed, and reduce() minted a stub record whose threadId was
|
|
1364
1486
|
// the turnId. An open turn already has its turn.start (openMessage).
|
|
1365
|
-
|
|
1487
|
+
// `openerUuid`: the success result's `user_message_uuid`, which becomes the
|
|
1488
|
+
// trigger when this result OPENS its turn (see `openerTrigger`). The error
|
|
1489
|
+
// arm passes none.
|
|
1490
|
+
function closingTopTurnId(resultUuid: unknown, sessionId: string, openerUuid?: unknown): string {
|
|
1366
1491
|
let turnId = openTopTurnId;
|
|
1367
1492
|
if (turnId === undefined) {
|
|
1368
1493
|
turnId = topTurnId(resultUuid, undefined);
|
|
1369
|
-
a.openTurn(turnId, options.threadId ?? sessionId);
|
|
1494
|
+
a.openTurn(turnId, options.threadId ?? sessionId, openerTrigger(openerUuid));
|
|
1370
1495
|
}
|
|
1371
1496
|
openTopTurnId = undefined;
|
|
1372
1497
|
closedTopTurnIds.add(turnId);
|
|
@@ -1397,7 +1522,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1397
1522
|
return minted;
|
|
1398
1523
|
}
|
|
1399
1524
|
|
|
1400
|
-
// ONE subagent bracket per RUN (
|
|
1525
|
+
// ONE subagent bracket per RUN (ruling of 2026-09-23; INV-TURN,
|
|
1401
1526
|
// SPEC:743; SPEC:807 "subagent.done: Close the nested turn"). Through 0.7.0's
|
|
1402
1527
|
// B commit the bracket was per MESSAGE: a run of N nested messages emitted N
|
|
1403
1528
|
// subagent.start/subagent.done pairs on its one id, closing it N times with
|
|
@@ -1411,12 +1536,12 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1411
1536
|
// by the open turn, a retraction's message.remove by the removed message's
|
|
1412
1537
|
// own turn. What still backfills: tool.args.* and ext.* (no turnId at all).
|
|
1413
1538
|
// A top-level tool_result with NO turn open no longer lands on a closed turn:
|
|
1414
|
-
// since B-resume (
|
|
1539
|
+
// since B-resume (9c46845) it opens its own turn, named by its frame uuid (see
|
|
1415
1540
|
// the user branch), and a nested one for a run this invoke never opened opens
|
|
1416
1541
|
// a fresh run the same way.
|
|
1417
1542
|
//
|
|
1418
|
-
// B-STRICT NESTED TERMINALS (draft.4, the
|
|
1419
|
-
// 2026-09-24
|
|
1543
|
+
// B-STRICT NESTED TERMINALS (draft.4, the nested-turn ruling Q1,
|
|
1544
|
+
// 2026-09-24). A nested turn opens
|
|
1420
1545
|
// with exactly one subagent.start and closes with exactly one turn.done |
|
|
1421
1546
|
// turn.error | turn.abort carrying its turnId, IMMEDIATELY followed by its
|
|
1422
1547
|
// subagent.done (a no-fold bracket close that restores the owner). The five
|
|
@@ -1457,7 +1582,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1457
1582
|
// The ids of every Agent (or legacy Task) tool call seen in this invoke. Only
|
|
1458
1583
|
// a result for one of these can carry an AgentOutput: a third-party tool whose
|
|
1459
1584
|
// result happens to hold an `agentId` (a CRM, a ticketing system, any agent
|
|
1460
|
-
// registry) is not Anthropic's Agent run report (
|
|
1585
|
+
// registry) is not Anthropic's Agent run report (a review of 5e7561c).
|
|
1461
1586
|
const agentCallIds = new Set<string>();
|
|
1462
1587
|
function openRun(parentToolUseId: string, turnId: string, parentTurnId: string): void {
|
|
1463
1588
|
if (openRuns.has(parentToolUseId)) return;
|
|
@@ -1530,9 +1655,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1530
1655
|
// tokens stripped) and the message it describes, emitted on that turn's turn.done.
|
|
1531
1656
|
const stopDetailsByTurn = new Map<string, { readonly messageId: string; readonly value: JsonValue }>();
|
|
1532
1657
|
|
|
1533
|
-
// The live denial's diagnostic fields, camelCased — the
|
|
1534
|
-
// on the
|
|
1535
|
-
//
|
|
1658
|
+
// The live denial's diagnostic fields, camelCased — the record under
|
|
1659
|
+
// PERMISSION_DENIED_META_KEY on the denied call's tool.done `_meta` (the
|
|
1660
|
+
// enriched `<turnId>:denials` carrier, or the tool_result that closes the
|
|
1661
|
+
// call). undefined when the live frame carried none of them (no empty record).
|
|
1536
1662
|
function liveDenialMeta(live: LiveDenial | undefined): { [k: string]: JsonValue } | undefined {
|
|
1537
1663
|
if (
|
|
1538
1664
|
live === undefined ||
|
|
@@ -1657,6 +1783,21 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1657
1783
|
* frame carries again).
|
|
1658
1784
|
*/
|
|
1659
1785
|
turnBindingCarried: boolean;
|
|
1786
|
+
/**
|
|
1787
|
+
* draft.5 §4: the latest NATIVE input trio (Anthropic's cache-exclusive
|
|
1788
|
+
* `input_tokens` and the two cache counters, field-wise latest wins across
|
|
1789
|
+
* message_start, complete frames and message_delta), from which the
|
|
1790
|
+
* cache-inclusive `usage.inputTokens` is derived, so a partial update never
|
|
1791
|
+
* needs a subtraction.
|
|
1792
|
+
*/
|
|
1793
|
+
rawInput: { input?: number; cacheRead?: number; cacheWrite?: number };
|
|
1794
|
+
/**
|
|
1795
|
+
* True once a stream `message_delta` usage merged. Without one (no partial
|
|
1796
|
+
* messages), an assistant frame's `output_tokens` is the SDK's placeholder
|
|
1797
|
+
* for a count it reports on the result, so the seal omits `outputTokens`
|
|
1798
|
+
* (draft.5 §8.0 item 4) and keeps the input and cache fields.
|
|
1799
|
+
*/
|
|
1800
|
+
usageDelta: boolean;
|
|
1660
1801
|
};
|
|
1661
1802
|
// workspace#7 — per-block accumulation between content_block_start and its
|
|
1662
1803
|
// content_block_stop. `emitted` marks blocks that arrive complete inside the
|
|
@@ -1703,7 +1844,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1703
1844
|
finalizeStreamBlock(p, idx, atFlush);
|
|
1704
1845
|
}
|
|
1705
1846
|
}
|
|
1706
|
-
a.closeMessage(p.emittedId, p.usage);
|
|
1847
|
+
a.closeMessage(p.emittedId, p.usage !== undefined && !p.usageDelta ? withoutOutputTokens(p.usage) : p.usage);
|
|
1707
1848
|
// The subagent bracket is per RUN now (see `openRun`), so sealing a nested
|
|
1708
1849
|
// message no longer closes its nested turn.
|
|
1709
1850
|
}
|
|
@@ -1770,8 +1911,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1770
1911
|
// streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
|
|
1771
1912
|
// (same end-then-opaque order as the complete arm), the MANDATORY
|
|
1772
1913
|
// tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
|
|
1773
|
-
// `atFlush` (INV-FLUSH (3), draft.4; the
|
|
1774
|
-
// fold + honest flush; opaque at flush forbidden";
|
|
1914
|
+
// `atFlush` (INV-FLUSH (3), draft.4; the fold/flush ruling, "snapshot
|
|
1915
|
+
// fold + honest flush; opaque at flush forbidden"; leg C1): the
|
|
1775
1916
|
// stream ENDED with this block open, so the close lands NO new content. The
|
|
1776
1917
|
// lifecycle closes stay (text.end with its already-received citations,
|
|
1777
1918
|
// reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
|
|
@@ -1854,6 +1995,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1854
1995
|
|
|
1855
1996
|
if (ev.type === "message_start") {
|
|
1856
1997
|
const m = ev.message;
|
|
1998
|
+
// Read BEFORE topTurnId mints: does this frame OPEN a top-level turn?
|
|
1999
|
+
const opensTopTurn = msg.parent_tool_use_id === null && openTopTurnId === undefined;
|
|
1857
2000
|
const turnId =
|
|
1858
2001
|
msg.parent_tool_use_id !== null
|
|
1859
2002
|
? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
|
|
@@ -1891,6 +2034,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1891
2034
|
parentTurnId,
|
|
1892
2035
|
blockIndex: 0,
|
|
1893
2036
|
usage: mapMessageUsage(m.usage),
|
|
2037
|
+
rawInput: nativeInput({}, m.usage),
|
|
2038
|
+
usageDelta: false,
|
|
1894
2039
|
streamed: true,
|
|
1895
2040
|
streamBlocks: new Map(),
|
|
1896
2041
|
ttftCarried: false,
|
|
@@ -1898,6 +2043,10 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
1898
2043
|
turnBindingCarried: false,
|
|
1899
2044
|
};
|
|
1900
2045
|
pending = open;
|
|
2046
|
+
// The turn's trigger rides its turn.start, so the turn opens explicitly
|
|
2047
|
+
// before openMessage would synthesize a trigger-less one.
|
|
2048
|
+
const trigger = opensTopTurn ? openerTrigger(msg.user_message_uuid) : undefined;
|
|
2049
|
+
if (trigger !== undefined) a.openTurn(turnId, options.threadId ?? msg.session_id, trigger);
|
|
1901
2050
|
a.openMessage({
|
|
1902
2051
|
id: open.emittedId,
|
|
1903
2052
|
role: "assistant",
|
|
@@ -2063,14 +2212,14 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2063
2212
|
// name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
|
|
2064
2213
|
// no bag, byte-identical.
|
|
2065
2214
|
//
|
|
2066
|
-
// X5 (
|
|
2215
|
+
// X5 (2026-09-23): it rides the delta's host-only `_meta`, not
|
|
2067
2216
|
// `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
|
|
2068
2217
|
// that must round-trip to the provider), and the Messages API never
|
|
2069
2218
|
// consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
|
|
2070
2219
|
// on start events, so the estimate is now LIVE-ONLY (it used to fold
|
|
2071
2220
|
// last-value-wins onto the reasoning block) — the same standing as its
|
|
2072
2221
|
// `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
|
|
2073
|
-
// consumer read the folded value (guuey/ggui checked
|
|
2222
|
+
// consumer read the folded value (guuey/ggui checked).
|
|
2074
2223
|
// `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
|
|
2075
2224
|
// primitive (the reasoning.start precedent in `emitAssistantBlock`), and
|
|
2076
2225
|
// the sugar's only extra step, de-cumulation, is a pass-through for a
|
|
@@ -2130,9 +2279,20 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2130
2279
|
// does not declare `output_tokens_details`), subset of outputTokens; see
|
|
2131
2280
|
// `readThinkingTokens`'s doc.
|
|
2132
2281
|
const reasoningTokens = readThinkingTokens(u);
|
|
2282
|
+
// draft.5 §4: the input side is re-derived from the merged native trio, so
|
|
2283
|
+
// a delta carrying any one counter keeps `inputTokens` cache-inclusive.
|
|
2284
|
+
const touchesInput =
|
|
2285
|
+
typeof u.input_tokens === "number" ||
|
|
2286
|
+
typeof u.cache_read_input_tokens === "number" ||
|
|
2287
|
+
typeof u.cache_creation_input_tokens === "number";
|
|
2288
|
+
p.rawInput = nativeInput(p.rawInput, u);
|
|
2289
|
+
const inputTokens = touchesInput
|
|
2290
|
+
? inclusiveInput(p.rawInput.input, p.rawInput.cacheRead, p.rawInput.cacheWrite)
|
|
2291
|
+
: undefined;
|
|
2292
|
+
p.usageDelta = true;
|
|
2133
2293
|
p.usage = {
|
|
2134
2294
|
...(p.usage ?? {}),
|
|
2135
|
-
...(
|
|
2295
|
+
...(inputTokens !== undefined ? { inputTokens } : {}),
|
|
2136
2296
|
...(typeof u.output_tokens === "number" ? { outputTokens: u.output_tokens } : {}),
|
|
2137
2297
|
...(typeof u.cache_read_input_tokens === "number"
|
|
2138
2298
|
? { cacheReadTokens: u.cache_read_input_tokens }
|
|
@@ -2219,14 +2379,14 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2219
2379
|
// itself (see the dedicated `permission_denied` branch below).
|
|
2220
2380
|
const live = deniedLiveByToolUseId.get(denial.tool_use_id);
|
|
2221
2381
|
const liveFields = liveDenialMeta(live);
|
|
2222
|
-
const
|
|
2223
|
-
liveFields !== undefined ?
|
|
2382
|
+
const denialMeta =
|
|
2383
|
+
liveFields !== undefined ? mergeHarnessMeta(undefined, { [PERMISSION_DENIED_META_KEY]: liveFields }) : undefined;
|
|
2224
2384
|
a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
|
|
2225
2385
|
a.toolDone({
|
|
2226
2386
|
toolCallId: denial.tool_use_id,
|
|
2227
2387
|
content: live !== undefined ? [{ type: "text", text: live.message }] : [],
|
|
2228
2388
|
outcome: "denied",
|
|
2229
|
-
...(
|
|
2389
|
+
...(denialMeta !== undefined ? { _meta: denialMeta } : {}),
|
|
2230
2390
|
});
|
|
2231
2391
|
}
|
|
2232
2392
|
a.closeMessage(denialMsgId);
|
|
@@ -2236,6 +2396,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2236
2396
|
function drive(msg: SDKMessage): void {
|
|
2237
2397
|
if (msg.type === "assistant") {
|
|
2238
2398
|
const m = msg.message;
|
|
2399
|
+
// Read BEFORE topTurnId mints: does this frame OPEN a top-level turn?
|
|
2400
|
+
const opensTopTurn = msg.parent_tool_use_id === null && openTopTurnId === undefined;
|
|
2239
2401
|
const turnId =
|
|
2240
2402
|
msg.parent_tool_use_id !== null
|
|
2241
2403
|
? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
|
|
@@ -2263,10 +2425,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2263
2425
|
if (msg.supersedes !== undefined && msg.supersedes.length > 0) {
|
|
2264
2426
|
retractUuids(msg.supersedes);
|
|
2265
2427
|
}
|
|
2266
|
-
// The raw uuid list is ALSO carried losslessly as `
|
|
2267
|
-
// this message's first content block
|
|
2268
|
-
// block
|
|
2269
|
-
//
|
|
2428
|
+
// The raw uuid list is ALSO carried losslessly as host-only `_meta` on
|
|
2429
|
+
// this message's first content block, or on `message.metadata` where no
|
|
2430
|
+
// block anchors it (§8.0 item 19, draft.5; through 0.7.x it rode
|
|
2431
|
+
// `providerMetadata`) — an audit trail independent of whether every
|
|
2432
|
+
// targeted uuid was resolvable above.
|
|
2270
2433
|
//
|
|
2271
2434
|
// 0.3.217 wrapper-level siblings join the SAME first-block carrier
|
|
2272
2435
|
// (closing the two disclosed gaps from the 0.3.217 bump audit), wire
|
|
@@ -2336,7 +2499,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2336
2499
|
wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
|
|
2337
2500
|
}
|
|
2338
2501
|
// `message.diagnostics` (a Messages API response field, first seen live on
|
|
2339
|
-
//
|
|
2502
|
+
// the defer-tool-sonnet5-resume-unavailable capture): per-response
|
|
2340
2503
|
// diagnostics, there `{cache_miss_reason: {type: "tools_changed",
|
|
2341
2504
|
// cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
|
|
2342
2505
|
// Response-only (never sent back on replay), so it rides host-only `_meta`
|
|
@@ -2388,7 +2551,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2388
2551
|
if (assistantApiErrorCode !== undefined) {
|
|
2389
2552
|
wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
|
|
2390
2553
|
}
|
|
2391
|
-
// rd-15 (
|
|
2554
|
+
// rd-15 (ruling of 2026-09-24: defer the neutral remedy field, fix the
|
|
2392
2555
|
// vendor carries; a 0.7.0 carry with zero golden moves). Three more
|
|
2393
2556
|
// @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
|
|
2394
2557
|
// 0.3.280 (so read through the JSON boundary), carried verbatim under their
|
|
@@ -2440,6 +2603,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2440
2603
|
parentTurnId,
|
|
2441
2604
|
blockIndex: 0,
|
|
2442
2605
|
usage: undefined,
|
|
2606
|
+
rawInput: {},
|
|
2607
|
+
usageDelta: false,
|
|
2443
2608
|
streamed: false,
|
|
2444
2609
|
streamBlocks: new Map(),
|
|
2445
2610
|
ttftCarried: false,
|
|
@@ -2447,6 +2612,9 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2447
2612
|
turnBindingCarried: false,
|
|
2448
2613
|
};
|
|
2449
2614
|
pending = open;
|
|
2615
|
+
// The turn's trigger rides its turn.start (see `openerTrigger`).
|
|
2616
|
+
const trigger = opensTopTurn ? openerTrigger(msg.user_message_uuid) : undefined;
|
|
2617
|
+
if (trigger !== undefined) a.openTurn(turnId, options.threadId ?? msg.session_id, trigger);
|
|
2450
2618
|
a.openMessage({
|
|
2451
2619
|
id: open.emittedId,
|
|
2452
2620
|
role: "assistant",
|
|
@@ -2457,7 +2625,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2457
2625
|
}
|
|
2458
2626
|
const messageId = open.emittedId;
|
|
2459
2627
|
// rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
|
|
2460
|
-
// {type, category, explanation,
|
|
2628
|
+
// {type: "refusal", category, explanation}, the shape @anthropic-ai/sdk
|
|
2629
|
+
// 0.93.0 declares; any further member is kept too) is carried verbatim on its
|
|
2461
2630
|
// turn's closing turn.done.messageMetadata, which folds onto the message it
|
|
2462
2631
|
// names (SPEC §5 turn.done row). The CLOSING response's value only: a later
|
|
2463
2632
|
// response of the turn without one clears it. Every `fallback_credit_token`,
|
|
@@ -2509,18 +2678,22 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2509
2678
|
if (resumeReason !== undefined) wrapperMetaRaw["resume_reason"] = resumeReason;
|
|
2510
2679
|
}
|
|
2511
2680
|
}
|
|
2512
|
-
// X5 (
|
|
2681
|
+
// X5 (the 2026-09-23 re-cut): the bag mixes two kinds of fact. SPEC
|
|
2513
2682
|
// §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
|
|
2514
2683
|
// round-trip to the provider) and `_meta` host-only side metadata.
|
|
2515
|
-
//
|
|
2516
|
-
//
|
|
2517
|
-
//
|
|
2518
|
-
//
|
|
2519
|
-
//
|
|
2520
|
-
//
|
|
2521
|
-
// (message.metadata is
|
|
2684
|
+
// Every key in HOST_ONLY_WRAPPER_KEYS is a CLI-wrapper fact the Messages
|
|
2685
|
+
// API never consumes, so where the bag anchors on a BLOCK it rides that
|
|
2686
|
+
// block's start event `_meta` (`reduce()` folds it onto `block._meta`,
|
|
2687
|
+
// keeping the per-frame anchoring). Since draft.5 (§10 item 45) the only
|
|
2688
|
+
// key left for `providerMetadata` is `resumed_from_incomplete_thinking`.
|
|
2689
|
+
// The split is by key, so the combined bag, and the `message.metadata`
|
|
2690
|
+
// path below that uses it, stay byte-identical (message.metadata is
|
|
2691
|
+
// already `AgMeta`). A frame whose first block is a tool call anchors no
|
|
2692
|
+
// host half (tool.start folds no `_meta`), so its host keys arrive on a
|
|
2693
|
+
// `message.metadata` event after the block (the streamed path already
|
|
2694
|
+
// carries the turn-binding family there).
|
|
2522
2695
|
//
|
|
2523
|
-
// Consumer check (
|
|
2696
|
+
// Consumer check (2026-09-23): ggui has none of these names.
|
|
2524
2697
|
// No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
|
|
2525
2698
|
// the native frame. guuey asked that the triad move as ONE unit; the
|
|
2526
2699
|
// result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
|
|
@@ -2540,7 +2713,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2540
2713
|
// Everything below the block loop (wrapper carry via message.metadata,
|
|
2541
2714
|
// usage, error close, uuid registration) still runs.
|
|
2542
2715
|
const suppressed = open.streamed;
|
|
2543
|
-
// draft.4 `phase` (§8.0 item 27, a SHOULD per the
|
|
2716
|
+
// draft.4 `phase` (§8.0 item 27, a SHOULD per the A.10.5
|
|
2544
2717
|
// ruling): a `thinking` block listed in `narration_block_indexes` whose
|
|
2545
2718
|
// text is NON-EMPTY is interim narration → `phase:"interim"` on that
|
|
2546
2719
|
// reasoning block. A listed empty block (display "omitted") gets none.
|
|
@@ -2649,6 +2822,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2649
2822
|
// `output_tokens_details`, the CLI-assembled complete frame's usage does
|
|
2650
2823
|
// not — without this merge the join would erase the streamed count.
|
|
2651
2824
|
open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
|
|
2825
|
+
open.rawInput = nativeInput(open.rawInput, m.usage);
|
|
2652
2826
|
|
|
2653
2827
|
// If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
|
|
2654
2828
|
// the turn ends as a turn.error so consumers see the error rather than a
|
|
@@ -2663,7 +2837,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2663
2837
|
const errCode: NonNullable<SDKAssistantError> = msg.error;
|
|
2664
2838
|
const retriable = assistantErrorRetriable(errCode);
|
|
2665
2839
|
if (msg.parent_tool_use_id !== null) {
|
|
2666
|
-
// A NESTED error frame (
|
|
2840
|
+
// A NESTED error frame (ruling 1, 2026-09-23): the error is
|
|
2667
2841
|
// owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
|
|
2668
2842
|
// own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
|
|
2669
2843
|
// parent closes as an error only when its OWN result frame says so.
|
|
@@ -2674,7 +2848,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2674
2848
|
// failure rides the NON-terminal `error` event (SPEC:609) on the nested
|
|
2675
2849
|
// turn: live-only but truthful and correctly owned, and inside the
|
|
2676
2850
|
// run's still-open bracket, so before its subagent.done. The folded gap
|
|
2677
|
-
// ("a nested turn has no failure outcome") is
|
|
2851
|
+
// ("a nested turn has no failure outcome") is an open spec question.
|
|
2678
2852
|
a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
|
|
2679
2853
|
// B-strict: the nested turn now HAS a failure outcome. The FIRST error
|
|
2680
2854
|
// frame's close is stashed and released as the nested turn.error when
|
|
@@ -2701,7 +2875,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2701
2875
|
if (msg.type === "user") {
|
|
2702
2876
|
// SDKUserMessageReplay (`isReplay: true`, typed only on that arm; a
|
|
2703
2877
|
// runtime `isReplay: false` also exists, so only `=== true` counts) emits
|
|
2704
|
-
// NO core event and does NOT seal the open message (
|
|
2878
|
+
// NO core event and does NOT seal the open message (a lead of
|
|
2705
2879
|
// 2026-09-23). The CLI 2.1.280 replay builders are the host's own-prompt
|
|
2706
2880
|
// acks (sent on stdin accept, never held), queued-prompt merges, history
|
|
2707
2881
|
// re-sends (filtered to `!toolUseResult`, so no tool_results), and
|
|
@@ -2721,10 +2895,28 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2721
2895
|
// `ext.anthropic.frame{kind:"user"}`. The replay's `tool_use_result`
|
|
2722
2896
|
// sibling, read here for live frames, is no longer read on replays.
|
|
2723
2897
|
if ("isReplay" in msg && msg.isReplay === true) return;
|
|
2724
|
-
// guuey#26: a tool_result binds to the fold
|
|
2725
|
-
//
|
|
2726
|
-
//
|
|
2727
|
-
|
|
2898
|
+
// guuey#26: a tool_result binds to the fold, and a COMPLETE-mode message
|
|
2899
|
+
// is sealed first, exactly as the per-frame close used to. A STREAMED
|
|
2900
|
+
// message is never sealed by a live user frame: its native boundary is its
|
|
2901
|
+
// own stream (message_stop, with the complete assistant frames that join
|
|
2902
|
+
// the lifecycle), and with partial messages on the CLI runs each tool as
|
|
2903
|
+
// soon as its tool_use block completes, so a tool_result arrives while the
|
|
2904
|
+
// message is still streaming. Sealing there split the message: with
|
|
2905
|
+
// parallel calls a later call's tool.args.assembled closed on a partial
|
|
2906
|
+
// input, its remaining deltas had no lifecycle to join and became ext
|
|
2907
|
+
// carries, and its complete frame re-opened a `:cont:` copy that started
|
|
2908
|
+
// the call a second time (a second tool.start, which parks the fold); and a
|
|
2909
|
+
// result arriving before the message_delta stranded the message's final
|
|
2910
|
+
// usage the same way. The result's tool.done adopts its own
|
|
2911
|
+
// `<tool_use_id>:result` message (spec §5), which needs no seal: adoption
|
|
2912
|
+
// parks only on a sealed target id or a closed / unopened turn, never on
|
|
2913
|
+
// another open message. (This comment's earlier premise, that adoption
|
|
2914
|
+
// depends on the seal, predates the explicit `:result` id.) The streamed
|
|
2915
|
+
// message is sealed by the next message's start, the turn's result, or
|
|
2916
|
+
// flush; message_stop still never seals, since a complete frame may follow.
|
|
2917
|
+
if (!(pending !== undefined && pending.streamed)) {
|
|
2918
|
+
closePendingMessage();
|
|
2919
|
+
}
|
|
2728
2920
|
// A tool_result answering a Task call ENDS that subagent run, by what it
|
|
2729
2921
|
// reports (B-strict, see `openRun`): its nested terminal and bracket close
|
|
2730
2922
|
// come before the result's own tool.done. A result for any other tool
|
|
@@ -2748,8 +2940,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2748
2940
|
// the conversation itself (the SDKUserMessage doc; the host's own prompts
|
|
2749
2941
|
// come back only as isReplay acks, returned above). The live case: the
|
|
2750
2942
|
// CLI's `isSynthetic: true` nudge "[Your previous response had no visible
|
|
2751
|
-
// output. …]" after an empty reply (
|
|
2752
|
-
// defer-tool-sonnet5-resume-unavailable,
|
|
2943
|
+
// output. …]" after an empty reply (the
|
|
2944
|
+
// defer-tool-sonnet5-resume-unavailable, the corpus's only such
|
|
2753
2945
|
// frame). This branch maps only tool_result blocks, so it had no event at
|
|
2754
2946
|
// all, and the census could not see the text go (its path normalizes to
|
|
2755
2947
|
// the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
|
|
@@ -2784,12 +2976,12 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2784
2976
|
// frames do: nothing lands on a nested turn after its subagent.done, or
|
|
2785
2977
|
// on a turn nobody opened, and no id repeats across invokes.
|
|
2786
2978
|
// INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
|
|
2787
|
-
// content event for a turn the stream has not opened;
|
|
2979
|
+
// content event for a turn the stream has not opened;
|
|
2788
2980
|
// 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
|
|
2789
2981
|
// invoke's first frame is the deferred call's tool_result, before
|
|
2790
|
-
// system/init;
|
|
2982
|
+
// system/init; the defer-resume capture) opens the turn it lands
|
|
2791
2983
|
// in, named by this frame's uuid. The resumed invoke's assistant frames
|
|
2792
|
-
// then join it and its result closes it. Through
|
|
2984
|
+
// then join it and its result closes it. Through 11a4bb6 its tool.done
|
|
2793
2985
|
// had no turn and reduce() parked from the first event. Where that result
|
|
2794
2986
|
// folds relative to the PREVIOUS invoke's open tool block is candidate
|
|
2795
2987
|
// 20's bar question, not decided here.
|
|
@@ -2814,7 +3006,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2814
3006
|
// `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
|
|
2815
3007
|
// loudly"): a turn nobody opened, whose id REPEATED across the
|
|
2816
3008
|
// invokes one Reducer folds (the rd-14 ids-across-invokes rule;
|
|
2817
|
-
//
|
|
3009
|
+
// the message.start review, wf_140b3183-767), and it parked.
|
|
2818
3010
|
toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
|
|
2819
3011
|
openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
|
|
2820
3012
|
}
|
|
@@ -2849,7 +3041,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2849
3041
|
// minus `content` (already the tool.done content) and `prompt` (already
|
|
2850
3042
|
// the tool input). Its `usage` is the subagent's own and stays out of
|
|
2851
3043
|
// AgUsage (B-strict: the parent's accounting already includes it).
|
|
2852
|
-
//
|
|
3044
|
+
// The subagent captures surfaced every one of these
|
|
2853
3045
|
// fields as a census drop.
|
|
2854
3046
|
const agentOutput =
|
|
2855
3047
|
sibling !== undefined && typeof sibling["agentId"] === "string"
|
|
@@ -2863,9 +3055,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2863
3055
|
// renders the text the model reads. `tool_use_result` is typed `unknown`
|
|
2864
3056
|
// (runtime-only shape, like structuredContent above), so the array is
|
|
2865
3057
|
// validated at the opaque boundary by JsonValue.parse — no cast. The
|
|
2866
|
-
// tool.done `content` stays model-faithful (the rendered text
|
|
2867
|
-
//
|
|
2868
|
-
//
|
|
3058
|
+
// tool.done `content` stays model-faithful (the rendered text, and no
|
|
3059
|
+
// resource-link block: §8.0 item 31's rendering-only case); the list
|
|
3060
|
+
// rides the adopted tool.done's host-only `_meta` as a host record
|
|
3061
|
+
// (RESOURCE_LINKS_META_KEY, SPEC §2.1), verbatim, under the same
|
|
3062
|
+
// single-result attribution rule as the sibling's other fields.
|
|
2869
3063
|
const siblingResourceLinks =
|
|
2870
3064
|
sibling !== undefined && Array.isArray(sibling["resourceLinks"])
|
|
2871
3065
|
? JsonValue.parse(sibling["resourceLinks"])
|
|
@@ -2890,8 +3084,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2890
3084
|
// so the model-facing reason survives (§2.2 draft.4: isError and
|
|
2891
3085
|
// errorText belong to outcome "error"). Before this, the same call
|
|
2892
3086
|
// folded "error" here and then "denied" again from the result's
|
|
2893
|
-
// permission_denials (
|
|
2894
|
-
// Second key (
|
|
3087
|
+
// permission_denials (the resume-deny leg).
|
|
3088
|
+
// Second key (same basis): when no kind is stamped, a
|
|
2895
3089
|
// live `permission_denied` notice already seen for this id is the
|
|
2896
3090
|
// harness's own denial record (the CLI emits it at decision time,
|
|
2897
3091
|
// always before this result). No kind is stamped on a frame holding
|
|
@@ -2922,12 +3116,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2922
3116
|
// carrier skips it. The live `permission_denied` notice for the id
|
|
2923
3117
|
// (the CLI emits it from its canUseTool wrapper at decision time,
|
|
2924
3118
|
// always before this tool_result) rides here instead, the same
|
|
2925
|
-
//
|
|
3119
|
+
// `_meta` record the carrier gives it, so D drops nothing.
|
|
2926
3120
|
const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
|
|
2927
|
-
const resultProviderFields: { [k: string]: JsonValue } = {
|
|
2928
|
-
...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
|
|
2929
|
-
...(liveFields ?? {}),
|
|
2930
|
-
};
|
|
2931
3121
|
a.toolDone({
|
|
2932
3122
|
toolCallId: block.tool_use_id,
|
|
2933
3123
|
content: toolContent,
|
|
@@ -2955,23 +3145,26 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2955
3145
|
? { structuredContent: sc }
|
|
2956
3146
|
: {}),
|
|
2957
3147
|
...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
|
|
2958
|
-
// The facet's harness keys
|
|
2959
|
-
//
|
|
2960
|
-
//
|
|
2961
|
-
//
|
|
2962
|
-
//
|
|
3148
|
+
// The facet's harness keys ride the same `_meta`, MERGED into the MCP
|
|
3149
|
+
// sibling's `_meta` (never replacing it), so they fold with the
|
|
3150
|
+
// tool-result block: the Agent run report ("anthropic/agentOutput"),
|
|
3151
|
+
// rd-15's CLI `tool_result_meta` entry ("anthropic/toolResultMeta"),
|
|
3152
|
+
// and the draft.5 host records, the MCP `resourceLinks` list and the
|
|
3153
|
+
// live denial's context. The "anthropic/" namespace is the
|
|
3154
|
+
// harness's own: see `mergeHarnessMeta`. This tool.done carries no
|
|
3155
|
+
// `providerMetadata`: nothing on it round-trips to the provider.
|
|
2963
3156
|
...(() => {
|
|
2964
3157
|
const report = applySibling && agentCallIds.has(block.tool_use_id) ? agentOutput : undefined;
|
|
2965
3158
|
const entry = toolResultMetaById.get(block.tool_use_id);
|
|
3159
|
+
const links = applySibling ? siblingResourceLinks : undefined;
|
|
2966
3160
|
const merged = mergeHarnessMeta(applySibling ? siblingMeta : undefined, {
|
|
2967
3161
|
...(report !== undefined ? { "anthropic/agentOutput": report } : {}),
|
|
2968
3162
|
...(entry !== undefined ? { "anthropic/toolResultMeta": entry } : {}),
|
|
3163
|
+
...(links !== undefined ? { [RESOURCE_LINKS_META_KEY]: links } : {}),
|
|
3164
|
+
...(liveFields !== undefined ? { [PERMISSION_DENIED_META_KEY]: liveFields } : {}),
|
|
2969
3165
|
});
|
|
2970
3166
|
return merged !== undefined ? { _meta: merged } : {};
|
|
2971
3167
|
})(),
|
|
2972
|
-
...(Object.keys(resultProviderFields).length > 0
|
|
2973
|
-
? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
|
|
2974
|
-
: {}),
|
|
2975
3168
|
});
|
|
2976
3169
|
}
|
|
2977
3170
|
}
|
|
@@ -2989,7 +3182,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
2989
3182
|
// B-strict: a subagent run still open (a background or unreported sub-run)
|
|
2990
3183
|
// is NOT closed by its parent's result; it closes when the framework
|
|
2991
3184
|
// reports it, or at flush.
|
|
2992
|
-
const turnId = closingTopTurnId(msg.uuid, msg.session_id);
|
|
3185
|
+
const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
|
|
2993
3186
|
// CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
|
|
2994
3187
|
// succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
|
|
2995
3188
|
// the final assistant text in result — or, with is_error true, the error
|
|
@@ -3055,11 +3248,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3055
3248
|
// when that text is empty. retriable = the HTTP status says rate limit
|
|
3056
3249
|
// or server failure (see `apiErrorStatusRetriable`); usage = the turn's
|
|
3057
3250
|
// accrued usage, as above.
|
|
3058
|
-
// The terminal_reason step (
|
|
3059
|
-
// CLI also sets is_error on a result that is NOT an API error.
|
|
3060
|
-
// resume-unavailable leg (
|
|
3251
|
+
// The terminal_reason step (facet-local, 2026-09-23): the
|
|
3252
|
+
// CLI also sets is_error on a result that is NOT an API error. The
|
|
3253
|
+
// resume-unavailable leg (defer-tool-sonnet5-resume-unavailable) is a resumed invoke whose deferred
|
|
3061
3254
|
// tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
|
|
3062
|
-
// result "", no status, no api_error_code. Through
|
|
3255
|
+
// result "", no status, no api_error_code. Through a5ac025 it closed
|
|
3063
3256
|
// turn.error{message: "", code: "api_error"}, claiming an API failure
|
|
3064
3257
|
// that never happened. `code` is free-form (SPEC :618), so this fills
|
|
3065
3258
|
// existing fields from the frame's own value; a live API error
|
|
@@ -3073,9 +3266,37 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3073
3266
|
});
|
|
3074
3267
|
return;
|
|
3075
3268
|
}
|
|
3076
|
-
const finishReasonRaw = stopReasonRaw(msg.stop_reason);
|
|
3077
3269
|
const stopDetails = stopDetailsByTurn.get(turnId);
|
|
3078
3270
|
stopDetailsByTurn.delete(turnId);
|
|
3271
|
+
// draft.5 §8.0 item 32: a result that parks a tool call (`deferred_tool_use`
|
|
3272
|
+
// present, stop_reason "tool_deferred", not an error) is a paused turn
|
|
3273
|
+
// waiting on an approval. push() emits one hitl.ask{kind:"approval"} for the
|
|
3274
|
+
// parked call (askId `approval_<call id>`, the form the openai facet mints
|
|
3275
|
+
// for its approval asks), then closes the turn paused with that ask and
|
|
3276
|
+
// finishReason "paused", with no finishReasonRaw (the native reason is
|
|
3277
|
+
// exactly what "paused" names). The result-meta deferredToolUse carry stays.
|
|
3278
|
+
// A later invoke that resumes the call opens its own turn, minted from its
|
|
3279
|
+
// own frames (INV-XINV). Never keyed on terminal_reason. An is_error result
|
|
3280
|
+
// never reaches here: it closed above as turn.error (CL-09), and so did a
|
|
3281
|
+
// turn an API-error frame decided; the deferred tool found unavailable on
|
|
3282
|
+
// resume ("tool_deferred_unavailable") is such an is_error close.
|
|
3283
|
+
const deferredCall = readDeferredCall(msg);
|
|
3284
|
+
const stop: unknown = msg.stop_reason;
|
|
3285
|
+
if (deferredCall !== undefined && stop === "tool_deferred") {
|
|
3286
|
+
const ask = { askId: `approval_${deferredCall}`, kind: "approval" as const, toolCallId: deferredCall };
|
|
3287
|
+
a.emit({ type: "hitl.ask", turnId, ...ask });
|
|
3288
|
+
a.closeTurnDone(turnId, {
|
|
3289
|
+
outcome: { type: "paused", asks: [ask] },
|
|
3290
|
+
finishReason: "paused",
|
|
3291
|
+
...(turnUsage !== undefined ? { usage: turnUsage } : {}),
|
|
3292
|
+
safety,
|
|
3293
|
+
...(stopDetails !== undefined
|
|
3294
|
+
? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
|
|
3295
|
+
: {}),
|
|
3296
|
+
});
|
|
3297
|
+
return;
|
|
3298
|
+
}
|
|
3299
|
+
const finishReasonRaw = stopReasonRaw(msg.stop_reason);
|
|
3079
3300
|
a.closeTurnDone(turnId, {
|
|
3080
3301
|
outcome: { type: "success", result: structuredOutput ?? msg.result },
|
|
3081
3302
|
finishReason: mapStopReason(msg.stop_reason),
|
|
@@ -3166,18 +3387,20 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3166
3387
|
// carry is RETIRED (superseded, not layered — one carrier per concept,
|
|
3167
3388
|
// §0.6); note `tool_use_id` was NOT carried by that route, so this
|
|
3168
3389
|
// promotion is strictly more lossless. Wrapper siblings ride the text
|
|
3169
|
-
// block's
|
|
3170
|
-
// convention
|
|
3390
|
+
// block's host-only `_meta` (camelCased per the facet's carry
|
|
3391
|
+
// convention; draft.5 §8.0 item 21 — draft.2 through draft.4 placed them
|
|
3392
|
+
// in `providerMetadata`, which §12 reserves for values that round-trip to
|
|
3393
|
+
// the provider, and a notice is never model input).
|
|
3171
3394
|
// The open turn, or (between turns) the one this notice opens; the next
|
|
3172
3395
|
// assistant frame then joins it and its result closes it.
|
|
3173
3396
|
const turnId = topTurnId(msg.uuid, undefined);
|
|
3174
|
-
const noticeMeta =
|
|
3397
|
+
const noticeMeta = AgMeta.parse({
|
|
3175
3398
|
level: msg.level,
|
|
3176
3399
|
...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
|
|
3177
3400
|
...(msg.tool_use_id !== undefined ? { toolUseId: msg.tool_use_id } : {}),
|
|
3178
3401
|
});
|
|
3179
3402
|
a.openMessage({ id: msg.uuid, role: "notice", turnId, threadId: options.threadId ?? msg.session_id, noticeSource: "framework" });
|
|
3180
|
-
a.contentBlock(msg.uuid, { type: "text", text: msg.content,
|
|
3403
|
+
a.contentBlock(msg.uuid, { type: "text", text: msg.content, _meta: noticeMeta });
|
|
3181
3404
|
a.closeMessage(msg.uuid);
|
|
3182
3405
|
return;
|
|
3183
3406
|
}
|
|
@@ -3194,7 +3417,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3194
3417
|
closePendingMessage();
|
|
3195
3418
|
const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
|
|
3196
3419
|
retractUuids(uuids);
|
|
3197
|
-
// X4 (
|
|
3420
|
+
// X4 (the 2026-09-23 re-cut): only the retraction has a core home.
|
|
3198
3421
|
// A notice yields 0..N `message.remove`s, so there is no single event to
|
|
3199
3422
|
// hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
|
|
3200
3423
|
// ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
|
|
@@ -3205,11 +3428,11 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3205
3428
|
// rides the uniform carry beside its `model_refusal_no_fallback` sibling
|
|
3206
3429
|
// (SPEC §8 item 22 / §12), the WHOLE frame verbatim, AFTER the removes
|
|
3207
3430
|
// (the frame is itself "emitted AFTER the retraction"). Item 22 says a
|
|
3208
|
-
// mapped frame goes to its home "instead" of the bulk carry.
|
|
3209
|
-
//
|
|
3431
|
+
// mapped frame goes to its home "instead" of the bulk carry. A ruling
|
|
3432
|
+
// of 2026-09-23 (SPEC blob bef014c) holds that the clause covers frames
|
|
3210
3433
|
// whose content that home already conveys, and `message.remove` conveys
|
|
3211
3434
|
// only the retraction. So the residual fields fall under item 22's
|
|
3212
|
-
// no-drop MUST, and the whole frame rides. (
|
|
3435
|
+
// no-drop MUST, and the whole frame rides. (A clarifying
|
|
3213
3436
|
// line for item 22 is queued for the review bar.) `ext.*` is live-only
|
|
3214
3437
|
// and non-folding, so the second copy of `retracted_message_uuids`
|
|
3215
3438
|
// cannot double-fold (the M22 hazard). This is the only producer for R&D
|
|
@@ -3317,8 +3540,8 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3317
3540
|
// A copy: `frame` IS the host's object when it was already JSON, and
|
|
3318
3541
|
// this raw channel would otherwise emit it by reference. JsonValue.parse
|
|
3319
3542
|
// copies and, like every other carry here, drops an own "__proto__"
|
|
3320
|
-
// (
|
|
3321
|
-
// reserved-key rule
|
|
3543
|
+
// (2026-09-24, matching the openai facet's ddde89d and the 0.6.6
|
|
3544
|
+
// reserved-key rule a76277c: an emitted map carries no own __proto__).
|
|
3322
3545
|
a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
|
|
3323
3546
|
return a.drain();
|
|
3324
3547
|
}
|
|
@@ -3349,7 +3572,7 @@ function createInnerClaudeNormalizer(options: ClaudeNormalizerOptions, invokeSte
|
|
|
3349
3572
|
|
|
3350
3573
|
/**
|
|
3351
3574
|
* Build the Claude-facet normalizer: the inner normalizer wrapped in core's
|
|
3352
|
-
* withAtomicPush (the
|
|
3575
|
+
* withAtomicPush (the guard ruling, 2026-09-24, binding). push() never
|
|
3353
3576
|
* throws (SPEC:933):
|
|
3354
3577
|
* - each native is first read as plain JSON (core toJsonValueSafe): a host
|
|
3355
3578
|
* may hand in the in-process object, whose members need not be JSON (an
|