@sema-agent/core 7.65.0 → 7.66.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.
Files changed (129) hide show
  1. package/CHANGELOG.md +269 -0
  2. package/dist/agents/delegation-registry-seat.d.ts +15 -0
  3. package/dist/agents/delegation-registry-seat.js +13 -0
  4. package/dist/agents/org-delivery-gate.d.ts +8 -1
  5. package/dist/agents/org-delivery-gate.js +9 -3
  6. package/dist/agents/peer-session-drain.d.ts +51 -12
  7. package/dist/agents/peer-session-drain.js +44 -31
  8. package/dist/agents/read-inbox-tool.d.ts +6 -2
  9. package/dist/agents/read-inbox-tool.js +18 -5
  10. package/dist/agents/subagent.d.ts +3 -1
  11. package/dist/agents/subagent.js +79 -75
  12. package/dist/brain/reasoning.d.ts +2 -0
  13. package/dist/brain/reasoning.js +1 -0
  14. package/dist/core/allow-entry.d.ts +9 -0
  15. package/dist/core/allow-entry.js +7 -1
  16. package/dist/core/ask-origin.d.ts +23 -3
  17. package/dist/core/ask-origin.js +11 -1
  18. package/dist/core/engine-notice.d.ts +3 -3
  19. package/dist/core/governance-codes.js +1 -0
  20. package/dist/core/human-input-projection.d.ts +9 -0
  21. package/dist/core/human-input-projection.js +13 -0
  22. package/dist/core/input-author.d.ts +66 -6
  23. package/dist/core/input-author.js +21 -3
  24. package/dist/core/memory-engine/consolidation.d.ts +23 -9
  25. package/dist/core/memory-engine/consolidation.js +30 -5
  26. package/dist/core/memory-engine/control-plane-adoption.d.ts +11 -10
  27. package/dist/core/memory-engine/control-plane-adoption.js +54 -29
  28. package/dist/core/memory-engine/delegation-settlement.d.ts +18 -12
  29. package/dist/core/memory-engine/delegation-settlement.js +36 -26
  30. package/dist/core/memory-engine/engine.d.ts +17 -6
  31. package/dist/core/memory-engine/engine.js +78 -35
  32. package/dist/core/memory-engine/file-backend.d.ts +4 -1
  33. package/dist/core/memory-engine/file-backend.js +5 -1
  34. package/dist/core/memory-engine/index.d.ts +2 -2
  35. package/dist/core/memory-engine/index.js +2 -2
  36. package/dist/core/memory-engine/layout.d.ts +57 -36
  37. package/dist/core/memory-engine/layout.js +109 -134
  38. package/dist/core/memory-engine/memory-backend-contract.js +7 -7
  39. package/dist/core/memory-engine/memory-deployment.d.ts +3 -2
  40. package/dist/core/memory-engine/memory-deployment.js +6 -3
  41. package/dist/core/memory-engine/origin-clearance.d.ts +43 -15
  42. package/dist/core/memory-engine/origin-clearance.js +143 -55
  43. package/dist/core/model-receipt.d.ts +2 -1
  44. package/dist/core/model-receipt.js +5 -0
  45. package/dist/core/mods/dollar.d.ts +12 -0
  46. package/dist/core/mods/kernel/dispatch.d.ts +3 -1
  47. package/dist/core/mods/kernel/dispatch.js +5 -2
  48. package/dist/core/mods/kernel/events.d.ts +3 -1
  49. package/dist/core/mods/kernel/events.js +2 -2
  50. package/dist/core/mods/prompt-submit.d.ts +4 -0
  51. package/dist/core/mods/prompt-submit.js +24 -0
  52. package/dist/core/mods/stations.d.ts +23 -4
  53. package/dist/core/mods/stations.js +14 -7
  54. package/dist/core/retired-host-table-account.d.ts +19 -0
  55. package/dist/core/retired-host-table-account.js +28 -0
  56. package/dist/core/retired-tool-name-account.d.ts +60 -0
  57. package/dist/core/retired-tool-name-account.js +32 -0
  58. package/dist/core/roles.d.ts +3 -1
  59. package/dist/core/roles.js +5 -2
  60. package/dist/core/runner/compact-session.js +2 -1
  61. package/dist/core/runner/contracts.d.ts +1 -1
  62. package/dist/core/runner/gate-exit.js +9 -2
  63. package/dist/core/runner/memory-consolidation-driver.js +2 -2
  64. package/dist/core/runner/prepare-config-doors.js +1 -1
  65. package/dist/core/runner/prepare-delegation-surface.d.ts +1 -1
  66. package/dist/core/runner/prepare-delegation-surface.js +5 -3
  67. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  68. package/dist/core/runner/prepare-memory.js +26 -5
  69. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  70. package/dist/core/runner/prepare-park-ask.js +3 -1
  71. package/dist/core/runner/prepare-policy-chain.js +2 -1
  72. package/dist/core/runner/prepare-project-context.js +2 -2
  73. package/dist/core/runner/prepare-question-face.d.ts +2 -2
  74. package/dist/core/runner/prepare-task.d.ts +5 -1
  75. package/dist/core/runner/prepare-task.js +5 -4
  76. package/dist/core/runner/prepare-wiring-manifest.js +5 -4
  77. package/dist/core/runner/prompt-suggestions.js +1 -1
  78. package/dist/core/runner/run-identity-wiring.js +2 -2
  79. package/dist/core/runner/run-leg.js +3 -3
  80. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  81. package/dist/core/runner/run-notification-lane.js +2 -2
  82. package/dist/core/runner/runtask.js +6 -3
  83. package/dist/core/runner/steer-admission.d.ts +11 -2
  84. package/dist/core/runner/stream-steer-verb.d.ts +5 -2
  85. package/dist/core/runner/stream-steer-verb.js +67 -14
  86. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -27
  87. package/dist/core/runner/sub-agent-deny-lists.js +22 -33
  88. package/dist/core/runner-deps.d.ts +4 -4
  89. package/dist/core/shell-run-candidates.js +3 -3
  90. package/dist/core/side-query.js +1 -1
  91. package/dist/core/skill-grant.d.ts +7 -0
  92. package/dist/core/skill-grant.js +14 -5
  93. package/dist/core/task-event.d.ts +14 -0
  94. package/dist/core/tool-policy.js +2 -3
  95. package/dist/core/tool-spec.d.ts +13 -3
  96. package/dist/core/user-attachment.d.ts +5 -1
  97. package/dist/core/user-attachment.js +11 -5
  98. package/dist/engine/harness/agent-harness.d.ts +19 -11
  99. package/dist/engine/harness/agent-harness.js +7 -4
  100. package/dist/engine/llm/types.d.ts +22 -10
  101. package/dist/index.d.ts +4 -2
  102. package/dist/index.js +3 -1
  103. package/dist/shell/lex.d.ts +50 -15
  104. package/dist/shell/lex.js +43 -9
  105. package/dist/tools/fs/fs-bash.js +3 -3
  106. package/dist/tools/fs/removal-targets.d.ts +8 -2
  107. package/dist/tools/fs/removal-targets.js +31 -4
  108. package/dist/tools/fs/shell-read-argv.js +7 -1
  109. package/dist/tools/fs/shell-read-bindings.d.ts +21 -5
  110. package/dist/tools/fs/shell-read-bindings.js +130 -44
  111. package/dist/tools/fs/shell-read-plan.js +95 -29
  112. package/dist/tools/fs/shell-read-sourced.d.ts +25 -0
  113. package/dist/tools/fs/shell-read-sourced.js +119 -0
  114. package/dist/tools/fs/shell-read-word.d.ts +2 -2
  115. package/dist/tools/fs/shell-read-word.js +4 -5
  116. package/dist/tools/fs/shell-read-workdir.d.ts +19 -3
  117. package/dist/tools/fs/shell-read-workdir.js +60 -15
  118. package/dist/tools/fs/shell-reentry-text.d.ts +10 -2
  119. package/dist/tools/fs/shell-reentry-text.js +11 -4
  120. package/package.json +2 -2
  121. package/test/export-surface.snapshot.json +13 -7
  122. package/wire-changes/core-stores-sql@7.66.0.json +30 -0
  123. package/wire-changes/core-stores-sql@7.66.1.json +30 -0
  124. package/wire-changes/core@7.66.0.json +1218 -0
  125. package/wire-changes/core@7.66.1.json +46 -0
  126. package/wire-changes/mods-kernel@7.66.0.json +65 -0
  127. package/wire-changes/mods-kernel@7.66.1.json +30 -0
  128. package/wire-changes/primitives@7.66.0.json +30 -0
  129. package/wire-changes/primitives@7.66.1.json +30 -0
@@ -46,6 +46,7 @@ import { uuidv7 } from "../internal/harness.js";
46
46
  import { addWorktree } from "../core/git-worktree-env.js";
47
47
  import { shellQuote } from "../tools/fs/search.js";
48
48
  import { BG_AGENT_REAP_STOP_ERROR, chosenAgentName } from "../core/task-registry.js";
49
+ import { delegationRegistryOf } from "./delegation-registry-seat.js";
49
50
  import { agentOutcomeIsError } from "../core/task-registry-agent.js";
50
51
  import { readDurableOrgAdmission } from "../core/memory-admission.js";
51
52
  import { governanceRetryClass } from "../core/governance-codes.js";
@@ -1549,10 +1550,11 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
1549
1550
  execute: async (args, ctx) => {
1550
1551
  const a = canonicalSubagentTypeArgs(args, acceptedSubagentTypes(), generalPurposeShadowed);
1551
1552
  const parentSpecSeat = parentSpecSeatOfCtx(ctx);
1553
+ const background = opts.background, backgroundRegistry = delegationRegistryOf(ctx, background);
1552
1554
  const reviveClaim = ctx.reviveClaim;
1553
- const parkedLane = reviveClaim?.parkedResume !== undefined ? opts.background?.registry.parkedCompletionSink(reviveClaim.row.handle) : undefined;
1554
- const backgroundSink = opts.background !== undefined ? resolveCompletionSink(ctx.onTaskNotification ?? parkedLane, opts.background.notify) : undefined;
1555
- const backgroundLane = opts.background !== undefined && admitsBackgroundLaunch(backgroundSink);
1555
+ const parkedLane = reviveClaim?.parkedResume !== undefined ? backgroundRegistry?.parkedCompletionSink(reviveClaim.row.handle) : undefined;
1556
+ const backgroundSink = background !== undefined ? resolveCompletionSink(ctx.onTaskNotification ?? parkedLane, background.notify) : undefined;
1557
+ const backgroundLane = background !== undefined && admitsBackgroundLaunch(backgroundSink);
1556
1558
  if (reviveClaim !== undefined && !backgroundLane) {
1557
1559
  return notStartedResult({
1558
1560
  isError: true,
@@ -1614,7 +1616,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
1614
1616
  });
1615
1617
  }
1616
1618
  }
1617
- const backgroundAsked = opts.background !== undefined && (a.run_in_background !== false || def?.background === true || agentName !== undefined);
1619
+ const backgroundAsked = background !== undefined && (a.run_in_background !== false || def?.background === true || agentName !== undefined);
1618
1620
  const wantsBackground = backgroundLane && backgroundAsked;
1619
1621
  const ranSyncNote = backgroundAsked && !backgroundLane ? AGENT_RAN_SYNC_NO_CHANNEL_NOTE : undefined;
1620
1622
  const stations = reviveClaim === undefined ? ctx.agentStations : undefined;
@@ -1993,7 +1995,9 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
1993
1995
  throw new Error("observed child has no steer lane (report undeliverable)");
1994
1996
  if (author !== "observer")
1995
1997
  pendingTrigger.push(text);
1996
- await steer(author, text);
1998
+ const answer = await steer(author, text);
1999
+ if ("drop" in answer)
2000
+ throw new Error(`observed child's steer lane did not take the report (${answer.drop})`);
1997
2001
  };
1998
2002
  if (observerArm) {
1999
2003
  pendingTrigger.push(prompt);
@@ -2180,8 +2184,8 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2180
2184
  const editedFiles = stepRecorder.editedFiles();
2181
2185
  return { ...(recentSteps ? { recentSteps } : {}), ...(editedFiles ? { editedFiles } : {}) };
2182
2186
  };
2183
- const treeScope = reviveClaim?.row.scope ?? parentSpecSeat?.principal ?? opts.background?.scope;
2184
- const entryCapPoolAnchor = opts.background?.registry ?? opts;
2187
+ const treeScope = reviveClaim?.row.scope ?? parentSpecSeat?.principal ?? background?.scope;
2188
+ const entryCapPoolAnchor = backgroundRegistry ?? opts;
2185
2189
  const entryCaps = ctx.delegationEntryCaps ?? { maxConcurrent: DELEGATION_MAX_CONCURRENT_DEFAULT, maxCumulativePerSession: DELEGATION_MAX_PER_SESSION_DEFAULT };
2186
2190
  const entryCapRoot = reviveClaim !== undefined
2187
2191
  ? (reviveClaim.row.rootSessionId ?? reviveClaim.row.parentSessionId ?? (reviveClaim.row.sessionScoped ? reviveClaim.row.owner : undefined))
@@ -2189,11 +2193,11 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2189
2193
  const entryPoolSeat = { poolAnchor: entryCapPoolAnchor, scope: treeScope, root: entryCapRoot };
2190
2194
  const openEntryGate = () => openDelegationEntryGate({
2191
2195
  ...entryPoolSeat,
2192
- registry: opts.background?.registry,
2193
- store: opts.background?.agentStore,
2196
+ registry: backgroundRegistry,
2197
+ store: background?.agentStore,
2194
2198
  caps: entryCaps,
2195
2199
  signal: ctx.signal,
2196
- caller: { owner: ctx.taskId ?? opts.background?.owner, ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}) },
2200
+ caller: { owner: ctx.taskId ?? background?.owner, ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}) },
2197
2201
  });
2198
2202
  const provenanceRequest = ctx.delegationProvenanceForChildren?.();
2199
2203
  const childProvenanceRef = provenanceRequest !== undefined ? { current: newDelegationProvenanceAggregate() } : undefined;
@@ -2408,8 +2412,8 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2408
2412
  ? getOrCreateSessionRetainLedger(ctx.sessionId, { ttlMs: FAILED_SESSION_RETAIN_TTL_MS, max: RETAIN_DEFAULT_MAX })
2409
2413
  : ctx.subagentRetain;
2410
2414
  if (ledger !== undefined && !ledger.disposed) {
2411
- if (opts.background)
2412
- ensureSessionReapHook(opts.background.registry);
2415
+ if (backgroundRegistry)
2416
+ ensureSessionReapHook(backgroundRegistry);
2413
2417
  const failedRetainStrip = stripSpawnTurnQuestionFace(buildChildSpec(undefined));
2414
2418
  const { signal: _spawnSignal, ...plainSpec } = failedRetainStrip.spec;
2415
2419
  const entry = ledger.register(ctx.toolCallId, {
@@ -2512,8 +2516,8 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2512
2516
  const forkTree = await delegationOwnerOf(ctx.delegationOwner);
2513
2517
  if (!forkTree.bound)
2514
2518
  return ownerUnboundResult(false, forkTree);
2515
- const forkBg = wantsBackground ? opts.background : undefined;
2516
- const forkPlacementHandle = forkBg?.agentStore !== undefined ? forkBg.registry.mintTaskId("background_agent") : undefined;
2519
+ const forkBg = wantsBackground ? background : undefined;
2520
+ const forkPlacementHandle = forkBg?.agentStore !== undefined ? backgroundRegistry.mintTaskId("background_agent") : undefined;
2517
2521
  const forkOpts = forkPlacementHandle !== undefined ? { placement: subagentTranscriptPlacement(ctx, treeScope, forkPlacementHandle) } : undefined;
2518
2522
  try {
2519
2523
  if (ctx.hostSessionFork) {
@@ -2538,7 +2542,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2538
2542
  const forkWorktreeNote = worktreeDir !== undefined ? forkWorktreeTranslationNote(ctx.parentCwd, worktreeDir) : undefined;
2539
2543
  const forkObjective = `${FORK_DIRECTIVE_FRAME}${prompt}${forkWorktreeNote !== undefined ? `\n\n${forkWorktreeNote}` : ""}${parentSpecSeat?.advisorModel !== undefined ? `\n\n${ADVISOR_FORK_SENTENCE}` : ""}`;
2540
2544
  if (wantsBackground) {
2541
- const bg = opts.background;
2545
+ const bg = background, bgRegistry = backgroundRegistry;
2542
2546
  const notify = backgroundSink;
2543
2547
  const abort = new AbortController();
2544
2548
  const sessionScopedBg = ctx.backgroundScope === "session" && ctx.sessionId !== undefined;
@@ -2614,7 +2618,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2614
2618
  };
2615
2619
  let taskId;
2616
2620
  try {
2617
- taskId = bg.registry.registerBackgroundAgent({
2621
+ taskId = bgRegistry.registerBackgroundAgent({
2618
2622
  ...(forkPlacementHandle !== undefined ? { id: forkPlacementHandle } : {}),
2619
2623
  ...(bgOwner !== undefined ? { owner: bgOwner } : {}),
2620
2624
  ...(bgScope !== undefined ? { scope: bgScope } : {}),
@@ -2653,16 +2657,16 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2653
2657
  return notStartedResult({ isError: true, content: `Sub-agent not started in background: the background task could not be registered.${wt ? `\n${wt}` : ""}`, details: { error: "register_failed", ...faultDetails(e) } });
2654
2658
  }
2655
2659
  if (forkEntryGate.key !== undefined)
2656
- chargeDelegationEntryHandle(bg.registry, forkEntryGate.key, bg.agentStore, taskId);
2660
+ chargeDelegationEntryHandle(bgRegistry, forkEntryGate.key, bg.agentStore, taskId);
2657
2661
  oweTerminalDelivery(notify, { task_id: taskId, task_type: "background_agent" });
2658
2662
  childInternals.peerSelfRef?.addAxis("h", taskId);
2659
- bg.registry.bindBackgroundAgentSession(taskId, forkedId, opts.runner.sessions);
2663
+ bgRegistry.bindBackgroundAgentSession(taskId, forkedId, opts.runner.sessions);
2660
2664
  stepRecorder.lockTo(taskId);
2661
2665
  const forkBgHangAt = Date.now();
2662
- bg.registry.attachAgentTerminalNotifier(taskId, () => {
2663
- const stoppedByReap = bg.registry.getStopAttribution(taskId) ?? "system";
2664
- const completionIdReap = bg.registry.getCompletionId(taskId);
2665
- const seqReap = bg.registry.backgroundAgentCycleSeq(taskId);
2666
+ bgRegistry.attachAgentTerminalNotifier(taskId, () => {
2667
+ const stoppedByReap = bgRegistry.getStopAttribution(taskId) ?? "system";
2668
+ const completionIdReap = bgRegistry.getCompletionId(taskId);
2669
+ const seqReap = bgRegistry.backgroundAgentCycleSeq(taskId);
2666
2670
  const reapFrame = {
2667
2671
  task_id: taskId,
2668
2672
  task_type: "background_agent",
@@ -2688,7 +2692,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2688
2692
  catch {
2689
2693
  }
2690
2694
  };
2691
- const bgForkCycleSeq = bg.registry.backgroundAgentCycleSeq(taskId);
2695
+ const bgForkCycleSeq = bgRegistry.backgroundAgentCycleSeq(taskId);
2692
2696
  sinkEmit({
2693
2697
  kind: "spawn",
2694
2698
  taskId,
@@ -2713,7 +2717,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2713
2717
  const forkQuestionStrip = sessionScopedBg ? stripSpawnTurnQuestionFace(bgForkSpecBase) : undefined;
2714
2718
  const bgForkSpec = forkQuestionStrip !== undefined ? forkQuestionStrip.spec : bgForkSpecBase;
2715
2719
  const s2ForkNotifyReady = (inject) => {
2716
- bg.registry.attachAgentNotify(taskId, inject);
2720
+ bgRegistry.attachAgentNotify(taskId, inject);
2717
2721
  };
2718
2722
  const bgForkActivityBeat = createBgActivityBeat(ctx.toolCallId, (toolStarts) => {
2719
2723
  const currentAction = stepRecorder.currentAction();
@@ -2733,7 +2737,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2733
2737
  ...(currentTool !== undefined ? { currentTool } : {}),
2734
2738
  usage: { toolUses: toolStarts },
2735
2739
  });
2736
- }, () => bg.registry.noteBackgroundAgentActivity(taskId));
2740
+ }, () => bgRegistry.noteBackgroundAgentActivity(taskId));
2737
2741
  const bgForkInternals = bgSink
2738
2742
  ? {
2739
2743
  ...forkInternals,
@@ -2814,11 +2818,11 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2814
2818
  const forkBgResult = withHandbackWarning(forkBgWarning, child.result);
2815
2819
  const okBg = child.terminal.kind === "completed";
2816
2820
  const reapedBg = !okBg && abort.signal.aborted;
2817
- const collateralBg = reapedBg && bg.registry.getAccessibleTask(taskId, { ...(bgOwner !== undefined ? { owner: bgOwner } : {}), ...(bgScope !== undefined ? { scope: bgScope } : {}) })?.status === "running";
2821
+ const collateralBg = reapedBg && bgRegistry.getAccessibleTask(taskId, { ...(bgOwner !== undefined ? { owner: bgOwner } : {}), ...(bgScope !== undefined ? { scope: bgScope } : {}) })?.status === "running";
2818
2822
  const failedFork = !okBg && !reapedBg;
2819
2823
  const errCodeFork = failedFork ? childFace.errorCode : undefined;
2820
2824
  const errClassFork = failedFork ? classifySubagentError({ kind: "failed", ...(childFace.errorCode !== undefined ? { code: childFace.errorCode } : {}) }) : undefined;
2821
- const settleWinnerFork = bg.registry.settleBackgroundAgent(taskId, {
2825
+ const settleWinnerFork = bgRegistry.settleBackgroundAgent(taskId, {
2822
2826
  cycle: 0,
2823
2827
  status: okBg ? "completed" : reapedBg ? "killed" : "failed",
2824
2828
  ...resultSettleFields(forkBgResult),
@@ -2826,12 +2830,12 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2826
2830
  ...(errCodeFork !== undefined ? { errorCode: errCodeFork } : {}),
2827
2831
  ...(errClassFork !== undefined ? { retryable: errClassFork.retryable, errorKind: errClassFork.errorKind } : {}),
2828
2832
  });
2829
- const completionIdFork = settleWinnerFork !== undefined ? bg.registry.getCompletionId(taskId) : undefined;
2833
+ const completionIdFork = settleWinnerFork !== undefined ? bgRegistry.getCompletionId(taskId) : undefined;
2830
2834
  const settledBg = settleWinnerFork ?? (abort.signal.aborted ? "killed" : okBg ? "completed" : "failed");
2831
- const stoppedByBg = settledBg === "killed" ? bg.registry.getStopAttribution(taskId) ?? "system" : undefined;
2835
+ const stoppedByBg = settledBg === "killed" ? bgRegistry.getStopAttribution(taskId) ?? "system" : undefined;
2832
2836
  const stillbornFork = child.terminal.kind === "failed" && child.terminal.code === "resume.session_not_found";
2833
2837
  if (stillbornFork) {
2834
- await releaseBoundChildSession({ registry: bg.registry, taskId }, forkedId, () => (releaseForked ? releaseForked() : opts.runner.sessions.release?.(forkedId)));
2838
+ await releaseBoundChildSession({ registry: bgRegistry, taskId }, forkedId, () => (releaseForked ? releaseForked() : opts.runner.sessions.release?.(forkedId)));
2835
2839
  }
2836
2840
  const residualFork = residualFields();
2837
2841
  const resumableFork = false;
@@ -2841,8 +2845,8 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2841
2845
  const forkTerminalSummary = failReasonFork !== undefined
2842
2846
  ? `Agent "${shortDesc}" failed: ${failReasonFork}${ccElapsedTag(forkElapsedMs)}`.slice(0, 300) + errorKindClause(errClassFork)
2843
2847
  : `${ccCompletionText(shortDesc, settledBg, childFace.status, forkElapsedMs)}`;
2844
- const ownsTerminalFacesFork = bg.registry.claimAgentTerminalNotify(taskId);
2845
- const forkResultField = await completionResultField(forkBgResult, (report) => persistTaskArtifact(ctx.taskArtifacts, taskId, report), (ref) => bg.registry.recordArtifactRef(taskId, ref, completionIdFork), notifier);
2848
+ const ownsTerminalFacesFork = bgRegistry.claimAgentTerminalNotify(taskId);
2849
+ const forkResultField = await completionResultField(forkBgResult, (report) => persistTaskArtifact(ctx.taskArtifacts, taskId, report), (ref) => bgRegistry.recordArtifactRef(taskId, ref, completionIdFork), notifier);
2846
2850
  const forkFrame = {
2847
2851
  task_id: taskId,
2848
2852
  task_type: "background_agent",
@@ -2879,18 +2883,18 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2879
2883
  const msgFork = childThrownText(e);
2880
2884
  const errCodeForkReject = killed ? undefined : thrownErrorCode(e);
2881
2885
  const errClassForkReject = killed ? undefined : classifySubagentError({ kind: "failed", ...(errCodeForkReject !== undefined ? { code: errCodeForkReject } : {}) });
2882
- const settleWinnerForkReject = bg.registry.settleBackgroundAgent(taskId, {
2886
+ const settleWinnerForkReject = bgRegistry.settleBackgroundAgent(taskId, {
2883
2887
  cycle: 0,
2884
2888
  status: killed ? "killed" : "failed",
2885
2889
  error: killed ? BG_AGENT_REAP_STOP_ERROR : msgFork,
2886
2890
  ...(errCodeForkReject !== undefined ? { errorCode: errCodeForkReject } : {}),
2887
2891
  ...(errClassForkReject !== undefined ? { retryable: errClassForkReject.retryable, errorKind: errClassForkReject.errorKind } : {}),
2888
2892
  });
2889
- const completionIdForkReject = settleWinnerForkReject !== undefined ? bg.registry.getCompletionId(taskId) : undefined;
2893
+ const completionIdForkReject = settleWinnerForkReject !== undefined ? bgRegistry.getCompletionId(taskId) : undefined;
2890
2894
  const settledBg = settleWinnerForkReject ?? (killed ? "killed" : "failed");
2891
- const stoppedByBg = settledBg === "killed" ? bg.registry.getStopAttribution(taskId) ?? "system" : undefined;
2895
+ const stoppedByBg = settledBg === "killed" ? bgRegistry.getStopAttribution(taskId) ?? "system" : undefined;
2892
2896
  const summaryBg = `${shortDesc} — ${settledBg === "failed" ? `failed: ${msgFork}` : settledBg}`.slice(0, 300) + (settledBg === "failed" ? errorKindClause(errClassForkReject) : "");
2893
- const ownsTerminalFacesForkReject = bg.registry.claimAgentTerminalNotify(taskId);
2897
+ const ownsTerminalFacesForkReject = bgRegistry.claimAgentTerminalNotify(taskId);
2894
2898
  const forkRejectFrame = {
2895
2899
  task_id: taskId,
2896
2900
  task_type: "background_agent",
@@ -3038,7 +3042,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3038
3042
  };
3039
3043
  }
3040
3044
  if (wantsBackground) {
3041
- const bg = opts.background;
3045
+ const bg = background, bgRegistry = backgroundRegistry;
3042
3046
  if (ctx.checkpointStoreForChildren !== undefined && ctx.checkpointStoreForChildren !== "disabled" && bg.checkpointStore !== undefined && bg.checkpointStore !== ctx.checkpointStoreForChildren)
3043
3047
  throw configError("background.checkpointStore is not the store this run's children park in (the host's resolved checkpoint seat, TaskSpec/RunnerDeps.checkpointStore) — wire the one store, or leave the option unset and let the seat ride.", "config.invalid_checkpoint_store");
3044
3048
  const childParkStore = ctx.checkpointStoreForChildren === undefined ? bg.checkpointStore : ctx.checkpointStoreForChildren === "disabled" ? undefined : ctx.checkpointStoreForChildren;
@@ -3132,7 +3136,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3132
3136
  };
3133
3137
  let taskId;
3134
3138
  try {
3135
- taskId = bg.registry.registerBackgroundAgent(reviveRow !== undefined
3139
+ taskId = bgRegistry.registerBackgroundAgent(reviveRow !== undefined
3136
3140
  ? {
3137
3141
  id: reviveRow.handle,
3138
3142
  owner: reviveRow.owner,
@@ -3202,7 +3206,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3202
3206
  return notStartedResult({ isError: true, content: `Sub-agent not started in background: the background task could not be registered.${wt ? `\n${wt}` : ""}`, details: { error: "register_failed", ...faultDetails(e) } });
3203
3207
  }
3204
3208
  if (capLedgerKey !== undefined)
3205
- chargeDelegationEntryHandle(bg.registry, capLedgerKey, bg.agentStore, reviveRow === undefined ? taskId : undefined);
3209
+ chargeDelegationEntryHandle(bgRegistry, capLedgerKey, bg.agentStore, reviveRow === undefined ? taskId : undefined);
3206
3210
  if (parkedResume === undefined)
3207
3211
  oweTerminalDelivery(notify, { task_id: taskId, task_type: "background_agent" });
3208
3212
  childInternals.peerSelfRef?.addAxis("h", taskId);
@@ -3220,14 +3224,14 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3220
3224
  const bgChildSessionId = reviveRow?.sessionId ?? uuidv7();
3221
3225
  const bgStartedAt = Date.now();
3222
3226
  stepRecorder.lockTo(taskId);
3223
- bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3224
- const bgCycleSeq = bg.registry.backgroundAgentCycleSeq(taskId);
3227
+ bgRegistry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3228
+ const bgCycleSeq = bgRegistry.backgroundAgentCycleSeq(taskId);
3225
3229
  let retainedCycle;
3226
3230
  const cycleSeqOfFrames = () => retainedCycle?.cycleSeq ?? (parkedResume !== undefined ? (reviveRow?.seq ?? 1) + 1 : reviveRow?.seq);
3227
- bg.registry.attachAgentTerminalNotifier(taskId, (ending) => {
3228
- const stoppedByLanded = ending.status === "killed" ? bg.registry.getStopAttribution(taskId) ?? "system" : undefined;
3229
- const completionIdLanded = bg.registry.getCompletionId(taskId);
3230
- const seqLanded = bg.registry.backgroundAgentCycleSeq(taskId);
3231
+ bgRegistry.attachAgentTerminalNotifier(taskId, (ending) => {
3232
+ const stoppedByLanded = ending.status === "killed" ? bgRegistry.getStopAttribution(taskId) ?? "system" : undefined;
3233
+ const completionIdLanded = bgRegistry.getCompletionId(taskId);
3234
+ const seqLanded = bgRegistry.backgroundAgentCycleSeq(taskId);
3231
3235
  const landedElapsedMs = Date.now() - bgStartedAt;
3232
3236
  const landedFrame = {
3233
3237
  task_id: taskId,
@@ -3247,7 +3251,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3247
3251
  const landedLane = ending.parkLane ?? cycleSink;
3248
3252
  notifier.notify(() => landedLane?.(landedFrame, { priority: "next" }), "subagent.landedTerminalNotify");
3249
3253
  });
3250
- const bgDurableProbe = bg.registry.durableAgentRowProbe(taskId);
3254
+ const bgDurableProbe = bgRegistry.durableAgentRowProbe(taskId);
3251
3255
  const bgRowConfirmed = async () => (bgDurableProbe ? await bgDurableProbe().catch(() => false) : false);
3252
3256
  sinkEmit({
3253
3257
  kind: "spawn",
@@ -3284,18 +3288,18 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3284
3288
  : undefined
3285
3289
  : ctx.subagentRetain;
3286
3290
  if (sessionScopedBg && bgRetainLedger)
3287
- ensureSessionReapHook(bg.registry);
3288
- const bgRetain = await tryRetainChild(bgRetainLedger, sessionScopedBg && ctx.subagentRetain ? ctx.subagentRetain.ttlMs : undefined, bgChildSessionId, bgDurableProbe, { registry: bg.registry, taskId }, backgroundLegFacts(taskId));
3291
+ ensureSessionReapHook(bgRegistry);
3292
+ const bgRetain = await tryRetainChild(bgRetainLedger, sessionScopedBg && ctx.subagentRetain ? ctx.subagentRetain.ttlMs : undefined, bgChildSessionId, bgDurableProbe, { registry: bgRegistry, taskId }, backgroundLegFacts(taskId));
3289
3293
  retainedCycle = bgRetain;
3290
3294
  if (bgRetain) {
3291
- bg.registry.markRetainedContinuation(taskId);
3295
+ bgRegistry.markRetainedContinuation(taskId);
3292
3296
  const origRelease = bgRetain.release;
3293
3297
  bgRetain.release = async () => {
3294
- bg.registry.unmarkRetainedContinuation(taskId);
3298
+ bgRegistry.unmarkRetainedContinuation(taskId);
3295
3299
  await origRelease();
3296
3300
  };
3297
3301
  }
3298
- bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3302
+ bgRegistry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3299
3303
  const forwardDurableApproval = ctx.durableApprovalForChildren !== undefined &&
3300
3304
  bg.agentStore !== undefined &&
3301
3305
  childParkStore !== undefined &&
@@ -3311,12 +3315,12 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3311
3315
  let reviveAttachedResolve;
3312
3316
  const reviveAttached = reviveRow !== undefined ? new Promise((r) => (reviveAttachedResolve = r)) : undefined;
3313
3317
  const s2NotifyReady = (inject) => {
3314
- bg.registry.attachAgentNotify(taskId, inject);
3318
+ bgRegistry.attachAgentNotify(taskId, inject);
3315
3319
  if (parkedResume !== undefined)
3316
- bg.registry.finalizeParkedResume(taskId);
3320
+ bgRegistry.finalizeParkedResume(taskId);
3317
3321
  const legOrgVerdict = childInternals.ownOrgAdmissionRef?.current;
3318
3322
  if (legOrgVerdict !== undefined)
3319
- bg.registry.recordBackgroundAgentOrgAdmission(taskId, legOrgVerdict);
3323
+ bgRegistry.recordBackgroundAgentOrgAdmission(taskId, legOrgVerdict);
3320
3324
  reviveAttachedResolve?.();
3321
3325
  };
3322
3326
  const bgActivityBeat = createBgActivityBeat(ctx.toolCallId, (toolStarts) => {
@@ -3337,7 +3341,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3337
3341
  ...(currentTool !== undefined ? { currentTool } : {}),
3338
3342
  usage: { toolUses: toolStarts },
3339
3343
  });
3340
- }, () => bg.registry.noteBackgroundAgentActivity(taskId));
3344
+ }, () => bgRegistry.noteBackgroundAgentActivity(taskId));
3341
3345
  const bgPlacement = placedTreeOwner !== undefined
3342
3346
  ? { ...subagentTranscriptPlacement(ctx, bgScope, taskId), owner: placedTreeOwner }
3343
3347
  : undefined;
@@ -3400,7 +3404,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3400
3404
  const rollbackAndThrow = async (e) => {
3401
3405
  let disp = "retry";
3402
3406
  try {
3403
- disp = await bg.registry.rollbackParkedClaim(claimStores, pr.ticket);
3407
+ disp = await bgRegistry.rollbackParkedClaim(claimStores, pr.ticket);
3404
3408
  }
3405
3409
  catch {
3406
3410
  }
@@ -3461,7 +3465,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3461
3465
  }
3462
3466
  }
3463
3467
  const afterCheckpointResolve = async () => {
3464
- const won = await bg.registry.consumeParkedFlip(taskId, { agentStore: bg.agentStore }, pr.ticket);
3468
+ const won = await bgRegistry.consumeParkedFlip(taskId, { agentStore: bg.agentStore }, pr.ticket);
3465
3469
  if (!won)
3466
3470
  throw new Error("the parked row moved under the resume (a stop or another transition won) — resume aborted");
3467
3471
  moveTerminalDelivery(parkedLane, notify, { task_id: taskId, task_type: "background_agent" });
@@ -3520,7 +3524,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3520
3524
  reopened = false;
3521
3525
  }
3522
3526
  if (reopened) {
3523
- const reParked = bg.registry.parkBackgroundAgent(taskId, {
3527
+ const reParked = bgRegistry.parkBackgroundAgent(taskId, {
3524
3528
  checkpointToken: pr.ticket.token,
3525
3529
  completionSink: cycleSink,
3526
3530
  resolveStop: async () => {
@@ -3624,7 +3628,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3624
3628
  attested = false;
3625
3629
  }
3626
3630
  const parked = attested
3627
- ? bg.registry.parkBackgroundAgent(taskId, {
3631
+ ? bgRegistry.parkBackgroundAgent(taskId, {
3628
3632
  checkpointToken: token,
3629
3633
  seq: seqAtSettle ?? 1,
3630
3634
  completionSink: cycleSink,
@@ -3649,7 +3653,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3649
3653
  }
3650
3654
  const ok = child.terminal.kind === "completed";
3651
3655
  const reaped = !ok && abort.signal.aborted;
3652
- const collateral = reaped && bg.registry.getAccessibleTask(taskId, { ...(bgOwner !== undefined ? { owner: bgOwner } : {}), ...(bgScope !== undefined ? { scope: bgScope } : {}) })?.status === "running";
3656
+ const collateral = reaped && bgRegistry.getAccessibleTask(taskId, { ...(bgOwner !== undefined ? { owner: bgOwner } : {}), ...(bgScope !== undefined ? { scope: bgScope } : {}) })?.status === "running";
3653
3657
  const failedBg = !ok && !reaped;
3654
3658
  const unparkedPauseReason = unparkedPause !== undefined && failedBg ? unparkedDurablePauseReason(unparkedPause) : undefined;
3655
3659
  const errCodeBg = failedBg
@@ -3662,7 +3666,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3662
3666
  : childFace.errorCode
3663
3667
  : undefined;
3664
3668
  const errClassBg = failedBg ? classifySubagentError({ kind: "failed", ...(childFace.errorCode !== undefined ? { code: childFace.errorCode } : {}) }) : undefined;
3665
- const settleWinnerBg = bg.registry.settleBackgroundAgent(taskId, {
3669
+ const settleWinnerBg = bgRegistry.settleBackgroundAgent(taskId, {
3666
3670
  cycle: 0,
3667
3671
  status: ok ? "completed" : reaped ? "killed" : "failed",
3668
3672
  seq: seqAtSettle ?? 1,
@@ -3672,13 +3676,13 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3672
3676
  ...(errClassBg !== undefined ? { retryable: errClassBg.retryable, errorKind: errClassBg.errorKind } : {}),
3673
3677
  ...(failedBg && child.retryAfterMs !== undefined ? { retryAfterMs: child.retryAfterMs } : {}),
3674
3678
  });
3675
- const completionIdBg = settleWinnerBg !== undefined ? bg.registry.getCompletionId(taskId) : undefined;
3679
+ const completionIdBg = settleWinnerBg !== undefined ? bgRegistry.getCompletionId(taskId) : undefined;
3676
3680
  const settled = settleWinnerBg ??
3677
3681
  (abort.signal.aborted ? "killed" : ok ? "completed" : "failed");
3678
3682
  if (!bgRetain && reviveRow === undefined && !(await bgRowConfirmed())) {
3679
- await releaseBoundChildSession({ registry: bg.registry, taskId }, child.sessionId, () => opts.runner.sessions.release(child.sessionId));
3683
+ await releaseBoundChildSession({ registry: bgRegistry, taskId }, child.sessionId, () => opts.runner.sessions.release(child.sessionId));
3680
3684
  }
3681
- const stoppedBy = settled === "killed" ? bg.registry.getStopAttribution(taskId) ?? "system" : undefined;
3685
+ const stoppedBy = settled === "killed" ? bgRegistry.getStopAttribution(taskId) ?? "system" : undefined;
3682
3686
  const observerNote = observerNoteFor(await startBoundedObserverDrain());
3683
3687
  const residual = residualFields();
3684
3688
  const bgDurableRow = await bgRowConfirmed();
@@ -3696,8 +3700,8 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3696
3700
  ? `Agent "${shortDesc}" failed: ${failReasonBg}${ccElapsedTag(bgElapsedMs)}${observerNote}`.slice(0, 300) + errorKindClause(errClassBg)
3697
3701
  : `${ccCompletionText(shortDesc, settled, childFace.status, bgElapsedMs)}${observerNote}`;
3698
3702
  const completionSink = cycleSink;
3699
- const ownsTerminalFaces = completionSink !== undefined && bg.registry.claimAgentTerminalNotify(taskId);
3700
- const bgResultField = await completionResultField(bgHandbackResult, (report) => persistTaskArtifact(ctx.taskArtifacts, taskId, report), (ref) => bg.registry.recordArtifactRef(taskId, ref, completionIdBg), notifier);
3703
+ const ownsTerminalFaces = completionSink !== undefined && bgRegistry.claimAgentTerminalNotify(taskId);
3704
+ const bgResultField = await completionResultField(bgHandbackResult, (report) => persistTaskArtifact(ctx.taskArtifacts, taskId, report), (ref) => bgRegistry.recordArtifactRef(taskId, ref, completionIdBg), notifier);
3701
3705
  const completionFrame = {
3702
3706
  task_id: taskId,
3703
3707
  task_type: "background_agent",
@@ -3721,10 +3725,10 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3721
3725
  if (ownsTerminalFaces)
3722
3726
  sinkEmit(backgroundChildTerminal(completionFrame, { taskId, sessionScoped: sessionScopedBg === true, ...(child.sessionId ? { sessionId: child.sessionId, transcriptId: child.sessionId } : {}), parentToolCallId: ctx.toolCallId, ...(bgCycleSeq !== undefined ? { generation: bgCycleSeq } : {}) }));
3723
3727
  const gateOwners = ownsTerminalFaces && settled === "completed" && bgRetain !== undefined ? childOwnerKeys(child.taskId, bgRetain.childSessionId) : [];
3724
- const aliveBgCount = runningBackgroundUnder(bg.registry, gateOwners);
3728
+ const aliveBgCount = runningBackgroundUnder(bgRegistry, gateOwners);
3725
3729
  if (bgRetain !== undefined && aliveBgCount > 0) {
3726
3730
  parkCompletionNotify({
3727
- registry: bg.registry,
3731
+ registry: bgRegistry,
3728
3732
  entry: bgRetain,
3729
3733
  owners: gateOwners,
3730
3734
  pendingCount: aliveBgCount,
@@ -3757,7 +3761,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3757
3761
  const msg = childThrownText(e);
3758
3762
  const errCodeBgReject = killed ? undefined : thrownErrorCode(e);
3759
3763
  const errClassBgReject = killed ? undefined : classifySubagentError({ kind: "failed", ...(errCodeBgReject !== undefined ? { code: errCodeBgReject } : {}) });
3760
- const settleWinnerBgReject = bg.registry.settleBackgroundAgent(taskId, {
3764
+ const settleWinnerBgReject = bgRegistry.settleBackgroundAgent(taskId, {
3761
3765
  cycle: 0,
3762
3766
  status: killed ? "killed" : "failed",
3763
3767
  error: msg,
@@ -3765,15 +3769,15 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3765
3769
  ...(errCodeBgReject !== undefined ? { errorCode: errCodeBgReject } : {}),
3766
3770
  ...(errClassBgReject !== undefined ? { retryable: errClassBgReject.retryable, errorKind: errClassBgReject.errorKind } : {}),
3767
3771
  });
3768
- const completionIdBgReject = settleWinnerBgReject !== undefined ? bg.registry.getCompletionId(taskId) : undefined;
3772
+ const completionIdBgReject = settleWinnerBgReject !== undefined ? bgRegistry.getCompletionId(taskId) : undefined;
3769
3773
  const settled = settleWinnerBgReject ?? (killed ? "killed" : "failed");
3770
3774
  if (!bgRetain && reviveRow === undefined && !(await bgRowConfirmed())) {
3771
- await releaseBoundChildSession({ registry: bg.registry, taskId }, bgChildSessionId, () => opts.runner.sessions.release(bgChildSessionId));
3775
+ await releaseBoundChildSession({ registry: bgRegistry, taskId }, bgChildSessionId, () => opts.runner.sessions.release(bgChildSessionId));
3772
3776
  }
3773
- const stoppedBy = settled === "killed" ? bg.registry.getStopAttribution(taskId) ?? "system" : undefined;
3777
+ const stoppedBy = settled === "killed" ? bgRegistry.getStopAttribution(taskId) ?? "system" : undefined;
3774
3778
  const observerNote = observerNoteFor(await startBoundedObserverDrain());
3775
3779
  const rejectSink = cycleSink;
3776
- const ownsTerminalFacesReject = rejectSink !== undefined && bg.registry.claimAgentTerminalNotify(taskId);
3780
+ const ownsTerminalFacesReject = rejectSink !== undefined && bgRegistry.claimAgentTerminalNotify(taskId);
3777
3781
  const rejectFrame = {
3778
3782
  task_id: taskId,
3779
3783
  task_type: "background_agent",
@@ -3870,9 +3874,9 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3870
3874
  ledger: ctx.subagentRetain,
3871
3875
  parentToolCallId: ctx.toolCallId,
3872
3876
  runner: opts.runner,
3873
- ...(opts.background?.notify ? { notify: opts.background.notify } : {}),
3877
+ ...(background?.notify ? { notify: background.notify } : {}),
3874
3878
  sink: ctx.onSubagentSpawn,
3875
- ...(opts.background ? { registry: opts.background.registry } : {}),
3879
+ ...(backgroundRegistry ? { registry: backgroundRegistry } : {}),
3876
3880
  entryGate: syncEntryGate,
3877
3881
  ...(opts.onObserverError !== undefined ? { onNotifyError: (f) => opts.onObserverError?.(f.error, { site: f.site }) } : {}),
3878
3882
  ...(ctx.onQuestion !== undefined ? { currentOnQuestion: ctx.onQuestion } : {}),
@@ -14,6 +14,8 @@ import type { ThinkingLevel } from "../internal/harness-types.js";
14
14
  * later config-domain slice (design/96 S6); here it is a pure, tested mapping.
15
15
  */
16
16
  export type ReasoningIntensity = ThinkingLevel;
17
+ /** The seven tiers in rank order, read off the one rank table — for a sentence that names the closed set. */
18
+ export declare const THINKING_LEVELS: readonly ThinkingLevel[];
17
19
  /** Type guard: is `v` one of the 7 {@link ThinkingLevel} tiers? (A legacy/unknown reasoning string is not.) */
18
20
  export declare function isThinkingLevel(v: unknown): v is ThinkingLevel;
19
21
  /**
@@ -8,6 +8,7 @@ const RANK = {
8
8
  xhigh: 5,
9
9
  max: 6,
10
10
  };
11
+ export const THINKING_LEVELS = Object.freeze(Object.keys(RANK));
11
12
  export function isThinkingLevel(v) {
12
13
  return typeof v === "string" && Object.prototype.hasOwnProperty.call(RANK, v);
13
14
  }
@@ -49,6 +49,15 @@ export type AllowEntryInert = {
49
49
  readonly entry: string;
50
50
  readonly reason: AllowEntryInertReason;
51
51
  } & AllowEntryInertDetail;
52
+ /**
53
+ * Does the reader read this entry as a tool the engine retired with NO successor (`removed` / `folded`: no `currentName`)? Such a name reaches no
54
+ * tool in any roster, now or later, and never did anything a rewrite could restore — so a RESTRICTING list (a task's tool-name list, a skill's
55
+ * `disallowed-tools`) leaves it out and says so in the retired-name notice instead of refusing; a name that was RENAMED has a successor, the
56
+ * entry guarded a tool that is still mounted, and stays refused. So does a name whose tool the roster carries under ANOTHER CASE (`TEAMCREATE`
57
+ * beside `TeamCreate`: the entry was written for that tool — the policy audit asks the same question): `roster` is the one the reader read
58
+ * the entry against; absent, no tool is known to be mounted. The one question the engine's tables put to the one reader's answer.
59
+ */
60
+ export declare function isRetiredLeftOut(e: Pick<AllowEntryInert, "entry" | "reason" | "verdict" | "currentName">, roster: ReadonlySet<string> | undefined): boolean;
52
61
  /** One entry the grammar reads (kind closed): a whole non-shell tool; a covering spelling — a set of tool names
53
62
  * ({@link isCoveringRuleName}: a protocol peer, a glob over a protocol name's tool segment, and on a deny list a `*` anywhere in
54
63
  * the name, `*` alone every tool); the whole shell tool; and one kind per rule grammar (`ruleToolGrammarOf`) — a shell command
@@ -2,7 +2,7 @@ import { heldBy, wireOf } from "./tool-name-readings.js";
2
2
  import { ruleIssue } from "./permission-rules.js";
3
3
  import { isCoveringRuleName, ruleNameCovers } from "./namespaced-rule-name.js";
4
4
  import { ruleSpellingOf } from "./permission-rule-syntax.js";
5
- import { splitNamespacedName, toolNameFaultOf } from "./tool-name-aliases.js";
5
+ import { nearMissSpellingOf, splitNamespacedName, toolNameFaultOf } from "./tool-name-aliases.js";
6
6
  import { catalogToolNames, isShellFaceToolName } from "./tool-registry.js";
7
7
  import { ALLOW_RULE_MEMBERS } from "./allow-rule-shadow.js";
8
8
  import { callHostTargetOf } from "./host-target.js";
@@ -24,6 +24,12 @@ export function nonStringMemberLabel(value) {
24
24
  export function nonListValueLabel(read) {
25
25
  return read.kind === "not_a_list" ? `<not a list: ${read.type}>` : "<a list whose entries cannot be read>";
26
26
  }
27
+ export function isRetiredLeftOut(e, roster) {
28
+ if (e.reason !== "tool_name" || e.verdict !== "retired" || e.currentName !== undefined)
29
+ return false;
30
+ const name = ruleSpellingOf(e.entry)?.toolName;
31
+ return name === undefined || roster === undefined || nearMissSpellingOf(name, roster) === undefined;
32
+ }
27
33
  function ruleRowOf(parsed) {
28
34
  return { ...parsed, scope: { kind: "global" }, adds: [{ dot: { actor: "list", counter: 1 }, origin: "user", createdAt: "" }] };
29
35
  }
@@ -956,9 +956,29 @@ export declare function foldArbitrationRow(classes: ReadonlySet<AskClass>, readF
956
956
  export declare function classifyAsk(d: Extract<PermissionResult, {
957
957
  action: "ask";
958
958
  }>, facts: AskClassFacts): AskClassification;
959
- /** The refusal the model reads when an ask reaches a run with no approver: the reference implementation's sentence
960
- * the call did NOT run because this session has no approval surface — with the run's own fact beside it
961
- * and the ask's prompt as what was requested. The gate appends the caller-side remedy. */
959
+ /** The two causes whose refusal sentence is minted by {@link unresolvedAskDenialMessage}: nobody could be asked because no approver is
960
+ * wired, or because the wired one answered `unavailable` for this ask. */
961
+ export type UnresolvedAskCause = "no_approver_wired" | "approver_unavailable";
962
+ /**
963
+ * The base sentence of a refusal for an ask nobody could answer — the one mint for both causes, in the two forms the park state allows.
964
+ * `parkFailed` is whether a durable park was ATTEMPTED for this call and could not be minted; the park-failure note the gate's deny exit
965
+ * appends ({@link import("./runner/gate-exit.js")}) is then the only sentence that speaks about the park, so a clause that depends on the
966
+ * park state is in exactly one form of the base: "do not retry it in this session" and "no durable approval gate is armed" belong to a run
967
+ * with no park attempt, "it can be issued again once its park can be minted" to a park that failed, and no refusal says both.
968
+ * · `no_approver_wired` — the reference implementation's sentence: the call did NOT run because this session has no approval surface,
969
+ * with the run's own fact beside it and the ask's prompt as what was requested. The gate appends the caller-side remedy.
970
+ * · `approver_unavailable` — the approver affirmed that nobody is reachable for this ask; with no park attempt this is the fail-closed
971
+ * fallback that stands.
972
+ */
973
+ export declare function unresolvedAskDenialMessage(cause: UnresolvedAskCause, toolName: string, question: string, parkFailed: boolean): string;
974
+ /**
975
+ * The question a refusal minted by {@link unresolvedAskDenialMessage} (no park attempt) quotes — its tail after the fixed stem — or
976
+ * `undefined` when `text` is not that refusal (a binding's sentence, a hook's, a fold's own): the deny exit re-words a base sentence only
977
+ * when it is the one this module minted, over the very question the resolver quoted (a card's allow-rule note included).
978
+ */
979
+ export declare function unresolvedAskQuestionOf(cause: UnresolvedAskCause, toolName: string, text: string): string | undefined;
980
+ /** The refusal the model reads when an ask reaches a run with no approver (no park attempt): {@link unresolvedAskDenialMessage}'s
981
+ * `no_approver_wired` form. */
962
982
  export declare function headlessDenialMessage(toolName: string, askMessage: string): string;
963
983
  /**
964
984
  * The refusal the model reads when the `dontAsk` permission mode refuses an ask (`deniedBy: "mode"`): the reference implementation's
@@ -464,8 +464,18 @@ export function classifyAsk(d, facts) {
464
464
  const askClass = ASK_CLASSES.find((c) => classes.has(c));
465
465
  return { classes, askClass, row: foldArbitrationRow(classes, facts.readFace, facts.askFace), ...(facts.askFace !== undefined ? { askFace: facts.askFace } : {}) };
466
466
  }
467
+ export function unresolvedAskDenialMessage(cause, toolName, question, parkFailed) {
468
+ if (cause === "approver_unavailable") {
469
+ return `approval required for "${toolName}" but the approver reported unavailable (no reachable operator for this ask)${parkFailed ? "" : " and no durable approval gate is armed"} — denied fail-closed: ${question}`;
470
+ }
471
+ return `Permission for this tool use was denied: it requires interactive approval, and permission prompts are not available in this session (nobody can be asked to approve "${toolName}" in this run — headless auto-deny). The action was NOT performed. Do not claim it succeeded${parkFailed ? "" : ", and do not retry it in this session"} — report the limitation to the user, or suggest an alternative. What was requested: ${question}`;
472
+ }
473
+ export function unresolvedAskQuestionOf(cause, toolName, text) {
474
+ const stem = unresolvedAskDenialMessage(cause, toolName, "", false);
475
+ return text.startsWith(stem) ? text.slice(stem.length) : undefined;
476
+ }
467
477
  export function headlessDenialMessage(toolName, askMessage) {
468
- return `Permission for this tool use was denied: it requires interactive approval, and permission prompts are not available in this session (nobody can be asked to approve "${toolName}" in this run — headless auto-deny). The action was NOT performed. Do not claim it succeeded, and do not retry it in this session — report the limitation to the user, or suggest an alternative. What was requested: ${askMessage}`;
478
+ return unresolvedAskDenialMessage("no_approver_wired", toolName, askMessage, false);
469
479
  }
470
480
  const REFUSED_CAPABILITY_GUIDANCE = "IMPORTANT: you may try to accomplish this with other tools that would naturally be used for it (for example `head` instead of `cat`), but do not work around this denial in malicious ways — for example, do not use your ability to run tests to run non-test actions; only work around it in reasonable ways that keep to the intent behind it. If you believe this capability is essential to complete the user's request, STOP and explain to the user what you were trying to do and why you need this permission, and let the user decide how to proceed.";
471
481
  export function dontAskRefusalMessage(input) {
@@ -618,9 +618,9 @@ export interface EngineNotice {
618
618
  * the entry out and the run goes on; this says so, because the person who wrote it believes it guards a tool. A retired name that
619
619
  * was RENAMED (it has a successor the entry used to guard) is not here: it is still refused at prepare with the name to write, and
620
620
  * the same code rides that thrown error. Audience `user`. Once per audited layer per prepared task, and only when the run goes on.
621
- * `detail: { layer, entries: [{ field, entry, layer, guidance }], total, sessionId }` — `layer` ∈ `caller_policy` / `session_rules` /
622
- * `ancestor_session_rules`, `field` ∈ `deny` / `ask`, `guidance` the retirement table's own line, `entries` unique by (field,
623
- * entry) in scan order (at most 32), `total` every one.
621
+ * `detail: { layer, entries: [{ field, entry, layer, guidance, source? }], total, sessionId }` — `layer` ∈ `caller_policy` / `session_rules` /
622
+ * `ancestor_session_rules` / `task_selector` (a task's tool-name lists) / `skill_table` (a skill's `disallowed-tools`; `source` names the list's
623
+ * owner), `field` ∈ `deny` / `ask`, `guidance` the retirement table's own line, `entries` unique by (field, entry, source) in scan order (at most 32), `total` every one.
624
624
  * - `"config.durable_gate_unavailable"` — a durable-approval MANDATE is in force on a leg with NO
625
625
  * checkpoint store: the per-principal `forceDurableGate` entitlement, or the task's own
626
626
  * `durableApproval` opt-in with no live approver seat (`durableMandateSourceOf`, the predicate the
@@ -95,6 +95,7 @@ export const NON_GOVERNANCE_MEMORY_CODES = new Set([
95
95
  "memory.target_outside_store",
96
96
  "memory.scope_home_not_directory",
97
97
  "memory.control_plane_links_unsupported",
98
+ "memory.control_plane_strays",
98
99
  "memory.root_anchor_backfilled",
99
100
  "memory.root_reanchored",
100
101
  ]);