@sema-agent/core 7.57.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 (399) hide show
  1. package/CHANGELOG.md +1161 -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-steps.js +2 -4
  10. package/dist/agents/subagent.js +33 -34
  11. package/dist/brain/anthropic.js +161 -45
  12. package/dist/brain/errors.d.ts +9 -3
  13. package/dist/brain/errors.js +7 -1
  14. package/dist/brain/failover.js +2 -1
  15. package/dist/brain/open-responses.js +3 -3
  16. package/dist/brain/openai.js +103 -53
  17. package/dist/brain/provider-dialect.d.ts +11 -0
  18. package/dist/brain/provider-dialect.js +5 -2
  19. package/dist/brain/reasoning-request.js +5 -4
  20. package/dist/brain/reasoning.d.ts +19 -0
  21. package/dist/brain/reasoning.js +17 -2
  22. package/dist/brain/request-route.d.ts +4 -1
  23. package/dist/brain/request-route.js +4 -1
  24. package/dist/brain/route-adjudicator.d.ts +84 -18
  25. package/dist/brain/route-adjudicator.js +89 -22
  26. package/dist/brain/route-conformance.js +1 -1
  27. package/dist/brain/stream-engine.js +84 -49
  28. package/dist/brain/stream-shared.d.ts +30 -0
  29. package/dist/brain/stream-shared.js +34 -1
  30. package/dist/brain/timeout.d.ts +62 -5
  31. package/dist/brain/timeout.js +93 -6
  32. package/dist/core/a2a.d.ts +2 -1
  33. package/dist/core/a2a.js +23 -10
  34. package/dist/core/account-row.d.ts +61 -0
  35. package/dist/core/account-row.js +51 -0
  36. package/dist/core/advisor-verdict.d.ts +2 -1
  37. package/dist/core/advisor-verdict.js +1 -1
  38. package/dist/core/allow-entry.d.ts +20 -7
  39. package/dist/core/allow-entry.js +18 -9
  40. package/dist/core/approval-object.d.ts +29 -15
  41. package/dist/core/approval-object.js +47 -19
  42. package/dist/core/ask-origin.d.ts +21 -2
  43. package/dist/core/ask-origin.js +5 -1
  44. package/dist/core/auto-compaction.d.ts +4 -0
  45. package/dist/core/auto-compaction.js +2 -2
  46. package/dist/core/auto-mode-directive.d.ts +29 -5
  47. package/dist/core/auto-mode-directive.js +38 -8
  48. package/dist/core/background-agent-store.d.ts +16 -3
  49. package/dist/core/checkpoint-requirements.d.ts +19 -1
  50. package/dist/core/checkpoint-requirements.js +5 -1
  51. package/dist/core/checkpoint-store.d.ts +85 -23
  52. package/dist/core/checkpoint-store.js +31 -9
  53. package/dist/core/child-clamp-seats.d.ts +29 -0
  54. package/dist/core/child-clamp-seats.js +56 -1
  55. package/dist/core/compliance.d.ts +2 -2
  56. package/dist/core/compliance.js +1 -1
  57. package/dist/core/effective-path-target.d.ts +8 -2
  58. package/dist/core/effective-path-target.js +8 -3
  59. package/dist/core/engine-notice.d.ts +99 -9
  60. package/dist/core/engine-notice.js +19 -5
  61. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  62. package/dist/core/fs-write-gate-policy.js +7 -3
  63. package/dist/core/gate-fold.js +7 -4
  64. package/dist/core/gate-lanes.js +19 -6
  65. package/dist/core/gate-outcome.d.ts +32 -3
  66. package/dist/core/gate-outcome.js +19 -1
  67. package/dist/core/git-worktree-env.d.ts +53 -11
  68. package/dist/core/git-worktree-env.js +96 -12
  69. package/dist/core/governance-codes.d.ts +9 -1
  70. package/dist/core/governance-codes.js +13 -0
  71. package/dist/core/hooks.d.ts +35 -4
  72. package/dist/core/hooks.js +17 -11
  73. package/dist/core/human-input-projection.d.ts +1 -0
  74. package/dist/core/human-input-projection.js +3 -0
  75. package/dist/core/image-admission.d.ts +6 -5
  76. package/dist/core/image-admission.js +18 -14
  77. package/dist/core/locked-config.d.ts +20 -3
  78. package/dist/core/locked-config.js +40 -3
  79. package/dist/core/mailbox-store.d.ts +45 -1
  80. package/dist/core/mailbox-store.js +53 -9
  81. package/dist/core/mcp-call-meta.d.ts +66 -0
  82. package/dist/core/mcp-call-meta.js +103 -0
  83. package/dist/core/mcp-connection-pool.d.ts +3 -1
  84. package/dist/core/mcp-connection-pool.js +3 -1
  85. package/dist/core/mcp-failure.d.ts +117 -15
  86. package/dist/core/mcp-failure.js +71 -3
  87. package/dist/core/mcp-probe.d.ts +4 -0
  88. package/dist/core/mcp-probe.js +1 -1
  89. package/dist/core/mcp-server-link.d.ts +27 -3
  90. package/dist/core/mcp-server-link.js +25 -1
  91. package/dist/core/mcp-server-spec.d.ts +46 -18
  92. package/dist/core/mcp-server-spec.js +1 -18
  93. package/dist/core/mcp.d.ts +16 -20
  94. package/dist/core/mcp.js +112 -55
  95. package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
  96. package/dist/core/memory-engine/consolidation-driver.js +3 -3
  97. package/dist/core/memory-engine/consolidation.d.ts +4 -0
  98. package/dist/core/memory-engine/consolidation.js +1 -0
  99. package/dist/core/memory-engine/delegation-settlement.js +5 -12
  100. package/dist/core/memory-engine/distiller.js +2 -2
  101. package/dist/core/memory-engine/dual-root.d.ts +50 -1
  102. package/dist/core/memory-engine/dual-root.js +44 -1
  103. package/dist/core/memory-engine/engine.d.ts +67 -14
  104. package/dist/core/memory-engine/engine.js +384 -212
  105. package/dist/core/memory-engine/export-bundle.d.ts +23 -0
  106. package/dist/core/memory-engine/export-bundle.js +23 -4
  107. package/dist/core/memory-engine/file-backend.d.ts +128 -55
  108. package/dist/core/memory-engine/file-backend.js +290 -117
  109. package/dist/core/memory-engine/index.d.ts +1 -1
  110. package/dist/core/memory-engine/layout.d.ts +59 -11
  111. package/dist/core/memory-engine/layout.js +190 -40
  112. package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
  113. package/dist/core/memory-engine/memory-backend-contract.js +39 -2
  114. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  115. package/dist/core/memory-engine/scope-contract.js +80 -11
  116. package/dist/core/memory-engine/sync-client.d.ts +9 -1
  117. package/dist/core/memory-engine/sync-client.js +31 -8
  118. package/dist/core/memory-engine/sync.d.ts +5 -0
  119. package/dist/core/memory-engine/types.d.ts +6 -0
  120. package/dist/core/mode-policy.d.ts +8 -5
  121. package/dist/core/mode-policy.js +5 -4
  122. package/dist/core/mods/classic-events.d.ts +5 -1
  123. package/dist/core/mods/host.js +1 -1
  124. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  125. package/dist/core/mods/kernel/dispatch.js +12 -9
  126. package/dist/core/mods/kernel/events.d.ts +6 -1
  127. package/dist/core/mods/kernel/events.js +2 -2
  128. package/dist/core/mods/kernel/registration.d.ts +9 -1
  129. package/dist/core/mods/kernel/registration.js +3 -0
  130. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  131. package/dist/core/mods/kernel/site-rules.js +10 -0
  132. package/dist/core/mods/package.d.ts +23 -0
  133. package/dist/core/mods/package.js +118 -0
  134. package/dist/core/mods/stations.d.ts +33 -12
  135. package/dist/core/mods/stations.js +45 -11
  136. package/dist/core/mods/tool-call.d.ts +5 -1
  137. package/dist/core/mods/tool-call.js +13 -4
  138. package/dist/core/parent-spec-seat.d.ts +8 -3
  139. package/dist/core/parent-spec-seat.js +2 -0
  140. package/dist/core/park-selfcheck.js +6 -0
  141. package/dist/core/path-guard-rows.d.ts +20 -0
  142. package/dist/core/path-guard-rows.js +11 -0
  143. package/dist/core/peer-seat.d.ts +248 -0
  144. package/dist/core/peer-seat.js +439 -0
  145. package/dist/core/permission-rule-consent.js +10 -4
  146. package/dist/core/permission-rule-model.d.ts +16 -0
  147. package/dist/core/permission-rule-model.js +1 -1
  148. package/dist/core/present-plan-tool.d.ts +20 -3
  149. package/dist/core/present-plan-tool.js +48 -4
  150. package/dist/core/protocol-http-auth.d.ts +40 -29
  151. package/dist/core/protocol-http-auth.js +30 -32
  152. package/dist/core/redaction-marks.d.ts +16 -0
  153. package/dist/core/redaction-marks.js +16 -0
  154. package/dist/core/redaction-passes.js +8 -9
  155. package/dist/core/resume-startup-cause.js +1 -0
  156. package/dist/core/retention.d.ts +41 -15
  157. package/dist/core/retention.js +59 -12
  158. package/dist/core/rewrite-rejudge.d.ts +38 -0
  159. package/dist/core/rewrite-rejudge.js +42 -2
  160. package/dist/core/roles.d.ts +34 -2
  161. package/dist/core/roles.js +43 -4
  162. package/dist/core/run-origin.d.ts +40 -0
  163. package/dist/core/run-origin.js +37 -0
  164. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  165. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  166. package/dist/core/runner/announce-once-ledger.d.ts +5 -4
  167. package/dist/core/runner/announce-once-ledger.js +4 -2
  168. package/dist/core/runner/call-hook-stations.js +2 -2
  169. package/dist/core/runner/compaction-restate.d.ts +15 -6
  170. package/dist/core/runner/compaction-restate.js +28 -2
  171. package/dist/core/runner/contracts.d.ts +33 -21
  172. package/dist/core/runner/credential-origin-seat.js +4 -3
  173. package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
  174. package/dist/core/runner/cwd-alignment-probe.js +21 -0
  175. package/dist/core/runner/decide-continuation.d.ts +2 -2
  176. package/dist/core/runner/gate-exit.d.ts +30 -8
  177. package/dist/core/runner/gate-exit.js +15 -8
  178. package/dist/core/runner/image-removed-seat.d.ts +12 -0
  179. package/dist/core/runner/image-removed-seat.js +19 -0
  180. package/dist/core/runner/inline-image.js +1 -1
  181. package/dist/core/runner/memory-consolidation-driver.js +3 -3
  182. package/dist/core/runner/park-commit.d.ts +1 -1
  183. package/dist/core/runner/park-commit.js +3 -0
  184. package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
  185. package/dist/core/runner/prepare-ask-lane.js +2 -1
  186. package/dist/core/runner/prepare-boundary-parks.js +2 -2
  187. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -5
  188. package/dist/core/runner/prepare-caps-and-workflow.js +3 -1
  189. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  190. package/dist/core/runner/prepare-config-doors.js +14 -10
  191. package/dist/core/runner/prepare-context-lane.js +2 -0
  192. package/dist/core/runner/prepare-delegation-surface.d.ts +8 -0
  193. package/dist/core/runner/prepare-delegation-surface.js +16 -18
  194. package/dist/core/runner/prepare-gate-stations.js +1 -1
  195. package/dist/core/runner/prepare-hands-readface.d.ts +11 -3
  196. package/dist/core/runner/prepare-hands-readface.js +9 -1
  197. package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
  198. package/dist/core/runner/prepare-inherited-gate.js +14 -27
  199. package/dist/core/runner/prepare-memory.d.ts +3 -0
  200. package/dist/core/runner/prepare-memory.js +26 -37
  201. package/dist/core/runner/prepare-park-ask.d.ts +1 -1
  202. package/dist/core/runner/prepare-park-ask.js +2 -1
  203. package/dist/core/runner/prepare-policy-chain.d.ts +7 -7
  204. package/dist/core/runner/prepare-policy-chain.js +18 -15
  205. package/dist/core/runner/prepare-project-context.d.ts +2 -2
  206. package/dist/core/runner/prepare-project-context.js +2 -2
  207. package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
  208. package/dist/core/runner/prepare-prompt-inputs.js +8 -19
  209. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  210. package/dist/core/runner/prepare-protocol-tools.js +11 -3
  211. package/dist/core/runner/prepare-run-refs.d.ts +2 -3
  212. package/dist/core/runner/prepare-run-refs.js +4 -1
  213. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  214. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  215. package/dist/core/runner/prepare-task.js +28 -13
  216. package/dist/core/runner/prepare-wiring-manifest.d.ts +2 -1
  217. package/dist/core/runner/prepare-wiring-manifest.js +4 -3
  218. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  219. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  220. package/dist/core/runner/reply-pricing.d.ts +30 -0
  221. package/dist/core/runner/reply-pricing.js +19 -0
  222. package/dist/core/runner/resume-admission.js +5 -3
  223. package/dist/core/runner/resume-apply.js +6 -1
  224. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  225. package/dist/core/runner/resume-policy-outcome.js +5 -5
  226. package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
  227. package/dist/core/runner/role-seat-defaulted.js +40 -0
  228. package/dist/core/runner/run-brain-sinks.js +2 -0
  229. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  230. package/dist/core/runner/run-harness-handlers.js +1 -8
  231. package/dist/core/runner/run-identity-wiring.d.ts +2 -5
  232. package/dist/core/runner/run-identity-wiring.js +6 -4
  233. package/dist/core/runner/run-leg.d.ts +2 -0
  234. package/dist/core/runner/run-leg.js +42 -29
  235. package/dist/core/runner/run-notification-lane.js +3 -0
  236. package/dist/core/runner/run-stop-and-final-verify.js +2 -2
  237. package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
  238. package/dist/core/runner/run-terminal-adoption.js +9 -3
  239. package/dist/core/runner/run-turn-boundary.js +77 -70
  240. package/dist/core/runner/runtask.d.ts +1 -1
  241. package/dist/core/runner/runtask.js +2 -2
  242. package/dist/core/runner/side-call-account.d.ts +1 -1
  243. package/dist/core/runner/side-call-account.js +3 -18
  244. package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
  245. package/dist/core/runner/sub-agent-deny-lists.js +10 -0
  246. package/dist/core/runner/terminal-account.js +3 -3
  247. package/dist/core/runner/tool-end-body.js +2 -1
  248. package/dist/core/runner/tool-occurrence.d.ts +5 -2
  249. package/dist/core/runner/tool-occurrence.js +4 -3
  250. package/dist/core/runner/turn-attachments.d.ts +26 -22
  251. package/dist/core/runner/turn-attachments.js +24 -26
  252. package/dist/core/runner/write-protection-station.d.ts +8 -2
  253. package/dist/core/runner/write-protection-station.js +2 -0
  254. package/dist/core/runner-deps.d.ts +3 -3
  255. package/dist/core/secret-env.d.ts +32 -2
  256. package/dist/core/secret-env.js +65 -3
  257. package/dist/core/sensitive-path-policy.js +9 -10
  258. package/dist/core/session-log-transfer.d.ts +24 -0
  259. package/dist/core/session-log-transfer.js +166 -0
  260. package/dist/core/session-policy-store.d.ts +3 -1
  261. package/dist/core/session-policy-store.js +13 -9
  262. package/dist/core/session-store.d.ts +86 -24
  263. package/dist/core/session-store.js +162 -24
  264. package/dist/core/session.d.ts +92 -1
  265. package/dist/core/shell-read-silence.js +1 -0
  266. package/dist/core/side-query.d.ts +11 -1
  267. package/dist/core/side-query.js +9 -0
  268. package/dist/core/skill-grant-binding.d.ts +31 -2
  269. package/dist/core/skill-grant-binding.js +31 -1
  270. package/dist/core/skill-grant.d.ts +8 -5
  271. package/dist/core/skill-grant.js +6 -6
  272. package/dist/core/steer-replay.d.ts +4 -2
  273. package/dist/core/steer-replay.js +2 -1
  274. package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
  275. package/dist/core/store-contracts/checkpoint-store-contract.js +20 -2
  276. package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
  277. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  278. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  279. package/dist/core/store-contracts/session-store-contract.js +236 -2
  280. package/dist/core/synthetic-read-verdict.js +2 -1
  281. package/dist/core/task-event.d.ts +92 -8
  282. package/dist/core/task-notification.js +16 -10
  283. package/dist/core/task-registry-agent.js +1 -0
  284. package/dist/core/task-registry-shared.d.ts +7 -1
  285. package/dist/core/task-spec.d.ts +49 -1
  286. package/dist/core/task-stream.d.ts +2 -1
  287. package/dist/core/terminal-cause.d.ts +11 -1
  288. package/dist/core/tool-catalog-entries.js +1 -0
  289. package/dist/core/tool-check-reading.d.ts +1 -0
  290. package/dist/core/tool-check-reading.js +3 -3
  291. package/dist/core/tool-policy.d.ts +16 -0
  292. package/dist/core/tool-result-store.d.ts +17 -10
  293. package/dist/core/tool-result-store.js +3 -1
  294. package/dist/core/tool-roster.d.ts +112 -5
  295. package/dist/core/tool-roster.js +42 -1
  296. package/dist/core/tool-spec.d.ts +3 -1
  297. package/dist/core/types.d.ts +3 -3
  298. package/dist/core/types.js +1 -1
  299. package/dist/core/untrusted-egress.d.ts +0 -2
  300. package/dist/core/untrusted-egress.js +10 -14
  301. package/dist/core/user-attachment.js +1 -1
  302. package/dist/core/wiring-manifest.d.ts +18 -6
  303. package/dist/core/wiring-manifest.js +4 -3
  304. package/dist/core/workspace-snapshot.d.ts +44 -0
  305. package/dist/core/workspace-snapshot.js +34 -0
  306. package/dist/core/write-protect.d.ts +43 -3
  307. package/dist/core/write-protect.js +43 -16
  308. package/dist/engine/compaction/compaction.js +29 -3
  309. package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
  310. package/dist/engine/execution-env/node-execution-env.js +24 -23
  311. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  312. package/dist/engine/harness/agent-harness.d.ts +30 -2
  313. package/dist/engine/harness/agent-harness.js +43 -12
  314. package/dist/engine/harness/messages.d.ts +3 -1
  315. package/dist/engine/harness/messages.js +3 -2
  316. package/dist/engine/harness/types.d.ts +56 -7
  317. package/dist/engine/harness/types.js +5 -1
  318. package/dist/engine/llm/rejected-images.d.ts +46 -0
  319. package/dist/engine/llm/rejected-images.js +54 -0
  320. package/dist/engine/llm/tool-turns.d.ts +2 -1
  321. package/dist/engine/llm/types.d.ts +30 -10
  322. package/dist/engine/llm/types.js +1 -1
  323. package/dist/engine/loop/agent-loop.d.ts +8 -0
  324. package/dist/engine/loop/agent-loop.js +52 -15
  325. package/dist/engine/loop/types.d.ts +3 -1
  326. package/dist/engine/session/import-validate.js +3 -0
  327. package/dist/engine/session/memory-repo.d.ts +17 -9
  328. package/dist/engine/session/memory-repo.js +44 -34
  329. package/dist/engine/session/path-to-root.d.ts +38 -0
  330. package/dist/engine/session/path-to-root.js +39 -0
  331. package/dist/engine/session/repo-utils.d.ts +22 -4
  332. package/dist/engine/session/repo-utils.js +49 -1
  333. package/dist/engine/session/storage-base.d.ts +10 -1
  334. package/dist/engine/session/storage-base.js +11 -22
  335. package/dist/index.d.ts +29 -16
  336. package/dist/index.js +21 -11
  337. package/dist/internal/harness-types.d.ts +2 -2
  338. package/dist/internal/harness.d.ts +3 -2
  339. package/dist/internal/harness.js +2 -2
  340. package/dist/internal/llm.d.ts +1 -0
  341. package/dist/orchestration/workflow-observe.d.ts +17 -1
  342. package/dist/orchestration/workflow-observe.js +20 -0
  343. package/dist/orchestration/workflow-types.d.ts +32 -7
  344. package/dist/orchestration/workflow.js +739 -489
  345. package/dist/shell/counting-pass.d.ts +50 -0
  346. package/dist/shell/counting-pass.js +502 -0
  347. package/dist/shell/lex.d.ts +4 -2
  348. package/dist/shell/lex.js +93 -34
  349. package/dist/shell/shell-words.d.ts +1 -1
  350. package/dist/shell/shell-words.js +7 -6
  351. package/dist/stores/file/index.d.ts +4 -1
  352. package/dist/stores/file/index.js +4 -1
  353. package/dist/stores/file/mailbox-store.js +6 -10
  354. package/dist/stores/file/session-store.d.ts +15 -8
  355. package/dist/stores/file/session-store.js +28 -13
  356. package/dist/tools/fs/fs-bash.d.ts +6 -0
  357. package/dist/tools/fs/fs-bash.js +6 -3
  358. package/dist/tools/fs/fs-write.d.ts +6 -3
  359. package/dist/tools/fs/fs-write.js +8 -7
  360. package/dist/tools/fs/index.d.ts +3 -0
  361. package/dist/tools/fs/index.js +7 -3
  362. package/dist/tools/fs/program-read-model.d.ts +13 -0
  363. package/dist/tools/fs/program-read-model.js +15 -0
  364. package/dist/tools/fs/program-read-model.rows.js +1 -1
  365. package/dist/tools/fs/read-deny.d.ts +13 -10
  366. package/dist/tools/fs/read-deny.js +25 -5
  367. package/dist/tools/fs/read-floor.d.ts +19 -0
  368. package/dist/tools/fs/read-floor.js +23 -0
  369. package/dist/tools/fs/safety.js +40 -8
  370. package/dist/tools/fs/search.js +6 -24
  371. package/dist/tools/fs/shell-read-check.d.ts +9 -2
  372. package/dist/tools/fs/shell-read-check.js +61 -16
  373. package/dist/tools/fs/shell-read-establish.js +2 -1
  374. package/dist/tools/fs/shell-read-identity.js +1 -1
  375. package/dist/tools/fs/shell-read-judge.d.ts +26 -9
  376. package/dist/tools/fs/shell-read-judge.js +10 -6
  377. package/dist/tools/fs/shell-read-plan.d.ts +6 -1
  378. package/dist/tools/fs/shell-read-plan.js +22 -15
  379. package/dist/tools/fs/shell-read-start.js +1 -0
  380. package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
  381. package/dist/tools/fs/shell-reentry-text.js +25 -3
  382. package/dist/tools/monitor.d.ts +4 -0
  383. package/dist/tools/monitor.js +2 -0
  384. package/dist/tools/worktree.d.ts +42 -15
  385. package/dist/tools/worktree.js +60 -32
  386. package/package.json +5 -2
  387. package/test/export-surface.snapshot.json +149 -1
  388. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  389. package/wire-changes/core-stores-sql@7.59.0.json +29 -0
  390. package/wire-changes/core@7.58.0.json +2188 -0
  391. package/wire-changes/core@7.59.0.json +2459 -0
  392. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  393. package/wire-changes/mods-kernel@7.59.0.json +29 -0
  394. package/wire-changes/primitives@7.58.0.json +29 -0
  395. package/wire-changes/primitives@7.59.0.json +29 -0
  396. package/dist/primitives/credential-ref.d.ts +0 -89
  397. package/dist/primitives/credential-ref.js +0 -125
  398. package/dist/primitives/index.d.ts +0 -2
  399. package/dist/primitives/index.js +0 -1
@@ -11,6 +11,7 @@ import { callerToolMembership } from "../../agents/inherited-tool-pool.js";
11
11
  import { refuseLateRosterChanges, snapshotCallerRoster } from "./caller-roster.js";
12
12
  import { toolPolicyPathRules, toolPolicyWriteGuardRows } from "../tool-policy.js";
13
13
  import { dataRootSpellings } from "../sensitive-path-policy.js";
14
+ import { writeLocationOf } from "../../tools/worktree.js";
14
15
  import { bindPathRules, createHeadLeads } from "../path-rule-binding.js";
15
16
  import { whereItsAnsweredPrefixLeads } from "../../tools/fs/read-deny-home.js";
16
17
  import { loadAnnounceOnceLedger } from "./announce-once-ledger.js";
@@ -76,6 +77,7 @@ export { DEFAULT_IRREVERSIBLE_SCOPE, checkpointScopeOf, placementValueOrAbsent }
76
77
  export { mcpManifestEntries } from "./prepare-wiring-manifest.js";
77
78
  import { compactionSummaryFallback, compactionSummaryIsDerived } from "./derived-route-fallback.js";
78
79
  import { prepareAdvisor } from "./prepare-advisor.js";
80
+ import { announceRoleSeatsDefaulted } from "./role-seat-defaulted.js";
79
81
  import { prepareProtocolTools } from "./prepare-protocol-tools.js";
80
82
  import { prepareQuestionFace } from "./prepare-question-face.js";
81
83
  import { prepareLsp } from "./prepare-lsp.js";
@@ -99,13 +101,16 @@ import { handsWriteHalfMounts } from "../../tools/fs/index.js";
99
101
  import { askSeatEffective } from "../wiring-manifest.js";
100
102
  import { durableParkGapFor } from "../park-selfcheck.js";
101
103
  import { createToolCallEntry, createToolCallStation } from "../mods/tool-call.js";
104
+ import { createMcpRequestMetaSeat } from "../mcp-call-meta.js";
102
105
  import { deliverEngineNotice } from "../types.js";
103
106
  import { toolCallFaceOf, ToolRosterDeltaSeat } from "../tool-roster.js";
104
107
  import { mountedMcpOf } from "../mounted-mcp.js";
105
108
  import { McpConnectionPool } from "../mcp-connection-pool.js";
106
109
  import { rosterCanPersistMemory } from "../tool-registry.js";
107
- import { AdvertisedWritableDirs } from "./advertised-writable-dirs.js";
110
+ import { AdvertisedWritableDirs, checkedPlanFileShape, planFileInvalid, planFileShown } from "./advertised-writable-dirs.js";
108
111
  import { resolveTaskRootCanonical } from "./task-root-canonical.js";
112
+ import { projectMarkerFsOf, resolveSessionProject } from "../memory-engine/scope-contract.js";
113
+ import { createWorkspaceFrameSeat } from "../workspace-snapshot.js";
109
114
  import { createStructuredProjector } from "./tool-output-projection.js";
110
115
  import { toolResultMediaRefusedSeat } from "./tool-result-media-seat.js";
111
116
  import { asThrownError, thrownText } from "../thrown-value.js";
@@ -309,6 +314,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
309
314
  })();
310
315
  if (modePolicyOf(declaredModeAtDoor).enablePlanMode)
311
316
  spec = { ...spec, enablePlanMode: true };
317
+ checkedPlanFileShape(spec.planFile);
312
318
  const { toolFaceLists, promptLean, promptTraits, promptHost, promptBinding, lockedPreflight, resolvedInteractionPosture, microCompactKnob, resolvedRole, model, thinking, compModel, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailRef, brainCallGuardrailMs } = doors;
313
319
  announceToolModelGate(deps.onNotice, model.id, doors.modelGate);
314
320
  const modelGateManifest = toolModelGateManifest(doors.modelGate);
@@ -345,6 +351,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
345
351
  await holdSessionLock?.(sessionId);
346
352
  const onceLedger = await loadAnnounceOnceLedger(session, resume?.seed.announcedListings, deps.onError);
347
353
  const hostTaskId = spec.taskId ?? sessionId;
354
+ announceRoleSeatsDefaulted({ spec, deps, onceLedger, rootLeg: !delegation.isDelegatedChild, sessionId, runId });
348
355
  const placementRootResolved = (internals = restorePlacementRoot(internals, resume?.seed.placementRootSessionId))?.placementRoot ?? internals?.rootSessionId ?? sessionId;
349
356
  const effectiveCompModel = compactionSummaryIsDerived(spec.compactionModel !== undefined, compModel) ? await compactionSummaryFallback({ derived: compModel, primary: model, brain: deps.brain, getApiKeyAndHeaders: spec.getApiKeyAndHeaders, onNotice: deps.onNotice, sessionId, runId }) : compModel;
350
357
  warnCompactionWindowHazard(deps.tracer, spec, model, effectiveCompModel, hostTaskId, runnerSelf?.contextOverlayOf?.(resolvedRole.modelRef));
@@ -439,7 +446,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
439
446
  }
440
447
  }
441
448
  const ownedEnv = ownedEnvSeat.current;
442
- const { taskRootFinal, rebaseRestoredPath } = await prepareWorkspaceRestore({ ownedEnv, deps, spec, internals, resume, taskRootInitial, placement, abortController, sessionId });
449
+ const { taskRootFinal, rebaseRestoredPath, remote: workspaceRemote } = await prepareWorkspaceRestore({ ownedEnv, deps, spec, internals, resume, taskRootInitial, placement, abortController, sessionId });
443
450
  const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({ env: executionEnv, given: taskRootFinal, onNotice: deps.onNotice, sessionId, runId });
444
451
  const legHome = validatePath(executionEnv.homeDir, { intent: "validate-coordinate" });
445
452
  const legAnchors = { root: taskRootCanonical, ...(legHome !== undefined ? { home: legHome } : {}) };
@@ -476,11 +483,15 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
476
483
  const effectivePathDenyRules = policyDenyRows.filter((r) => r.unanchored === undefined);
477
484
  const writeTargetJudgeRef = {};
478
485
  const legExemptRoots = Object.freeze(dataRootSpellings(deps.memoryEngineDir));
479
- const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]) };
486
+ const { seat: worktreeSeat, writeLocation, checkout } = writeLocationOf({ spelled: taskRootFinal, canonical: taskRootCanonical });
487
+ const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]), checkout };
480
488
  const sideCallBookRef = {};
481
- const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, enterPlanMode, permissionMode, readDenyEntries: () => personRows.tablesReady().then(() => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: pathTables?.ruleRows() ?? effectivePathDenyRules })), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
489
+ const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, ...(spec.planFile !== undefined ? { planFileSource: { path: spec.planFile, shown: planFileShown(spec.planFile), read: (signal) => advertisedWritableDirs?.readPlanFile(signal) ?? Promise.resolve({ ok: false, reason: "this run admitted no plan file" }) } } : {}), enterPlanMode, permissionMode, readDenyEntries: () => personRows.tablesReady().then(() => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: pathTables?.ruleRows() ?? effectivePathDenyRules })), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
482
490
  const tools = roster.tools;
483
491
  const crossBoundary = await prepareCrossBoundaryLane({ token: crossBoundaryTree, posture: doors.crossBoundaryPosture, externalContentTargetActive, env: executionEnv, session, resumeLeg: resume !== undefined, sessionId, runId, hostTaskId, deps });
492
+ const sessionProject = await resolveSessionProject(projectMarkerFsOf(executionEnv), taskRootCanonical, spec.projectId);
493
+ if (sessionProject.markerFault !== undefined)
494
+ deps.onError?.(sessionProject.markerFault, { phase: "config", sessionId });
484
495
  const pausedRef = {};
485
496
  const undeliveredContinuationRef = { current: { parkedSteers: [], orphanTasks: [] } };
486
497
  const remoteEnvFailures = [];
@@ -540,9 +551,12 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
540
551
  roster.mount(createOutputTool(outputRef, spec.outputSchema, compiled.strict ? compiled.modelSchema : undefined), { source: "synthetic", mountedBy: "optional" });
541
552
  }
542
553
  const rosterSeat = new ToolRosterDeltaSeat();
543
- const { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, mcpRedial } = await prepareProtocolTools({ lockedPreflight, hostFloor: doors.hostFloor, spec, deps, modBus: legMods.bus, ...(mcpPool !== undefined ? { mcpPool } : {}), reminderMark, reminderDisclosureCounts, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback });
554
+ const mcpRequestMeta = createMcpRequestMetaSeat(sessionId);
555
+ const { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, mcpRedial } = await prepareProtocolTools({ lockedPreflight, hostFloor: doors.hostFloor, spec, deps, modBus: legMods.bus, ...(mcpPool !== undefined ? { mcpPool } : {}), reminderMark, reminderDisclosureCounts, mcpRequestMeta, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback });
544
556
  const callIssuedAtRef = {};
545
557
  const workCutRef = { continuation: false, abortedBeforeTurnEnd: false };
558
+ if (spec.planFile !== undefined && (!handsEnabled || spec.handsReadOnly === true))
559
+ throw planFileInvalid(spec.planFile, handsEnabled ? "is declared on a leg whose hands are read-only (handsReadOnly), so no file tool can write it" : "is declared on a leg with no execution environment, so no file tool can write it");
546
560
  const advertisedWritableDirs = handsEnabled
547
561
  ? new AdvertisedWritableDirs(executionEnv, (dir, reason) => deps.onError?.(new Error(`${dir.advertiser} advertised writable directory skipped: ${dir.path} — ${reason}`), { phase: "config", sessionId }), taskRootCanonical, [...(spec.additionalDirectories ?? []), ...(spec.additionalReadDirectories ?? [])])
548
562
  : undefined;
@@ -571,6 +585,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
571
585
  sessionId,
572
586
  ...(captureLineage.own !== undefined ? { sessionIncarnation: captureLineage.own } : {}),
573
587
  taskRootPath: taskRootFinal,
588
+ sessionProject,
574
589
  reminderMark,
575
590
  writeToolsMounted: (handsWriteHalfPlanned || tools.some((t) => t.name === "Write")) &&
576
591
  valveLeaves(spec, toolFaceSnapshot.selector)({ name: "Write" }) &&
@@ -619,9 +634,9 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
619
634
  internals.ownOrgAdmissionRef.current = ownOrgVerdictRef.current;
620
635
  }
621
636
  const modelFileReaderSeat = {};
622
- const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences };
637
+ const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences, writeLocation };
623
638
  const handsReadFace = handsEnabled ? await prepareHandsMount(handsReadFaceInput) : resolveHandsLessReadFace(handsReadFaceInput);
624
- const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, shellReadLandings, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, envHandToolNames, sealReadStateSeat } = handsReadFace;
639
+ const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, shellReadFloor, shellReadLandings, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, envHandToolNames, sealReadStateSeat } = handsReadFace;
625
640
  resolvedReadFace = handsReadFace.resolvedReadFace;
626
641
  resolvedWriteFace = handsReadFace.resolvedWriteFace;
627
642
  readDenyAdditionsNormalized = handsReadFace.readDenyAdditionsNormalized;
@@ -629,7 +644,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
629
644
  handsLessResolvedWriteFace = handsReadFace.handsLessResolvedWriteFace;
630
645
  shellGatedTools = handsReadFace.shellGatedTools;
631
646
  await armAutoMode();
632
- const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle });
647
+ const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, shellReadFloor, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
633
648
  const { liveQuestionFace, contentAskBindings, contentAskRoutable, lateStrandedAnswers, discloseStrandedAnswers, settleContentAskBindings, durableQuestionFace, questionToolMounted, mountedQuestionTool } = prepareQuestionFace({ frozenOnQuestion, spec, deps, checkpointStore, runtimeCaps, resolvedInteractionPosture, resume, sessionId, roster, toolFaceSnapshot, inheritedUnavailableAsks: () => inheritedUnavailableAsks });
634
649
  if (spec.handsReadOnly !== true) {
635
650
  const sessionScope = sessionId ?? spec.principal ?? spec.taskId ?? "default";
@@ -789,9 +804,9 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
789
804
  releaseSignal = () => sig.removeEventListener("abort", onExternalAbort);
790
805
  }
791
806
  }
792
- const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedToolChecks } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, readFace: () => resolvedReadFace, permissionMode, scratchpadDir: spec.envFacts?.scratchpadDir, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
793
- const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, harness, pausedRef, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest });
794
- toolCallStationRef.current = createToolCallStation({ bus: legMods.bus, occurrences: toolOccurrences, blockedToolCalls, identity: hookIdentity, reminderMark });
807
+ const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedToolChecks } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, writeLocation, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, readFace: () => resolvedReadFace, permissionMode, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
808
+ const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard: advertisedWritableDirs?.planFile !== undefined ? { ...legWriteGuard, exemptFiles: [advertisedWritableDirs.planFile] } : legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, harness, pausedRef, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest, runOrigin: doors.runOrigin });
809
+ toolCallStationRef.current = createToolCallStation({ bus: legMods.bus, occurrences: toolOccurrences, blockedToolCalls, identity: hookIdentity, reminderMark, requestMeta: mcpRequestMeta });
795
810
  const writeProtectionCheck = writeProtection.mount?.check;
796
811
  writeTargetJudgeRef.current = writeProtection.judgeWriteTarget;
797
812
  if (fileHistoryBoundary !== undefined) {
@@ -804,7 +819,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
804
819
  const stampCallTarget = attachmentRootCanonical === undefined ? undefined : legCallTargetStamp({ env: executionEnv, root: attachmentRootCanonical, cwd: () => handsCwdRef?.current, judgesPaths: () => parkLaneArmed || effectivePolicy?.pathRules !== undefined || basePolicyForResumeEdit?.pathRules !== undefined || permissionRuleLane !== undefined || skillSpecs.some((s) => compileSkillGrant(s, "model").rows.some((r) => r.compiled.kind === "path")) || allowedToolTables.request.holdsPathRows() || allowedToolTables.deployment.holdsPathRows(), leads: () => headLeads.resolve([...toolPolicyPathRules([effectivePolicy, basePolicyForResumeEdit, ...(inheritedParentConstraints ?? []).map((c) => c.policy)], legAnchors), ...bindPathRules(listPathRows().map((rule) => ({ parsed: rule, ruleText: rule.rule })), legAnchors)]) });
805
820
  const { askLane } = prepareAskLane({ gateMachineryActive, abortController, effectivePolicy, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, advertisedWritableDirs, exemptRoots: legExemptRoots, tools, inheritedUnavailableAsks, inheritedAskGrants, onAsk, humanReviewRef, now, ruleOffersOf, grantBindingOf, askSourceIdentity, riskAxesOf, autoModeDenialTracking: autoModeDenialTrackingRef, spec, deps, sessionId, runId, modBus: legMods.bus, notifyOwnHookCrash, grantReadRoot: handsReadFace.grantReadRoot });
806
821
  const inheritedAnchorRecords = chainAnchorRecords(chainTop, inheritedParentConstraints ?? []);
807
- const { saga } = prepareSuspendSaga({ gateMachineryActive, crossBoundary, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection: () => legMods.skillScopes.frozen(), reminderMark, handsCwdRef, handsRoot: attachmentRootCanonical, handsHome: attachmentRootCanonical !== undefined ? legAnchors.home : undefined, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors: chainTop !== legAnchors ? inheritedAnchorRecords.pathRuleAnchors : undefined, inheritedPathRuleInstallations: inheritedAnchorRecords.pathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, toolCeiling: toolCeilingRead, toolListsJudged, ownToolLists, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
822
+ const { saga } = prepareSuspendSaga({ gateMachineryActive, crossBoundary, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection: () => legMods.skillScopes.frozen(), reminderMark, handsCwdRef, handsRoot: attachmentRootCanonical, handsHome: attachmentRootCanonical !== undefined ? legAnchors.home : undefined, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors: chainTop !== legAnchors ? inheritedAnchorRecords.pathRuleAnchors : undefined, inheritedPathRuleInstallations: inheritedAnchorRecords.pathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, runOrigin: doors.runOrigin, toolCeiling: toolCeilingRead, toolListsJudged, ownToolLists, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
808
823
  const { suspendForResource, suspendForPlatformLimit, suspendForReview } = prepareBoundaryParks({ saga, spec, checkpointStore, checkpointScope, abortController, harness, session, sessions, sessionId, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, incompleteSuspendAdapter });
809
824
  const { parkAsk } = prepareParkAsk({ askLane, saga, spec, deps, sessionId, checkpointStore, checkpointScope, toolRosterDeltas: rosterSeat, parkLaneArmed, contentAskRoutable, liveQuestionFace, mountedQuestionTool, contentAskBindings, lateStrandedAnswers, discloseStrandedAnswers, onAsk, runtimeCaps, inheritedUnavailableAsks, basePolicyForResumeEdit, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, shellReadLandings, advertisedWritableDirs, exemptRoots: legExemptRoots, offloadStore, ownedEnv, incompleteSuspendAdapter, session, sessions, suspendChainBase, maxSuspends, remoteEnvFailures, shellGatedTools, irreversibilityTier, toolMarkSources, effectiveShellGate, durableApproval, priorLedger, liveSpendRef, resourceTotal, ruleOffersOf, grantBindingOf, now, humanReviewRef, abortController, harness, pausedRef });
810
825
  const seatInputsFor = skillGateWiring({ tools, skillToolName: SKILL_TOOL_NAME, seatOf: skillSeatOf, mode: () => permissionMode.current, lane: skillGrantLane, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.skill_allowed", version: 1, taskId: hostTaskId, ...info, entries: [...info.entries], ts: Date.now() })), allowEntries: { deploymentAllows: { ...allowEntryLanes.deployment, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "deployment", ...info, entries: [...info.entries], ts: Date.now() })) }, requestAllows: { ...allowEntryLanes.request, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "request", ...info, entries: [...info.entries], ts: Date.now() })) } } });
@@ -814,7 +829,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
814
829
  const preparedHolder = {};
815
830
  const { cacheBreakDetector, cacheFingerprint, promptOverheadTokens, compactionRestore, normalizeAttachmentPath, isDedupStubResult, recentlyReadFiles, onCompactionApplied, detectExternalChanges, syntheticReadVerdict, consolidationWriteJudge, listBackgroundTasks, centerCompactionCandidate, effectiveReadFaceObserved, effectiveWriteFaceObserved, effectiveReadDenyObserved } = prepareTurnWiring({ deps, systemPromptSeat, harnessTools, fpRef, model, promptIdentityDigest: promptManifest.identity.artifact, systemBlocks, thinking, spec, sessionId, turnSnapshotRef, promptManifest, charsPerToken, handsEnabled, executionEnv, attachmentRootCanonical, readRoots, modelFileReader: modelFileReaderSeat.current, reminderMark, reminderDisclosureCounts, resolvedReadFace, handsCwdRef, readFileStateForCheckpoint, denyNarrowingPolicy, skillGrants: skillGrantLane, callerPolicy: installedToolPolicy, inheritedPolicies: (inheritedParentConstraints ?? []).map((c) => c.policy), persistedRuleLane: permissionRuleLane, ruleLaneFacts, personRowsBeyondRun, orgRuleLane: permissionRuleOrgLane, stampCallTarget, abortController, hostTaskId, taskScope, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef, harnessRef, carrierReadFace, carrierWriteFace, readDenyAdditionsNormalized, preparedHolder });
816
831
  await onceLedger.settle(session, announcedListingsRef);
817
- const buildPrepared = () => ({ harness, session, sessionId, runId, crossBoundary, ...(doors.hostFloor !== undefined ? { hostFloor: doors.hostFloor } : {}), registryAccess: { owner: hostTaskId, scope: taskScope }, reminderMark, reminderDisclosureCounts, fullShellReachable, approvalPosture: { get mode() { return permissionMode.current; }, askEffective: askSeatEffective(wiringManifest) }, ...(outputStyleFrame !== undefined ? { outputStyleFrame } : {}), permissionMode, editedFilesSnapshot, taskRootPath: taskRootFinal, model, thinking, compModel: effectiveCompModel, mcp, ...(mcpRedial !== undefined ? { mcpRedial } : {}), ...(a2a.tools.length > 0 ? { a2a } : {}), blockedRef, outputRef, abortController, conflictRef, blockedToolCalls, toolOccurrences, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, ...(attachmentRootCanonical !== undefined ? { handsRoot: attachmentRootCanonical } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), exemptRoots: legExemptRoots, ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), consolidationWriteJudge, ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, promptIdentity, activeTools, ...(deferred.size > 0 ? { deferredToolNames: deferred } : {}), toolMaterializeStatic, deferDirectCall, ...(staticFaceForRef.current !== undefined ? { staticFaceFor: staticFaceForRef.current } : {}), ownedEnv, pausedRef, undeliveredContinuationRef, suspendProgressRef, remoteEnvFailures, reviewRequestRef, suspendLoopRef, suspendForResource, ...(suspendForPlatformLimit !== undefined ? { suspendForPlatformLimit } : {}), ...(envLifetimeSuspendAt !== undefined ? { envLifetimeSuspendAt } : {}), ...(usageGovernance !== undefined ? { usageGovernance } : {}), callIssuedAtRef, workCutRef, brainCallGuardrailRef, gateStopRef, stopForDenialLimit, suspendForReview, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}), resourceLedger: priorLedger, liveSpendRef, humanReviewRef, now, tools, toolRoster, toolRosterDeltas: rosterSeat, structuredProjector, toolEffects, wakeRecovered, promptOverheadTokens, lastBrainContext, lastSentRequest: () => lastBrainContextRef.current, ...(advisor.instruction !== undefined ? { advisorInstruction: advisor.instruction } : {}), ...(compactionRestore !== undefined ? { compactionRestore } : {}), recentlyReadFiles, normalizeAttachmentPath, isDedupStubResult, ...(onCompactionApplied ? { onCompactionApplied } : {}), compactionReuseRef, trimPressureRef, microCompact, ...(memoryEngineSession ? { memoryEngineSession } : {}), ...(subagentRetain ? { subagentRetain } : {}), ...(lspDiagnostics && nudgeLspOnEdit && withheldDiagnosticsOf ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent, withheldOf: withheldDiagnosticsOf } } : {}), stopRequestedRef, announcedSnapshotRecovered: onceLedger.recovered, ...(dateChange ? { dateChange } : {}), ...(instructionSources ? { instructionSources } : {}), ...(projectInstructionContent !== undefined ? { projectInstructionContent } : {}), ...(workflowSizeGuideline ? { workflowSizeGuideline } : {}), ...(detectExternalChanges ? { detectExternalChanges } : {}), ...(toolsDeltaRef ? { toolsDeltaRef } : {}), ...(mcpUnavailable ? { mcpUnavailable } : {}), ...(agentListing ? { agentListing } : {}), ...(skillsListing ? { skillsListing } : {}), announcedListingsRef, frameReceipts: { pending: [], listingSnapshotOwed: false }, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, modBus: legMods.bus, sideCallBookRef, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(shellReadLandings !== undefined ? { shellReadLandings } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}), ...(toolCallStationRef.current !== undefined ? { toolCallStation: toolCallStationRef.current } : {}) });
832
+ const buildPrepared = () => ({ harness, session, sessionId, runId, crossBoundary, ...(doors.hostFloor !== undefined ? { hostFloor: doors.hostFloor } : {}), registryAccess: { owner: hostTaskId, scope: taskScope }, reminderMark, reminderDisclosureCounts, fullShellReachable, approvalPosture: { get mode() { return permissionMode.current; }, askEffective: askSeatEffective(wiringManifest) }, ...(outputStyleFrame !== undefined ? { outputStyleFrame } : {}), permissionMode, editedFilesSnapshot, taskRootPath: taskRootFinal, model, thinking, compModel: effectiveCompModel, mcp, ...(mcpRedial !== undefined ? { mcpRedial } : {}), ...(a2a.tools.length > 0 ? { a2a } : {}), blockedRef, outputRef, abortController, conflictRef, blockedToolCalls, toolOccurrences, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, ...(attachmentRootCanonical !== undefined ? { handsRoot: attachmentRootCanonical } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), exemptRoots: legExemptRoots, ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), workspaceFrame: createWorkspaceFrameSeat({ root: taskRootCanonical, ...(handsCwdRef !== undefined ? { cwdRef: handsCwdRef } : {}), ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(sessionProject.project !== undefined ? { project: sessionProject.project } : {}), remote: workspaceRemote }), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), consolidationWriteJudge, ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, promptIdentity, activeTools, ...(deferred.size > 0 ? { deferredToolNames: deferred } : {}), toolMaterializeStatic, deferDirectCall, ...(staticFaceForRef.current !== undefined ? { staticFaceFor: staticFaceForRef.current } : {}), ownedEnv, pausedRef, undeliveredContinuationRef, suspendProgressRef, remoteEnvFailures, reviewRequestRef, suspendLoopRef, suspendForResource, ...(suspendForPlatformLimit !== undefined ? { suspendForPlatformLimit } : {}), ...(envLifetimeSuspendAt !== undefined ? { envLifetimeSuspendAt } : {}), ...(usageGovernance !== undefined ? { usageGovernance } : {}), callIssuedAtRef, workCutRef, brainCallGuardrailRef, gateStopRef, stopForDenialLimit, suspendForReview, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}), resourceLedger: priorLedger, liveSpendRef, humanReviewRef, now, tools, toolRoster, toolRosterDeltas: rosterSeat, structuredProjector, toolEffects, wakeRecovered, promptOverheadTokens, lastBrainContext, lastSentRequest: () => lastBrainContextRef.current, ...(advisor.instruction !== undefined ? { advisorInstruction: advisor.instruction } : {}), ...(compactionRestore !== undefined ? { compactionRestore } : {}), recentlyReadFiles, normalizeAttachmentPath, isDedupStubResult, ...(onCompactionApplied ? { onCompactionApplied } : {}), compactionReuseRef, trimPressureRef, microCompact, ...(memoryEngineSession ? { memoryEngineSession } : {}), ...(subagentRetain ? { subagentRetain } : {}), ...(lspDiagnostics && nudgeLspOnEdit && withheldDiagnosticsOf ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent, withheldOf: withheldDiagnosticsOf } } : {}), stopRequestedRef, announcedSnapshotRecovered: onceLedger.recovered, ...(dateChange ? { dateChange } : {}), ...(instructionSources ? { instructionSources } : {}), ...(projectInstructionContent !== undefined ? { projectInstructionContent } : {}), ...(workflowSizeGuideline ? { workflowSizeGuideline } : {}), ...(detectExternalChanges ? { detectExternalChanges } : {}), ...(toolsDeltaRef ? { toolsDeltaRef } : {}), ...(mcpUnavailable ? { mcpUnavailable } : {}), ...(agentListing ? { agentListing } : {}), ...(skillsListing ? { skillsListing } : {}), announcedListingsRef, frameReceipts: { pending: [], listingSnapshotOwed: false }, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, modBus: legMods.bus, sideCallBookRef, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(shellReadLandings !== undefined ? { shellReadLandings } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}), ...(toolCallStationRef.current !== undefined ? { toolCallStation: toolCallStationRef.current } : {}) });
818
833
  refuseLateRosterChanges(callerRoster.roster);
819
834
  rollback.commit();
820
835
  commitModeSeats(abortController.signal);
@@ -129,6 +129,7 @@ export interface PrepareWiringManifestInput {
129
129
  /** borrowed-readonly — from the file-history phase's one fold of the two off switches: the manifest's word, relayed. */ fileHistoryFact: NonNullable<WiringManifest["fileHistory"]>; /** borrowed-readonly — from the project-context phase: did it call the deployment's seam (the arm's own predicate), relayed. */
130
130
  projectMemoryFact: NonNullable<WiringManifest["projectMemory"]>;
131
131
  /** borrowed-readonly — from the policy-chain phase: this leg's own session-rule layer published its key for the children's chain (`ownSessionRulesRef.current !== undefined`), relayed as `sessionRules.childrenReadLive`. */ sessionRulesChildrenReadLive: boolean;
132
+ /** borrowed-readonly — the config doors' one reading of the leg's run origin, relayed into `leg` (absent ⇒ the host said nothing). */ runOrigin: NonNullable<WiringManifest["leg"]>["runOrigin"];
132
133
  /** borrowed-readonly — the advisor phase's answer, relayed. */ advisorFact?: WiringManifest["advisor"]; /** borrowed-readonly — the config doors' compiled host floor's posture, relayed (absent ⇒ none declared). */
133
134
  hostFloorPosture: WiringManifest["hostFloor"];
134
135
  /** borrowed-readonly — the arming outcome the caps phase reads live (the manifest's auto-mode face at this leg's start). */
@@ -216,7 +217,7 @@ export interface PrepareWiringManifestResult {
216
217
  * · a status `connected` ⇒ `connected` with the server's tools among `rosterNames` — the names of the roster the row is read
217
218
  * against: a run's (the valve and the deployment's overlay applied), or the no-run probe's own dials (no run, so no lists apply);
218
219
  * · a status `failed` ⇒ `failed` with the failure record the materialization stamped (`errorCode`/`delivered`/
219
- * `httpStatus` = the MCP vocabulary's `McpFailure` spread flat) and the remote text SECRET-REDACTED (an HTTP endpoint's error body rides the SDK's message
220
+ * `httpStatus`/`authorization` = the MCP vocabulary's `McpFailure` spread flat, copied by its one projection `failureFields`) and the remote text SECRET-REDACTED (an HTTP endpoint's error body rides the SDK's message
220
221
  * verbatim, and a body that echoes the bearer it rejected must not reach a stream consumer),
221
222
  * then neutralized + bounded to the reminder's own 240 (the same bound the once-per-session
222
223
  * ledger applies to that text — one face, one width);
@@ -3,6 +3,7 @@ import { teamRoleOf } from "../../agents/team-role.js";
3
3
  import { resolveCheckpointStore } from "../checkpoint-store.js";
4
4
  import { createHookEnvCapabilities, mintHookInvocationIdentity } from "../hooks.js";
5
5
  import { chainJudges } from "../mods/stations.js";
6
+ import { failureFields } from "../mcp-failure.js";
6
7
  import { toolNamesOfServer } from "../mounted-mcp.js";
7
8
  import { isRemoteExecutionEnv, missingRestoreSurface } from "../remote-env.js";
8
9
  import { isVolatileOffloadStore } from "../tool-result-store.js";
@@ -28,7 +29,7 @@ export function mcpManifestEntries(entries, statuses, rosterNames) {
28
29
  ...source,
29
30
  status: "failed",
30
31
  ...liveness,
31
- ...(status.errorCode !== undefined ? { errorCode: status.errorCode, delivered: status.delivered, ...(status.httpStatus !== undefined ? { httpStatus: status.httpStatus } : {}) } : {}),
32
+ ...failureFields(status),
32
33
  ...(status.error !== undefined ? { error: inlineUntrusted(status.error, 240) } : {}),
33
34
  toolCount: 0,
34
35
  };
@@ -117,7 +118,7 @@ function announceDurableGateUnavailable(args) {
117
118
  });
118
119
  }
119
120
  export function prepareWiringManifest(input) {
120
- const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, sessionBox, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture } = input;
121
+ const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, sessionBox, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin } = input;
121
122
  const onAsk = askSeat.value;
122
123
  const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name);
123
124
  const hasEffectAwareGate = policyLayers.length > 0 || chainJudges(standingModBus);
@@ -182,7 +183,7 @@ export function prepareWiringManifest(input) {
182
183
  const wiringQuestionStripped = internals?.questionFaceStripped === true;
183
184
  const wiringManifest = deriveWiringManifest({
184
185
  half: "effective",
185
- leg: resume !== undefined ? "resume" : internals?.isDelegatedChild === true ? "child" : "root",
186
+ leg: resume !== undefined ? "resume" : internals?.isDelegatedChild === true ? "child" : "root", ...(runOrigin !== undefined ? { runOrigin } : {}),
186
187
  teamRole: teamRoleOf({ isDelegatedChild: delegation.isDelegatedChild, ...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}) }),
187
188
  ...(spec.peerPresence !== undefined ? { peerPresence: spec.peerPresence } : {}),
188
189
  askForm: askSeat.form,
@@ -52,6 +52,9 @@ export interface PrepareWorkspaceRestoreResult {
52
52
  * spelling of the old root); the identity function when no divergence was armed. Consumers (T7):
53
53
  * the readFileState checkpoint seed, the handsCwd seed, the activeWorktree restore. */
54
54
  rebaseRestoredPath: (p: string) => string;
55
+ /** owned — the leg's ONE remoteness reading: its paths name locations in a remote / non-host env (read by the
56
+ * observation sink below and the leg's `workspace_changed` frame alike). */
57
+ remote: boolean;
55
58
  }
56
59
  /** The B-4 phase body — the workspace-restore slice, verbatim (see the module header for the contract). */
57
60
  export declare function prepareWorkspaceRestore(input: PrepareWorkspaceRestoreInput): Promise<PrepareWorkspaceRestoreResult>;
@@ -107,19 +107,19 @@ export async function prepareWorkspaceRestore(input) {
107
107
  }
108
108
  }
109
109
  }
110
+ const workspaceEnv = ownedEnv ?? deps.executionEnv;
111
+ const remote = workspaceEnv !== undefined && workspaceEnv !== null && (isRemoteExecutionEnv(workspaceEnv) || workspaceEnv.hostLocalPaths === false);
110
112
  if (internals?.onWorkspaceResolved !== undefined) {
111
113
  try {
112
- const workspaceEnv = ownedEnv ?? deps.executionEnv;
113
114
  internals.onWorkspaceResolved({
114
115
  cwd: taskRootPath,
115
116
  isolated: internals.isolation === "worktree",
116
- remote: workspaceEnv !== undefined &&
117
- (isRemoteExecutionEnv(workspaceEnv) || workspaceEnv.hostLocalPaths === false),
117
+ remote,
118
118
  ...(input.placement !== undefined ? { placement: input.placement } : {}),
119
119
  });
120
120
  }
121
121
  catch {
122
122
  }
123
123
  }
124
- return { taskRootFinal: taskRootPath, rebaseRestoredPath };
124
+ return { taskRootFinal: taskRootPath, rebaseRestoredPath, remote };
125
125
  }
@@ -0,0 +1,30 @@
1
+ import type { Model, Usage } from "../../internal/llm.js";
2
+ import { type ModelPricing } from "../pricing.js";
3
+ import type { RunnerDeps } from "../types.js";
4
+ /** One reply's usage priced by the engine: the model that served it, its price table, whether a table exists at all, and the
5
+ * re-priced figures. */
6
+ export interface PricedReply {
7
+ readonly served: Model | undefined;
8
+ readonly modelId: string;
9
+ readonly price: ModelPricing;
10
+ /** A price table EXISTS for the serving model (`isModelPriced`'s predicate): `false` ⇒ `costMicroUsd` is a fabricated 0 — unknown, not free. */
11
+ readonly priced: boolean;
12
+ readonly totalInputTokens: number;
13
+ readonly uncachedInputTokens: number;
14
+ readonly costMicroUsd: number;
15
+ }
16
+ /**
17
+ * THE one place a model call made BESIDE the main loop is priced — the run's side-call lanes (`recordSideCallUsage`) and
18
+ * `Runner.sideQuery`'s account line both read it, so a run's reported cost and a side query's cost are the same arithmetic. The
19
+ * call's model prices independently of the main loop's telemetry state. A degrading brain may have served the reply from its
20
+ * fallback: the model that ANSWERED is the one priced (the main loop re-points its pricing at it the same way). A fallback the
21
+ * catalog does not know prices from the deployment's table by id when that has one, else as unpriced spend, and takes the cache
22
+ * family that never undercounts.
23
+ */
24
+ export declare function priceReply(usage: Usage, call: {
25
+ readonly model: Model;
26
+ readonly servedBy?: string;
27
+ }, seats: {
28
+ readonly pricing: RunnerDeps["pricing"];
29
+ readonly catalog: RunnerDeps["models"];
30
+ }): PricedReply;
@@ -0,0 +1,19 @@
1
+ import { isModelPriced, modelCostToPricing } from "../pricing.js";
2
+ import { cacheFamilyOf, usageCostMicroUsd } from "./usage-accounting.js";
3
+ function catalogModel(id, catalog) {
4
+ if (catalog === undefined)
5
+ return undefined;
6
+ for (const m of Object.values(catalog))
7
+ if (m.id === id)
8
+ return m;
9
+ return Object.hasOwn(catalog, id) ? catalog[id] : undefined;
10
+ }
11
+ export function priceReply(usage, call, seats) {
12
+ const { pricing, catalog } = seats;
13
+ const served = call.servedBy === undefined ? call.model : catalogModel(call.servedBy, catalog);
14
+ const modelId = served?.id ?? call.servedBy ?? call.model.id;
15
+ const price = pricing?.[modelId] ?? modelCostToPricing(served?.cost);
16
+ const priced = served !== undefined ? isModelPriced(served, pricing) : pricing?.[modelId] !== undefined;
17
+ const family = served !== undefined ? cacheFamilyOf(served) : "input-excludes-cached";
18
+ return { served, modelId, price, priced, ...usageCostMicroUsd(family, usage, price) };
19
+ }
@@ -1,4 +1,4 @@
1
- import { CheckpointError, readPendingSteerQueue, refuseRetiredModeSeed, resolveCheckpointStore, validatePendingSteer } from "../checkpoint-store.js";
1
+ import { CheckpointError, judgeParkedSteerRepeat, readPendingSteerQueue, refuseRetiredModeSeed, resolveCheckpointStore, validatePendingSteer } from "../checkpoint-store.js";
2
2
  import { assertResumeConfigRecord, checkpointStoreSeat, refuseResumeDoors } from "./prepare-config-doors.js";
3
3
  import { asResumeConfigRefusal } from "../mode-policy.js";
4
4
  import { describeSuppliedValue } from "./decide-continuation.js";
@@ -15,7 +15,7 @@ export async function resumeAdmission(input) {
15
15
  const { token, outcome, taskConfig, runner, sessions, parentConstraintRegistry } = input;
16
16
  let internals = input.internals;
17
17
  if (outcome === null || typeof outcome !== "object") {
18
- throw new CheckpointError("checkpoint.invalid_outcome", `resume outcome must be an object naming its gate (got ${outcome === null ? "null" : typeof outcome})`);
18
+ throw new CheckpointError("checkpoint.invalid_outcome", `resume outcome must be an object naming its gate (got ${outcome === null ? "null" : typeof outcome})`, { field: "outcome" });
19
19
  }
20
20
  asResumeConfigRefusal("taskConfig", () => assertResumeConfigRecord(taskConfig));
21
21
  let config = { ...taskConfig, ...(Array.isArray(taskConfig.skills) ? { skills: detachSkillLists(taskConfig.skills) } : {}) };
@@ -49,7 +49,7 @@ export async function resumeAdmission(input) {
49
49
  const resumeSignal = config.signal;
50
50
  let suppliedMessage;
51
51
  refuseRetiredModeSeed(cp.state);
52
- config = refuseResumeDoors(config, cp.state.inheritedGate, runner.deps, sessions, internals?.holder);
52
+ config = refuseResumeDoors(config, cp.state, runner.deps, sessions, internals?.holder);
53
53
  const parkedSteers = readPendingSteerQueue(cp.state);
54
54
  if (outcomeGate === "wake") {
55
55
  suppliedMessage = outcome.message;
@@ -80,6 +80,8 @@ export async function resumeAdmission(input) {
80
80
  }
81
81
  if (suppliedMessage !== undefined) {
82
82
  wakeMessage = validatePendingSteer(suppliedMessage);
83
+ if (judgeParkedSteerRepeat(parkedSteers, wakeMessage) !== undefined)
84
+ wakeMessage = undefined;
83
85
  }
84
86
  else if (parkedSteers.length === 0) {
85
87
  throw new CheckpointError("wake.nothing_to_deliver", "cannot wake: no message was supplied and the checkpoint holds no parked pendingSteer — an empty " +
@@ -4,6 +4,8 @@ import { chainPolicyOnLeg, chainTopAnchors } from "./child-tree.js";
4
4
  import { mintHookInvocationIdentity } from "../hooks.js";
5
5
  import { admitLegMods, classicEventBase, failedHandlerClause, screenUserPrompt } from "../mods/stations.js";
6
6
  import { checkToolPolicyProjection, policyCannotAnswer, refuseOutOfContractDecision } from "../tool-policy.js";
7
+ import { requestGrantBinding } from "../skill-grant-binding.js";
8
+ import { skillGrantBindingMembers } from "../skill-grant.js";
7
9
  import { callFaceSeat, parkedCallFaceOf } from "../tool-roster.js";
8
10
  import { readCallTarget } from "../effective-path-target.js";
9
11
  import { inlineUntrusted } from "../untrusted-text.js";
@@ -74,9 +76,11 @@ export async function resumeApply(input) {
74
76
  p.then((v) => { editSignal.removeEventListener("abort", onAbort); resolve(v); }, (e) => { editSignal.removeEventListener("abort", onAbort); reject(e); });
75
77
  });
76
78
  };
79
+ const servedSkills = plainPolicyOutcome?.decision === "allow" && cp.pendingAction.kind === "tool_approval" ? skillsThatLoad(normalizeSkills(config.skills)) : [];
77
80
  if (plainPolicyOutcome?.decision === "allow" && cp.pendingAction.kind === "tool_approval") {
78
- const servedSkills = skillsThatLoad(normalizeSkills(config.skills));
79
81
  const claimed = judgeApprovalObject(cp.pendingAction, { args: plainPolicyOutcome.updatedInput ?? cp.pendingAction.args, skills: servedSkills, skillToolName: SKILL_TOOL_NAME }, "claim");
82
+ if (claimed !== "match" && claimed.member === "tool")
83
+ throw new CheckpointError("checkpoint.unsupported_version", claimed.message, { reason: "tool_identity_missing" });
80
84
  if (claimed !== "match")
81
85
  throw new CheckpointError("checkpoint.invalid_outcome", claimed.message, { field: "boundGrantDigest" });
82
86
  }
@@ -94,6 +98,7 @@ export async function resumeApply(input) {
94
98
  toolName: cp.pendingAction.toolName,
95
99
  args: editedArgs,
96
100
  toolCallId: cp.pendingAction.toolCallId,
101
+ ...requestGrantBinding((call, args) => skillGrantBindingMembers(call, args, servedSkills, SKILL_TOOL_NAME), cp.pendingAction, editedArgs),
97
102
  budget: editBudget,
98
103
  ...callFaceSeat(parkedCallFaceOf(cp.pendingAction)),
99
104
  ...(cp.state.handsCwd !== undefined ? { cwd: cp.state.handsCwd } : {}),
@@ -10,6 +10,7 @@ import { chainInstallationGaps, chainInstallationRefusal } from "./child-tree.js
10
10
  import { screeningInstallationsOf, unraisableGuardsOf } from "../mods/stations.js";
11
11
  import { refusePersistedToolNames, refuseRenamedDelegationMounts } from "./sub-agent-deny-lists.js";
12
12
  import { asResumeConfigRefusal } from "../mode-policy.js";
13
+ import { screenRecordedRunOrigin } from "../run-origin.js";
13
14
  export function resumeCheckpointScreen(input) {
14
15
  const { cp, resumeSignal, internals, tools, runner } = input;
15
16
  const { realApproval: realApprovalRow, face: faceRow, f012: f012Row } = CHECKPOINT_FEATURES;
@@ -91,6 +92,7 @@ export function resumeCheckpointScreen(input) {
91
92
  "(the checkpoint stays pending and is resumable without it).");
92
93
  }
93
94
  asResumeConfigRefusal("inheritedGate", () => refusePersistedToolNames((internals?.toolCeiling ?? undefined) === undefined ? cp.state.toolCeiling : undefined, cp.state.inheritedGate?.constraintChain, (internals?.ownToolLists ?? undefined) === undefined ? cp.state.ownToolLists : undefined));
95
+ asResumeConfigRefusal("inheritedGate", () => void screenRecordedRunOrigin(cp.state.runOrigin));
94
96
  asResumeConfigRefusal("taskConfig", () => refuseRenamedDelegationMounts(tools));
95
97
  if (cp.state.inheritedGate?.requiresParentConstraint === true) {
96
98
  const supplied = internals?.inheritedGate?.parentConstraints?.length ?? 0;
@@ -33,17 +33,17 @@ export function resumePolicyOutcome(input) {
33
33
  if (updatedInputRaw !== undefined) {
34
34
  const captured = capturedJsonOf(updatedInputRaw);
35
35
  if (!captured.ok)
36
- throw new CheckpointError("checkpoint.invalid_outcome", bindingRefusalOf(cp.pendingAction.kind === "tool_approval" ? cp.pendingAction.toolName : "the parked call", updatedInputRaw, captured.fault));
36
+ throw new CheckpointError("checkpoint.invalid_outcome", bindingRefusalOf(cp.pendingAction.kind === "tool_approval" ? cp.pendingAction.toolName : "the parked call", updatedInputRaw, captured.fault), { field: "updatedInput" });
37
37
  updatedInput = captured.value;
38
38
  }
39
39
  const decision = decide.decision;
40
40
  if (decision !== "allow" && decision !== "deny") {
41
- throw new CheckpointError("checkpoint.invalid_outcome", `resume decision "${describeSuppliedValue(decision)}" is outside the policy_ask domain — a decide is exactly "allow" or "deny"; refusing pre-CAS, the checkpoint stays pending`);
41
+ throw new CheckpointError("checkpoint.invalid_outcome", `resume decision "${describeSuppliedValue(decision)}" is outside the policy_ask domain — a decide is exactly "allow" or "deny"; refusing pre-CAS, the checkpoint stays pending`, { field: "decision" });
42
42
  }
43
43
  refuseSuppliedKeys(decide, REFUSED_DECIDE_KEYS);
44
44
  const hostDecision = captureHostDecision(cp, decide.hostDecision, "policy_ask", { word: decision, allows: decision === "allow" });
45
45
  const reason = decide.reason;
46
- assertOutcomeText(reason, "reason");
46
+ assertOutcomeText(reason, "reason", { field: "reason" });
47
47
  const feedback = decide.feedback;
48
48
  assertOutcomeText(feedback, "feedback", { field: "feedback" });
49
49
  plainPolicyOutcome = {
@@ -59,7 +59,7 @@ export function resumePolicyOutcome(input) {
59
59
  };
60
60
  refuseUnfitFeedback(plainPolicyOutcome);
61
61
  if (plainPolicyOutcome.decision === "deny" && plainPolicyOutcome.reason && sanitizeUntrustedText(plainPolicyOutcome.reason) !== plainPolicyOutcome.reason) {
62
- throw new CheckpointError("checkpoint.invalid_outcome", sentinelTagRefusal("resume deny/reject reason"));
62
+ throw new CheckpointError("checkpoint.invalid_outcome", sentinelTagRefusal("resume deny/reject reason"), { field: "reason" });
63
63
  }
64
64
  }
65
65
  if (plainPolicyOutcome !== undefined) {
@@ -74,7 +74,7 @@ export function resumePolicyOutcome(input) {
74
74
  }
75
75
  }
76
76
  else if (checkpointVersionOf(cp) >= CHECKPOINT_FEATURES.binding.version) {
77
- throw new CheckpointError("checkpoint.invalid_outcome", `resume of a binding-version (v${checkpointVersionOf(cp)}) checkpoint whose pending tool call has no persisted boundInputHash — refusing to resume an unbound binding-version checkpoint (corruption / downgrade guard)`);
77
+ throw new CheckpointError("checkpoint.invalid_outcome", `resume of a binding-version (v${checkpointVersionOf(cp)}) checkpoint whose pending tool call has no persisted boundInputHash — refusing to resume an unbound binding-version checkpoint (corruption / downgrade guard)`, { reason: "bound_input_hash_missing" });
78
78
  }
79
79
  if (cp.reopenReason === "env_failed") {
80
80
  if (cp.resolvedOutcome === undefined) {
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The person's account of a role seat the engine stands in for (`model.role_defaulted`).
3
+ *
4
+ * A role seat that names a model word the deployment's catalog does not hold supplies no model: the roles family reads it as an unset
5
+ * seat (`seatRead`, `src/core/roles.ts` — the tier default and the fallback chain follow; a subagent seat falls to the parent's model),
6
+ * so the run goes on instead of refusing at every prepare. That is only honest when it is said: this prepare-time phase names each such
7
+ * seat once per conversation, from the SAME role maps (the merged deployment-and-task map, and the deployment's own map that a delegated child's
8
+ * seat reads) and the SAME catalog the reads use (`unheldRoleSeats`), whether or not a
9
+ * later read of this leg reaches the seat. `default` (the main model's seat) and `classifier` (its own stand-in and line,
10
+ * `classifier.role_defaulted`) are never named here.
11
+ *
12
+ * Root legs only: a delegated child inherits the deployment's maps and would repeat the parent's line once per spawn.
13
+ */
14
+ import { type EngineNotice } from "../engine-notice.js";
15
+ import { type ModelRoles, type UnheldRoleSeat } from "../roles.js";
16
+ import type { Model } from "../types.js";
17
+ import { type AnnounceOnceLedger } from "./announce-once-ledger.js";
18
+ export declare const ROLE_DEFAULTED = "model.role_defaulted";
19
+ /** The notice for one unheld seat. `word` is bounded and quoted as every refusal of this family quotes it. */
20
+ export declare function roleDefaultedNotice(u: UnheldRoleSeat, ids: {
21
+ sessionId: string;
22
+ runId?: string;
23
+ }): EngineNotice;
24
+ export interface AnnounceRoleSeatsInput {
25
+ /** borrowed-readonly — the rebound spec's role map (the task's own seats). */
26
+ spec: {
27
+ roles?: ModelRoles;
28
+ };
29
+ /** borrowed-readonly — the deployment's maps and the catalog the reads ask, and the notice sink. */
30
+ deps: {
31
+ models?: Record<string, Model>;
32
+ roles?: ModelRoles;
33
+ onNotice?: (notice: EngineNotice) => void;
34
+ };
35
+ /** borrowed-readonly — the once-per-session ledger the notice's dedupe rides. */
36
+ onceLedger: Pick<AnnounceOnceLedger, "oncePerSession">;
37
+ /** borrowed-readonly — true for the root leg of a conversation; a delegated child names nothing (its parent already did). */
38
+ rootLeg: boolean;
39
+ sessionId: string;
40
+ runId: string | undefined;
41
+ }
42
+ /** The phase: one line per unheld seat per conversation (the dedupe key is the seat and the word, so a seat re-pointed at another
43
+ * unknown word is said again). */
44
+ export declare function announceRoleSeatsDefaulted(input: AnnounceRoleSeatsInput): void;
@@ -0,0 +1,40 @@
1
+ import { deliverEngineNotice } from "../engine-notice.js";
2
+ import { bindingShown, roleFallbackChain, unheldRoleSeats } from "../roles.js";
3
+ import { announceDigest } from "./announce-once-ledger.js";
4
+ export const ROLE_DEFAULTED = "model.role_defaulted";
5
+ const STANDS_IN = {
6
+ summarize: "the compaction summary runs on the conversation's own model (or the tier default for that role, when tiers are declared)",
7
+ subagent: "child runs go on the parent run's model",
8
+ verifier: "the verification gate runs on the main model",
9
+ consolidate: "memory consolidation runs on the summarize role's model, and is refused when that supplies none",
10
+ };
11
+ export function roleDefaultedNotice(u, ids) {
12
+ const shown = bindingShown(u.word);
13
+ return {
14
+ code: ROLE_DEFAULTED,
15
+ message: `${u.seat} names the model ${shown}, which this deployment's model catalog does not hold, so the seat is read as an unset one: ${STANDS_IN[u.role] ?? "its fallback chain decides"}. ` +
16
+ `Declare ${shown} in the catalog (RunnerDeps.models) or correct the seat. Said once per conversation for this seat.`,
17
+ detail: {
18
+ seat: u.seat,
19
+ role: u.role,
20
+ model: u.word.length > 80 ? `${u.word.slice(0, 80)}…` : u.word,
21
+ reason: "unknown_model_ref",
22
+ fallback: [...roleFallbackChain(u.role)],
23
+ sessionId: ids.sessionId,
24
+ ...(ids.runId !== undefined ? { runId: ids.runId } : {}),
25
+ },
26
+ sessionId: ids.sessionId,
27
+ };
28
+ }
29
+ export function announceRoleSeatsDefaulted(input) {
30
+ if (!input.rootLeg)
31
+ return;
32
+ const seen = new Set();
33
+ for (const u of [...unheldRoleSeats({}, input.deps), ...unheldRoleSeats(input.spec, input.deps)]) {
34
+ const key = `${u.seat}\n${u.word}`;
35
+ if (seen.has(key))
36
+ continue;
37
+ seen.add(key);
38
+ input.onceLedger.oncePerSession(announceDigest(ROLE_DEFAULTED, key), () => deliverEngineNotice(input.deps.onNotice, roleDefaultedNotice(u, { sessionId: input.sessionId, ...(input.runId !== undefined ? { runId: input.runId } : {}) })));
39
+ }
40
+ }
@@ -19,6 +19,8 @@ export function runBrainSinks(input) {
19
19
  ...(s.retryAtMs !== undefined ? { retryAtMs: s.retryAtMs } : {}),
20
20
  ...(s.elapsedMs !== undefined ? { elapsedMs: s.elapsedMs } : {}),
21
21
  ...(s.timeoutMs !== undefined ? { timeoutMs: s.timeoutMs } : {}),
22
+ ...(s.waitSegment !== undefined ? { waitSegment: s.waitSegment } : {}),
23
+ ...(s.sleptMs !== undefined ? { sleptMs: s.sleptMs } : {}),
22
24
  ...(s.attempt !== undefined ? { attempt: s.attempt } : {}),
23
25
  ...(s.maxRetries !== undefined ? { maxRetries: s.maxRetries } : {}),
24
26
  ...(s.errClass !== undefined ? { errClass: s.errClass } : {}),
@@ -34,13 +34,12 @@ export interface RunHarnessHandlersResult {
34
34
  type: "tool_execution_end";
35
35
  }>) => void;
36
36
  onTurnEnd: () => void;
37
- /** The single workspace_changed mint (cwd diff vs the closure's dedupe state); the run body
37
+ /** The leg's workspace-frame observation (`Prepared.workspaceFrame.observe`); the run body
38
38
  * calls it after a resume's approved-call resolution, which bypasses onToolEnd. */
39
39
  announceWorkspaceMove: () => void;
40
40
  }
41
41
  /** R5 抽取:runLocked 的五个 harness 事件处理器(onMessageUpdate/onMessageEnd/
42
42
  * onToolStart/onToolEnd/onTurnEnd,~530 行)整块搬迁。正文逐字;唯一字面变化 = this.deps.onError →
43
- * deps.runnerHooks.onError(1 处)。`lastWorkspaceCwd` 是纯 R5 局部(读写全在 onToolEnd 内,零段外
44
- * 读者),声明随迁进工厂体——调用点放在原声明位之后,初值 `prepared.cwdRef?.current` 的求值时机不变
45
- * (中间只有声明无执行)。*/
43
+ * deps.runnerHooks.onError(1 处)。工作区帧的去重状态住在腿的帧座(`Prepared.workspaceFrame`),
44
+ * 工厂体不持有、也不在调用时读 cwd。*/
46
45
  export declare function createHarnessHandlers(input: RunHarnessHandlersInput): RunHarnessHandlersResult;
@@ -33,14 +33,7 @@ export function createHarnessHandlers(input) {
33
33
  const label = toolLabels.get(e.toolName);
34
34
  return { toolCallId: e.toolCallId, spelledName: e.toolName, wireName: rosterToolName(prepared.toolRosterDeltas.current, e.toolName), ...(label !== undefined ? { label } : {}), args: e.args, ...requesterOf(prepared.modBus, e.toolCallId) };
35
35
  };
36
- let lastWorkspaceCwd = prepared.cwdRef?.current;
37
- const announceWorkspaceMove = () => {
38
- const cwdNow = prepared.cwdRef?.current;
39
- if (cwdNow !== undefined && cwdNow !== lastWorkspaceCwd) {
40
- lastWorkspaceCwd = cwdNow;
41
- queue.push({ type: "workspace_changed", cwd: cwdNow, ...ident() });
42
- }
43
- };
36
+ const announceWorkspaceMove = () => prepared.workspaceFrame.observe();
44
37
  const onMessageUpdate = (event) => {
45
38
  const ev = event.assistantMessageEvent;
46
39
  if (rs.turn.callStartAt === undefined)