@sema-agent/core 7.58.0 → 7.59.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.
Files changed (284) hide show
  1. package/CHANGELOG.md +776 -0
  2. package/README.md +6 -4
  3. package/dist/agents/cc-peer-directory.js +8 -8
  4. package/dist/agents/child-model-seat.d.ts +4 -2
  5. package/dist/agents/child-model-seat.js +5 -3
  6. package/dist/agents/peer-directory.d.ts +9 -0
  7. package/dist/agents/peer-directory.js +6 -2
  8. package/dist/agents/send-message-tool.js +21 -12
  9. package/dist/agents/subagent.js +33 -34
  10. package/dist/brain/anthropic.js +161 -45
  11. package/dist/brain/errors.d.ts +9 -3
  12. package/dist/brain/errors.js +7 -1
  13. package/dist/brain/failover.js +2 -1
  14. package/dist/brain/open-responses.js +3 -3
  15. package/dist/brain/openai.js +103 -53
  16. package/dist/brain/provider-dialect.d.ts +11 -0
  17. package/dist/brain/provider-dialect.js +5 -2
  18. package/dist/brain/reasoning-request.js +5 -4
  19. package/dist/brain/reasoning.d.ts +19 -0
  20. package/dist/brain/reasoning.js +17 -2
  21. package/dist/brain/request-route.d.ts +4 -1
  22. package/dist/brain/request-route.js +4 -1
  23. package/dist/brain/route-adjudicator.d.ts +84 -18
  24. package/dist/brain/route-adjudicator.js +87 -21
  25. package/dist/brain/route-conformance.js +1 -1
  26. package/dist/brain/stream-engine.js +84 -49
  27. package/dist/brain/stream-shared.d.ts +30 -0
  28. package/dist/brain/stream-shared.js +34 -1
  29. package/dist/brain/timeout.d.ts +62 -5
  30. package/dist/brain/timeout.js +93 -6
  31. package/dist/core/account-row.d.ts +61 -0
  32. package/dist/core/account-row.js +51 -0
  33. package/dist/core/advisor-verdict.d.ts +2 -1
  34. package/dist/core/advisor-verdict.js +1 -1
  35. package/dist/core/allow-entry.d.ts +18 -6
  36. package/dist/core/allow-entry.js +16 -8
  37. package/dist/core/approval-object.d.ts +29 -15
  38. package/dist/core/approval-object.js +47 -19
  39. package/dist/core/auto-compaction.js +1 -1
  40. package/dist/core/background-agent-store.d.ts +16 -3
  41. package/dist/core/checkpoint-requirements.d.ts +13 -1
  42. package/dist/core/checkpoint-requirements.js +3 -1
  43. package/dist/core/checkpoint-store.d.ts +58 -12
  44. package/dist/core/checkpoint-store.js +18 -6
  45. package/dist/core/child-clamp-seats.d.ts +29 -0
  46. package/dist/core/child-clamp-seats.js +56 -1
  47. package/dist/core/compliance.d.ts +2 -2
  48. package/dist/core/compliance.js +1 -1
  49. package/dist/core/effective-path-target.d.ts +8 -2
  50. package/dist/core/effective-path-target.js +8 -3
  51. package/dist/core/engine-notice.d.ts +98 -8
  52. package/dist/core/engine-notice.js +19 -5
  53. package/dist/core/gate-fold.js +1 -1
  54. package/dist/core/gate-lanes.js +8 -4
  55. package/dist/core/gate-outcome.d.ts +32 -3
  56. package/dist/core/gate-outcome.js +19 -1
  57. package/dist/core/governance-codes.d.ts +9 -1
  58. package/dist/core/governance-codes.js +13 -0
  59. package/dist/core/hooks.d.ts +31 -3
  60. package/dist/core/hooks.js +5 -6
  61. package/dist/core/image-admission.d.ts +6 -5
  62. package/dist/core/image-admission.js +18 -14
  63. package/dist/core/locked-config.d.ts +5 -2
  64. package/dist/core/locked-config.js +2 -1
  65. package/dist/core/mailbox-store.d.ts +45 -1
  66. package/dist/core/mailbox-store.js +53 -9
  67. package/dist/core/mcp-failure.d.ts +114 -18
  68. package/dist/core/mcp-failure.js +63 -5
  69. package/dist/core/mcp-server-link.d.ts +22 -1
  70. package/dist/core/mcp-server-link.js +25 -1
  71. package/dist/core/mcp.d.ts +12 -8
  72. package/dist/core/mcp.js +42 -25
  73. package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
  74. package/dist/core/memory-engine/consolidation-driver.js +3 -3
  75. package/dist/core/memory-engine/consolidation.d.ts +4 -0
  76. package/dist/core/memory-engine/consolidation.js +1 -0
  77. package/dist/core/memory-engine/delegation-settlement.js +5 -12
  78. package/dist/core/memory-engine/distiller.js +2 -2
  79. package/dist/core/memory-engine/dual-root.d.ts +50 -1
  80. package/dist/core/memory-engine/dual-root.js +44 -1
  81. package/dist/core/memory-engine/engine.d.ts +67 -14
  82. package/dist/core/memory-engine/engine.js +384 -212
  83. package/dist/core/memory-engine/export-bundle.d.ts +23 -0
  84. package/dist/core/memory-engine/export-bundle.js +23 -4
  85. package/dist/core/memory-engine/file-backend.d.ts +128 -55
  86. package/dist/core/memory-engine/file-backend.js +290 -117
  87. package/dist/core/memory-engine/index.d.ts +1 -1
  88. package/dist/core/memory-engine/layout.d.ts +59 -11
  89. package/dist/core/memory-engine/layout.js +190 -40
  90. package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
  91. package/dist/core/memory-engine/memory-backend-contract.js +39 -2
  92. package/dist/core/memory-engine/sync-client.d.ts +9 -1
  93. package/dist/core/memory-engine/sync-client.js +31 -8
  94. package/dist/core/memory-engine/sync.d.ts +5 -0
  95. package/dist/core/memory-engine/types.d.ts +6 -0
  96. package/dist/core/mods/classic-events.d.ts +5 -1
  97. package/dist/core/mods/kernel/dispatch.js +2 -1
  98. package/dist/core/mods/kernel/events.d.ts +2 -1
  99. package/dist/core/mods/kernel/events.js +2 -2
  100. package/dist/core/mods/kernel/registration.d.ts +4 -0
  101. package/dist/core/mods/kernel/registration.js +3 -0
  102. package/dist/core/mods/stations.d.ts +31 -10
  103. package/dist/core/mods/stations.js +44 -10
  104. package/dist/core/mods/tool-call.js +1 -1
  105. package/dist/core/parent-spec-seat.d.ts +8 -3
  106. package/dist/core/parent-spec-seat.js +2 -0
  107. package/dist/core/park-selfcheck.js +6 -0
  108. package/dist/core/peer-seat.d.ts +70 -8
  109. package/dist/core/peer-seat.js +143 -11
  110. package/dist/core/permission-rule-consent.js +10 -4
  111. package/dist/core/permission-rule-model.d.ts +16 -0
  112. package/dist/core/permission-rule-model.js +1 -1
  113. package/dist/core/present-plan-tool.d.ts +11 -3
  114. package/dist/core/present-plan-tool.js +2 -2
  115. package/dist/core/resume-startup-cause.js +1 -0
  116. package/dist/core/rewrite-rejudge.d.ts +1 -0
  117. package/dist/core/rewrite-rejudge.js +2 -2
  118. package/dist/core/roles.d.ts +34 -2
  119. package/dist/core/roles.js +43 -4
  120. package/dist/core/runner/announce-once-ledger.d.ts +5 -4
  121. package/dist/core/runner/announce-once-ledger.js +4 -2
  122. package/dist/core/runner/call-hook-stations.js +2 -2
  123. package/dist/core/runner/contracts.d.ts +20 -16
  124. package/dist/core/runner/credential-origin-seat.js +4 -3
  125. package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
  126. package/dist/core/runner/cwd-alignment-probe.js +21 -0
  127. package/dist/core/runner/decide-continuation.d.ts +2 -2
  128. package/dist/core/runner/gate-exit.d.ts +12 -4
  129. package/dist/core/runner/gate-exit.js +10 -7
  130. package/dist/core/runner/image-removed-seat.d.ts +12 -0
  131. package/dist/core/runner/image-removed-seat.js +19 -0
  132. package/dist/core/runner/inline-image.js +1 -1
  133. package/dist/core/runner/memory-consolidation-driver.js +3 -3
  134. package/dist/core/runner/park-commit.d.ts +1 -1
  135. package/dist/core/runner/park-commit.js +3 -0
  136. package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
  137. package/dist/core/runner/prepare-ask-lane.js +2 -1
  138. package/dist/core/runner/prepare-boundary-parks.js +2 -2
  139. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -5
  140. package/dist/core/runner/prepare-caps-and-workflow.js +2 -0
  141. package/dist/core/runner/prepare-config-doors.js +2 -0
  142. package/dist/core/runner/prepare-context-lane.js +2 -0
  143. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  144. package/dist/core/runner/prepare-delegation-surface.js +1 -0
  145. package/dist/core/runner/prepare-hands-readface.d.ts +4 -0
  146. package/dist/core/runner/prepare-hands-readface.js +5 -0
  147. package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
  148. package/dist/core/runner/prepare-inherited-gate.js +14 -27
  149. package/dist/core/runner/prepare-memory.js +10 -17
  150. package/dist/core/runner/prepare-park-ask.d.ts +1 -1
  151. package/dist/core/runner/prepare-park-ask.js +2 -1
  152. package/dist/core/runner/prepare-policy-chain.d.ts +3 -3
  153. package/dist/core/runner/prepare-policy-chain.js +16 -13
  154. package/dist/core/runner/prepare-project-context.d.ts +2 -2
  155. package/dist/core/runner/prepare-project-context.js +2 -2
  156. package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
  157. package/dist/core/runner/prepare-prompt-inputs.js +8 -19
  158. package/dist/core/runner/prepare-protocol-tools.js +9 -1
  159. package/dist/core/runner/prepare-run-refs.d.ts +2 -3
  160. package/dist/core/runner/prepare-run-refs.js +4 -1
  161. package/dist/core/runner/prepare-task.js +4 -2
  162. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -1
  163. package/dist/core/runner/prepare-wiring-manifest.js +2 -1
  164. package/dist/core/runner/reply-pricing.d.ts +30 -0
  165. package/dist/core/runner/reply-pricing.js +19 -0
  166. package/dist/core/runner/resume-admission.js +4 -2
  167. package/dist/core/runner/resume-apply.js +6 -1
  168. package/dist/core/runner/resume-policy-outcome.js +5 -5
  169. package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
  170. package/dist/core/runner/role-seat-defaulted.js +40 -0
  171. package/dist/core/runner/run-brain-sinks.js +2 -0
  172. package/dist/core/runner/run-identity-wiring.d.ts +2 -5
  173. package/dist/core/runner/run-identity-wiring.js +5 -4
  174. package/dist/core/runner/run-leg.d.ts +2 -0
  175. package/dist/core/runner/run-leg.js +37 -28
  176. package/dist/core/runner/run-stop-and-final-verify.js +2 -2
  177. package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
  178. package/dist/core/runner/run-terminal-adoption.js +9 -3
  179. package/dist/core/runner/run-turn-boundary.js +77 -70
  180. package/dist/core/runner/runtask.d.ts +1 -1
  181. package/dist/core/runner/runtask.js +2 -2
  182. package/dist/core/runner/side-call-account.d.ts +1 -1
  183. package/dist/core/runner/side-call-account.js +3 -18
  184. package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
  185. package/dist/core/runner/sub-agent-deny-lists.js +10 -0
  186. package/dist/core/runner/tool-end-body.js +2 -2
  187. package/dist/core/runner/tool-occurrence.d.ts +1 -1
  188. package/dist/core/runner/tool-occurrence.js +2 -2
  189. package/dist/core/runner/turn-attachments.d.ts +26 -22
  190. package/dist/core/runner/turn-attachments.js +24 -26
  191. package/dist/core/runner-deps.d.ts +1 -1
  192. package/dist/core/secret-env.d.ts +32 -2
  193. package/dist/core/secret-env.js +65 -3
  194. package/dist/core/sensitive-path-policy.js +3 -3
  195. package/dist/core/session-policy-store.d.ts +3 -1
  196. package/dist/core/session-policy-store.js +13 -9
  197. package/dist/core/session-store.d.ts +2 -5
  198. package/dist/core/side-query.d.ts +11 -1
  199. package/dist/core/side-query.js +9 -0
  200. package/dist/core/skill-grant-binding.d.ts +31 -2
  201. package/dist/core/skill-grant-binding.js +31 -1
  202. package/dist/core/skill-grant.d.ts +8 -5
  203. package/dist/core/skill-grant.js +6 -6
  204. package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
  205. package/dist/core/store-contracts/checkpoint-store-contract.js +3 -2
  206. package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
  207. package/dist/core/synthetic-read-verdict.js +2 -1
  208. package/dist/core/task-event.d.ts +32 -8
  209. package/dist/core/task-notification.js +16 -10
  210. package/dist/core/task-registry-agent.js +1 -0
  211. package/dist/core/task-registry-shared.d.ts +5 -0
  212. package/dist/core/task-spec.d.ts +12 -1
  213. package/dist/core/terminal-cause.d.ts +10 -0
  214. package/dist/core/tool-check-reading.d.ts +1 -0
  215. package/dist/core/tool-check-reading.js +3 -3
  216. package/dist/core/tool-policy.d.ts +16 -0
  217. package/dist/core/tool-roster.d.ts +112 -5
  218. package/dist/core/tool-roster.js +42 -1
  219. package/dist/core/tool-spec.d.ts +3 -1
  220. package/dist/core/types.d.ts +2 -2
  221. package/dist/core/types.js +1 -1
  222. package/dist/core/user-attachment.js +1 -1
  223. package/dist/core/wiring-manifest.d.ts +6 -3
  224. package/dist/engine/compaction/compaction.js +29 -3
  225. package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
  226. package/dist/engine/execution-env/node-execution-env.js +9 -12
  227. package/dist/engine/harness/agent-harness.d.ts +25 -2
  228. package/dist/engine/harness/agent-harness.js +41 -12
  229. package/dist/engine/harness/messages.d.ts +3 -1
  230. package/dist/engine/harness/messages.js +3 -2
  231. package/dist/engine/harness/types.d.ts +8 -0
  232. package/dist/engine/llm/rejected-images.d.ts +46 -0
  233. package/dist/engine/llm/rejected-images.js +54 -0
  234. package/dist/engine/llm/tool-turns.d.ts +2 -1
  235. package/dist/engine/llm/types.d.ts +18 -7
  236. package/dist/engine/loop/agent-loop.d.ts +8 -0
  237. package/dist/engine/loop/agent-loop.js +52 -15
  238. package/dist/engine/loop/types.d.ts +3 -1
  239. package/dist/engine/session/path-to-root.d.ts +38 -0
  240. package/dist/engine/session/path-to-root.js +39 -0
  241. package/dist/engine/session/storage-base.js +4 -21
  242. package/dist/index.d.ts +16 -10
  243. package/dist/index.js +11 -7
  244. package/dist/internal/harness-types.d.ts +1 -1
  245. package/dist/internal/harness.d.ts +1 -0
  246. package/dist/internal/llm.d.ts +1 -0
  247. package/dist/orchestration/workflow-observe.d.ts +17 -1
  248. package/dist/orchestration/workflow-observe.js +20 -0
  249. package/dist/orchestration/workflow-types.d.ts +32 -7
  250. package/dist/orchestration/workflow.js +739 -489
  251. package/dist/shell/counting-pass.d.ts +50 -0
  252. package/dist/shell/counting-pass.js +502 -0
  253. package/dist/shell/lex.d.ts +4 -2
  254. package/dist/shell/lex.js +93 -34
  255. package/dist/shell/shell-words.d.ts +1 -1
  256. package/dist/shell/shell-words.js +7 -6
  257. package/dist/stores/file/mailbox-store.js +6 -10
  258. package/dist/tools/fs/fs-bash.d.ts +6 -0
  259. package/dist/tools/fs/fs-bash.js +6 -3
  260. package/dist/tools/fs/index.js +6 -2
  261. package/dist/tools/fs/program-read-model.d.ts +13 -0
  262. package/dist/tools/fs/program-read-model.js +15 -0
  263. package/dist/tools/fs/program-read-model.rows.js +1 -1
  264. package/dist/tools/fs/read-deny.d.ts +13 -10
  265. package/dist/tools/fs/read-deny.js +25 -5
  266. package/dist/tools/fs/read-floor.d.ts +19 -0
  267. package/dist/tools/fs/read-floor.js +23 -0
  268. package/dist/tools/fs/shell-read-check.d.ts +1 -1
  269. package/dist/tools/fs/shell-read-check.js +2 -1
  270. package/dist/tools/fs/shell-read-judge.d.ts +16 -8
  271. package/dist/tools/fs/shell-read-judge.js +10 -6
  272. package/dist/tools/fs/shell-read-plan.d.ts +6 -1
  273. package/dist/tools/fs/shell-read-plan.js +22 -15
  274. package/dist/tools/fs/shell-read-start.js +1 -0
  275. package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
  276. package/dist/tools/fs/shell-reentry-text.js +25 -3
  277. package/dist/tools/monitor.d.ts +4 -0
  278. package/dist/tools/monitor.js +2 -0
  279. package/package.json +3 -2
  280. package/test/export-surface.snapshot.json +87 -1
  281. package/wire-changes/core-stores-sql@7.59.0.json +29 -0
  282. package/wire-changes/core@7.59.0.json +2459 -0
  283. package/wire-changes/mods-kernel@7.59.0.json +29 -0
  284. package/wire-changes/primitives@7.59.0.json +29 -0
@@ -4,7 +4,7 @@ import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
4
4
  import { compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, manualCompactOutcomeOf, maybeCompact, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
5
5
  import { emitTrace } from "../trace.js";
6
6
  import { redactThenCut } from "../../agents/subagent-steps.js";
7
- import { ATTACHMENT_BYTE_CAP, CHANGED_FILES_MAX, TOTAL_TOKENS_REMINDER_DEFAULT_MODE, attachmentEnvelopeTags, clipToBytes, collectDateChange, collectDueAttachments, collectInstructionsChange, commitAgentListing, commitInstructionsChange, commitSkillsListing, isIntactSource, rebaseCadenceWindows, renderAgentListingFrame, renderMcpDroppedTools, renderMcpInstructionsDelta, selectMcpDroppedBatch, renderSkillsListingFrame, renderToolsDelta } from "./turn-attachments.js";
7
+ import { ATTACHMENT_BYTE_CAP, CHANGED_FILES_MAX, TOTAL_TOKENS_REMINDER_DEFAULT_MODE, attachmentEnvelopeTags, clipToBytes, collectDateChange, collectDueAttachments, collectInstructionsChange, commitAgentListing, commitInstructionsChange, commitSkillsListing, isIntactSource, rebaseCadenceWindows, renderAgentListingFrame, renderMcpInstructionsDelta, selectMcpDroppedBatch, renderSkillsListingFrame } from "./turn-attachments.js";
8
8
  import { announceListingTruncation } from "../skill-listing-budget.js";
9
9
  import { buildWorkingFileAttachments, centerAdoptionOption, contextInstructionFilesOption, emitInputTruncated, forkContextOption, legCompactionSettings, legContextOverlayOption } from "./compaction-call-options.js";
10
10
  import { classicEventBase, dispatchClassic, stringMembersAnswer, stringMembersOf } from "../mods/stations.js";
@@ -20,6 +20,13 @@ import { contextUsageSections } from "../../prompt-assembly/section-usage.js";
20
20
  import { asThrownError } from "../thrown-value.js";
21
21
  const BATCH_CONTEXT_MIN_KEEP_BYTES = 160;
22
22
  const BATCH_TRUNCATION_MARKER = "\n…[truncated]";
23
+ function consumeDelivered(pending, delivered) {
24
+ for (const d of delivered) {
25
+ const at = pending.indexOf(d);
26
+ if (at !== -1)
27
+ pending.splice(at, 1);
28
+ }
29
+ }
23
30
  export function createTurnBoundary(input) {
24
31
  const { prepared, stats, rs, deps } = input;
25
32
  const { spec, queue, loopLatch: { callerStop }, manualCompactRef, todoToolMounted, taskToolsMounted, walltimeMonotonicDeadline, timeout, ident, postToolBatchArmed, batchArgs, compactionBrain, withinTaskCompaction, compactionBreaker, windowSafetyOptions, rapidRefill, drainManualCompact, runnerHooks, runner } = deps;
@@ -152,7 +159,8 @@ export function createTurnBoundary(input) {
152
159
  turnOwesRequest &&
153
160
  prepared.batchHaltRef.current === undefined &&
154
161
  !boundarySteered &&
155
- !prepared.abortController.signal.aborted) {
162
+ !prepared.abortController.signal.aborted &&
163
+ !frameCarried(prepared.frameReceipts, "limit_approach")) {
156
164
  const thresholds = approachCfg?.at ?? LIMIT_APPROACH_DEFAULT_THRESHOLDS;
157
165
  const ratios = [];
158
166
  if (rs.budget.maxTokensWindow !== undefined && rs.budget.maxTokensWindow > 0) {
@@ -177,22 +185,31 @@ export function createTurnBoundary(input) {
177
185
  tightest = r;
178
186
  const index = rs.counters.approachNoticesSent;
179
187
  if (tightest !== undefined && tightest.ratio >= thresholds[index]) {
180
- rs.counters.approachNoticesSent += 1;
181
188
  const percent = Math.min(100, Math.round(tightest.ratio * 100));
182
189
  const body = limitApproachFrames(index === 0 ? 0 : 1, tightest.axis, percent, prepared.reminderMark);
183
- void prepared.harness.steer(body, { engineMinted: true }).catch(() => undefined);
184
- queue.push({ type: "steering_injected", source: "limit_approach", preview: body.slice(0, 220), ...ident() });
190
+ const preview = body.slice(0, 220);
191
+ prepared.frameReceipts.pending.push({
192
+ source: "limit_approach",
193
+ text: body,
194
+ commit: () => {
195
+ rs.counters.approachNoticesSent += 1;
196
+ queue.push({ type: "steering_injected", source: "limit_approach", preview, ...ident() });
197
+ },
198
+ });
199
+ void prepared.harness.steer(body, { engineMinted: true }).catch(() => {
200
+ prepared.frameReceipts.pending = prepared.frameReceipts.pending.filter((r) => r.text !== body);
201
+ });
185
202
  boundarySteered = true;
186
203
  }
187
204
  }
188
205
  if (prepared.reviewRequestRef.pending !== undefined) {
189
- const { reason } = prepared.reviewRequestRef.pending;
206
+ const { reason, requestedByCallId } = prepared.reviewRequestRef.pending;
190
207
  prepared.reviewRequestRef.pending = undefined;
191
208
  const honorable = prepared.suspendForReview !== undefined &&
192
209
  !prepared.abortController.signal.aborted &&
193
210
  prepared.pausedRef.current === undefined;
194
211
  if (honorable && prepared.suspendForReview) {
195
- await prepared.suspendForReview(reason);
212
+ await prepared.suspendForReview(reason, requestedByCallId);
196
213
  legContinues = !prepared.abortController.signal.aborted && prepared.pausedRef.current === undefined;
197
214
  return undefined;
198
215
  }
@@ -215,7 +232,9 @@ export function createTurnBoundary(input) {
215
232
  }
216
233
  let boundaryAttachmentBytes = 0;
217
234
  let attachmentsPayload;
218
- const receiptCommits = [];
235
+ const recordSteps = new Map();
236
+ const bundleReceipts = [];
237
+ const carried = (source) => frameCarried(prepared.frameReceipts, source);
219
238
  if ((rs.attach.dateState !== undefined ||
220
239
  rs.attach.instrState !== undefined ||
221
240
  rs.attach.sizeGuidelineState !== undefined ||
@@ -229,7 +248,7 @@ export function createTurnBoundary(input) {
229
248
  const due = [];
230
249
  if (rs.attach.attachState !== undefined) {
231
250
  const attachState = rs.attach.attachState;
232
- const changedFilesOn = Boolean(rs.attach.attachmentsCfg?.changedFiles);
251
+ const changedFilesOn = Boolean(rs.attach.attachmentsCfg?.changedFiles) && !carried("changed_files");
233
252
  let changed;
234
253
  if (changedFilesOn && prepared.detectExternalChanges !== undefined) {
235
254
  const maxFiles = typeof rs.attach.attachmentsCfg?.changedFiles === "object"
@@ -246,10 +265,9 @@ export function createTurnBoundary(input) {
246
265
  rs.attach.attachState.surfacedMtime.delete(p);
247
266
  changed = scan.changed;
248
267
  }
249
- const backgroundTasksOn = (rs.attach.attachmentsCfg?.backgroundTasks ?? eventDefaultOn("background_tasks")) === true;
268
+ const backgroundTasksOn = (rs.attach.attachmentsCfg?.backgroundTasks ?? eventDefaultOn("background_tasks")) === true && !carried("background_tasks");
250
269
  const bgTasks = backgroundTasksOn && rs.attach.attachState.postCompactPending ? prepared.listBackgroundTasks() : undefined;
251
- const toolsDeltaOn = rs.attach.attachmentsCfg?.toolsDelta === true;
252
- let announcedOnceDirty = false;
270
+ const toolsDeltaOn = rs.attach.attachmentsCfg?.toolsDelta === true && !carried("tools_delta");
253
271
  const tdRef = toolsDeltaOn ? prepared.toolsDeltaRef : undefined;
254
272
  const pendingTools = tdRef !== undefined && tdRef.pending.length > 0 ? [...tdRef.pending] : undefined;
255
273
  const pendingRemovedTools = tdRef !== undefined && tdRef.pendingRemoved.length > 0 ? [...tdRef.pendingRemoved] : undefined;
@@ -264,7 +282,7 @@ export function createTurnBoundary(input) {
264
282
  const mcpDelta = prepared.mcp.instructionsDelta;
265
283
  const mcpAdds = mcpInstructionsOn && mcpDelta.pendingAdds.length > 0 ? [...mcpDelta.pendingAdds] : undefined;
266
284
  const mcpRemovals = mcpInstructionsOn && mcpDelta.pendingRemovals.length > 0 ? [...mcpDelta.pendingRemovals] : undefined;
267
- const mcpDropped = mcpInstructionsOn && prepared.mcp.droppedTools.length > 0 ? selectMcpDroppedBatch(prepared.mcp.droppedTools) : undefined;
285
+ const mcpDropped = mcpInstructionsOn && !carried("mcp_dropped_tools") && prepared.mcp.droppedTools.length > 0 ? selectMcpDroppedBatch(prepared.mcp.droppedTools) : undefined;
268
286
  const budgetUsdOn = rs.attach.attachmentsCfg?.budgetUsd === true && rs.budget.maxCostMicroUsd !== undefined;
269
287
  const totalTokensDeclared = rs.attach.attachmentsCfg?.totalTokensReminder;
270
288
  const totalTokensMode = rs.attach.attachmentsCfg?.totalTokensReminderMode ?? TOTAL_TOKENS_REMINDER_DEFAULT_MODE;
@@ -273,7 +291,7 @@ export function createTurnBoundary(input) {
273
291
  totalTokensMode !== "fixed" &&
274
292
  totalTokensMode !== "infinite";
275
293
  const totalTokensOn = totalTokensDeclared === true || totalTokensArmedByDefault;
276
- const toolSearchReminderOn = rs.attach.attachmentsCfg?.toolSearchReminder === true && prepared.deferredToolNames !== undefined;
294
+ const toolSearchReminderOn = rs.attach.attachmentsCfg?.toolSearchReminder === true && prepared.deferredToolNames !== undefined && !carried("tool_search_usage_reminder");
277
295
  const undiscoveredTools = toolSearchReminderOn
278
296
  ? [...prepared.deferredToolNames].filter((n) => !prepared.activeTools.has(n)).sort()
279
297
  : undefined;
@@ -286,7 +304,7 @@ export function createTurnBoundary(input) {
286
304
  todoMounted: todoToolMounted,
287
305
  taskListMounted: taskToolsMounted,
288
306
  config: {
289
- todoReminder: rs.attach.attachmentsCfg?.todoReminder === true,
307
+ todoReminder: rs.attach.attachmentsCfg?.todoReminder === true && !carried("todo_reminder") && !carried("task_reminder"),
290
308
  ...(rs.attach.attachmentsCfg?.todoReminderMode !== undefined ? { todoReminderMode: rs.attach.attachmentsCfg.todoReminderMode } : {}),
291
309
  toolSearchReminder: toolSearchReminderOn,
292
310
  changedFiles: changedFilesOn,
@@ -336,27 +354,16 @@ export function createTurnBoundary(input) {
336
354
  : {}),
337
355
  ...(mcpDropped !== undefined ? { mcpDroppedTools: mcpDropped } : {}),
338
356
  }));
339
- if (pendingTools !== undefined || mcpToolsDelta !== undefined) {
340
- const exact = renderToolsDelta({
341
- ...(pendingTools !== undefined ? { added: pendingTools } : {}),
342
- ...(prepared.toolMaterializeStatic ? { staticFace: true } : {}),
343
- ...(prepared.toolMaterializeStatic && pendingTools !== undefined
344
- ? { swappedUnderStatic: pendingTools.filter((n) => prepared.staticFaceFor?.(n) !== true) }
345
- : {}),
346
- ...(prepared.toolMaterializeStatic && pendingReaddedTools !== undefined
347
- ? { readdedSwappedUnderStatic: pendingReaddedTools.filter((n) => prepared.staticFaceFor?.(n) !== true) }
348
- : {}),
349
- ...(mcpToolsDelta ?? {}),
350
- });
351
- if (exact !== undefined && due.some((a) => a.source === "tools_delta" && a.body === exact)) {
352
- const ref = prepared.toolsDeltaRef;
357
+ if ((pendingTools !== undefined || mcpToolsDelta !== undefined) && due.some((a) => a.source === "tools_delta")) {
358
+ const ref = prepared.toolsDeltaRef;
359
+ recordSteps.set("tools_delta", () => {
353
360
  if (pendingTools !== undefined)
354
- ref.pending.splice(0, pendingTools.length);
361
+ consumeDelivered(ref.pending, pendingTools);
355
362
  if (pendingRemovedTools !== undefined)
356
- ref.pendingRemoved.splice(0, pendingRemovedTools.length);
363
+ consumeDelivered(ref.pendingRemoved, pendingRemovedTools);
357
364
  if (pendingReaddedTools !== undefined)
358
- ref.pendingReadded.splice(0, pendingReaddedTools.length);
359
- }
365
+ consumeDelivered(ref.pendingReadded, pendingReaddedTools);
366
+ });
360
367
  }
361
368
  if ((mcpAdds !== undefined || mcpRemovals !== undefined) &&
362
369
  due.some((a) => a.source === "mcp_instructions" && a.body === renderMcpInstructionsDelta(mcpAdds ?? [], mcpRemovals ?? []))) {
@@ -365,64 +372,57 @@ export function createTurnBoundary(input) {
365
372
  if (mcpRemovals !== undefined)
366
373
  mcpDelta.pendingRemovals.splice(0, mcpRemovals.length);
367
374
  }
368
- if (mcpDropped !== undefined &&
369
- due.some((a) => a.source === "mcp_dropped_tools" && a.body === renderMcpDroppedTools(mcpDropped))) {
370
- prepared.mcp.droppedTools.splice(0, mcpDropped.length);
371
- if (!noNextRequest()) {
375
+ if (mcpDropped !== undefined && due.some((a) => a.source === "mcp_dropped_tools")) {
376
+ recordSteps.set("mcp_dropped_tools", () => {
377
+ consumeDelivered(prepared.mcp.droppedTools, mcpDropped);
372
378
  prepared.announcedListingsRef.advisories = withAnnounceDigests(prepared.announcedListingsRef.advisories, mcpDropped.map(droppedToolDigest));
373
- announcedOnceDirty = true;
374
- }
379
+ prepared.frameReceipts.listingSnapshotOwed = true;
380
+ });
375
381
  }
376
382
  if (agentListingDue && due.some((a) => a.source === "agent_listing")) {
377
383
  const listing = prepared.agentListing;
378
384
  const frame = renderAgentListingFrame(attachState, listing.entries, listing.toolName, listing.models, listing.budget);
379
- receiptCommits.push({
380
- source: "agent_listing",
381
- commit: () => {
382
- commitAgentListing(attachState, listing.entries, listing.models);
383
- prepared.announcedListingsRef.agents = listing.entries.map((e) => e.name);
384
- if (listing.models !== undefined)
385
- prepared.announcedListingsRef.models = [...listing.models];
386
- prepared.frameReceipts.listingSnapshotOwed = true;
387
- announceListingTruncation(deps.runner.deps.onNotice, { listing: "agents", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
388
- },
385
+ recordSteps.set("agent_listing", () => {
386
+ commitAgentListing(attachState, listing.entries, listing.models);
387
+ prepared.announcedListingsRef.agents = listing.entries.map((e) => e.name);
388
+ if (listing.models !== undefined)
389
+ prepared.announcedListingsRef.models = [...listing.models];
390
+ prepared.frameReceipts.listingSnapshotOwed = true;
391
+ announceListingTruncation(deps.runner.deps.onNotice, { listing: "agents", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
389
392
  });
390
393
  }
391
394
  if (skillsListingDue && due.some((a) => a.source === "skills_listing")) {
392
395
  const listing = prepared.skillsListing;
393
396
  const frame = renderSkillsListingFrame(attachState, listing.entries, listing.budget);
394
- receiptCommits.push({
395
- source: "skills_listing",
396
- commit: () => {
397
- commitSkillsListing(attachState, listing.entries);
398
- prepared.announcedListingsRef.skills = listing.entries.map((e) => e.name);
399
- prepared.frameReceipts.listingSnapshotOwed = true;
400
- announceListingTruncation(deps.runner.deps.onNotice, { listing: "skills", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
401
- },
397
+ recordSteps.set("skills_listing", () => {
398
+ commitSkillsListing(attachState, listing.entries);
399
+ prepared.announcedListingsRef.skills = listing.entries.map((e) => e.name);
400
+ prepared.frameReceipts.listingSnapshotOwed = true;
401
+ announceListingTruncation(deps.runner.deps.onNotice, { listing: "skills", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
402
402
  });
403
403
  }
404
- if (announcedOnceDirty)
405
- prepared.frameReceipts.listingSnapshotOwed = true;
406
404
  }
407
405
  if (rs.attach.dateState !== undefined && !frameCarried(prepared.frameReceipts, "date_change")) {
408
406
  const today = prepared.dateChange.today();
409
407
  const cand = collectDateChange(rs.attach.dateState, today);
410
408
  if (cand !== undefined) {
411
409
  due.unshift(cand);
412
- receiptCommits.push({ source: "date_change", commit: () => void (rs.attach.dateState.announcedDate = today) });
410
+ recordSteps.set("date_change", () => void (rs.attach.dateState.announcedDate = today));
413
411
  }
414
412
  }
415
- if (rs.attach.sizeGuidelineState !== undefined) {
416
- const guideline = rs.attach.sizeGuidelineState.current();
417
- if (guideline !== rs.attach.sizeGuidelineState.announcedGuideline) {
413
+ if (rs.attach.sizeGuidelineState !== undefined && !carried("workflow_size_guideline_change")) {
414
+ const sizeState = rs.attach.sizeGuidelineState;
415
+ const guideline = sizeState.current();
416
+ if (guideline !== sizeState.announcedGuideline) {
418
417
  due.splice(due.length > 0 && due[0].source === "date_change" ? 1 : 0, 0, {
419
418
  source: "workflow_size_guideline_change",
420
419
  body: workflowSizeGuidelineChangeNotice(guideline),
421
420
  });
422
- rs.attach.sizeGuidelineState.announcedGuideline = guideline;
421
+ recordSteps.set("workflow_size_guideline_change", () => void (sizeState.announcedGuideline = guideline));
423
422
  }
424
423
  }
425
- if (rs.attach.instrState !== undefined && rs.attach.instrProbe !== undefined) {
424
+ if (rs.attach.instrState !== undefined && rs.attach.instrProbe !== undefined && !carried("instructions_change")) {
425
+ const instrState = rs.attach.instrState;
426
426
  let probed = null;
427
427
  try {
428
428
  const PROBE_CEILING_MS = 2_000;
@@ -436,10 +436,10 @@ export function createTurnBoundary(input) {
436
436
  catch {
437
437
  probed = null;
438
438
  }
439
- const cand = collectInstructionsChange(rs.attach.instrState, probed);
439
+ const cand = collectInstructionsChange(instrState, probed);
440
440
  if (cand !== undefined) {
441
441
  due.splice(due.length > 0 && due[0].source === "date_change" ? 1 : 0, 0, cand.attachment);
442
- commitInstructionsChange(rs.attach.instrState, cand.announced);
442
+ recordSteps.set("instructions_change", () => commitInstructionsChange(instrState, cand.announced));
443
443
  }
444
444
  }
445
445
  if (due.length > 0) {
@@ -447,9 +447,16 @@ export function createTurnBoundary(input) {
447
447
  for (const a of due)
448
448
  if (!isIntactSource(a.source))
449
449
  boundaryAttachmentBytes += Buffer.byteLength(a.body, "utf8");
450
- rs.attach.attachmentsInjected += due.length;
451
450
  for (const a of due) {
452
- queue.push({ type: "steering_injected", source: a.source, preview: redactThenCut(a.body, 220), ...ident() });
451
+ const record = a.commit ?? recordSteps.get(a.source);
452
+ bundleReceipts.push({
453
+ source: a.source,
454
+ commit: () => {
455
+ queue.push({ type: "steering_injected", source: a.source, preview: redactThenCut(a.body, 220), ...ident() });
456
+ rs.attach.attachmentsInjected += 1;
457
+ record?.();
458
+ },
459
+ });
453
460
  }
454
461
  }
455
462
  }
@@ -485,7 +492,7 @@ export function createTurnBoundary(input) {
485
492
  }
486
493
  if ((attachmentsPayload !== undefined || batchContextBlock !== undefined) && prepared.batchHaltRef.current === undefined) {
487
494
  const payload = attachmentsPayload !== undefined && batchContextBlock !== undefined ? `${attachmentsPayload}\n${batchContextBlock}` : (attachmentsPayload ?? batchContextBlock);
488
- for (const c of receiptCommits)
495
+ for (const c of bundleReceipts)
489
496
  prepared.frameReceipts.pending.push({ source: c.source, text: payload, commit: c.commit });
490
497
  void prepared.harness.steer(payload, { engineMinted: true }).catch(() => {
491
498
  prepared.frameReceipts.pending = prepared.frameReceipts.pending.filter((r) => r.text !== payload);
@@ -137,7 +137,7 @@ export declare class Runner implements RunnerSelfSeat {
137
137
  /** one-shot brain-routed utility query (see {@link runSideQuery} for the full contract):
138
138
  * preserves system/multi-turn messages/tool DEFINITIONS, routes through the deployment's brain with
139
139
  * the same model resolution as tasks, returns real usage/model. No session, no tool execution, no
140
- * policy gate, no accounting — caller-trusted. */
140
+ * policy gate, no run accounting — caller-trusted; the result's `account` is its engine-priced line for the host's session account. */
141
141
  sideQuery(spec: SideQuerySpec): Promise<SideQueryResult>;
142
142
  /** The out-of-run code-only rewind, no model call and no session entry — the contract is {@link rewindSessionFiles}'s (refused while a leg of this Runner holds or awaits the session's lock, or a write issued to it has not settled). */
143
143
  rewindFiles(request: RewindFilesRequest): Promise<RewindFilesResult>;
@@ -239,7 +239,7 @@ export class Runner {
239
239
  announceReadDenySwap(this.deps.onNotice, seats, this.deps);
240
240
  }
241
241
  sideQuery(spec) {
242
- return runWithReasoningWireFacts(() => { }, () => runWithCapabilityWithheld(() => { }, () => runSideQuery(spec, { brain: this.deps.brain, models: this.deps.models, roles: this.deps.roles })));
242
+ return runWithReasoningWireFacts(() => { }, () => runWithCapabilityWithheld(() => { }, () => runSideQuery(spec, { brain: this.deps.brain, models: this.deps.models, roles: this.deps.roles, pricing: this.deps.pricing })));
243
243
  }
244
244
  rewindFiles(request) { return rewindSessionFiles({ deps: this.deps, sessions: this.sessions, readStates: this.sessionReadStates, ...this.verbLockSeats }, request); }
245
245
  compactSession(request) { return compactIdleSession({ deps: this.deps, sessions: this.sessions, ...this.verbLockSeats }, request); }
@@ -454,7 +454,7 @@ export class Runner {
454
454
  });
455
455
  const { flushGitMirror, unsubGitRetry, unsubBoundary, unsub } = runGitLane({ prepared, queue, rs, ident, onMessageUpdate, onMessageEnd, onToolStart, onToolEnd, onTurnEnd, onTurnBoundary, runner: this.depsSeat });
456
456
  return withLegRequestSinks(() => runLeg({
457
- spec, queue, prepared, resume, rs, entryActor, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, writeFamilyOf, startedToolCallIds,
457
+ spec, queue, prepared, resume, rs, entryActor, operatorObjective: internals?.operatorObjective === true, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, writeFamilyOf, startedToolCallIds,
458
458
  announceWorkspaceMove, withBrainSinks, flushGitMirror, loopLatch, notificationLane, unsubscribeTaskNotifications, unsubGitRetry, unsubBoundary, unsub,
459
459
  runner: this.depsSeat,
460
460
  next: ({ final, threw, abortedLive, userInterruptedLive, strandedHumanAnswers }) => runTerminalAdoption({
@@ -6,7 +6,7 @@
6
6
  * fence, so another lane is a row here, not a second accounting function.
7
7
  */
8
8
  import type { AssistantMessageDiagnostic, Model, Usage } from "../../internal/llm.js";
9
- import { type ModelPricing } from "../pricing.js";
9
+ import type { ModelPricing } from "../pricing.js";
10
10
  import type { AssertAllKeysHandled } from "../ask-origin.js";
11
11
  import type { Brain, RunnerDeps, TaskSpec } from "../types.js";
12
12
  import type { Stats } from "./assemble-result.js";
@@ -1,38 +1,23 @@
1
1
  import { readDegradation } from "../../brain/degrading.js";
2
2
  import { runWithReasoningWireFacts, runWithStatusSink } from "../../brain/status-sink.js";
3
- import { isModelPriced, modelCostToPricing } from "../pricing.js";
4
3
  import { emitTrace } from "../trace.js";
5
- import { cacheFamilyOf, usageCostMicroUsd } from "./usage-accounting.js";
4
+ import { priceReply } from "./reply-pricing.js";
6
5
  export const SIDE_CALL_LANE_TOTAL = {
7
6
  compaction: "compactionMicroUsd",
8
7
  classifier: "sideCallMicroUsd",
9
8
  mod: "sideCallMicroUsd",
10
9
  advisor: "sideCallMicroUsd",
11
10
  };
12
- function catalogModel(id, catalog) {
13
- if (catalog === undefined)
14
- return undefined;
15
- for (const m of Object.values(catalog))
16
- if (m.id === id)
17
- return m;
18
- return Object.hasOwn(catalog, id) ? catalog[id] : undefined;
19
- }
20
11
  export function recordSideCallUsage(stats, usage, lane, call) {
21
12
  if (usage === undefined || call.usageMissing === true)
22
13
  stats.usageMissing = true;
23
14
  if (usage === undefined)
24
15
  return;
25
- const { model: requested, account } = call;
26
- const pricing = account.pricing();
27
- const served = call.servedBy === undefined ? requested : catalogModel(call.servedBy, account.catalog);
28
- const modelId = served?.id ?? call.servedBy ?? requested.id;
29
- const price = pricing?.[modelId] ?? modelCostToPricing(served?.cost);
30
- const priced = served !== undefined ? isModelPriced(served, pricing) : pricing?.[modelId] !== undefined;
16
+ const { account } = call;
17
+ const { modelId, served, price, priced, totalInputTokens, uncachedInputTokens, costMicroUsd } = priceReply(usage, call, { pricing: account.pricing(), catalog: account.catalog });
31
18
  if (!priced)
32
19
  account.telemetry.unpricedSpend = true;
33
20
  account.noteUnevaluablePriceTable(price);
34
- const family = served !== undefined ? cacheFamilyOf(served) : "input-excludes-cached";
35
- const { totalInputTokens, uncachedInputTokens, costMicroUsd } = usageCostMicroUsd(family, usage, price);
36
21
  stats.tokens += usage.totalTokens || 0;
37
22
  stats.promptTokens += uncachedInputTokens;
38
23
  stats.totalInputTokens += totalInputTokens;
@@ -79,6 +79,30 @@ export declare function delegationPoolReading(callerTools: NonNullable<TaskSpec[
79
79
  * ({@link CheckpointErrorReason}): a list the row recorded that is not a list / has a member that is not a string / has a spelling no tool name can have / is not in the
80
80
  * spelling a row records, a record that is not one, a renamed delegation mount, an occupied table of declared names. */
81
81
  export type PersistedToolFaceReason = Extract<CheckpointErrorReason, "not_a_list" | "not_a_string" | "unknown_name" | "unsupported_pattern" | "invalid_record" | "renamed_mount" | "registry_occupied">;
82
+ /** The code of the policy-name refusal — the one spelling its mint and every problem it lists carry. */
83
+ export declare const POLICY_NAME_REFUSAL_CODE = "config.legacy_tool_name";
84
+ /** The layers the prepare-time policy-name audit reads, by the words the trace already gives the first: the run's own policy
85
+ * (`caller_policy`), the stored rules of its session, and the rules an ancestor's session handed it. */
86
+ export type PolicyNameLayer = "caller_policy" | "session_rules" | "ancestor_session_rules";
87
+ /** One entry the policy-name audit refuses, in the shape the entry problems of a rejection body are minted in (code · field ·
88
+ * entry · reason, the engine entry reading's words) plus the layer it sits in: `field` is the policy list (`deny` / `ask` /
89
+ * `allow`), `reason` the name judgment's verdict word (`near_miss` for another spelling of a carried name). */
90
+ export interface PolicyNameProblem {
91
+ readonly code: typeof POLICY_NAME_REFUSAL_CODE;
92
+ readonly field: "deny" | "ask" | "allow";
93
+ readonly entry: string;
94
+ readonly reason: "retired" | "unprefixed_namespace" | "unmintable_segment" | "near_miss";
95
+ readonly layer: PolicyNameLayer;
96
+ }
97
+ /** A refused entry with the sentence that names it. */
98
+ export interface PolicyNameFinding {
99
+ readonly message: string;
100
+ readonly problem: PolicyNameProblem;
101
+ }
102
+ /** The refusal of a policy layer whose name lists hold entries that reach no tool ({@link POLICY_NAME_REFUSAL_CODE}): the sentence is
103
+ * the first entry's, `detail.problems` lists the refused entries of the layer in scan order (within the bounds above), `detail.total`
104
+ * counts every one. */
105
+ export declare function policyNameRefusal(first: PolicyNameFinding, more: readonly PolicyNameFinding[]): Error;
82
106
  /**
83
107
  * The names a definition's denied-tools entries stand for, for a lane that has neither a roster nor a notice sink at the point
84
108
  * it builds its own policy (a workflow leg's agentType): each entry is read by the one reading, so `Tool(content)` denies the
@@ -74,6 +74,16 @@ function refused(message, code, reason) {
74
74
  e.detail = { reason };
75
75
  return e;
76
76
  }
77
+ export const POLICY_NAME_REFUSAL_CODE = "config.legacy_tool_name";
78
+ const POLICY_NAME_PROBLEMS_SHOWN = 32;
79
+ const POLICY_NAME_ENTRY_CHARS = 128;
80
+ export function policyNameRefusal(first, more) {
81
+ const e = new Error(first.message);
82
+ e.code = POLICY_NAME_REFUSAL_CODE;
83
+ const listed = [first, ...more].map((f) => f.problem).filter((p) => p.entry.length <= POLICY_NAME_ENTRY_CHARS);
84
+ e.detail = { problems: listed.slice(0, POLICY_NAME_PROBLEMS_SHOWN), total: 1 + more.length };
85
+ return e;
86
+ }
77
87
  const LIST_WORD = { allowed: "allowed tools", denied: "denied tools" };
78
88
  const NEAR_MISS_EFFECT = {
79
89
  allowed: "it admits nothing, so the tool it was written for is not granted",
@@ -66,7 +66,7 @@ export function emitSettled(table, start, end, frames) {
66
66
  if (!occ.startEmitted)
67
67
  frames.push(startFrameOf(occ, true));
68
68
  const gate = occ.gateRounds.at(-1);
69
- const isError = end.isError || gate?.disposition.kind === "denied", notExecuted = end.notExecuted === true || neverExecuted(occ);
69
+ const neverRan = neverExecuted(occ), isError = end.isError || gate?.disposition.kind === "denied", notExecuted = end.notExecuted === true || neverRan;
70
70
  table.close(occ.toolCallId, end.interrupted === true ? "interrupted" : "settled");
71
71
  frames.push({
72
72
  type: "tool_end",
@@ -77,7 +77,7 @@ export function emitSettled(table, start, end, frames) {
77
77
  ...toolEndBodyFrom(end.result, isError, frames, gate, end.gatedCallIdOfRun),
78
78
  ...(gate?.disposition.kind === "denied" && occ.wireName !== undefined ? { wireName: occ.wireName } : {}),
79
79
  ...(notExecuted ? { notExecuted: true } : {}), ...(occ.answeredInPlaceBy !== undefined ? { answeredBy: occ.answeredInPlaceBy } : {}), ...(occ.requestedBy !== undefined ? { requestedBy: occ.requestedBy } : {}),
80
- ...(occ.rewrite !== undefined && !notExecuted ? { rewrite: occ.rewrite } : {}),
80
+ ...(occ.rewrite !== undefined && !neverRan ? { rewrite: occ.rewrite } : {}),
81
81
  });
82
82
  return { ...(gate !== undefined ? { gate } : {}), isError, ...(notExecuted ? { notExecuted: true } : {}) };
83
83
  }
@@ -93,7 +93,7 @@ export interface ToolOccurrenceTable {
93
93
  gateRound(toolCallId: string, outcome: GateOutcome, finalInput?: unknown, rewrite?: import("../task-event.js").ToolInputRewrite): void;
94
94
  /** A station after the gate refused the call: one more gate record, minted as a veto of whatever the latest one
95
95
  * settled (a person's yes stays on the settlement; the refusing layer is the disposition). Returns the record. */
96
- refuse(toolCallId: string, layer: DeniedBy): GateOutcome;
96
+ refuse(toolCallId: string, layer: DeniedBy, extension?: string): GateOutcome;
97
97
  /** An extension at `tool.call` answered for the call before its body was called (the kernel's record says the body had
98
98
  * not started): the body is never called for this attempt. Once per attempt; a second is an engine defect. */
99
99
  answeredInPlace(toolCallId: string, by: string): void;
@@ -91,10 +91,10 @@ export function createToolOccurrenceTable() {
91
91
  occ.finalInput = finalInput;
92
92
  occ.rewrite = rewrite;
93
93
  },
94
- refuse(toolCallId, layer) {
94
+ refuse(toolCallId, layer, extension) {
95
95
  const occ = held(toolCallId, "a refusal");
96
96
  const latest = occ.gateRounds.at(-1);
97
- const round = mintGateOutcome({ deniedBy: layer, ...(latest?.settlement !== undefined && latest.origin !== undefined ? { settled: { settlement: latest.settlement, origin: latest.origin } } : {}) });
97
+ const round = mintGateOutcome({ deniedBy: layer, ...(extension !== undefined ? { extension } : {}), ...(latest?.settlement !== undefined && latest.origin !== undefined ? { settled: { settlement: latest.settlement, origin: latest.origin } } : {}) });
98
98
  occ.gateRounds.push(round);
99
99
  return round;
100
100
  },
@@ -1,5 +1,5 @@
1
1
  import type { McpDroppedTool } from "../mcp.js";
2
- import type { AnnouncedMcpFailure } from "../../internal/harness.js";
2
+ import { type McpUnavailableEntry } from "../mcp-failure.js";
3
3
  import type { McpInstructionsEntry } from "../prompt-section-seat.js";
4
4
  import type { TaskSpec } from "../types.js";
5
5
  import { type SkillListingEntry, type SkillsBlockRender } from "./synthetic-tools.js";
@@ -89,11 +89,12 @@ export type AttachmentDeliveryClass = {
89
89
  };
90
90
  /**
91
91
  * @contract attachments.delivery_class — every attachment source is one of two classes, declared HERE
92
- * and nowhere else. An INTACT source's consumption is "recorded when delivered" (a listing's announced
93
- * set, a drained pending list, an append-⇔-commit fixed frame), so a clipped frame could never be
94
- * recorded and would re-render at every boundary; the lane therefore never clips or drops it, and the
95
- * producer bounds it (`bound`). A CLIPPABLE source is a window-based reminder that re-fires at the next
96
- * quiet boundary, so the bundle cap ({@link ATTACHMENT_BYTE_CAP}) may clip or drop it. `satisfies
92
+ * and nowhere else; the class answers whether the bundle cap may clip it — every source's consumption is
93
+ * recorded on the carrying message's receipt (`FrameReceipt`), never at collection. An INTACT source's consumption
94
+ * is a kept fact (an announced set, a drained pending list, a once digest, an announced value), so a clipped frame
95
+ * could never be recorded; the lane never clips or drops it, and the producer bounds it (`bound`). A CLIPPABLE
96
+ * source's frame is said again at the next quiet boundary when it did not ride, so the bundle cap
97
+ * ({@link ATTACHMENT_BYTE_CAP}) may clip or drop it. `satisfies
97
98
  * Record<AttachmentSource, …>` is the totality guard: a new source that is not classed here — or an
98
99
  * intact one without its bound — does not compile.
99
100
  */
@@ -191,6 +192,10 @@ export declare function attachmentEnvelopeTags(source: AttachmentSource): string
191
192
  export interface TurnAttachment {
192
193
  source: AttachmentSource;
193
194
  body: string;
195
+ /** The producer's record step for THIS frame (a window's stamp, the surfaced marks, the latch), handed over instead of
196
+ * run: the caller runs it on the receipt of the message carrying the frame (`FrameReceipt`). A frame the lane cap
197
+ * drops is not returned, so its step never runs and the frame is due again; a clipped frame keeps it. */
198
+ commit?: () => void;
194
199
  }
195
200
  /** H4 — the thin projection of a todo list kept run-local (NEVER the wire-capped `tool_end.structured` card).
196
201
  * Pure CONTENT memory: the write-window anchor lives on {@link AttachmentState.todoLastWriteTurn}
@@ -610,10 +615,12 @@ export interface AttachmentInputs {
610
615
  mcpDroppedTools?: ReadonlyArray<McpDroppedTool>;
611
616
  }
612
617
  /**
613
- * Compute every reminder due at this clean turn boundary. Pure decision + render — no I/O; the only
614
- * mutation is the window bookkeeping on the state the caller owns (reminder turns, surfacedMtime),
615
- * done HERE because the caller only invokes this once per boundary after its injection gate passed —
616
- * splitting "decide" from "mark sent" would just invite a drift between the two.
618
+ * Compute every reminder due at this clean turn boundary. Pure decision + render — no I/O, and no record:
619
+ * what a delivered frame records (a reminder window's stamp, the surfaced marks, the post-compaction latch) is
620
+ * the frame's own {@link TurnAttachment.commit}, decided HERE beside the render (so the two cannot drift) and
621
+ * run by the caller on the receipt of the message that carries it. Two writes are not records of delivery and
622
+ * stay here: the padded countdown's floor (a fact about the measured usage) and the latch an EMPTY registry
623
+ * consumes (nothing is rendered, so nothing is owed).
617
624
  *
618
625
  * Returns attachments in EVIDENCE-STRENGTH order (todo/task → tool_search_usage_reminder →
619
626
  * output_style → budget_usd → total_tokens_reminder → background_tasks → tools_delta → agent_listing →
@@ -748,11 +755,12 @@ export interface McpToolsDeltaFacts {
748
755
  }
749
756
  /**
750
757
  * The `mcp_unavailable` frame — the declared MCP servers that did not connect for this message, each the once-per-session ledger's
751
- * pair (`name` and the REMOTE `error` text, neutralized and bounded at intake). The reference's failed-servers arm
758
+ * pair (`name` and the REMOTE `error` text, neutralized and bounded at intake). A server whose failure record carries `authorization`
759
+ * is told in the needs-authorization arm ahead ({@link needsAuthorizationArm}), every other in the reference's failed-servers arm
752
760
  * (cli296.js:250575) "configured but failed to connect", with its duration clause made true of this engine: a server that stays declared is tried again by the
753
761
  * next run that prepares, so it is unavailable "for now", not "for this session", and whether it connects then depends on the error.
754
762
  */
755
- export declare function renderMcpUnavailable(failed: ReadonlyArray<AnnouncedMcpFailure>): string | undefined;
763
+ export declare function renderMcpUnavailable(entries: ReadonlyArray<McpUnavailableEntry>): string | undefined;
756
764
  /** Whether the `mcp_unavailable` lane is on for a task's attachments config — the one reading, asked by the config door (so a switch
757
765
  * nobody can read refuses the task before any resource is acquired) and by the leg's first request: absent is the registry's
758
766
  * default, a boolean is itself (an explicit `true` is not vetoed by a registry flip), anything else is refused by name
@@ -763,11 +771,11 @@ export declare function mcpUnavailableOn(cfg: TaskSpec["attachments"] | null): b
763
771
  * carrying message's receipt settles exactly those. */
764
772
  export declare function owedMcpUnavailable(prepared: {
765
773
  readonly mcpUnavailable?: {
766
- pending: AnnouncedMcpFailure[];
774
+ pending: McpUnavailableEntry[];
767
775
  };
768
776
  }, cfg: TaskSpec["attachments"] | null): {
769
777
  body: string;
770
- entries: AnnouncedMcpFailure[];
778
+ entries: McpUnavailableEntry[];
771
779
  } | undefined;
772
780
  /**
773
781
  * G1 — deferred-tool materialization announce (boundary notice). The reference's template (cli296.js:128211): "The following deferred tools are now available via", in full:
@@ -787,12 +795,8 @@ export declare function owedMcpUnavailable(prepared: {
787
795
  * listing back, so a withdrawn tool genuinely leaves (and a re-advertised one genuinely returns)
788
796
  * the roster mid-task. CC's trailing "Load via ToolSearch as before" / "Do not search for them —
789
797
  * ToolSearch will return no match" clauses are kept, because sema mounts the SAME ToolSearch name.
790
- * The reference's `failed` arm is its own frame here ({@link renderMcpUnavailable}): it must reach the leg's first request.
791
- * DELIBERATELY ABSENT (state unreachable — announcing them would be a §25 honesty breach):
792
- * - `needs-auth` (@626543): sema's MCP auth surface is STATIC deployment-supplied headers
793
- * (`McpServerSpec.transport.headers` / `principalHeader`) with no OAuth flow and no
794
- * authorization-required status — an auth rejection surfaces as an ordinary connect failure and is
795
- * covered by the `mcp_unavailable` frame.
798
+ * The reference's `failed` and `needs-auth` arms are their own frame here ({@link renderMcpUnavailable}): they must reach the leg's first request.
799
+ * DELIBERATELY ABSENT (state unreachable — announcing it would be a §25 honesty breach):
796
800
  * - `pending`: `materializeMcpTools` is fully AWAITED inside prepareTask (one
797
801
  * `Promise.allSettled` over every server) before the run loop's first turn, so "still connecting"
798
802
  * does not exist at any turn boundary — `McpServerStatus.status` is `connected | failed` only.
@@ -1047,8 +1051,8 @@ export declare const MCP_DROPPED_BATCH_MAX_BYTES = 4096;
1047
1051
  /**
1048
1052
  * Bounded-batch selection for the dropped-tools announce: the longest prefix of COMPLETE entries whose
1049
1053
  * render fits {@link MCP_DROPPED_BATCH_MAX_BYTES} (always ≥1), so an oversized list drains
1050
- * monotonically across boundaries — the run loop splices exactly the delivered batch, the tail rides
1051
- * later boundaries. Pure/deterministic so the drain predicate can re-derive the exact snapshot. The ≥1
1054
+ * monotonically across boundaries — the delivered batch's receipt takes exactly those entries off, the tail
1055
+ * rides later boundaries. Pure/deterministic. The ≥1
1052
1056
  * floor is SAFE because entries are bounded at the mcp.ts producer (tool ≤160 cps, reason ≤240 cps,
1053
1057
  * both single-lined) — one rendered entry is always a few hundred bytes.
1054
1058
  */