@silverprotocol/claude-agent-sdk 0.12.5 → 1.0.0-rc.1

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
@@ -314,7 +314,7 @@ function toolResultContentToAgBlocks(content) {
314
314
  }
315
315
  // Assistant-side mcp_tool_result content → AgBlock[] (distinct shape from the
316
316
  // user-side tool_result content mapped by `toolResultContentToAgBlocks` above).
317
- // A `for...of` loop, not `.map` — playbook 2026-07-03 SDK-bump adaptation: the
317
+ // A `for...of` loop, not `.map` — the 2026-07-03 SDK-bump adaptation: the
318
318
  // 0.3.199 `SDKMessage` union widened enough that `.map`/`.forEach`/`.filter`
319
319
  // callback PARAMETER inference silently degrades to implicit `any` on this
320
320
  // content shape (a known TS limitation calling an array method on a value typed
@@ -383,12 +383,12 @@ function isDenialKind(kind) {
383
383
  }
384
384
  // Which assistant `error` codes are transient (retriable). An API-error turn's
385
385
  // stashed top-level close and a nested frame's non-terminal `error` share it.
386
- // Finding #2 (minor): `overloaded` (transient capacity error, a first
386
+ // `overloaded` (transient capacity error, a first
387
387
  // cousin of rate_limit/server_error) joins the retriable set.
388
388
  // `model_not_found` (a permanent misconfiguration — e.g. a stale/
389
389
  // decommissioned model id) is deliberately EXCLUDED: explicit
390
- // false-by-omission, not an oversight (playbook 2026-07-03 SDK-bump
391
- // adaptation, Finding #2). `account_on_hold` (0.3.258) is likewise a
390
+ // false-by-omission, not an oversight (the 2026-07-03 SDK-bump
391
+ // adaptation). `account_on_hold` (0.3.258) is likewise a
392
392
  // deliberate non-retriable: a billing-class code (the account is on
393
393
  // hold — a first cousin of `billing_error`, cleared by the account
394
394
  // holder, never by re-sending the turn).
@@ -413,7 +413,7 @@ function emitAssistantBlock(a, block, messageId, blockIndex, blockProviderMetada
413
413
  case "text": {
414
414
  // Claude's assistant message is a COMPLETE structure (not a live stream), so
415
415
  // citations are already known at the point text.end fires — they ride the
416
- // STREAMED-text citations carrier (audit M22: text.end.citations), never as
416
+ // STREAMED-text citations carrier (text.end.citations), never as
417
417
  // a duplicate id-less supplement block.
418
418
  const id = `${messageId}:text:${blockIndex}`;
419
419
  const citations = block.citations != null && block.citations.length > 0 ? mapCitations(block.citations) : undefined;
@@ -608,15 +608,17 @@ function isSDKMessage(v) {
608
608
  // Task* subagent-progress family) with NO existing AgJSON vocabulary home.
609
609
  //
610
610
  // The Task* family (task_started/task_progress/task_updated/task_notification)
611
- // was STUDIED against the facet's ALREADY-derived subagent lifecycle
612
- // (parent_tool_use_id -> subagentStart/Done in `drive()` below) and
613
- // deliberately NOT folded into it: `tool_use_id` is OPTIONAL on every Task*
614
- // arm (a `task_type:"local_workflow"` background task carries NONE at all —
615
- // this family is a broader "tasks panel" superset, not 1:1 with Task-tool
616
- // subagent adoption), and task_progress/task_notification's own
611
+ // rides this carry whole. Its content is not folded into the subagent
612
+ // lifecycle: `tool_use_id` is OPTIONAL on every Task* arm (a
613
+ // `task_type:"local_workflow"` background task carries NONE at all — this
614
+ // family is a broader "tasks panel" superset, not 1:1 with Task-tool subagent
615
+ // adoption), and task_progress/task_notification's own
617
616
  // `summary`/`last_tool_name` would DUPLICATE content the nested subagent's
618
- // own tool_use/tool_result stream already conveys once correlation resolves
619
- // — the M22 double-fold hazard. `description` enrichment onto
617
+ // own tool_use/tool_result stream already conveys — a double fold. One part
618
+ // IS mapped: a task_notification correlated to an open run (by tool_use_id,
619
+ // or by task_id through its task_started) closes that run with its nested
620
+ // terminal and subagent.done (B-strict, SPEC §8.0 item 29), before the
621
+ // frame's carry (see `drive()`). `description` enrichment onto
620
622
  // subagent.start was also considered and rejected: `subagent.start`'s
621
623
  // schema carries no providerMetadata slot (only agentId/agentName), and
622
624
  // reaching it would require bypassing the `subagentStart()` sugar
@@ -633,14 +635,14 @@ function isSDKMessage(v) {
633
635
  // carried, not forced onto an unrelated event.
634
636
  //
635
637
  // SDKPermissionDeniedMessage is the ONE arm that DOES map onto an existing
636
- // home (the W1 `<turnId>:denials` carrier, audit M19) — see the dedicated
638
+ // home (the `<turnId>:denials` carrier) — see the dedicated
637
639
  // branch + `deniedLiveByToolUseId` in `createClaudeNormalizer()` below; it
638
640
  // is deliberately EXCLUDED from the carried sets here.
639
641
  //
640
642
  // SDKModelRefusalFallbackMessage is HALF-mapped: its retraction goes to
641
643
  // `message.remove` (§8 item 19) and the rest of the frame has no home. It is
642
644
  // NOT in the sets below either. Its dedicated branch does the retraction and
643
- // then emits the same `ext.anthropic.frame` carry itself (X4, 2026-09-23, on
645
+ // then emits the same `ext.anthropic.frame` carry itself (since 2026-09-23, on
644
646
  // the item-22 reading for half-mapped frames — see that branch).
645
647
  //
646
648
  // ONE uniform key — `ext.anthropic.frame{kind, frame}` (SPEC §8 item 22 /
@@ -743,7 +745,7 @@ function anthropicFrameKind(msg) {
743
745
  function readUserMessageUuids(v) {
744
746
  return Array.isArray(v) && v.every((s) => typeof s === "string") ? [...v] : undefined;
745
747
  }
746
- // X5 (2026-09-23): the assistant-wrapper keys that ride a block's HOST-ONLY
748
+ // Since 2026-09-23: the assistant-wrapper keys that ride a block's HOST-ONLY
747
749
  // `_meta` rather than replay-load-bearing `providerMetadata` (SPEC §12). They
748
750
  // are CLI-wrapper facts the Messages API never consumes. See the split in
749
751
  // drive()'s assistant branch.
@@ -949,10 +951,13 @@ function readStartupFailureReason(v) {
949
951
  // The type's own lead sentence frames the whole enum as a refusal to start:
950
952
  // "Why Claude Code refused to start, so a host can offer the fix instead of a
951
953
  // retry." So a PRESENT reason means NOT retriable, except for the values
952
- // upstream itself EXPLICITLY describes as retriable. Through 0.3.292 that set is
953
- // exactly one value:
954
+ // upstream itself EXPLICITLY describes as retriable. Through 0.3.296 that set is
955
+ // exactly two values:
954
956
  // - `worktree_unverified`: "the session's worktree could not be verified
955
957
  // right now; retrying may succeed."
958
+ // - `org_config_required_unavailable` (0.3.296): the organization's required
959
+ // policy limits and managed settings "could not be loaded (network, proxy,
960
+ // or an Anthropic error); retrying may succeed."
956
961
  // Three more values read as if they might clear on their own, but upstream
957
962
  // never says a retry helps, so each is a deliberate non-retriable — explicit
958
963
  // false-by-omission (the model_not_found / account_on_hold voice in the
@@ -968,12 +973,13 @@ function readStartupFailureReason(v) {
968
973
  // Every other documented value (org_pin_api_key_conflict, provider_not_allowed,
969
974
  // org_pin_mismatch, managed_settings_invalid, gateway_signin_required,
970
975
  // gateway_access_denied, proxy_invalid, temp_dir_unusable, cwd_unavailable, shell_tool_missing,
971
- // worktree_resume_refused, cli_version_too_old, bypass_root) names a
972
- // configuration, policy or environment fix, and an unknown future value
976
+ // worktree_resume_refused, cli_version_too_old, bypass_root, and 0.3.296's
977
+ // org_config_refused: "signing in again or an admin's change is the fix, not a
978
+ // retry") names a configuration, policy or environment fix, and an unknown future value
973
979
  // inherits the enum's "offer the fix instead of a retry" framing. An ABSENT
974
980
  // reason never reaches this function: the error arm keeps its old rule, so
975
981
  // older producers are byte-identical.
976
- const RETRIABLE_STARTUP_FAILURE_REASONS = new Set(["worktree_unverified"]);
982
+ const RETRIABLE_STARTUP_FAILURE_REASONS = new Set(["worktree_unverified", "org_config_required_unavailable"]);
977
983
  function startupFailureRetriable(reason) {
978
984
  return RETRIABLE_STARTUP_FAILURE_REASONS.has(reason);
979
985
  }
@@ -988,6 +994,21 @@ function startupFailureRetriable(reason) {
988
994
  function apiErrorStatusRetriable(status) {
989
995
  return typeof status === "number" && (status === 429 || status >= 500);
990
996
  }
997
+ // The error fields an is_error success result carries by itself, when no
998
+ // assistant error frame decided its close first: code = the server's
999
+ // api_error_code when the CLI copied one through; else the CLI's own
1000
+ // terminal_reason when it names a cause other than a normal completion; else
1001
+ // the generic "api_error". message = the result text (on an API error, its
1002
+ // text), or the code when that text is empty. retriable = the HTTP status says
1003
+ // rate limit or server failure (see `apiErrorStatusRetriable`).
1004
+ function resultErrorFields(msg) {
1005
+ const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
1006
+ return {
1007
+ message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
1008
+ code,
1009
+ retriable: apiErrorStatusRetriable(msg.api_error_status),
1010
+ };
1011
+ }
991
1012
  // ─── 0.3.220 result-frame enrichment: fast mode + per-model serving identity ──
992
1013
  // `fast_mode_disabled_reason` (on BOTH result arms — why fast mode was blocked)
993
1014
  // and `ModelUsage.canonicalModel`/`provider` (the pricing-lookup identity behind
@@ -1226,7 +1247,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1226
1247
  // sub-session's own assistant arm at subagent.start time, so a later inner
1227
1248
  // tool_result (same non-null parent_tool_use_id) can route to it instead.
1228
1249
  const subagentTurnByParentToolUseId = new Map();
1229
- // INV-TURN (SPEC:743; ruling B, 2026-09-23): ONE turnId names
1250
+ // INV-TURN (SPEC:743; ruled 2026-09-23): ONE turnId names
1230
1251
  // exactly ONE turn. A top-level turn is `turn_` + the id of the frame that
1231
1252
  // OPENS it: the first assistant message's id (`m.id`, from a complete frame
1232
1253
  // or a stream `message_start`) in the ordinary case, or the frame's own
@@ -1337,6 +1358,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1337
1358
  const closedNestedTurnIds = new Set();
1338
1359
  // Nested turnId → its FIRST API error frame's close (released at run close).
1339
1360
  const nestedStashedErrors = new Map();
1361
+ // Nested turnIds whose stashed close came from a refusal frame (see the
1362
+ // top-level `refusedTurns`): closed by the framework, the run closes as
1363
+ // turn.done{finishReason:"refusal"}; at flush it stays turn.error.
1364
+ const refusedNestedTurns = new Set();
1340
1365
  // task_started: task_id → the spawning tool_use_id, for a task_notification
1341
1366
  // that carries only its task_id.
1342
1367
  const toolUseIdByTaskId = new Map();
@@ -1351,7 +1376,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1351
1376
  openRuns.set(parentToolUseId, { turnId, parentTurnId });
1352
1377
  a.subagentStart(turnId, parentTurnId);
1353
1378
  }
1354
- function closeRun(parentToolUseId, close) {
1379
+ function closeRun(parentToolUseId, close, atFlush = false) {
1355
1380
  const run = openRuns.get(parentToolUseId);
1356
1381
  if (run === undefined)
1357
1382
  return;
@@ -1360,7 +1385,19 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1360
1385
  closedNestedTurnIds.add(run.turnId);
1361
1386
  const stashed = nestedStashedErrors.get(run.turnId);
1362
1387
  nestedStashedErrors.delete(run.turnId);
1363
- if (stashed !== undefined) {
1388
+ const refused = refusedNestedTurns.delete(run.turnId);
1389
+ if (stashed !== undefined && refused && !atFlush) {
1390
+ // A refusal frame decided this nested close, and the framework ended the
1391
+ // run: the block signal rides finishReason (as the top-level refusal
1392
+ // close), with no usage (a nested terminal carries none, SPEC §8.0 item
1393
+ // 29). At flush it stays turn.error below (INV-FLUSH).
1394
+ a.closeTurnDone(run.turnId, {
1395
+ outcome: { type: "error", message: stashed.message, code: stashed.code, retriable: stashed.retriable },
1396
+ finishReason: "refusal",
1397
+ safety: [{ category: "refusal", blocked: true }],
1398
+ });
1399
+ }
1400
+ else if (stashed !== undefined) {
1364
1401
  a.closeTurnError(run.turnId, { message: stashed.message, code: stashed.code, retriable: stashed.retriable });
1365
1402
  }
1366
1403
  else if (close.kind === "success") {
@@ -1378,11 +1415,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1378
1415
  // INV-FLUSH orders its own closes.
1379
1416
  function abortOpenRuns() {
1380
1417
  for (const parentToolUseId of [...openRuns.keys()].reverse()) {
1381
- closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" });
1418
+ closeRun(parentToolUseId, { kind: "aborted", reason: "stream-truncated" }, true);
1382
1419
  }
1383
1420
  }
1384
- // Playbook 2026-07-03 SDK-bump adaptation, Finding #1 (critical) — refusal-
1385
- // fallback retraction (§8 item 19). `supersedes` / `retracted_message_uuids`
1421
+ // Refusal-fallback retraction (§8 item 19; the 2026-07-03 SDK-bump
1422
+ // adaptation). `supersedes` / `retracted_message_uuids`
1386
1423
  // name PRIOR DELIVERED MESSAGES by their wire-frame `uuid` (`msg.uuid`) — a
1387
1424
  // DIFFERENT id space from the messageIds this facet actually emits (`m.id`
1388
1425
  // for an assistant frame's `message.start`, `${tool_use_id}:result` for an
@@ -1423,6 +1460,14 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1423
1460
  };
1424
1461
  }
1425
1462
  const stashedTurnErrors = new Map();
1463
+ // Top-level turnIds whose stashed close came from a refusal frame: an
1464
+ // assistant error frame whose message.stop_reason is "refusal". CLI 2.1.280
1465
+ // sends a refusal it does not retry as such a frame (error
1466
+ // "invalid_request"), then a result with is_error true. Its result closes
1467
+ // the turn as turn.done{outcome error, finishReason "refusal", safety}, so
1468
+ // the block signal reaches the fold (SPEC §4); a flush with no result keeps
1469
+ // the stashed turn.error (INV-TURN lists the flush closes).
1470
+ const refusedTurns = new Set();
1426
1471
  /** Remove and return the stashed error close for `turnId`, if any. */
1427
1472
  function takeStashedTurnError(turnId) {
1428
1473
  const stashed = stashedTurnErrors.get(turnId);
@@ -1515,12 +1560,12 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1515
1560
  },
1516
1561
  });
1517
1562
  }
1518
- // Emit what the block's content_block_stop produces — text.end (with the M22
1563
+ // Emit what the block's content_block_stop produces — text.end (with the
1519
1564
  // streamed-citations carrier), reasoning.end + the replay-load-bearing opaque
1520
1565
  // (same end-then-opaque order as the complete arm), the MANDATORY
1521
1566
  // tool.args.assembled (spec §4/§8.1), or the buffered compaction block.
1522
1567
  // `atFlush` (INV-FLUSH (3), draft.4; the fold/flush ruling, "snapshot
1523
- // fold + honest flush; opaque at flush forbidden"; leg C1): the
1568
+ // fold + honest flush; opaque at flush forbidden"): the
1524
1569
  // stream ENDED with this block open, so the close lands NO new content. The
1525
1570
  // lifecycle closes stay (text.end with its already-received citations,
1526
1571
  // reasoning.end), and the block's scratch is DROPPED: no tool.args.assembled
@@ -1818,7 +1863,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1818
1863
  // name kept; null kept: "no estimate yet" is a real value). Absent key ⇒
1819
1864
  // no bag, byte-identical.
1820
1865
  //
1821
- // X5 (2026-09-23): it rides the delta's host-only `_meta`, not
1866
+ // Since 2026-09-23: it rides the delta's host-only `_meta`, not
1822
1867
  // `providerMetadata`. The latter is REPLAY-LOAD-BEARING (SPEC §12: values
1823
1868
  // that must round-trip to the provider), and the Messages API never
1824
1869
  // consumes this CLI estimate. Consequence: `reduce()` folds `_meta` only
@@ -1851,7 +1896,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1851
1896
  return;
1852
1897
  }
1853
1898
  if (d.type === "citations_delta" && b.kind === "text") {
1854
- // Buffered — the M22 streamed-citations carrier is text.end, at stop.
1899
+ // Buffered — the streamed-citations carrier is text.end, at stop.
1855
1900
  b.citations.push(...mapCitations([d.citation]));
1856
1901
  return;
1857
1902
  }
@@ -1953,7 +1998,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
1953
1998
  }
1954
1999
  // Emit a result's permission_denials as tool.start + tool.done denied pairs,
1955
2000
  // inside a dedicated carrier message: the assistant message is already
1956
- // sealed, and INV-MSG (audit M19) forbids attaching to sealed messages or
2001
+ // sealed, and INV-MSG forbids attaching to sealed messages or
1957
2002
  // closed turns. BOTH result arms call it, at the same point (after the seal
1958
2003
  // and the run closes, before result-meta and the close). Through 0.6.4 only
1959
2004
  // the success arm did, so an error-subtype result (SDKResultError declares
@@ -2017,7 +2062,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2017
2062
  : undefined;
2018
2063
  if (continued === undefined)
2019
2064
  closePendingMessage();
2020
- // Finding #1 (critical): this frame supersedes prior delivered messages
2065
+ // Refusal-fallback retraction: this frame supersedes prior delivered messages
2021
2066
  // (refusal-fallback retry) — evict them "on arrival", per the field's own
2022
2067
  // doc, before opening the canonical replacement below. Idempotent with
2023
2068
  // the end-of-turn `model_refusal_fallback` notice (see the `system`
@@ -2158,7 +2203,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2158
2203
  // vendor carries; a 0.7.0 carry with zero golden moves). Three more
2159
2204
  // @internal CLI 2.1.280 assistant-wrapper strings, UNDECLARED in sdk.d.ts
2160
2205
  // 0.3.280 (so read through the JSON boundary), carried verbatim under their
2161
- // wire names on the frame's first block's host-only `_meta` (the X5 route,
2206
+ // wire names on the frame's first block's host-only `_meta` (the wrapper-key route,
2162
2207
  // which folds onto block._meta; never providerMetadata, SPEC §12):
2163
2208
  // - `error_details`: "Raw API error message: preserves details (e.g.
2164
2209
  // prompt-too-long token counts) that user-facing content discards"
@@ -2236,8 +2281,9 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2236
2281
  // response of the turn without one clears it. Every `fallback_credit_token`,
2237
2282
  // at any depth, is deleted first (a provider credit token is never
2238
2283
  // emitted). Null (every committed golden) carries nothing. Keyed by turn,
2239
- // so a nested (subagent) response never touches its parent's entry, and
2240
- // only top-level turns close with turn.done.
2284
+ // so a nested (subagent) response never touches its parent's entry; only a
2285
+ // top-level turn.done carries it (a nested terminal carries no
2286
+ // messageMetadata).
2241
2287
  const stopDetails = m.stop_details;
2242
2288
  if (isJsonObject(stopDetails)) {
2243
2289
  stopDetailsByTurn.set(turnId, { messageId, value: withoutCreditTokens(JsonValue.parse(stopDetails)) });
@@ -2286,7 +2332,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2286
2332
  wrapperMetaRaw["resume_reason"] = resumeReason;
2287
2333
  }
2288
2334
  }
2289
- // X5 (the 2026-09-23 re-cut): the bag mixes two kinds of fact. SPEC
2335
+ // The 2026-09-23 re-cut: the bag mixes two kinds of fact. SPEC
2290
2336
  // §12 makes `providerMetadata` REPLAY-LOAD-BEARING (values that must
2291
2337
  // round-trip to the provider) and `_meta` host-only side metadata.
2292
2338
  // Every key in HOST_ONLY_WRAPPER_KEYS is a CLI-wrapper fact the Messages
@@ -2328,7 +2374,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2328
2374
  // reasoning block. A listed empty block (display "omitted") gets none.
2329
2375
  // The index is FRAME-local. Never inferred from position, text or turn
2330
2376
  // end; never decoded from the signature; the vendor list itself still
2331
- // rides host-only `_meta` verbatim (X5).
2377
+ // rides host-only `_meta` verbatim.
2332
2378
  const narrationIndexes = new Set(narrationBlockIndexes ?? []);
2333
2379
  if (suppressed && narrationIndexes.size > 0) {
2334
2380
  // STREAMED: the complete frame precedes its blocks' content_block_stop
@@ -2436,6 +2482,21 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2436
2482
  // turn's result frame (which carries the turn's usage) emits it, or
2437
2483
  // `flush()` does if no result ever arrives (see `stashedTurnErrors`).
2438
2484
  if (msg.error !== undefined) {
2485
+ // A reported fix is never silently dropped (SPEC §8.0 item 33). An
2486
+ // error frame's turn can close without a turn.done (the stashed
2487
+ // turn.error, a flush, a nested run), where the turn.done
2488
+ // messageMetadata carry of `stop_details` above never reaches the wire:
2489
+ // the CLI's refusal message (error "invalid_request", stop_reason
2490
+ // "refusal") carries the refusal's category, explanation and
2491
+ // recommended model there. So it rides `message.metadata` on this
2492
+ // still-open message whatever the close, verbatim under its wire name,
2493
+ // less every provider credit token (§13.10), and folds into the
2494
+ // message's `metadata`. A refusal its result closes as turn.done also
2495
+ // carries it on that turn.done's messageMetadata. Null carries nothing.
2496
+ if (isJsonObject(stopDetails)) {
2497
+ const metadata = { stop_details: withoutCreditTokens(JsonValue.parse(stopDetails)) };
2498
+ a.emit({ type: "message.metadata", messageId, metadata });
2499
+ }
2439
2500
  // The API error ended the model's output — nothing can continue this
2440
2501
  // message. Seal it now, so `message.end` still precedes the (deferred)
2441
2502
  // close.
@@ -2443,7 +2504,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2443
2504
  const errCode = msg.error;
2444
2505
  const retriable = assistantErrorRetriable(errCode);
2445
2506
  if (msg.parent_tool_use_id !== null) {
2446
- // A NESTED error frame (ruling 1, 2026-09-23): the error is
2507
+ // A NESTED error frame (ruled 2026-09-23): the error is
2447
2508
  // owned by the NESTED turn (SPEC:97 a subagent is a full turn with its
2448
2509
  // own turnId; INV-OWNER, SPEC:753), so it never closes the parent. The
2449
2510
  // parent closes as an error only when its OWN result frame says so.
@@ -2457,21 +2518,27 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2457
2518
  // ("a nested turn has no failure outcome") is an open spec question.
2458
2519
  a.emit({ type: "error", turnId, message: errCode, code: errCode, retriable });
2459
2520
  // B-strict: the nested turn now HAS a failure outcome. The FIRST error
2460
- // frame's close is stashed and released as the nested turn.error when
2461
- // its run closes (see `closeRun`), whatever the Task result reports.
2462
- if (!nestedStashedErrors.has(turnId))
2521
+ // frame's close is stashed and released as the nested terminal when
2522
+ // its run closes (turn.done{finishReason refusal} for a refusal frame,
2523
+ // else turn.error; see `closeRun`), whatever the Task result reports.
2524
+ if (!nestedStashedErrors.has(turnId)) {
2463
2525
  nestedStashedErrors.set(turnId, { message: errCode, code: errCode, retriable });
2526
+ if (m.stop_reason === "refusal")
2527
+ refusedNestedTurns.add(turnId);
2528
+ }
2464
2529
  }
2465
2530
  else if (!stashedTurnErrors.has(turnId)) {
2466
2531
  // First error frame wins: a turn already carrying a stashed close keeps
2467
2532
  // it (through 0.6.2, before the stash, the first error frame closed the turn).
2468
2533
  stashedTurnErrors.set(turnId, { message: errCode, code: errCode, retriable });
2534
+ if (m.stop_reason === "refusal")
2535
+ refusedTurns.add(turnId);
2469
2536
  }
2470
2537
  }
2471
2538
  // `subagent.done` is NOT emitted here: it brackets the RUN (see `openRun`),
2472
2539
  // and this message's seal is deferred (INV-MSG) until nothing can continue it.
2473
2540
  // Record this frame's own uuid → the messageId it produced, so a LATER
2474
- // retraction naming this uuid can translate it (Finding #1). The EMITTED
2541
+ // retraction naming this uuid can translate it (§8 item 19). The EMITTED
2475
2542
  // id, so a retraction still names the message that actually exists on the
2476
2543
  // wire when this frame rode a derived carrier.
2477
2544
  registerUuid(msg.uuid, [messageId], turnId);
@@ -2573,10 +2640,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2573
2640
  // subagent reduce() correctly routes the result.
2574
2641
  const content = msg.message.content;
2575
2642
  if (typeof content !== "string") {
2576
- // Task 8c leg 4: prefer the REAL subagent turnId recorded at
2643
+ // Prefer the REAL subagent turnId recorded at
2577
2644
  // subagent.start time. Fall back to the old synthetic label only when
2578
2645
  // it is unknown (e.g. a result delivered before its subagent.start
2579
- // was ever observed) — defensive; leg 3's never-opened-turn guard now
2646
+ // was ever observed) — defensive; the never-opened-turn guard now
2580
2647
  // parks loudly on that label instead of fabricating a phantom turn.
2581
2648
  // Top-level: the OPEN top-level turn, explicitly (overlapping subagent
2582
2649
  // runs make the assembler's last-turn backfill unreliable). With no turn
@@ -2684,7 +2751,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2684
2751
  if (b.type === "tool_result")
2685
2752
  toolResultCount++;
2686
2753
  const applySibling = sibling !== undefined && toolResultCount === 1;
2687
- // Finding #1: this frame's own uuid may later be named by a retraction
2754
+ // Retraction (§8 item 19): this frame's own uuid may later be named by a retraction
2688
2755
  // (a refused leg's tombstoned tool_results, per the field's own doc) —
2689
2756
  // collect every adopted messageId this frame produces below.
2690
2757
  const resultMessageIds = [];
@@ -2778,7 +2845,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2778
2845
  });
2779
2846
  }
2780
2847
  }
2781
- // Finding #1: record this frame's uuid → the adopted messageId(s) it
2848
+ // Retraction (§8 item 19): record this frame's uuid → the adopted messageId(s) it
2782
2849
  // produced, so a later retraction naming this uuid can translate it.
2783
2850
  registerUuid(msg.uuid, resultMessageIds, toolTurnId);
2784
2851
  }
@@ -2829,10 +2896,36 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2829
2896
  // ride `ext.anthropic.result-meta` before the close (no core home on
2830
2897
  // turn.done — see resultMetaPayload's doc). It is emitted on an
2831
2898
  // API-error turn too, before its close like on every other turn.
2832
- const resultMeta = resultMetaPayload(msg, stashedError !== undefined || apiErrorTurn);
2899
+ // A refusal close: the stash came from a refusal frame, or (no frame
2900
+ // decided it) this is_error result itself says stop_reason "refusal".
2901
+ const refusedByFrame = stashedError !== undefined && refusedTurns.delete(turnId);
2902
+ const refusedByResult = stashedError === undefined && apiErrorTurn && msg.stop_reason === "refusal";
2903
+ const refusalClose = refusedByFrame || refusedByResult;
2904
+ const resultMeta = resultMetaPayload(msg, !refusalClose && (stashedError !== undefined || apiErrorTurn));
2833
2905
  if (resultMeta !== undefined) {
2834
2906
  a.emitExt("anthropic", "result-meta", resultMeta);
2835
2907
  }
2908
+ if (refusalClose) {
2909
+ // The refusal close: turn.done, whose finishReason carries the block
2910
+ // signal (SPEC §4) and whose outcome keeps the error the CLI reports
2911
+ // (outcome.type is the facet's choice). The fields are the frame's
2912
+ // stashed ones, or on a result-only refusal this result's own (as its
2913
+ // turn.error close would carry), never an invented code. The closing
2914
+ // response's stop_details rides messageMetadata, as on every turn.done.
2915
+ const fields = stashedError ?? resultErrorFields(msg);
2916
+ const refusalDetails = stopDetailsByTurn.get(turnId);
2917
+ stopDetailsByTurn.delete(turnId);
2918
+ a.closeTurnDone(turnId, {
2919
+ outcome: { type: "error", message: fields.message, code: fields.code, retriable: fields.retriable },
2920
+ finishReason: "refusal",
2921
+ ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2922
+ safety: [{ category: "refusal", blocked: true }],
2923
+ ...(refusalDetails !== undefined
2924
+ ? { messageId: refusalDetails.messageId, messageMetadata: { stop_details: refusalDetails.value } }
2925
+ : {}),
2926
+ });
2927
+ return;
2928
+ }
2836
2929
  if (stashedError !== undefined) {
2837
2930
  // The assistant error frame decided this close; this frame adds the
2838
2931
  // turn's usage, the same mapping turn.done would have carried (SPEC §4:
@@ -2864,11 +2957,11 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2864
2957
  // that never happened. `code` is free-form (SPEC :618), so this fills
2865
2958
  // existing fields from the frame's own value; a live API error
2866
2959
  // (terminal_reason "api_error", api-error-auth) is unchanged.
2867
- const code = readApiErrorCode(msg) ?? closeCauseTerminalReason(msg.terminal_reason) ?? "api_error";
2960
+ const fields = resultErrorFields(msg);
2868
2961
  a.closeTurnError(turnId, {
2869
- message: typeof msg.result === "string" && msg.result !== "" ? msg.result : code,
2870
- code,
2871
- retriable: apiErrorStatusRetriable(msg.api_error_status),
2962
+ message: fields.message,
2963
+ code: fields.code,
2964
+ retriable: fields.retriable,
2872
2965
  ...(turnUsage !== undefined ? { usage: turnUsage } : {}),
2873
2966
  });
2874
2967
  return;
@@ -2884,9 +2977,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2884
2977
  // exactly what "paused" names). The result-meta deferredToolUse carry stays.
2885
2978
  // A later invoke that resumes the call opens its own turn, minted from its
2886
2979
  // own frames (INV-XINV). Never keyed on terminal_reason. An is_error result
2887
- // never reaches here: it closed above as turn.error, and so did a
2888
- // turn an API-error frame decided; the deferred tool found unavailable on
2889
- // resume ("tool_deferred_unavailable") is such an is_error close.
2980
+ // never reaches here: it closed above, as turn.error or, for a refusal, as
2981
+ // turn.done, and so did a turn an API-error frame decided; the deferred
2982
+ // tool found unavailable on resume ("tool_deferred_unavailable") is such
2983
+ // an is_error close.
2890
2984
  const deferredCall = readDeferredCall(msg);
2891
2985
  const stop = msg.stop_reason;
2892
2986
  if (deferredCall !== undefined && stop === "tool_deferred") {
@@ -2925,6 +3019,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
2925
3019
  // frame emits it (below). Each turn has its own id now, so an entry can
2926
3020
  // only ever be this turn's.
2927
3021
  const stashedError = takeStashedTurnError(turnId);
3022
+ refusedTurns.delete(turnId);
2928
3023
  // Guard `errors` and `subtype` defensively: `isSDKMessage` only checks
2929
3024
  // `typeof v.subtype === "string"` for the result arm — it does NOT validate
2930
3025
  // the `errors` array. A malformed message (missing errors, wrong subtype) must
@@ -3007,7 +3102,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3007
3102
  return;
3008
3103
  }
3009
3104
  if (msg.type === "system" && msg.subtype === "model_refusal_fallback") {
3010
- // Finding #1 (critical): the end-of-turn authoritative eviction record —
3105
+ // Refusal-fallback retraction: the end-of-turn authoritative eviction record —
3011
3106
  // "the complete audit record for the turn" per the field's own doc.
3012
3107
  // Idempotent with the earlier `supersedes`-triggered eviction above (see
3013
3108
  // `retractUuids`'s doc); also the ONLY retraction path when a consumer
@@ -3018,7 +3113,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3018
3113
  closePendingMessage();
3019
3114
  const uuids = Array.isArray(msg.retracted_message_uuids) ? msg.retracted_message_uuids : [];
3020
3115
  retractUuids(uuids);
3021
- // X4 (the 2026-09-23 re-cut): only the retraction has a core home.
3116
+ // The 2026-09-23 re-cut: only the retraction has a core home.
3022
3117
  // A notice yields 0..N `message.remove`s, so there is no single event to
3023
3118
  // hang the rest on. The rest of the frame is the switch itself: `trigger`, `direction`
3024
3119
  // ('retry'; 'revert'/'sticky' are "no longer emitted" per 0.3.280),
@@ -3034,10 +3129,10 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3034
3129
  // whose content that home already conveys, and `message.remove` conveys
3035
3130
  // only the retraction. So the residual fields fall under item 22's
3036
3131
  // no-drop MUST, and the whole frame rides. (A clarifying
3037
- // line for item 22 is queued for the review bar.) `ext.*` is live-only
3132
+ // line for item 22 is queued for review.) `ext.*` is live-only
3038
3133
  // and non-folding, so the second copy of `retracted_message_uuids`
3039
- // cannot double-fold (the M22 hazard). This is the only producer for R&D
3040
- // item 3's `turn.model-switch`. Synthetic-only (needs a classifier refusal).
3134
+ // cannot double-fold. This is the only producer for the candidate
3135
+ // `turn.model-switch` event. Synthetic-only (needs a classifier refusal).
3041
3136
  a.emitExt("anthropic", "frame", { kind: msg.subtype, frame: carryVerbatim(msg) });
3042
3137
  return;
3043
3138
  }
@@ -3045,8 +3140,8 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3045
3140
  // Fixture-drift ratchet finding: this standalone LIVE denial notice is
3046
3141
  // the SAME fact the already-handled `SDKResultMessage.permission_denials[]`
3047
3142
  // aggregate turns into a tool.start+tool.done{denied} pair inside the
3048
- // W1 `<turnId>:denials` carrier (audit M19, above) — do NOT emit a
3049
- // second pair here (the M22 double-fold hazard). Record this frame's
3143
+ // `<turnId>:denials` carrier (above) — do NOT emit a
3144
+ // second pair here (a double fold). Record this frame's
3050
3145
  // richer diagnostic fields only; the aggregate handler consumes them.
3051
3146
  //
3052
3147
  // `decision_reason_code` (CLI 2.1.280, @internal — UNDECLARED in sdk.d.ts
@@ -3086,7 +3181,6 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3086
3181
  // comment above for the full per-arm reasoning, SPEC §8 item 22).
3087
3182
  const carriedKind = anthropicFrameKind(msg);
3088
3183
  if (carriedKind !== undefined) {
3089
- a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3090
3184
  // B-strict: a background sub-run's outcome arrives as task_notification,
3091
3185
  // correlated to its run by tool_use_id (or by task_id through the
3092
3186
  // task_started frame that named it).
@@ -3109,6 +3203,9 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3109
3203
  }
3110
3204
  }
3111
3205
  }
3206
+ // The carry rides after the home events this frame produced (a correlated
3207
+ // task_notification's nested terminal and subagent.done), SPEC §8.0 item 22.
3208
+ a.emitExt("anthropic", "frame", { kind: carriedKind, frame: carryVerbatim(msg) });
3112
3209
  return;
3113
3210
  }
3114
3211
  // A top-level type the union does not declare (see KNOWN_TOP_LEVEL_TYPES):
@@ -3149,7 +3246,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3149
3246
  flush() {
3150
3247
  // INV-MSG: nothing can continue the deferred message now — seal it with
3151
3248
  // its real usage rather than leaving INV-FLUSH to synthesize a bare
3152
- // `message.end`. At flush: no content is minted (INV-FLUSH (3), C1).
3249
+ // `message.end`. At flush: no content is minted (INV-FLUSH (3)).
3153
3250
  closePendingMessage(true);
3154
3251
  // B-strict: every subagent run still open closes here with its nested
3155
3252
  // terminal (turn.abort{stream-truncated}, or its stashed API error) and
@@ -3163,6 +3260,7 @@ function createInnerClaudeNormalizer(options, invokeStem) {
3163
3260
  a.closeTurnError(turnId, { ...stashed });
3164
3261
  }
3165
3262
  stashedTurnErrors.clear();
3263
+ refusedTurns.clear();
3166
3264
  return a.flush();
3167
3265
  },
3168
3266
  };