@silverprotocol/claude-agent-sdk 0.1.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/dist/index.js ADDED
@@ -0,0 +1,805 @@
1
+ import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
2
+ // ─── stop_reason → AgFinishReason (spec §4) ───────────────────────────────────
3
+ // Anthropic BetaStopReason superset → the neutral finish-reason superset.
4
+ function mapStopReason(stop) {
5
+ switch (stop) {
6
+ case "end_turn":
7
+ return "stop";
8
+ case "stop_sequence":
9
+ return "stop";
10
+ case "max_tokens":
11
+ return "token_limit";
12
+ case "model_context_window_exceeded":
13
+ return "context_window_exceeded";
14
+ case "tool_use":
15
+ return "tool_call";
16
+ case "pause_turn":
17
+ return "pause_turn";
18
+ case "refusal":
19
+ return "refusal";
20
+ case "compaction":
21
+ // Anthropic server-loop compaction checkpoint — a resumable pause, no asks.
22
+ return "pause_turn";
23
+ case null:
24
+ return "stop";
25
+ default:
26
+ return "unknown";
27
+ }
28
+ }
29
+ // ─── derive stable ids ────────────────────────────────────────────────────────
30
+ // A stable per-message turn id: the assistant message is the model's turn, so
31
+ // the SDK session id names the turn (a top-level turn shares the session). When
32
+ // absent, fall back to the message id.
33
+ function turnIdFor(sessionId, messageId) {
34
+ return sessionId && sessionId.length > 0 ? `turn_${sessionId}` : `turn_${messageId}`;
35
+ }
36
+ // ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
37
+ function imageSource(source) {
38
+ if (source.type === "base64") {
39
+ return { type: "base64", mediaType: source.media_type, data: source.data };
40
+ }
41
+ // url
42
+ return { type: "url", url: source.url };
43
+ }
44
+ // ─── usage mapping helpers ────────────────────────────────────────────────────
45
+ function mapModelUsage(mu) {
46
+ return {
47
+ inputTokens: mu.inputTokens,
48
+ outputTokens: mu.outputTokens,
49
+ cacheReadTokens: mu.cacheReadInputTokens,
50
+ cacheWriteTokens: mu.cacheCreationInputTokens,
51
+ costUsd: mu.costUSD,
52
+ serverToolRequests: mu.webSearchRequests,
53
+ cumulative: true,
54
+ };
55
+ }
56
+ function mapTurnUsage(usage, totalCostUsd, modelUsage) {
57
+ const byModel = {};
58
+ for (const [model, mu] of Object.entries(modelUsage)) {
59
+ byModel[model] = mapModelUsage(mu);
60
+ }
61
+ return {
62
+ inputTokens: usage.input_tokens,
63
+ outputTokens: usage.output_tokens,
64
+ cacheReadTokens: usage.cache_read_input_tokens,
65
+ cacheWriteTokens: usage.cache_creation_input_tokens,
66
+ serverToolRequests: usage.server_tool_use !== null
67
+ ? usage.server_tool_use.web_search_requests + usage.server_tool_use.web_fetch_requests
68
+ : undefined,
69
+ costUsd: totalCostUsd,
70
+ cumulative: true,
71
+ ...(Object.keys(byModel).length > 0 ? { byModel } : {}),
72
+ };
73
+ }
74
+ function mapMessageUsage(usage) {
75
+ return {
76
+ inputTokens: usage.input_tokens,
77
+ outputTokens: usage.output_tokens,
78
+ cacheReadTokens: usage.cache_read_input_tokens ?? undefined,
79
+ cacheWriteTokens: usage.cache_creation_input_tokens ?? undefined,
80
+ cumulative: true,
81
+ };
82
+ }
83
+ // ─── citation mapping helpers ─────────────────────────────────────────────────
84
+ function mapCitations(citations) {
85
+ const result = [];
86
+ for (const c of citations) {
87
+ if (c.type === "char_location") {
88
+ result.push({
89
+ kind: "char",
90
+ citedText: c.cited_text,
91
+ title: c.document_title ?? undefined,
92
+ documentIndex: c.document_index,
93
+ startCharIndex: c.start_char_index,
94
+ endCharIndex: c.end_char_index,
95
+ indexFrame: "source",
96
+ });
97
+ }
98
+ else if (c.type === "page_location") {
99
+ result.push({
100
+ kind: "page",
101
+ citedText: c.cited_text,
102
+ title: c.document_title ?? undefined,
103
+ documentIndex: c.document_index,
104
+ startPage: c.start_page_number,
105
+ endPage: c.end_page_number,
106
+ });
107
+ }
108
+ else if (c.type === "content_block_location") {
109
+ result.push({
110
+ kind: "block",
111
+ citedText: c.cited_text,
112
+ title: c.document_title ?? undefined,
113
+ documentIndex: c.document_index,
114
+ startBlockIndex: c.start_block_index,
115
+ endBlockIndex: c.end_block_index,
116
+ });
117
+ }
118
+ else if (c.type === "web_search_result_location") {
119
+ result.push({
120
+ kind: "url",
121
+ citedText: c.cited_text,
122
+ url: c.url,
123
+ title: c.title ?? undefined,
124
+ encryptedIndex: c.encrypted_index,
125
+ indexFrame: "response",
126
+ });
127
+ }
128
+ else if (c.type === "search_result_location") {
129
+ result.push({
130
+ kind: "block",
131
+ citedText: c.cited_text,
132
+ title: c.title ?? undefined,
133
+ source: c.source ?? undefined,
134
+ documentIndex: c.search_result_index,
135
+ startBlockIndex: c.start_block_index,
136
+ endBlockIndex: c.end_block_index,
137
+ });
138
+ }
139
+ }
140
+ return result;
141
+ }
142
+ // Map a non-lifecycle assistant content block (rich blocks with no dedicated
143
+ // lifecycle: container uploads, server-tool-result blocks, …) onto an AgBlock for
144
+ // content.block. BetaContentBlock has no `image` arm on the ASSISTANT side, so
145
+ // these pass through as provider-raw (spec §2 provider-raw), preserving the
146
+ // vendor shape losslessly — nothing is silently dropped. The block is plain JSON;
147
+ // JsonValue.parse validates it at the opaque pass-through boundary (no cast).
148
+ function assistantContentBlockToAgBlock(block) {
149
+ return {
150
+ type: "provider-raw",
151
+ vendor: "anthropic",
152
+ raw: JsonValue.parse(block),
153
+ };
154
+ }
155
+ // ─── user/tool_result content fan-out (spec §2 — tool.done content blocks) ────
156
+ // The tool_result block's `content` is a string OR an array of param blocks; map
157
+ // to AgBlock[] (text / image), preserving the MCP content shape. The remaining
158
+ // rich param blocks pass through as provider-raw (spec §2; plain JSON validated
159
+ // at the opaque boundary by JsonValue.parse — no cast).
160
+ function toolResultContentToAgBlocks(content) {
161
+ if (typeof content === "string") {
162
+ return content.length > 0 ? [{ type: "text", text: content }] : [];
163
+ }
164
+ const out = [];
165
+ for (const part of content) {
166
+ if (part.type === "text") {
167
+ out.push({ type: "text", text: part.text });
168
+ }
169
+ else if (part.type === "image") {
170
+ out.push({ type: "image", source: imageSource(part.source) });
171
+ }
172
+ else {
173
+ out.push({ type: "provider-raw", vendor: "anthropic", raw: JsonValue.parse(part) });
174
+ }
175
+ }
176
+ return out;
177
+ }
178
+ // Assistant-side mcp_tool_result content → AgBlock[] (distinct shape from the
179
+ // user-side tool_result content mapped by `toolResultContentToAgBlocks` above).
180
+ // A `for...of` loop, not `.map` — playbook 2026-07-03 SDK-bump adaptation: the
181
+ // 0.3.199 `SDKMessage` union widened enough that `.map`/`.forEach`/`.filter`
182
+ // callback PARAMETER inference silently degrades to implicit `any` on this
183
+ // content shape (a known TS limitation calling an array method on a value typed
184
+ // as a union of structurally-different array types); a plain loop sidesteps it
185
+ // without an explicit-but-redundant parameter annotation, matching this file's
186
+ // established iteration style everywhere else.
187
+ function mcpToolResultContentToAgBlocks(content) {
188
+ if (typeof content === "string") {
189
+ return content.length > 0 ? [{ type: "text", text: content }] : [];
190
+ }
191
+ const out = [];
192
+ for (const tb of content)
193
+ out.push({ type: "text", text: tb.text });
194
+ return out;
195
+ }
196
+ // ─── assistant content block fan-out (spec §4 mapping table) ──────────────────
197
+ // Per content[] block, drive the engine to emit its lifecycle events under the
198
+ // open message named by `messageId`. `blockProviderMetadata` is the refusal-
199
+ // fallback `supersedes` carrier (playbook 2026-07-03 SDK-bump adaptation,
200
+ // Finding #1 / §8 item 19): the caller passes it ONLY for blockIndex 0 of a
201
+ // superseding message, mirroring the established "signature on first block"
202
+ // precedent (§8 item 8, Gemini thoughtSignature). `text`/`thinking`/
203
+ // `redacted_thinking`/`tool_use` family all have a providerMetadata slot on
204
+ // their *.start event and land it there; the remaining rarer block-0 shapes
205
+ // (image/resource/mcp_tool_result/compaction) have no providerMetadata slot on
206
+ // `content.block` and drop the annotation (NOT the retraction itself, which
207
+ // already executed via `message.remove` regardless — see `drive()`).
208
+ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetadata) {
209
+ switch (block.type) {
210
+ case "text": {
211
+ // Claude's assistant message is a COMPLETE structure (not a live stream), so
212
+ // citations are already known at the point text.end fires — they ride the
213
+ // STREAMED-text citations carrier (audit M22: text.end.citations), never as
214
+ // a duplicate id-less supplement block.
215
+ const id = `${messageId}:text:${blockIndex}`;
216
+ const citations = block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
217
+ a.textStart(id, messageId, blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : undefined);
218
+ a.textDelta(id, messageId, block.text);
219
+ a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
220
+ return;
221
+ }
222
+ case "thinking": {
223
+ const id = `${messageId}:reasoning:${blockIndex}`;
224
+ if (blockProviderMetadata !== undefined) {
225
+ // reasoningStart's sugar signature has no providerMetadata parameter
226
+ // (only textStart's does) — `a.emit()` is the documented base
227
+ // primitive for exactly this case (schema DOES support it on
228
+ // reasoning.start; StreamAssembler docstring: "guarantees no
229
+ // AgClosedEventType is ever unreachable").
230
+ a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
231
+ }
232
+ else {
233
+ a.reasoningStart(id, messageId);
234
+ }
235
+ a.reasoningDelta(id, messageId, block.thinking);
236
+ a.reasoningEnd(id, messageId);
237
+ // The Anthropic thinking signature is replay-load-bearing (spec §8/§10):
238
+ // sets `opaque` on the reasoning block named by `id`. Echo or multi-turn
239
+ // reasoning breaks.
240
+ if (block.signature && block.signature.length > 0) {
241
+ a.reasoningOpaque(id, messageId, {
242
+ kind: "signature",
243
+ value: block.signature,
244
+ provider: "anthropic",
245
+ });
246
+ }
247
+ return;
248
+ }
249
+ case "redacted_thinking": {
250
+ // No visible text; the redacted blob is the replay-load-bearing opaque part.
251
+ const id = `${messageId}:reasoning:${blockIndex}`;
252
+ if (blockProviderMetadata !== undefined) {
253
+ a.emit({ type: "reasoning.start", id, messageId, providerMetadata: blockProviderMetadata });
254
+ }
255
+ else {
256
+ a.reasoningStart(id, messageId);
257
+ }
258
+ a.reasoningEnd(id, messageId);
259
+ a.reasoningOpaque(id, messageId, {
260
+ kind: "redacted",
261
+ value: block.data,
262
+ provider: "anthropic",
263
+ });
264
+ return;
265
+ }
266
+ case "tool_use":
267
+ case "server_tool_use":
268
+ case "mcp_tool_use": {
269
+ // `input` is opaque JSON (spec §0.1) typed `unknown` by the SDK — validate
270
+ // it at this genuine deserialization boundary into JsonValue (no cast).
271
+ // Emit the buffered-args lifecycle: start → one args.delta (the whole JSON,
272
+ // since Claude gives the assembled object up front) → the MANDATORY
273
+ // args.assembled (spec §4/§8.1).
274
+ const toolCallId = block.id;
275
+ const input = JsonValue.parse(block.input);
276
+ // server_tool_use blocks are always provider-executed; regular tool_use blocks
277
+ // with a non-direct caller (e.g. code_execution_20250825) are also
278
+ // provider-executed. A direct caller or absent caller ⇒ not provider-executed.
279
+ const providerExecuted = block.type === "server_tool_use"
280
+ ? true
281
+ : "caller" in block && block.caller !== undefined
282
+ ? block.caller.type !== "direct"
283
+ : undefined;
284
+ a.toolStart({
285
+ toolCallId,
286
+ name: block.name,
287
+ // MCP tool calls carry the originating server (spec §4 tool.start.serverName).
288
+ serverName: block.type === "mcp_tool_use" ? block.server_name : undefined,
289
+ index: blockIndex,
290
+ messageId,
291
+ providerExecuted,
292
+ ...(blockProviderMetadata !== undefined ? { providerMetadata: blockProviderMetadata } : {}),
293
+ });
294
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
295
+ a.toolArgsAssembled(toolCallId, input);
296
+ return;
297
+ }
298
+ case "mcp_tool_result": {
299
+ // MCP tool results from the assistant side: map to tool.done with content + outcome.
300
+ const outcome = block.is_error ? "error" : "ok";
301
+ const content = mcpToolResultContentToAgBlocks(block.content);
302
+ a.toolDone({
303
+ toolCallId: block.tool_use_id,
304
+ content,
305
+ outcome,
306
+ isError: block.is_error,
307
+ messageId,
308
+ });
309
+ return;
310
+ }
311
+ case "compaction": {
312
+ // Compaction blocks carry a provider-produced context summary (spec §4).
313
+ // The encrypted_content is replay-load-bearing opaque data (spec §2/§8).
314
+ a.contentBlock(messageId, {
315
+ type: "compaction",
316
+ text: block.content ?? undefined,
317
+ opaque: block.encrypted_content !== null
318
+ ? { kind: "ciphertext", value: block.encrypted_content, provider: "anthropic" }
319
+ : undefined,
320
+ provider: "anthropic",
321
+ });
322
+ return;
323
+ }
324
+ default: {
325
+ // image / resource / other rich content blocks ride content.block (spec §4).
326
+ a.contentBlock(messageId, assistantContentBlockToAgBlock(block));
327
+ return;
328
+ }
329
+ }
330
+ }
331
+ // ─── structural guard: JsonValue → SDKMessage ─────────────────────────────────
332
+ // `push` receives the genuine JSON boundary (`JsonValue`, spec §0.1). The run-seam
333
+ // yields well-formed `SDKMessage`s, but this is the deserialization boundary so we
334
+ // confirm the discriminant + the per-arm load-bearing nested shape before driving
335
+ // the engine. A user-defined type guard (not a cast) narrows on success; a failure
336
+ // routes the raw payload to `ext.anthropic.unparsed` and returns (graceful, Tenet 6).
337
+ function isJsonObject(v) {
338
+ return typeof v === "object" && v !== null && !Array.isArray(v);
339
+ }
340
+ // Input is `unknown` (not `JsonValue`): `SDKMessage` is NOT assignable to
341
+ // `JsonValue` (its nested BetaMessage has no index signature), so a `v is SDKMessage`
342
+ // predicate over a `JsonValue` param is rejected by TS (TS2677). `unknown` is the
343
+ // genuine deserialization-boundary input type and is predicate-compatible. The
344
+ // caller passes a `JsonValue`, which widens to `unknown` losslessly.
345
+ function isSDKMessage(v) {
346
+ if (!isJsonObject(v))
347
+ return false;
348
+ const t = v.type;
349
+ if (t === "assistant") {
350
+ const message = v.message;
351
+ if (!isJsonObject(message))
352
+ return false;
353
+ return typeof message.id === "string" && Array.isArray(message.content);
354
+ }
355
+ if (t === "user") {
356
+ return isJsonObject(v.message) && "content" in v.message;
357
+ }
358
+ if (t === "result") {
359
+ return typeof v.subtype === "string";
360
+ }
361
+ // system / partial-assistant / status / … — structurally valid SDKMessage arms
362
+ // that carry no AgJSON-relevant content. Accept (the normalizer no-ops on them).
363
+ return typeof t === "string";
364
+ }
365
+ // ─── uniform lossless carry: the fixture-drift ratchet's remaining 15
366
+ // `silently-dropped` claude arms (2026-07-03 follow-up to the
367
+ // SDKInformationalMessage flagship fix) ────────────────────────────────────
368
+ // Per-arm field inspection (sdk.d.ts) confirmed each carries genuine
369
+ // consumer-facing content (hook stdout/stderr, slash-command output,
370
+ // OAuth-flow instructions, toast notifications, file-persistence receipts,
371
+ // tool-use-summary prose, recalled-memory body text, a no-fallback refusal's
372
+ // own diagnostic fields, suggested-prompt text, mirror-sync errors, and the
373
+ // Task* subagent-progress family) with NO existing AgJSON vocabulary home.
374
+ //
375
+ // The Task* family (task_started/task_progress/task_updated/task_notification)
376
+ // was STUDIED against the facet's ALREADY-derived subagent lifecycle
377
+ // (parent_tool_use_id -> subagentStart/Done in `drive()` below) and
378
+ // deliberately NOT folded into it: `tool_use_id` is OPTIONAL on every Task*
379
+ // arm (a `task_type:"local_workflow"` background task carries NONE at all —
380
+ // this family is a broader "tasks panel" superset, not 1:1 with Task-tool
381
+ // subagent adoption), and task_progress/task_notification's own
382
+ // `summary`/`last_tool_name` would DUPLICATE content the nested subagent's
383
+ // own tool_use/tool_result stream already conveys once correlation resolves
384
+ // — the M22 double-fold hazard. `description` enrichment onto
385
+ // subagent.start was also considered and rejected: `subagent.start`'s
386
+ // schema carries no providerMetadata slot (only agentId/agentName), and
387
+ // reaching it would require bypassing the `subagentStart()` sugar
388
+ // primitive's turn-stack bookkeeping via the raw `emit()` base primitive —
389
+ // a core/src change, outside this task's facet+manifest+SPEC-§8/§12
390
+ // boundary invariant.
391
+ //
392
+ // SDKModelRefusalNoFallbackMessage was STUDIED against the existing
393
+ // `stop_reason:"refusal"` terminal handling (mapStopReason + the
394
+ // closeTurnDone safety flag in `drive()`'s result-success branch): that
395
+ // path ALREADY produces the terminal "a refusal happened" signal, so this
396
+ // frame's OWN diagnostic fields (api_refusal_category/explanation/
397
+ // original_model/content) are enrichment with no precise existing home —
398
+ // carried, not forced onto an unrelated event.
399
+ //
400
+ // SDKPermissionDeniedMessage is the ONE arm that DOES map onto an existing
401
+ // home (the W1 `<turnId>:denials` carrier, audit M19) — see the dedicated
402
+ // branch + `deniedLiveByToolUseId` in `createClaudeNormalizer()` below; it
403
+ // is deliberately EXCLUDED from the carried sets here.
404
+ //
405
+ // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
406
+ // §12) — not 15 distinct ext keys (ext-vocabulary sprawl, the standing
407
+ // review Minor this closes). `kind` is the frame's own discriminating
408
+ // subtype/type string; `frame` is the VERBATIM native message
409
+ // (JsonValue.parse at the opaque pass-through boundary, no cast, no
410
+ // field-by-field reinterpretation — the whole frame rides losslessly).
411
+ const CARRIED_SYSTEM_SUBTYPES = new Set([
412
+ "model_refusal_no_fallback",
413
+ "local_command_output",
414
+ "hook_progress",
415
+ "hook_response",
416
+ "task_notification",
417
+ "task_started",
418
+ "task_updated",
419
+ "task_progress",
420
+ "notification",
421
+ "files_persisted",
422
+ "memory_recall",
423
+ "mirror_error",
424
+ ]);
425
+ const CARRIED_STANDALONE_TYPES = new Set(["auth_status", "tool_use_summary", "prompt_suggestion"]);
426
+ // Returns the uniform-carry `kind` string for `msg` if it is one of the arms
427
+ // disposed `carried` in sdk-surface.json, else undefined (leaves router-plane
428
+ // / dedicated-branch arms — including SDKPermissionDeniedMessage — untouched).
429
+ function anthropicFrameKind(msg) {
430
+ if (msg.type === "system") {
431
+ return CARRIED_SYSTEM_SUBTYPES.has(msg.subtype) ? msg.subtype : undefined;
432
+ }
433
+ return CARRIED_STANDALONE_TYPES.has(msg.type) ? msg.type : undefined;
434
+ }
435
+ // ─── the stateful normalizer ──────────────────────────────────────────────────
436
+ /**
437
+ * Build a stateful Claude-facet normalizer over a fresh {@link StreamAssembler}.
438
+ * Each `push(native)` validates `native` → `SDKMessage`, drives the engine via
439
+ * primitive calls, and drains the buffered `AgEvent[]`. `flush()` closes any
440
+ * dangling open message (none, in Claude's complete-message model) and drains.
441
+ */
442
+ export function createClaudeNormalizer() {
443
+ const a = new StreamAssembler();
444
+ // Task 8c leg 4 (guuey capstone finding A): the wire-visible `parentTurnId`
445
+ // label passed to subagent.start/.done (`turn_${parent_tool_use_id}`) is a
446
+ // synthetic cross-ref that was never opened as a real turn — it must stay on
447
+ // the wire (the guuey capstone asserts `parentTurnId === 'turn_<toolCallId>'`)
448
+ // but must NOT be reused to route an INNER tool_result's turnId. Track the
449
+ // REAL subagent turnId per spawning parent_tool_use_id, derived from the
450
+ // sub-session's own assistant arm at subagent.start time, so a later inner
451
+ // tool_result (same non-null parent_tool_use_id) can route to it instead.
452
+ const subagentTurnByParentToolUseId = new Map();
453
+ // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
454
+ // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
455
+ // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
456
+ // DIFFERENT id space from the messageIds this facet actually emits (`m.id`
457
+ // for an assistant frame's `message.start`, `${tool_use_id}:result` for an
458
+ // ADOPTED tool-result frame, §8 item 15). Track uuid → the messageId(s) it
459
+ // produced so a later retraction can translate before emitting
460
+ // `message.remove` — "translated through the facet's uuid→messageId
461
+ // convention" per the adaptation brief.
462
+ const messageIdsByUuid = new Map();
463
+ // Fixture-drift ratchet (SDKPermissionDeniedMessage, "handled" via existing-
464
+ // home mapping): live per-denial diagnostic recorded by the standalone
465
+ // `permission_denied` frame (fires DURING the turn, before the terminal
466
+ // result) — keyed by tool_use_id so the terminal `permission_denials[]`
467
+ // aggregate (the ALREADY-handled W1 `<turnId>:denials` carrier, audit M19)
468
+ // can enrich its tool.done with the actual rejection text + decision-reason
469
+ // context, instead of emitting a SECOND tool.start/tool.done pair for the
470
+ // same denial (the M22 double-fold hazard).
471
+ const deniedLiveByToolUseId = new Map();
472
+ function registerUuid(uuid, ids) {
473
+ if (uuid === undefined || ids.length === 0)
474
+ return;
475
+ const existing = messageIdsByUuid.get(uuid);
476
+ if (existing !== undefined)
477
+ existing.push(...ids);
478
+ else
479
+ messageIdsByUuid.set(uuid, [...ids]);
480
+ }
481
+ // Evict every messageId ever produced for each uuid in `uuids`. An uuid this
482
+ // facet never observed is skipped (Tenet 6: nothing is fabricated — the fold
483
+ // has nothing live under an unknown id anyway; `reduce()`'s `#removeMessage`
484
+ // is a documented no-op on an unknown id regardless). Safe to call from BOTH
485
+ // retraction sources without double-effect: `supersedes` fires "on arrival"
486
+ // (the field's own doc: evict immediately, treat this frame as canonical)
487
+ // and the end-of-turn `model_refusal_fallback` notice re-asserts the same
488
+ // uuids as "the complete audit record for the turn" — `#removeMessage`
489
+ // no-ops a repeat remove, so processing both sources is idempotent.
490
+ function retractUuids(uuids) {
491
+ for (const uuid of uuids) {
492
+ const ids = messageIdsByUuid.get(uuid);
493
+ if (ids === undefined)
494
+ continue;
495
+ for (const id of ids) {
496
+ a.emit({ type: "message.remove", id });
497
+ }
498
+ }
499
+ }
500
+ function drive(msg) {
501
+ if (msg.type === "assistant") {
502
+ const m = msg.message;
503
+ const turnId = turnIdFor(msg.session_id, m.id);
504
+ const parentTurnId = msg.parent_tool_use_id !== null ? `turn_${msg.parent_tool_use_id}` : undefined;
505
+ // Finding #1 (critical): this frame supersedes prior delivered messages
506
+ // (refusal-fallback retry) — evict them "on arrival", per the field's own
507
+ // doc, before opening the canonical replacement below. Idempotent with
508
+ // the end-of-turn `model_refusal_fallback` notice (see the `system`
509
+ // branch further down) — see `retractUuids`'s doc.
510
+ if (msg.supersedes !== undefined && msg.supersedes.length > 0) {
511
+ retractUuids(msg.supersedes);
512
+ }
513
+ // The raw uuid list is ALSO carried losslessly as `providerMetadata` on
514
+ // this message's first content block (mirrors the "signature on first
515
+ // block" precedent, §8 item 8) — an audit trail independent of whether
516
+ // every targeted uuid was resolvable above.
517
+ const supersedesMeta = msg.supersedes !== undefined && msg.supersedes.length > 0
518
+ ? AgProviderMeta.parse({ supersedes: msg.supersedes })
519
+ : undefined;
520
+ // A non-null parent_tool_use_id ⇒ this assistant message is a NESTED turn
521
+ // (subagent). subagent.start is the SOLE nested-turn opener (spec §4/§5) and
522
+ // seeds the turn so openMessage does NOT synthesize a duplicate turn.start.
523
+ if (parentTurnId !== undefined) {
524
+ if (msg.parent_tool_use_id !== null) {
525
+ subagentTurnByParentToolUseId.set(msg.parent_tool_use_id, turnId);
526
+ }
527
+ a.subagentStart(turnId, parentTurnId);
528
+ }
529
+ a.openMessage({
530
+ id: m.id,
531
+ role: "assistant",
532
+ turnId,
533
+ threadId: msg.session_id,
534
+ model: m.model,
535
+ });
536
+ // A plain indexed loop, not `.forEach` — see `mcpToolResultContentToAgBlocks`'s
537
+ // doc: `.forEach`'s callback parameter inference degrades to implicit `any`
538
+ // on this content shape post-0.3.199.
539
+ for (let i = 0; i < m.content.length; i++) {
540
+ emitAssistantBlock(a, m.content[i], m.id, i, i === 0 ? supersedesMeta : undefined);
541
+ }
542
+ a.closeMessage(m.id, mapMessageUsage(m.usage));
543
+ // If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
544
+ // emit a turn.error so consumers see the error rather than a silent empty turn.
545
+ if (msg.error !== undefined) {
546
+ const errCode = msg.error;
547
+ a.closeTurnError(turnId, {
548
+ message: errCode,
549
+ code: errCode,
550
+ // Finding #2 (minor): `overloaded` (transient capacity error, a first
551
+ // cousin of rate_limit/server_error) joins the retriable set.
552
+ // `model_not_found` (a permanent misconfiguration — e.g. a stale/
553
+ // decommissioned model id) is deliberately EXCLUDED: explicit
554
+ // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
555
+ // adaptation, Finding #2).
556
+ retriable: errCode === "rate_limit" || errCode === "server_error" || errCode === "overloaded",
557
+ });
558
+ }
559
+ if (parentTurnId !== undefined) {
560
+ a.subagentDone(turnId, parentTurnId);
561
+ }
562
+ // Record this frame's own uuid → the messageId it produced, so a LATER
563
+ // retraction naming this uuid can translate it (Finding #1).
564
+ registerUuid(msg.uuid, [m.id]);
565
+ return;
566
+ }
567
+ if (msg.type === "user") {
568
+ // A user message carrying tool_result blocks → tool.done per result.
569
+ // parent_tool_use_id (when set) identifies a subagent tool call — the
570
+ // tool.done's turnId should point at that parent call's turn so the
571
+ // subagent reduce() correctly routes the result.
572
+ const content = msg.message.content;
573
+ if (typeof content !== "string") {
574
+ // Task 8c leg 4: prefer the REAL subagent turnId recorded at
575
+ // subagent.start time. Fall back to the old synthetic label only when
576
+ // it is unknown (e.g. a result delivered before its subagent.start
577
+ // was ever observed) — defensive; leg 3's never-opened-turn guard now
578
+ // parks loudly on that label instead of fabricating a phantom turn.
579
+ const toolTurnId = msg.parent_tool_use_id !== null
580
+ ? (subagentTurnByParentToolUseId.get(msg.parent_tool_use_id) ??
581
+ `turn_${msg.parent_tool_use_id}`)
582
+ : undefined;
583
+ // tool_use_result sibling (SDK-injected rich MCP result; audit B7): carries
584
+ // structuredContent (incl. render-cache markers) + _meta.ui the block-level
585
+ // arm never sees. Applies only when the message has exactly ONE tool_result
586
+ // block (the sibling is message-level; multi-result attribution is ambiguous —
587
+ // skipped, and the census will surface it if a multi-result sibling ever occurs).
588
+ const rawMsg = isJsonObject(msg) ? msg : undefined;
589
+ const sibling = rawMsg !== undefined && isJsonObject(rawMsg["tool_use_result"])
590
+ ? rawMsg["tool_use_result"]
591
+ : undefined;
592
+ const siblingSc = sibling?.["structuredContent"] !== undefined
593
+ ? JsonValue.parse(sibling["structuredContent"])
594
+ : undefined;
595
+ const siblingMeta = sibling !== undefined && isJsonObject(sibling["_meta"])
596
+ ? AgMeta.parse(sibling["_meta"])
597
+ : undefined;
598
+ const siblingHasUi = siblingMeta !== undefined && siblingMeta["ui"] !== undefined;
599
+ // A `for...of` count, not `.filter(...).length` — see
600
+ // `mcpToolResultContentToAgBlocks`'s doc: array-method callback
601
+ // parameter inference degrades to implicit `any` on this content shape
602
+ // post-0.3.199.
603
+ let toolResultCount = 0;
604
+ for (const b of content)
605
+ if (b.type === "tool_result")
606
+ toolResultCount++;
607
+ const applySibling = sibling !== undefined && toolResultCount === 1;
608
+ // Finding #1: this frame's own uuid may later be named by a retraction
609
+ // (a refused leg's tombstoned tool_results, per the field's own doc) —
610
+ // collect every adopted messageId this frame produces below.
611
+ const resultMessageIds = [];
612
+ for (const block of content) {
613
+ if (block.type === "tool_result") {
614
+ const outcome = block.is_error === true ? "error" : "ok";
615
+ const toolContent = block.content === undefined ? [] : toolResultContentToAgBlocks(block.content);
616
+ // `structuredContent` is not declared on `ToolResultBlockParam` in the
617
+ // static SDK type, but the Claude Agent SDK injects it at runtime (spec §9
618
+ // / MCP outputSchema). Use isJsonObject to widen `block` to the opaque
619
+ // JSON-object boundary and extract the field via JsonValue.parse — no cast.
620
+ const blockAsObj = isJsonObject(block) ? block : undefined;
621
+ const sc = blockAsObj?.["structuredContent"] !== undefined
622
+ ? JsonValue.parse(blockAsObj["structuredContent"])
623
+ : undefined;
624
+ const resultMessageId = `${block.tool_use_id}:result`;
625
+ resultMessageIds.push(resultMessageId);
626
+ a.toolDone({
627
+ toolCallId: block.tool_use_id,
628
+ content: toolContent,
629
+ outcome,
630
+ isError: block.is_error === true,
631
+ turnId: toolTurnId,
632
+ // SPEC §5 tool.done adoption (audit B10; Task 8b): the Claude SDK
633
+ // closes the assistant message (message.end) BEFORE this tool_result
634
+ // arrives, so a messageId-less toolDone here has no open message to
635
+ // attach to and parks the fold (guuey fold-identity capstone caught
636
+ // this on a real claude tool conversation). A stable derived
637
+ // messageId engages the reducer's adoption path instead: the result
638
+ // lands in its OWN dedicated role:"tool" message.
639
+ messageId: resultMessageId,
640
+ // §2.1 routing: MCP-Apps structuredContent (sibling with _meta.ui)
641
+ // is surface data → uiData; base-MCP structuredContent → the model
642
+ // channel. The sibling's copy is authoritative over the block-level
643
+ // one (it carries the full payload incl. cache markers).
644
+ ...(applySibling && siblingHasUi && siblingSc !== undefined
645
+ ? { uiData: siblingSc }
646
+ : {}),
647
+ ...(applySibling && !siblingHasUi && siblingSc !== undefined
648
+ ? { structuredContent: siblingSc }
649
+ : sc !== undefined
650
+ ? { structuredContent: sc }
651
+ : {}),
652
+ ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
653
+ ...(applySibling && siblingMeta !== undefined ? { _meta: siblingMeta } : {}),
654
+ });
655
+ }
656
+ }
657
+ // Finding #1: record this frame's uuid → the adopted messageId(s) it
658
+ // produced, so a later retraction naming this uuid can translate it.
659
+ registerUuid(msg.uuid, resultMessageIds);
660
+ }
661
+ return;
662
+ }
663
+ if (msg.type === "result" && msg.subtype === "success") {
664
+ const turnId = turnIdFor(msg.session_id, msg.uuid);
665
+ const safety = msg.stop_reason === "refusal" ? [{ category: "refusal", blocked: true }] : undefined;
666
+ // structured_output (when a response schema is in effect) overrides the plain
667
+ // string result — it is the authoritative typed outcome payload (spec §4).
668
+ const structuredOutput = msg.structured_output !== undefined ? JsonValue.parse(msg.structured_output) : undefined;
669
+ // Emit permission_denials as tool.start + tool.done denied pairs, inside a
670
+ // dedicated carrier message: the assistant message is already sealed, and
671
+ // INV-MSG (audit M19) forbids attaching to sealed messages / closed turns.
672
+ if (msg.permission_denials.length > 0) {
673
+ const denialMsgId = `${turnId}:denials`;
674
+ a.openMessage({ id: denialMsgId, role: "assistant", turnId, threadId: msg.session_id });
675
+ for (const denial of msg.permission_denials) {
676
+ // Fixture-drift ratchet finding (SDKPermissionDeniedMessage,
677
+ // "handled" via existing-home mapping): enrich with the live
678
+ // standalone denial notice recorded above (keyed by tool_use_id),
679
+ // when one preceded this aggregate — the actual rejection text
680
+ // returned to the model, plus decision-reason/agent-id context —
681
+ // rather than leaving a bare empty-content stub. No second
682
+ // tool.start/tool.done pair is ever emitted for the live frame
683
+ // itself (see the dedicated `permission_denied` branch below).
684
+ const live = deniedLiveByToolUseId.get(denial.tool_use_id);
685
+ const liveMeta = live !== undefined &&
686
+ (live.decisionReasonType !== undefined || live.decisionReason !== undefined || live.agentId !== undefined)
687
+ ? AgProviderMeta.parse({
688
+ ...(live.decisionReasonType !== undefined ? { decisionReasonType: live.decisionReasonType } : {}),
689
+ ...(live.decisionReason !== undefined ? { decisionReason: live.decisionReason } : {}),
690
+ ...(live.agentId !== undefined ? { agentId: live.agentId } : {}),
691
+ })
692
+ : undefined;
693
+ a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
694
+ a.toolDone({
695
+ toolCallId: denial.tool_use_id,
696
+ content: live !== undefined ? [{ type: "text", text: live.message }] : [],
697
+ outcome: "denied",
698
+ ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
699
+ });
700
+ }
701
+ a.closeMessage(denialMsgId);
702
+ }
703
+ a.closeTurnDone(turnId, {
704
+ outcome: { type: "success", result: structuredOutput ?? msg.result },
705
+ finishReason: mapStopReason(msg.stop_reason),
706
+ usage: mapTurnUsage(msg.usage, msg.total_cost_usd, msg.modelUsage),
707
+ safety,
708
+ });
709
+ return;
710
+ }
711
+ if (msg.type === "result") {
712
+ // At this point msg.subtype can only be an error variant (success handled above).
713
+ const turnId = turnIdFor(msg.session_id, msg.uuid);
714
+ // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
715
+ // `typeof v.subtype === "string"` for the result arm — it does NOT validate
716
+ // the `errors` array. A malformed message (missing errors, wrong subtype) must
717
+ // not throw (Tenet 6: graceful, never throws).
718
+ const errors = Array.isArray(msg.errors) ? msg.errors : [];
719
+ const subtype = typeof msg.subtype === "string" ? msg.subtype : "error_unknown";
720
+ const retriable = subtype !== "error_max_turns";
721
+ a.closeTurnError(turnId, {
722
+ message: errors.length > 0 ? errors.join("; ") : subtype,
723
+ code: subtype,
724
+ retriable,
725
+ });
726
+ return;
727
+ }
728
+ if (msg.type === "system" && msg.subtype === "informational") {
729
+ // Fixture-drift ratchet FLAGSHIP finding (2026-07-03): CONTRADICTS
730
+ // playbook-sdk-bumps-report.md's prior classification of this arm as a
731
+ // "control-plane/CLI-UX signal, no model output". Direct field
732
+ // inspection (sdk.d.ts) shows `content`/`level`/`prevent_continuation?`
733
+ // are genuinely conversation/UX-relevant (transcript notices, an
734
+ // explanation for why a turn halted, e.g. a Stop hook denial) — not
735
+ // telemetry. LOCKED DISPOSITION: no first-class AgJSON event exists for
736
+ // this today (a `notice` core event is a future spec-process decision,
737
+ // §8 item 21) — carry it losslessly via the facet's established
738
+ // `ext.anthropic.*` convention rather than drop it.
739
+ a.emitExt("anthropic", "informational", {
740
+ content: msg.content,
741
+ level: msg.level,
742
+ ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
743
+ });
744
+ return;
745
+ }
746
+ if (msg.type === "system" && msg.subtype === "model_refusal_fallback") {
747
+ // Finding #1 (critical): the end-of-turn authoritative eviction record —
748
+ // "the complete audit record for the turn" per the field's own doc.
749
+ // Idempotent with the earlier `supersedes`-triggered eviction above (see
750
+ // `retractUuids`'s doc); also the ONLY retraction path when a consumer
751
+ // never observed (or a normalizer instance never processed) the
752
+ // superseding assistant frame's own `supersedes` field directly.
753
+ const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
754
+ retractUuids(uuids);
755
+ return;
756
+ }
757
+ if (msg.type === "system" && msg.subtype === "permission_denied") {
758
+ // Fixture-drift ratchet finding: this standalone LIVE denial notice is
759
+ // the SAME fact the already-handled `SDKResultMessage.permission_denials[]`
760
+ // aggregate turns into a tool.start+tool.done{denied} pair inside the
761
+ // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
762
+ // second pair here (the M22 double-fold hazard). Record this frame's
763
+ // richer diagnostic fields only; the aggregate handler consumes them.
764
+ deniedLiveByToolUseId.set(msg.tool_use_id, {
765
+ message: msg.message,
766
+ ...(msg.decision_reason_type !== undefined ? { decisionReasonType: msg.decision_reason_type } : {}),
767
+ ...(msg.decision_reason !== undefined ? { decisionReason: msg.decision_reason } : {}),
768
+ ...(msg.agent_id !== undefined ? { agentId: msg.agent_id } : {}),
769
+ });
770
+ return;
771
+ }
772
+ // Fixture-drift ratchet (2026-07-03 follow-up): the remaining 15
773
+ // `silently-dropped` arms carry genuine consumer-facing content with no
774
+ // existing AgJSON home — uniform lossless carry (see `anthropicFrameKind`
775
+ // doc comment above for the full per-arm reasoning, SPEC §8 item 22).
776
+ const carriedKind = anthropicFrameKind(msg);
777
+ if (carriedKind !== undefined) {
778
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: JsonValue.parse(msg) });
779
+ return;
780
+ }
781
+ // Other SDKMessage variants (system, partial-assistant, status, …) carry no
782
+ // AgJSON-relevant content on this seam → no events.
783
+ }
784
+ return {
785
+ push(native) {
786
+ if (!isSDKMessage(native)) {
787
+ // Graceful guard (Tenet 6): route the raw payload through the lossless
788
+ // vendor channel rather than throwing. Nest under `native` so a payload
789
+ // that carries its own `type` key (the common malformed-SDKMessage shape
790
+ // that lands here) does NOT clobber the `ext.anthropic.unparsed` event type
791
+ // (emitExt spreads object payloads at the top level).
792
+ a.emitExt("anthropic", "unparsed", { native });
793
+ return a.drain();
794
+ }
795
+ drive(native);
796
+ return a.drain();
797
+ },
798
+ flush() {
799
+ return a.flush();
800
+ },
801
+ };
802
+ }
803
+ export default createClaudeNormalizer;
804
+ export { mapStopReason };
805
+ //# sourceMappingURL=index.js.map