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