@silverprotocol/claude-agent-sdk 0.7.2 → 0.8.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 CHANGED
@@ -42,7 +42,7 @@ function stopReasonRaw(stop) {
42
42
  // invoke the second turn's message.start and content landed on T AFTER
43
43
  // turn.done(T) (the assembler's seen-turn set suppressed a second
44
44
  // turn.start), breaking INV-TURN (SPEC:743), and reduce() merged every turn
45
- // of a session into one AgTurnRecord (sp-protocol, 2026-09-23).
45
+ // of a session into one AgTurnRecord (2026-09-23).
46
46
  // ─── image source mapping (Anthropic → AgSource, spec §2) ─────────────────────
47
47
  function imageSource(source) {
48
48
  if (source.type === "base64") {
@@ -85,15 +85,57 @@ function readThinkingTokens(usage) {
85
85
  const thinking = details["thinking_tokens"];
86
86
  return typeof thinking === "number" ? thinking : undefined;
87
87
  }
88
+ // draft.5 §4 (input side): `inputTokens` counts EVERY input token the provider
89
+ // processed, cache reads and writes included, and `cacheReadTokens` /
90
+ // `cacheWriteTokens` are its breakdowns. Anthropic's `input_tokens` EXCLUDES
91
+ // cache tokens, so the facet ADDS the two cache counters in, on every AgUsage
92
+ // it emits (turn, message and `byModel` entries alike), the provider's own
93
+ // definition of total input. On a running-total object the sum of three
94
+ // co-scoped running totals is itself the running total, so nothing is
95
+ // de-cumulated. A cache counter that is absent (or null) counts 0, so with
96
+ // both absent the input counter is carried as is and no cache key is
97
+ // invented. A non-numeric input counter yields no `inputTokens` (a malformed
98
+ // frame never makes NaN). The facet never subtracts a cache counter out.
99
+ function inclusiveInput(input, cacheRead, cacheWrite) {
100
+ if (typeof input !== "number")
101
+ return undefined;
102
+ return input + (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0);
103
+ }
104
+ // The cache breakdown keys of an AgUsage: each present only when its native
105
+ // counter is a number, so an absent (or null) counter invents no key, on the
106
+ // wire or in memory (draft.5 §4: both absent ⇒ no cache key).
107
+ function cacheBreakdown(cacheRead, cacheWrite) {
108
+ return {
109
+ ...(typeof cacheRead === "number" ? { cacheReadTokens: cacheRead } : {}),
110
+ ...(typeof cacheWrite === "number" ? { cacheWriteTokens: cacheWrite } : {}),
111
+ };
112
+ }
113
+ // A message's native input trio merged field-wise with a newer usage object
114
+ // (only numeric counters overwrite), for the cache-inclusive `inputTokens` of a
115
+ // message whose usage arrives in parts (see PendingMessage.rawInput).
116
+ function nativeInput(prev, usage) {
117
+ if (!isJsonObject(usage))
118
+ return prev;
119
+ const input = usage["input_tokens"];
120
+ const cacheRead = usage["cache_read_input_tokens"];
121
+ const cacheWrite = usage["cache_creation_input_tokens"];
122
+ return {
123
+ ...prev,
124
+ ...(typeof input === "number" ? { input } : {}),
125
+ ...(typeof cacheRead === "number" ? { cacheRead } : {}),
126
+ ...(typeof cacheWrite === "number" ? { cacheWrite } : {}),
127
+ };
128
+ }
88
129
  // `thinkingTokens` (0.3.257) → `reasoningTokens`: the per-model twin of
89
130
  // `readThinkingTokens` above — same subset-of-outputTokens semantics (the SDK's
90
131
  // own doc: "already counted inside outputTokens"), same absent ⇒ no key rule.
132
+ // A `modelUsage` entry is the SDK's per-model RUNNING TOTAL over the query, so
133
+ // it keeps `cumulative: true` (the flag binds the object it sits on).
91
134
  function mapModelUsage(mu) {
92
135
  return {
93
- inputTokens: mu.inputTokens,
136
+ inputTokens: inclusiveInput(mu.inputTokens, mu.cacheReadInputTokens, mu.cacheCreationInputTokens),
94
137
  outputTokens: mu.outputTokens,
95
- cacheReadTokens: mu.cacheReadInputTokens,
96
- cacheWriteTokens: mu.cacheCreationInputTokens,
138
+ ...cacheBreakdown(mu.cacheReadInputTokens, mu.cacheCreationInputTokens),
97
139
  ...(mu.thinkingTokens !== undefined ? { reasoningTokens: mu.thinkingTokens } : {}),
98
140
  costUsd: mu.costUSD,
99
141
  serverToolRequests: mu.webSearchRequests,
@@ -104,7 +146,7 @@ function mapModelUsage(mu) {
104
146
  // but a result frame is discriminant-validated only, so a leaner producer (a
105
147
  // proxy, an older CLI) can omit it or a member. Through 0.7.0's stack an ABSENT
106
148
  // member passed the `!== null` check and threw a TypeError out of push()
107
- // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found by sp-protocol writing §10.23),
149
+ // (Tenet 6 / SPEC §8.0 "MUST NOT throw"; found while writing §10.23),
108
150
  // and a missing counter summed to NaN. Both counters numbers ⇒ their sum;
109
151
  // anything else ⇒ absent.
110
152
  function serverToolRequestCount(usage) {
@@ -117,6 +159,17 @@ function serverToolRequestCount(usage) {
117
159
  const fetch = stu["web_fetch_requests"];
118
160
  return typeof search === "number" && typeof fetch === "number" ? search + fetch : undefined;
119
161
  }
162
+ // A result frame's usage → the turn terminal's usage. Its token counters are
163
+ // PER TURN (a streaming-input invoke's second result reports that turn alone),
164
+ // so the object is flagged `cumulative: false` (draft.5 §8.0 item 4; through
165
+ // 0.7.x it read `true`, and a "running total" that went down from one terminal
166
+ // to the next was the tell). `total_cost_usd` is different: the SDK's running
167
+ // cost over the `query()` call, which continues from restored state on a
168
+ // resumed or forked session and restarts on its reset commands. Its scope is
169
+ // not the object's, so it carries `costScope: "query"` (§4): a consumer takes
170
+ // the latest per scope, may subtract adjacent snapshots, and never sums them.
171
+ // `byModel` entries are the SDK's per-model running totals and keep their own
172
+ // `cumulative: true`.
120
173
  function mapTurnUsage(usage, totalCostUsd, modelUsage) {
121
174
  const byModel = {};
122
175
  for (const [model, mu] of Object.entries(modelUsage)) {
@@ -124,28 +177,39 @@ function mapTurnUsage(usage, totalCostUsd, modelUsage) {
124
177
  }
125
178
  const reasoningTokens = readThinkingTokens(usage);
126
179
  return {
127
- inputTokens: usage.input_tokens,
180
+ inputTokens: inclusiveInput(usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
128
181
  outputTokens: usage.output_tokens,
129
- cacheReadTokens: usage.cache_read_input_tokens,
130
- cacheWriteTokens: usage.cache_creation_input_tokens,
182
+ ...cacheBreakdown(usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
131
183
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
132
184
  serverToolRequests: serverToolRequestCount(usage),
133
185
  costUsd: totalCostUsd,
134
- cumulative: true,
186
+ // The scope labels the cost, so it rides only beside a numeric costUsd.
187
+ ...(typeof totalCostUsd === "number" ? { costScope: "query" } : {}),
188
+ cumulative: false,
135
189
  ...(Object.keys(byModel).length > 0 ? { byModel } : {}),
136
190
  };
137
191
  }
192
+ // Message-level usage: the Anthropic message stream's RUNNING TOTALS, so
193
+ // `cumulative: true`, with the cache-inclusive input add.
138
194
  function mapMessageUsage(usage) {
139
195
  const reasoningTokens = readThinkingTokens(usage);
140
196
  return {
141
- inputTokens: usage.input_tokens,
197
+ inputTokens: inclusiveInput(usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
142
198
  outputTokens: usage.output_tokens,
143
- cacheReadTokens: usage.cache_read_input_tokens ?? undefined,
144
- cacheWriteTokens: usage.cache_creation_input_tokens ?? undefined,
199
+ ...cacheBreakdown(usage.cache_read_input_tokens, usage.cache_creation_input_tokens),
145
200
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
146
201
  cumulative: true,
147
202
  };
148
203
  }
204
+ // A message usage without its `outputTokens` (the no-partials seal; see
205
+ // PendingMessage.usageDelta). A copy: the pending usage is not mutated.
206
+ function withoutOutputTokens(usage) {
207
+ const out = {};
208
+ for (const [k, v] of Object.entries(usage))
209
+ if (k !== "outputTokens")
210
+ Object.assign(out, { [k]: v });
211
+ return out;
212
+ }
149
213
  // ─── citation mapping helpers ─────────────────────────────────────────────────
150
214
  function mapCitations(citations) {
151
215
  const result = [];
@@ -259,7 +323,7 @@ function mcpToolResultContentToAgBlocks(content) {
259
323
  out.push({ type: "text", text: tb.text });
260
324
  return out;
261
325
  }
262
- // `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on sp-probe's
326
+ // `tool_result_meta` (CLI 2.1.280, @internal, runtime-only; live on the
263
327
  // defer resume-deny capture): per tool_result, keyed by tool_use_id. Its
264
328
  // `non_execution_kind` is "the harness-stamped reason an is_error:true result did
265
329
  // not carry the tool's own execution output (user-rejected / permission-rule /
@@ -281,11 +345,14 @@ function readNonExecutionKinds(frame) {
281
345
  }
282
346
  return out;
283
347
  }
284
- // rd-15 (founder ruling 2026-09-24, fix the carries): each `tool_result_meta`
348
+ // rd-15 (ruling of 2026-09-24, fix the carries): each `tool_result_meta`
285
349
  // entry, keyed by its `id` (the tool_use_id), verbatim: {id, non_execution_kind?,
286
350
  // user_feedback?, remedy?} per the CLI's schema ("@internal Display metadata for
287
351
  // this message's tool_result blocks"). Read through the JSON boundary; an entry
288
- // without a string id is skipped. It rides the matching tool.done's `_meta`.
352
+ // without a string id is skipped. It rides the matching tool.done's `_meta`,
353
+ // through `carryVerbatim`: a CLI-authored subtree like the other wrapper
354
+ // carries, so a `fallback_credit_token` at any depth (a `remedy` can hold one)
355
+ // is deleted before it is emitted.
289
356
  function readToolResultMetaEntries(frame) {
290
357
  const out = new Map();
291
358
  if (!isJsonObject(frame))
@@ -295,13 +362,13 @@ function readToolResultMetaEntries(frame) {
295
362
  return out;
296
363
  for (const entry of list) {
297
364
  if (isJsonObject(entry) && typeof entry["id"] === "string")
298
- out.set(entry["id"], JsonValue.parse(entry));
365
+ out.set(entry["id"], carryVerbatim(entry));
299
366
  }
300
367
  return out;
301
368
  }
302
369
  // The non_execution_kinds that mean the call was NOT PERMITTED to run →
303
370
  // `outcome:"denied"` (SPEC :850: "denied is a distinct recorded outcome"; §8.0
304
- // item 15 routes Claude's permission denials to it; sp-protocol, 2026-09-23).
371
+ // item 15 routes Claude's permission denials to it; 2026-09-23).
305
372
  // `interrupted`, `cancelled`, absent and any unknown value are not denials and
306
373
  // keep "error" (no guessing).
307
374
  function isDenialKind(kind) {
@@ -567,7 +634,7 @@ function isSDKMessage(v) {
567
634
  // `message.remove` (§8 item 19) and the rest of the frame has no home. It is
568
635
  // NOT in the sets below either. Its dedicated branch does the retraction and
569
636
  // then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
570
- // sp-protocol's item-22 reading for half-mapped frames — see that branch).
637
+ // the item-22 reading for half-mapped frames — see that branch).
571
638
  //
572
639
  // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
573
640
  // §12) — not 15 distinct ext keys (ext-vocabulary sprawl, the standing
@@ -679,11 +746,27 @@ const HOST_ONLY_WRAPPER_KEYS = new Set([
679
746
  "api_error",
680
747
  "api_error_params",
681
748
  "api_error_code",
682
- // rd-15 (founder: defer the field, fix the carries): three more @internal
749
+ // rd-15 (defer the field, fix the carries): three more @internal
683
750
  // CLI assistant-wrapper strings, carried where the host can read them.
684
751
  "error_details",
685
752
  "advisor_model",
686
753
  "attribution_agent",
754
+ // draft.5 (§10 item 45; §8.0 item 19 for `supersedes`): the rest of the
755
+ // wrapper bag. Each is host-only by its own sdk.d.ts doc (never inside
756
+ // `message.content`, not replayed to the model): the /context and /usage
757
+ // twins, the turn-binding family, the interrupt-truncation flag, and the
758
+ // refusal-fallback supersede list, whose eviction already runs as
759
+ // `message.remove` (the list is an audit copy). Through 0.7.x they rode
760
+ // `providerMetadata`. `resumed_from_incomplete_thinking` is the one wrapper
761
+ // key NOT here: its doc makes it a flag a history replayed through the
762
+ // bridge must carry back, so it stays replay-side.
763
+ "context_usage",
764
+ "usage_report",
765
+ "user_message_uuid",
766
+ "user_message_uuids",
767
+ "resume_reason",
768
+ "aborted",
769
+ "supersedes",
687
770
  ]);
688
771
  // `narration_block_indexes` (0.3.272) — which of THIS frame's content blocks are
689
772
  // user-facing NARRATION rather than private reasoning. Undeclared in sdk.d.ts at
@@ -707,7 +790,8 @@ function readNarrationBlockIndexes(v) {
707
790
  // depth (withoutCreditTokens). Every verbatim carrier of this facet goes
708
791
  // through it: the whole-frame ext.anthropic.frame / ext.anthropic.unparsed
709
792
  // carries, provider-raw blocks, and the CLI/API wrapper subtrees
710
- // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats).
793
+ // (context_usage, usage_report, diagnostics, api_error_params, subagent_stats,
794
+ // the `tool_result_meta` entries).
711
795
  // Model- or tool-authored payloads (tool input, a deferred tool call, MCP
712
796
  // structuredContent / _meta / resourceLinks, structured_output) are NOT
713
797
  // stripped: a key there is user content, and the wire already carries the same
@@ -715,7 +799,7 @@ function readNarrationBlockIndexes(v) {
715
799
  function carryVerbatim(v) {
716
800
  return withoutCreditTokens(JsonValue.parse(v));
717
801
  }
718
- // rd-15 / SPEC §13.7 (queued): a provider credit or bearer token is never
802
+ // rd-15 / SPEC §13.10: a provider credit or bearer token is never
719
803
  // emitted. Anthropic's refusal `stop_details` can hold `fallback_credit_token`
720
804
  // (top level and per fallback), so every key of that name is deleted at any
721
805
  // depth; everything else is kept verbatim.
@@ -746,14 +830,24 @@ function toolResultText(content) {
746
830
  return joined !== "" ? joined : undefined;
747
831
  }
748
832
  // The namespace of the facet's own harness keys on a tool.done `_meta` (the
749
- // subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta").
833
+ // subagent report's "anthropic/agentOutput", rd-15's "anthropic/toolResultMeta",
834
+ // and since draft.5 the two host records below). SPEC §2.1 *Host records*: a
835
+ // producer carries such a record under a key in a namespace it owns.
750
836
  const HARNESS_META_PREFIX = "anthropic/";
837
+ // draft.5 (§2.1 Host records, §10 item 45): the SDK's verbatim
838
+ // `tool_use_result.resourceLinks` list (through 0.7.x on the tool.done's
839
+ // `providerMetadata.resourceLinks`).
840
+ const RESOURCE_LINKS_META_KEY = `${HARNESS_META_PREFIX}resourceLinks`;
841
+ // draft.5 (§10 item 45): the live `permission_denied` notice's decision context
842
+ // ({decisionReasonType?, decisionReasonCode?, decisionReason?, agentId?}; through
843
+ // 0.7.x those four rode the denied call's tool.done `providerMetadata` flat).
844
+ const PERMISSION_DENIED_META_KEY = `${HARNESS_META_PREFIX}permissionDenied`;
751
845
  // A tool.done's host-only `_meta`: the tool-authored MCP sibling `_meta` merged
752
846
  // with the facet's own harness keys. The harness namespace is RESERVED: every
753
847
  // sibling key under "anthropic/" is dropped before the harness keys are
754
848
  // written, so a tool (a malicious MCP server) can never present a forged
755
849
  // harness fact, such as an agent report or a remedy pointing a host at its URL,
756
- // even for a call the facet writes no harness key for (sp-cto's read of the
850
+ // even for a call the facet writes no harness key for (a review of the
757
851
  // rd-15 carry; the CLI itself strips its own reserved `com.anthropic/` prefix
758
852
  // from server `_meta`). Every other sibling key is kept verbatim. undefined
759
853
  // when nothing remains.
@@ -769,7 +863,7 @@ function mergeHarnessMeta(sibling, harness) {
769
863
  return Object.keys(out).length > 0 ? out : undefined;
770
864
  }
771
865
  // `wire_tool_inputs` (CLI 2.1.280, @internal, undeclared in sdk.d.ts; first seen
772
- // on sp-probe's subagent captures): "tool_use.input exactly as the API produced
866
+ // on the subagent captures): "tool_use.input exactly as the API produced
773
867
  // it, keyed by tool_use id, for a message whose message.content carries the
774
868
  // client-normalized input. Round-tripped so a replayed history echoes each
775
869
  // earlier tool call back to the API as the API emitted it" (the CLI's own
@@ -814,6 +908,12 @@ function jsonEqual(x, y) {
814
908
  }
815
909
  return false;
816
910
  }
911
+ // The id of the tool call a result's `deferred_tool_use` parked, when it names
912
+ // one (a string `id`); undefined otherwise. Read through the JSON boundary.
913
+ function readDeferredCall(v) {
914
+ const deferred = isJsonObject(v) ? v["deferred_tool_use"] : undefined;
915
+ return isJsonObject(deferred) && typeof deferred["id"] === "string" ? deferred["id"] : undefined;
916
+ }
817
917
  // A result's `terminal_reason` when it names why the turn ended other than a
818
918
  // normal completion (e.g. "tool_deferred_unavailable"); undefined otherwise. A
819
919
  // live API error's own value is "api_error", which is also the generic code, so
@@ -1012,7 +1112,7 @@ function resultMetaPayload(msg, closesAsError) {
1012
1112
  const raw = msg;
1013
1113
  // `origin` (SDKMessageOrigin, on the result arms): set on the result of a turn
1014
1114
  // the framework WOKE, not the user, e.g. {kind: "task-notification"} after a
1015
- // background subagent reported (sp-probe's bg capture, 5ba11da). turn.start's
1115
+ // background subagent reported (the background capture). turn.start's
1016
1116
  // `trigger` is a frozen enum, so it rides here verbatim.
1017
1117
  const origin = isJsonObject(raw) && isJsonObject(raw["origin"]) ? carryVerbatim(raw["origin"]) : undefined;
1018
1118
  const subagentStats = isJsonObject(raw) && isJsonObject(raw["subagent_stats"]) ? carryVerbatim(raw["subagent_stats"]) : undefined;
@@ -1027,17 +1127,17 @@ function resultMetaPayload(msg, closesAsError) {
1027
1127
  // `deferred_tool_use` (SUCCESS arm, declared `SDKDeferredToolUse {id, name,
1028
1128
  // input}`): the tool call a host's PreToolUse `defer` decision parked, which
1029
1129
  // the CLI resumes later ("Deferred tool resume"). CONTENT, not telemetry:
1030
- // the host needs it to act on the parked call. Through 0.6.4 the facet never
1031
- // read it (a silent drop). Carried WHOLE and verbatim (the `subagent_stats`
1032
- // precedent); whether it should instead map onto `turn.done.outcome.paused`
1033
- // (asks) is a question routed to sp-protocol / sp-rnd. Fixture-only: no
1034
- // capture sets a defer hook.
1130
+ // the host needs it to act on the parked call. Carried WHOLE and verbatim
1131
+ // here (the `subagent_stats` precedent), and on a deferred close
1132
+ // (stop_reason "tool_deferred") the turn ALSO closes paused with an approval
1133
+ // ask for it (see the success arm, draft.5 §8.0 item 32). The live capture is
1134
+ // defer-tool-sonnet5.
1035
1135
  const deferredToolUse = isJsonObject(raw) && isJsonObject(raw["deferred_tool_use"]) ? JsonValue.parse(raw["deferred_tool_use"]) : undefined;
1036
1136
  // `api_error_status` (SUCCESS arm, `number | null`): the HTTP status of the
1037
1137
  // API error that ended the turn. It already decides `retriable` on an
1038
1138
  // is_error close; it is now also CARRIED verbatim, beside `apiErrorCode`, as
1039
1139
  // the census allowlist's "carry candidate the first time an error seed
1040
- // surfaces it" (sp-probe's api-error-auth seed: 401). Absent or null ⇒ no key.
1140
+ // surfaces it" (the api-error-auth seed: 401). Absent or null ⇒ no key.
1041
1141
  const apiErrorStatus = isJsonObject(raw) && typeof raw["api_error_status"] === "number" ? raw["api_error_status"] : undefined;
1042
1142
  // `stop_reason` on a result that closes as turn.error: turn.error has no
1043
1143
  // finishReason slot (and finishReasonRaw is turn.done-only), so the native
@@ -1118,7 +1218,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1118
1218
  // sub-session's own assistant arm at subagent.start time, so a later inner
1119
1219
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
1120
1220
  const subagentTurnByParentToolUseId = new Map();
1121
- // INV-TURN (SPEC:743; sp-protocol ruling B, 2026-09-23): ONE turnId names
1221
+ // INV-TURN (SPEC:743; ruling B, 2026-09-23): ONE turnId names
1122
1222
  // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1123
1223
  // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1124
1224
  // or a stream `message_start`) in the ordinary case, or the frame's own
@@ -1161,20 +1261,40 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1161
1261
  }
1162
1262
  return openTopTurnId;
1163
1263
  }
1264
+ // The turn's trigger (AgTrigger, folded onto AgTurnRecord.trigger): the CLI's
1265
+ // `user_message_uuid` echo, read ONLY from the frame that OPENS a top-level
1266
+ // turn. The three stamped openers are a stream `message_start`, a complete
1267
+ // assistant frame and a success result that opens a result-only turn; each
1268
+ // caller checks `openTopTurnId === undefined` and `parent_tool_use_id === null`
1269
+ // before it mints the turn id, and passes the result to `a.openTurn` BEFORE
1270
+ // anything else of the turn is emitted, so the turn's one turn.start carries
1271
+ // it. turn.start is never re-sent to add one: a turn opened by a notice, a
1272
+ // tool_result or an error result, and a turn whose uuid first appears on a
1273
+ // later frame, carry no trigger. An error result is never an opener here,
1274
+ // because its echo can be a client-minted queue key (sdk.d.ts 0.3.280, the
1275
+ // delivery-failure case). `kind: "user"` means a user-role send the host
1276
+ // submitted with that uuid, not human authorship; `user_message_uuids` and
1277
+ // thinking_tokens frames are never read for it.
1278
+ function openerTrigger(uuid) {
1279
+ return typeof uuid === "string" && uuid.length > 0 ? { trigger: { kind: "user", ref: uuid } } : undefined;
1280
+ }
1164
1281
  // The result frame closes the open turn (or, for a result-only turn, the one
1165
1282
  // it opens itself) and clears it. A RESULT-ONLY turn (no assistant frame,
1166
1283
  // notice or stream opened it: the CL-09 result-only API-error path, a
1167
1284
  // startup-failure result, a local-command result) is OPENED here with an
1168
1285
  // explicit turn.start before anything else the result emits (INV-TURN,
1169
1286
  // SPEC:743: every turn is opened by exactly one turn.start and closed by
1170
- // exactly one terminal; sp-protocol, 2026-09-23). Through the B commit such a
1287
+ // exactly one terminal; 2026-09-23). Through the B commit such a
1171
1288
  // turn was only closed, and reduce() minted a stub record whose threadId was
1172
1289
  // the turnId. An open turn already has its turn.start (openMessage).
1173
- function closingTopTurnId(resultUuid, sessionId) {
1290
+ // `openerUuid`: the success result's `user_message_uuid`, which becomes the
1291
+ // trigger when this result OPENS its turn (see `openerTrigger`). The error
1292
+ // arm passes none.
1293
+ function closingTopTurnId(resultUuid, sessionId, openerUuid) {
1174
1294
  let turnId = openTopTurnId;
1175
1295
  if (turnId === undefined) {
1176
1296
  turnId = topTurnId(resultUuid, undefined);
1177
- a.openTurn(turnId, options.threadId ?? sessionId);
1297
+ a.openTurn(turnId, options.threadId ?? sessionId, openerTrigger(openerUuid));
1178
1298
  }
1179
1299
  openTopTurnId = undefined;
1180
1300
  closedTopTurnIds.add(turnId);
@@ -1215,7 +1335,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1215
1335
  // The ids of every Agent (or legacy Task) tool call seen in this invoke. Only
1216
1336
  // a result for one of these can carry an AgentOutput: a third-party tool whose
1217
1337
  // result happens to hold an `agentId` (a CRM, a ticketing system, any agent
1218
- // registry) is not Anthropic's Agent run report (sp-cto's read of f2c75d8).
1338
+ // registry) is not Anthropic's Agent run report (a review of 5e7561c).
1219
1339
  const agentCallIds = new Set();
1220
1340
  function openRun(parentToolUseId, turnId, parentTurnId) {
1221
1341
  if (openRuns.has(parentToolUseId))
@@ -1275,9 +1395,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1275
1395
  // rd-15: top-level turnId → the closing response's non-null stop_details (credit
1276
1396
  // tokens stripped) and the message it describes, emitted on that turn's turn.done.
1277
1397
  const stopDetailsByTurn = new Map();
1278
- // The live denial's diagnostic fields, camelCased — the providerMetadata bag
1279
- // on the enriched `<turnId>:denials` tool.done. undefined when the live
1280
- // frame carried none of them (no empty bag).
1398
+ // The live denial's diagnostic fields, camelCased — the record under
1399
+ // PERMISSION_DENIED_META_KEY on the denied call's tool.done `_meta` (the
1400
+ // enriched `<turnId>:denials` carrier, or the tool_result that closes the
1401
+ // call). undefined when the live frame carried none of them (no empty record).
1281
1402
  function liveDenialMeta(live) {
1282
1403
  if (live === undefined ||
1283
1404
  (live.decisionReasonType === undefined &&
@@ -1325,7 +1446,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1325
1446
  finalizeStreamBlock(p, idx, atFlush);
1326
1447
  }
1327
1448
  }
1328
- a.closeMessage(p.emittedId, p.usage);
1449
+ a.closeMessage(p.emittedId, p.usage !== undefined && !p.usageDelta ? withoutOutputTokens(p.usage) : p.usage);
1329
1450
  // The subagent bracket is per RUN now (see `openRun`), so sealing a nested
1330
1451
  // message no longer closes its nested turn.
1331
1452
  }
@@ -1390,8 +1511,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1390
1511
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
1391
1512
  // (same end-then-opaque order as the complete arm), the MANDATORY
1392
1513
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
1393
- // `atFlush` (INV-FLUSH (3), draft.4; the founder's fold/flush ruling, "snapshot
1394
- // fold + honest flush; opaque at flush forbidden"; sp-claude's leg C1): the
1514
+ // `atFlush` (INV-FLUSH (3), draft.4; the fold/flush ruling, "snapshot
1515
+ // fold + honest flush; opaque at flush forbidden"; leg C1): the
1395
1516
  // stream ENDED with this block open, so the close lands NO new content. The
1396
1517
  // lifecycle closes stay (text.end with its already-received citations,
1397
1518
  // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
@@ -1472,6 +1593,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1472
1593
  const ev = msg.event;
1473
1594
  if (ev.type === "message_start") {
1474
1595
  const m = ev.message;
1596
+ // Read BEFORE topTurnId mints: does this frame OPEN a top-level turn?
1597
+ const opensTopTurn = msg.parent_tool_use_id === null && openTopTurnId === undefined;
1475
1598
  const turnId = msg.parent_tool_use_id !== null
1476
1599
  ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1477
1600
  : topTurnId(m.id, msg.uuid);
@@ -1506,6 +1629,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1506
1629
  parentTurnId,
1507
1630
  blockIndex: 0,
1508
1631
  usage: mapMessageUsage(m.usage),
1632
+ rawInput: nativeInput({}, m.usage),
1633
+ usageDelta: false,
1509
1634
  streamed: true,
1510
1635
  streamBlocks: new Map(),
1511
1636
  ttftCarried: false,
@@ -1513,6 +1638,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1513
1638
  turnBindingCarried: false,
1514
1639
  };
1515
1640
  pending = open;
1641
+ // The turn's trigger rides its turn.start, so the turn opens explicitly
1642
+ // before openMessage would synthesize a trigger-less one.
1643
+ const trigger = opensTopTurn ? openerTrigger(msg.user_message_uuid) : undefined;
1644
+ if (trigger !== undefined)
1645
+ a.openTurn(turnId, options.threadId ?? msg.session_id, trigger);
1516
1646
  a.openMessage({
1517
1647
  id: open.emittedId,
1518
1648
  role: "assistant",
@@ -1675,14 +1805,14 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1675
1805
  // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
1676
1806
  // no bag, byte-identical.
1677
1807
  //
1678
- // X5 (sp-rnd, 2026-09-23): it rides the delta's host-only `_meta`, not
1808
+ // X5 (2026-09-23): it rides the delta's host-only `_meta`, not
1679
1809
  // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
1680
1810
  // that must round-trip to the provider), and the Messages API never
1681
1811
  // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
1682
1812
  // on start events, so the estimate is now LIVE-ONLY (it used to fold
1683
1813
  // last-value-wins onto the reasoning block) — the same standing as its
1684
1814
  // `system/thinking_tokens` twin, which rides `ext.anthropic.frame`. No
1685
- // consumer read the folded value (guuey/ggui checked via sp-team-main).
1815
+ // consumer read the folded value (guuey/ggui checked).
1686
1816
  // `reasoningDelta`'s sugar has no `_meta` option; `a.emit()` is the base
1687
1817
  // primitive (the reasoning.start precedent in `emitAssistantBlock`), and
1688
1818
  // the sugar's only extra step, de-cumulation, is a pass-through for a
@@ -1743,9 +1873,19 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1743
1873
  // does not declare `output_tokens_details`), subset of outputTokens; see
1744
1874
  // `readThinkingTokens`'s doc.
1745
1875
  const reasoningTokens = readThinkingTokens(u);
1876
+ // draft.5 §4: the input side is re-derived from the merged native trio, so
1877
+ // a delta carrying any one counter keeps `inputTokens` cache-inclusive.
1878
+ const touchesInput = typeof u.input_tokens === "number" ||
1879
+ typeof u.cache_read_input_tokens === "number" ||
1880
+ typeof u.cache_creation_input_tokens === "number";
1881
+ p.rawInput = nativeInput(p.rawInput, u);
1882
+ const inputTokens = touchesInput
1883
+ ? inclusiveInput(p.rawInput.input, p.rawInput.cacheRead, p.rawInput.cacheWrite)
1884
+ : undefined;
1885
+ p.usageDelta = true;
1746
1886
  p.usage = {
1747
1887
  ...(p.usage ?? {}),
1748
- ...(typeof u.input_tokens === "number" ? { inputTokens: u.input_tokens } : {}),
1888
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
1749
1889
  ...(typeof u.output_tokens === "number" ? { outputTokens: u.output_tokens } : {}),
1750
1890
  ...(typeof u.cache_read_input_tokens === "number"
1751
1891
  ? { cacheReadTokens: u.cache_read_input_tokens }
@@ -1831,13 +1971,13 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1831
1971
  // itself (see the dedicated `permission_denied` branch below).
1832
1972
  const live = deniedLiveByToolUseId.get(denial.tool_use_id);
1833
1973
  const liveFields = liveDenialMeta(live);
1834
- const liveMeta = liveFields !== undefined ? AgProviderMeta.parse(liveFields) : undefined;
1974
+ const denialMeta = liveFields !== undefined ? mergeHarnessMeta(undefined, { [PERMISSION_DENIED_META_KEY]: liveFields }) : undefined;
1835
1975
  a.toolStart({ toolCallId: denial.tool_use_id, name: denial.tool_name });
1836
1976
  a.toolDone({
1837
1977
  toolCallId: denial.tool_use_id,
1838
1978
  content: live !== undefined ? [{ type: "text", text: live.message }] : [],
1839
1979
  outcome: "denied",
1840
- ...(liveMeta !== undefined ? { providerMetadata: liveMeta } : {}),
1980
+ ...(denialMeta !== undefined ? { _meta: denialMeta } : {}),
1841
1981
  });
1842
1982
  }
1843
1983
  a.closeMessage(denialMsgId);
@@ -1846,6 +1986,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1846
1986
  function drive(msg) {
1847
1987
  if (msg.type === "assistant") {
1848
1988
  const m = msg.message;
1989
+ // Read BEFORE topTurnId mints: does this frame OPEN a top-level turn?
1990
+ const opensTopTurn = msg.parent_tool_use_id === null && openTopTurnId === undefined;
1849
1991
  const turnId = msg.parent_tool_use_id !== null
1850
1992
  ? nestedTurnId(msg.parent_tool_use_id, m.id, msg.uuid)
1851
1993
  : topTurnId(m.id, msg.uuid);
@@ -1869,10 +2011,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1869
2011
  if (msg.supersedes !== undefined && msg.supersedes.length > 0) {
1870
2012
  retractUuids(msg.supersedes);
1871
2013
  }
1872
- // The raw uuid list is ALSO carried losslessly as `providerMetadata` on
1873
- // this message's first content block (mirrors the "signature on first
1874
- // block" precedent, §8 item 8) — an audit trail independent of whether
1875
- // every targeted uuid was resolvable above.
2014
+ // The raw uuid list is ALSO carried losslessly as host-only `_meta` on
2015
+ // this message's first content block, or on `message.metadata` where no
2016
+ // block anchors it (§8.0 item 19, draft.5; through 0.7.x it rode
2017
+ // `providerMetadata`) — an audit trail independent of whether every
2018
+ // targeted uuid was resolvable above.
1876
2019
  //
1877
2020
  // 0.3.217 wrapper-level siblings join the SAME first-block carrier
1878
2021
  // (closing the two disclosed gaps from the 0.3.217 bump audit), wire
@@ -1940,7 +2083,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1940
2083
  wrapperMetaRaw["narration_block_indexes"] = narrationBlockIndexes;
1941
2084
  }
1942
2085
  // `message.diagnostics` (a Messages API response field, first seen live on
1943
- // sp-probe's defer-tool-sonnet5-resume-unavailable, 7c6880f): per-response
2086
+ // the defer-tool-sonnet5-resume-unavailable capture): per-response
1944
2087
  // diagnostics, there `{cache_miss_reason: {type: "tools_changed",
1945
2088
  // cache_missed_input_tokens: 3258}}`, i.e. why the prompt cache missed.
1946
2089
  // Response-only (never sent back on replay), so it rides host-only `_meta`
@@ -1993,7 +2136,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1993
2136
  if (assistantApiErrorCode !== undefined) {
1994
2137
  wrapperMetaRaw["api_error_code"] = assistantApiErrorCode;
1995
2138
  }
1996
- // rd-15 (founder ruling 2026-09-24: defer the neutral remedy field, fix the
2139
+ // rd-15 (ruling of 2026-09-24: defer the neutral remedy field, fix the
1997
2140
  // vendor carries; a 0.7.0 carry with zero golden moves). Three more
1998
2141
  // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
1999
2142
  // 0.3.280 (so read through the JSON boundary), carried verbatim under their
@@ -2045,6 +2188,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2045
2188
  parentTurnId,
2046
2189
  blockIndex: 0,
2047
2190
  usage: undefined,
2191
+ rawInput: {},
2192
+ usageDelta: false,
2048
2193
  streamed: false,
2049
2194
  streamBlocks: new Map(),
2050
2195
  ttftCarried: false,
@@ -2052,6 +2197,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2052
2197
  turnBindingCarried: false,
2053
2198
  };
2054
2199
  pending = open;
2200
+ // The turn's trigger rides its turn.start (see `openerTrigger`).
2201
+ const trigger = opensTopTurn ? openerTrigger(msg.user_message_uuid) : undefined;
2202
+ if (trigger !== undefined)
2203
+ a.openTurn(turnId, options.threadId ?? msg.session_id, trigger);
2055
2204
  a.openMessage({
2056
2205
  id: open.emittedId,
2057
2206
  role: "assistant",
@@ -2062,7 +2211,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2062
2211
  }
2063
2212
  const messageId = open.emittedId;
2064
2213
  // rd-15: a NON-NULL `stop_details` on a response (e.g. a refusal's
2065
- // {type, category, explanation, fallbacks?}) is carried verbatim on its
2214
+ // {type: "refusal", category, explanation}, the shape @anthropic-ai/sdk
2215
+ // 0.93.0 declares; any further member is kept too) is carried verbatim on its
2066
2216
  // turn's closing turn.done.messageMetadata, which folds onto the message it
2067
2217
  // names (SPEC §5 turn.done row). The CLOSING response's value only: a later
2068
2218
  // response of the turn without one clears it. Every `fallback_credit_token`,
@@ -2118,18 +2268,22 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2118
2268
  wrapperMetaRaw["resume_reason"] = resumeReason;
2119
2269
  }
2120
2270
  }
2121
- // X5 (sp-rnd re-cut, 2026-09-23): the bag mixes two kinds of fact. SPEC
2271
+ // X5 (the 2026-09-23 re-cut): the bag mixes two kinds of fact. SPEC
2122
2272
  // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2123
2273
  // round-trip to the provider) and `_meta` host-only side metadata.
2124
- // `narration_block_indexes` and the API-error triad are CLI-wrapper facts
2125
- // the Messages API never consumes, so where the bag anchors on a BLOCK they
2126
- // ride that block's start event `_meta` (`reduce()` folds it onto
2127
- // `block._meta`, keeping the per-frame anchoring). The rest keeps
2128
- // `providerMetadata`. The split is by key, so the combined bag, and the
2129
- // `message.metadata` path below that uses it, stay byte-identical
2130
- // (message.metadata is already `AgMeta`).
2274
+ // Every key in HOST_ONLY_WRAPPER_KEYS is a CLI-wrapper fact the Messages
2275
+ // API never consumes, so where the bag anchors on a BLOCK it rides that
2276
+ // block's start event `_meta` (`reduce()` folds it onto `block._meta`,
2277
+ // keeping the per-frame anchoring). Since draft.5 (§10 item 45) the only
2278
+ // key left for `providerMetadata` is `resumed_from_incomplete_thinking`.
2279
+ // The split is by key, so the combined bag, and the `message.metadata`
2280
+ // path below that uses it, stay byte-identical (message.metadata is
2281
+ // already `AgMeta`). A frame whose first block is a tool call anchors no
2282
+ // host half (tool.start folds no `_meta`), so its host keys arrive on a
2283
+ // `message.metadata` event after the block (the streamed path already
2284
+ // carries the turn-binding family there).
2131
2285
  //
2132
- // Consumer check (sp-team-main, 2026-09-23): ggui has none of these names.
2286
+ // Consumer check (2026-09-23): ggui has none of these names.
2133
2287
  // No guuey code reads `providerMetadata`, and its #367/#1652 scrub keys on
2134
2288
  // the native frame. guuey asked that the triad move as ONE unit; the
2135
2289
  // result frame's `apiErrorCode` stays on `ext.anthropic.result-meta`.
@@ -2150,7 +2304,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2150
2304
  // Everything below the block loop (wrapper carry via message.metadata,
2151
2305
  // usage, error close, uuid registration) still runs.
2152
2306
  const suppressed = open.streamed;
2153
- // draft.4 `phase` (§8.0 item 27, a SHOULD per the founder's A.10.5
2307
+ // draft.4 `phase` (§8.0 item 27, a SHOULD per the A.10.5
2154
2308
  // ruling): a `thinking` block listed in `narration_block_indexes` whose
2155
2309
  // text is NON-EMPTY is interim narration → `phase:"interim"` on that
2156
2310
  // reasoning block. A listed empty block (display "omitted") gets none.
@@ -2257,6 +2411,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2257
2411
  // `output_tokens_details`, the CLI-assembled complete frame's usage does
2258
2412
  // not — without this merge the join would erase the streamed count.
2259
2413
  open.usage = { ...(open.usage ?? {}), ...mapMessageUsage(m.usage) };
2414
+ open.rawInput = nativeInput(open.rawInput, m.usage);
2260
2415
  // If the assistant turn carries an error signal (rate_limit, billing_error, etc.),
2261
2416
  // the turn ends as a turn.error so consumers see the error rather than a
2262
2417
  // silent empty turn. CL-09: the close is STASHED, not emitted here — the
@@ -2270,7 +2425,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2270
2425
  const errCode = msg.error;
2271
2426
  const retriable = assistantErrorRetriable(errCode);
2272
2427
  if (msg.parent_tool_use_id !== null) {
2273
- // A NESTED error frame (sp-protocol ruling 1, 2026-09-23): the error is
2428
+ // A NESTED error frame (ruling 1, 2026-09-23): the error is
2274
2429
  // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2275
2430
  // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2276
2431
  // parent closes as an error only when its OWN result frame says so.
@@ -2281,7 +2436,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2281
2436
  // failure rides the NON-terminal `error` event (SPEC:609) on the nested
2282
2437
  // turn: live-only but truthful and correctly owned, and inside the
2283
2438
  // run's still-open bracket, so before its subagent.done. The folded gap
2284
- // ("a nested turn has no failure outcome") is sp-protocol's to bar.
2439
+ // ("a nested turn has no failure outcome") is an open spec question.
2285
2440
  a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2286
2441
  // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2287
2442
  // frame's close is stashed and released as the nested turn.error when
@@ -2307,7 +2462,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2307
2462
  if (msg.type === "user") {
2308
2463
  // SDKUserMessageReplay (`isReplay: true`, typed only on that arm; a
2309
2464
  // runtime `isReplay: false` also exists, so only `=== true` counts) emits
2310
- // NO core event and does NOT seal the open message (sp-rnd lead,
2465
+ // NO core event and does NOT seal the open message (a lead of
2311
2466
  // 2026-09-23). The CLI 2.1.280 replay builders are the host's own-prompt
2312
2467
  // acks (sent on stdin accept, never held), queued-prompt merges, history
2313
2468
  // re-sends (filtered to `!toolUseResult`, so no tool_results), and
@@ -2359,8 +2514,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2359
2514
  // the conversation itself (the SDKUserMessage doc; the host's own prompts
2360
2515
  // come back only as isReplay acks, returned above). The live case: the
2361
2516
  // CLI's `isSynthetic: true` nudge "[Your previous response had no visible
2362
- // output. …]" after an empty reply (sp-probe's
2363
- // defer-tool-sonnet5-resume-unavailable, 7c6880f, the corpus's only such
2517
+ // output. …]" after an empty reply (the
2518
+ // defer-tool-sonnet5-resume-unavailable, the corpus's only such
2364
2519
  // frame). This branch maps only tool_result blocks, so it had no event at
2365
2520
  // all, and the census could not see the text go (its path normalizes to
2366
2521
  // the assistant's). It rides the item-22 bulk carry verbatim, kind "user",
@@ -2397,12 +2552,12 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2397
2552
  // frames do: nothing lands on a nested turn after its subagent.done, or
2398
2553
  // on a turn nobody opened, and no id repeats across invokes.
2399
2554
  // INV-TURN (SPEC:743: a normalizer MUST synthesize turn.start before any
2400
- // content event for a turn the stream has not opened; sp-protocol,
2555
+ // content event for a turn the stream has not opened;
2401
2556
  // 2026-09-23): a TOP-LEVEL tool_result with NO turn open (a resumed
2402
2557
  // invoke's first frame is the deferred call's tool_result, before
2403
- // system/init; sp-probe's defer-resume capture) opens the turn it lands
2558
+ // system/init; the defer-resume capture) opens the turn it lands
2404
2559
  // in, named by this frame's uuid. The resumed invoke's assistant frames
2405
- // then join it and its result closes it. Through c54eb7f its tool.done
2560
+ // then join it and its result closes it. Through 11a4bb6 its tool.done
2406
2561
  // had no turn and reduce() parked from the first event. Where that result
2407
2562
  // folds relative to the PREVIOUS invoke's open tool block is candidate
2408
2563
  // 20's bar question, not decided here.
@@ -2430,7 +2585,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2430
2585
  // `turn_<parent_tool_use_id>` label instead (Task 8c leg 3, "park
2431
2586
  // loudly"): a turn nobody opened, whose id REPEATED across the
2432
2587
  // invokes one Reducer folds (the rd-14 ids-across-invokes rule;
2433
- // sp-protocol's message.start bar, wf_140b3183-767), and it parked.
2588
+ // the message.start review, wf_140b3183-767), and it parked.
2434
2589
  toolTurnId = nestedTurnId(parentToolUseId, undefined, msg.uuid);
2435
2590
  openRun(parentToolUseId, toolTurnId, `turn_${parentToolUseId}`);
2436
2591
  }
@@ -2463,7 +2618,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2463
2618
  // minus `content` (already the tool.done content) and `prompt` (already
2464
2619
  // the tool input). Its `usage` is the subagent's own and stays out of
2465
2620
  // AgUsage (B-strict: the parent's accounting already includes it).
2466
- // sp-probe's subagent captures (5ba11da) surfaced every one of these
2621
+ // The subagent captures surfaced every one of these
2467
2622
  // fields as a census drop.
2468
2623
  const agentOutput = sibling !== undefined && typeof sibling["agentId"] === "string"
2469
2624
  ? carryVerbatim(Object.fromEntries(Object.entries(sibling).filter(([k]) => k !== "content" && k !== "prompt")))
@@ -2476,9 +2631,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2476
2631
  // renders the text the model reads. `tool_use_result` is typed `unknown`
2477
2632
  // (runtime-only shape, like structuredContent above), so the array is
2478
2633
  // validated at the opaque boundary by JsonValue.parse — no cast. The
2479
- // tool.done `content` stays model-faithful (the rendered text); the links
2480
- // ride the adopted tool.done's providerMetadata, key verbatim, under the
2481
- // same single-result attribution rule as the sibling's other fields.
2634
+ // tool.done `content` stays model-faithful (the rendered text, and no
2635
+ // resource-link block: §8.0 item 31's rendering-only case); the list
2636
+ // rides the adopted tool.done's host-only `_meta` as a host record
2637
+ // (RESOURCE_LINKS_META_KEY, SPEC §2.1), verbatim, under the same
2638
+ // single-result attribution rule as the sibling's other fields.
2482
2639
  const siblingResourceLinks = sibling !== undefined && Array.isArray(sibling["resourceLinks"])
2483
2640
  ? JsonValue.parse(sibling["resourceLinks"])
2484
2641
  : undefined;
@@ -2504,8 +2661,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2504
2661
  // so the model-facing reason survives (§2.2 draft.4: isError and
2505
2662
  // errorText belong to outcome "error"). Before this, the same call
2506
2663
  // folded "error" here and then "denied" again from the result's
2507
- // permission_denials (sp-probe's resume-deny leg).
2508
- // Second key (sp-protocol, same basis): when no kind is stamped, a
2664
+ // permission_denials (the resume-deny leg).
2665
+ // Second key (same basis): when no kind is stamped, a
2509
2666
  // live `permission_denied` notice already seen for this id is the
2510
2667
  // harness's own denial record (the CLI emits it at decision time,
2511
2668
  // always before this result). No kind is stamped on a frame holding
@@ -2533,12 +2690,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2533
2690
  // carrier skips it. The live `permission_denied` notice for the id
2534
2691
  // (the CLI emits it from its canUseTool wrapper at decision time,
2535
2692
  // always before this tool_result) rides here instead, the same
2536
- // providerMetadata the carrier gave it, so D drops nothing.
2693
+ // `_meta` record the carrier gives it, so D drops nothing.
2537
2694
  const liveFields = liveDenialMeta(deniedLiveByToolUseId.get(block.tool_use_id));
2538
- const resultProviderFields = {
2539
- ...(applySibling && siblingResourceLinks !== undefined ? { resourceLinks: siblingResourceLinks } : {}),
2540
- ...(liveFields ?? {}),
2541
- };
2542
2695
  a.toolDone({
2543
2696
  toolCallId: block.tool_use_id,
2544
2697
  content: toolContent,
@@ -2566,23 +2719,26 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2566
2719
  ? { structuredContent: sc }
2567
2720
  : {}),
2568
2721
  ...(applySibling && siblingHasUi && sc !== undefined ? { structuredContent: sc } : {}),
2569
- // The facet's harness keys, the Agent run report ("anthropic/agentOutput")
2570
- // and rd-15's CLI `tool_result_meta` entry ("anthropic/toolResultMeta"),
2571
- // ride the same `_meta`, MERGED into the MCP sibling's `_meta` (never
2572
- // replacing it), so they fold with the tool-result block. The
2573
- // "anthropic/" namespace is the harness's own: see `mergeHarnessMeta`.
2722
+ // The facet's harness keys ride the same `_meta`, MERGED into the MCP
2723
+ // sibling's `_meta` (never replacing it), so they fold with the
2724
+ // tool-result block: the Agent run report ("anthropic/agentOutput"),
2725
+ // rd-15's CLI `tool_result_meta` entry ("anthropic/toolResultMeta"),
2726
+ // and the draft.5 host records, the MCP `resourceLinks` list and the
2727
+ // live denial's context. The "anthropic/" namespace is the
2728
+ // harness's own: see `mergeHarnessMeta`. This tool.done carries no
2729
+ // `providerMetadata`: nothing on it round-trips to the provider.
2574
2730
  ...(() => {
2575
2731
  const report = applySibling && agentCallIds.has(block.tool_use_id) ? agentOutput : undefined;
2576
2732
  const entry = toolResultMetaById.get(block.tool_use_id);
2733
+ const links = applySibling ? siblingResourceLinks : undefined;
2577
2734
  const merged = mergeHarnessMeta(applySibling ? siblingMeta : undefined, {
2578
2735
  ...(report !== undefined ? { "anthropic/agentOutput": report } : {}),
2579
2736
  ...(entry !== undefined ? { "anthropic/toolResultMeta": entry } : {}),
2737
+ ...(links !== undefined ? { [RESOURCE_LINKS_META_KEY]: links } : {}),
2738
+ ...(liveFields !== undefined ? { [PERMISSION_DENIED_META_KEY]: liveFields } : {}),
2580
2739
  });
2581
2740
  return merged !== undefined ? { _meta: merged } : {};
2582
2741
  })(),
2583
- ...(Object.keys(resultProviderFields).length > 0
2584
- ? { providerMetadata: AgProviderMeta.parse(resultProviderFields) }
2585
- : {}),
2586
2742
  });
2587
2743
  }
2588
2744
  }
@@ -2599,7 +2755,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2599
2755
  // B-strict: a subagent run still open (a background or unreported sub-run)
2600
2756
  // is NOT closed by its parent's result; it closes when the framework
2601
2757
  // reports it, or at flush.
2602
- const turnId = closingTopTurnId(msg.uuid, msg.session_id);
2758
+ const turnId = closingTopTurnId(msg.uuid, msg.session_id, msg.user_message_uuid);
2603
2759
  // CL-09 (0.3.280 sweep): `subtype: "success"` does NOT mean the turn
2604
2760
  // succeeded. Upstream's SDKResultMessage doc: "subtype "success" carries
2605
2761
  // the final assistant text in result — or, with is_error true, the error
@@ -2663,11 +2819,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2663
2819
  // when that text is empty. retriable = the HTTP status says rate limit
2664
2820
  // or server failure (see `apiErrorStatusRetriable`); usage = the turn's
2665
2821
  // accrued usage, as above.
2666
- // The terminal_reason step (sp-protocol, facet-local, 2026-09-23): the
2667
- // CLI also sets is_error on a result that is NOT an API error. sp-probe's
2668
- // resume-unavailable leg (7c6880f) is a resumed invoke whose deferred
2822
+ // The terminal_reason step (facet-local, 2026-09-23): the
2823
+ // CLI also sets is_error on a result that is NOT an API error. The
2824
+ // resume-unavailable leg (defer-tool-sonnet5-resume-unavailable) is a resumed invoke whose deferred
2669
2825
  // tool's MCP server is gone: terminal_reason "tool_deferred_unavailable",
2670
- // result "", no status, no api_error_code. Through b7dd7ff it closed
2826
+ // result "", no status, no api_error_code. Through a5ac025 it closed
2671
2827
  // turn.error{message: "", code: "api_error"}, claiming an API failure
2672
2828
  // that never happened. `code` is free-form (SPEC :618), so this fills
2673
2829
  // existing fields from the frame's own value; a live API error
@@ -2681,9 +2837,37 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2681
2837
  });
2682
2838
  return;
2683
2839
  }
2684
- const finishReasonRaw = stopReasonRaw(msg.stop_reason);
2685
2840
  const stopDetails = stopDetailsByTurn.get(turnId);
2686
2841
  stopDetailsByTurn.delete(turnId);
2842
+ // draft.5 §8.0 item 32: a result that parks a tool call (`deferred_tool_use`
2843
+ // present, stop_reason "tool_deferred", not an error) is a paused turn
2844
+ // waiting on an approval. push() emits one hitl.ask{kind:"approval"} for the
2845
+ // parked call (askId `approval_<call id>`, the form the openai facet mints
2846
+ // for its approval asks), then closes the turn paused with that ask and
2847
+ // finishReason "paused", with no finishReasonRaw (the native reason is
2848
+ // exactly what "paused" names). The result-meta deferredToolUse carry stays.
2849
+ // A later invoke that resumes the call opens its own turn, minted from its
2850
+ // own frames (INV-XINV). Never keyed on terminal_reason. An is_error result
2851
+ // never reaches here: it closed above as turn.error (CL-09), and so did a
2852
+ // turn an API-error frame decided; the deferred tool found unavailable on
2853
+ // resume ("tool_deferred_unavailable") is such an is_error close.
2854
+ const deferredCall = readDeferredCall(msg);
2855
+ const stop = msg.stop_reason;
2856
+ if (deferredCall !== undefined && stop === "tool_deferred") {
2857
+ const ask = { askId: `approval_${deferredCall}`, kind: "approval", toolCallId: deferredCall };
2858
+ a.emit({ type: "hitl.ask", turnId, ...ask });
2859
+ a.closeTurnDone(turnId, {
2860
+ outcome: { type: "paused", asks: [ask] },
2861
+ finishReason: "paused",
2862
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2863
+ safety,
2864
+ ...(stopDetails !== undefined
2865
+ ? { messageId: stopDetails.messageId, messageMetadata: { stop_details: stopDetails.value } }
2866
+ : {}),
2867
+ });
2868
+ return;
2869
+ }
2870
+ const finishReasonRaw = stopReasonRaw(msg.stop_reason);
2687
2871
  a.closeTurnDone(turnId, {
2688
2872
  outcome: { type: "success", result: structuredOutput ?? msg.result },
2689
2873
  finishReason: mapStopReason(msg.stop_reason),
@@ -2769,18 +2953,20 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2769
2953
  // carry is RETIRED (superseded, not layered — one carrier per concept,
2770
2954
  // §0.6); note `tool_use_id` was NOT carried by that route, so this
2771
2955
  // promotion is strictly more lossless. Wrapper siblings ride the text
2772
- // block's providerMetadata (camelCased per the facet's carry
2773
- // convention, mirroring the 0.3.217 first-block precedent).
2956
+ // block's host-only `_meta` (camelCased per the facet's carry
2957
+ // convention; draft.5 §8.0 item 21 — draft.2 through draft.4 placed them
2958
+ // in `providerMetadata`, which §12 reserves for values that round-trip to
2959
+ // the provider, and a notice is never model input).
2774
2960
  // The open turn, or (between turns) the one this notice opens; the next
2775
2961
  // assistant frame then joins it and its result closes it.
2776
2962
  const turnId = topTurnId(msg.uuid, undefined);
2777
- const noticeMeta = AgProviderMeta.parse({
2963
+ const noticeMeta = AgMeta.parse({
2778
2964
  level: msg.level,
2779
2965
  ...(msg.prevent_continuation !== undefined ? { preventContinuation: msg.prevent_continuation } : {}),
2780
2966
  ...(msg.tool_use_id !== undefined ? { toolUseId: msg.tool_use_id } : {}),
2781
2967
  });
2782
2968
  a.openMessage({ id: msg.uuid, role: "notice", turnId, threadId: options.threadId ?? msg.session_id, noticeSource: "framework" });
2783
- a.contentBlock(msg.uuid, { type: "text", text: msg.content, providerMetadata: noticeMeta });
2969
+ a.contentBlock(msg.uuid, { type: "text", text: msg.content, _meta: noticeMeta });
2784
2970
  a.closeMessage(msg.uuid);
2785
2971
  return;
2786
2972
  }
@@ -2796,7 +2982,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2796
2982
  closePendingMessage();
2797
2983
  const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
2798
2984
  retractUuids(uuids);
2799
- // X4 (sp-rnd re-cut, 2026-09-23): only the retraction has a core home.
2985
+ // X4 (the 2026-09-23 re-cut): only the retraction has a core home.
2800
2986
  // A notice yields 0..N `message.remove`s, so there is no single event to
2801
2987
  // hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
2802
2988
  // ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
@@ -2807,11 +2993,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2807
2993
  // rides the uniform carry beside its `model_refusal_no_fallback` sibling
2808
2994
  // (SPEC §8 item 22 / §12), the WHOLE frame verbatim, AFTER the removes
2809
2995
  // (the frame is itself "emitted AFTER the retraction"). Item 22 says a
2810
- // mapped frame goes to its home "instead" of the bulk carry. sp-protocol
2811
- // ruled on 2026-09-23 (SPEC blob bef014c) that the clause covers frames
2996
+ // mapped frame goes to its home "instead" of the bulk carry. A ruling
2997
+ // of 2026-09-23 (SPEC blob bef014c) holds that the clause covers frames
2812
2998
  // whose content that home already conveys, and `message.remove` conveys
2813
2999
  // only the retraction. So the residual fields fall under item 22's
2814
- // no-drop MUST, and the whole frame rides. (sp-protocol's clarifying
3000
+ // no-drop MUST, and the whole frame rides. (A clarifying
2815
3001
  // line for item 22 is queued for the review bar.) `ext.*` is live-only
2816
3002
  // and non-folding, so the second copy of `retracted_message_uuids`
2817
3003
  // cannot double-fold (the M22 hazard). This is the only producer for R&D
@@ -2916,8 +3102,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2916
3102
  // A copy: `frame` IS the host's object when it was already JSON, and
2917
3103
  // this raw channel would otherwise emit it by reference. JsonValue.parse
2918
3104
  // copies and, like every other carry here, drops an own "__proto__"
2919
- // (sp-main 2026-09-24, matching sp-openai cf55e08 and the 0.6.6
2920
- // reserved-key rule 314a183: an emitted map carries no own __proto__).
3105
+ // (2026-09-24, matching the openai facet's ddde89d and the 0.6.6
3106
+ // reserved-key rule a76277c: an emitted map carries no own __proto__).
2921
3107
  a.emitExt("anthropic", "unparsed", { native: carryVerbatim(frame) });
2922
3108
  return a.drain();
2923
3109
  }
@@ -2947,7 +3133,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2947
3133
  }
2948
3134
  /**
2949
3135
  * Build the Claude-facet normalizer: the inner normalizer wrapped in core's
2950
- * withAtomicPush (the fleet guard ruling, 2026-09-24, binding). push() never
3136
+ * withAtomicPush (the guard ruling, 2026-09-24, binding). push() never
2951
3137
  * throws (SPEC:933):
2952
3138
  * - each native is first read as plain JSON (core toJsonValueSafe): a host
2953
3139
  * may hand in the in-process object, whose members need not be JSON (an