@parcha/agentrun-serve 0.1.0-beta.34 → 0.1.0-beta.36

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 (450) hide show
  1. package/CHANGELOG.md +263 -0
  2. package/README.md +339 -179
  3. package/dist/adapters.d.ts +15 -2
  4. package/dist/adapters.js +34 -2
  5. package/dist/agent-rows.d.ts +3 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +25 -5
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +90 -8
  13. package/dist/archil-settings.js +150 -14
  14. package/dist/attach-images.d.ts +15 -0
  15. package/dist/attach-images.js +59 -0
  16. package/dist/background.d.ts +0 -6
  17. package/dist/background.js +0 -28
  18. package/dist/bash-read-only.d.ts +13 -0
  19. package/dist/bash-read-only.js +77 -0
  20. package/dist/box-image.d.ts +1 -97
  21. package/dist/box-image.js +4 -284
  22. package/dist/box-paths.d.ts +2 -7
  23. package/dist/box-paths.js +7 -13
  24. package/dist/box-settings.d.ts +0 -11
  25. package/dist/box-settings.js +4 -29
  26. package/dist/browser-commands.js +1 -1
  27. package/dist/browser-computer.d.ts +47 -3
  28. package/dist/browser-computer.js +286 -18
  29. package/dist/browser-cost.d.ts +2 -2
  30. package/dist/browser-cost.js +6 -4
  31. package/dist/browser-person.d.ts +19 -2
  32. package/dist/browser-person.js +55 -6
  33. package/dist/browser-wait-ended.d.ts +23 -0
  34. package/dist/browser-wait-ended.js +42 -0
  35. package/dist/cap.d.ts +19 -44
  36. package/dist/cap.js +31 -77
  37. package/dist/cli.js +36 -27
  38. package/dist/computer-keys.d.ts +20 -10
  39. package/dist/computer-keys.js +36 -57
  40. package/dist/computer-routes.d.ts +1 -4
  41. package/dist/computer-routes.js +3 -5
  42. package/dist/computer-setting.d.ts +8 -5
  43. package/dist/computer-setting.js +91 -26
  44. package/dist/computer-view.d.ts +11 -2
  45. package/dist/computer-view.js +2 -1
  46. package/dist/computers.d.ts +54 -8
  47. package/dist/computers.js +101 -22
  48. package/dist/console/assets/index-BI4Byidu.js +550 -0
  49. package/dist/console/assets/index-C19gUF2n.css +1 -0
  50. package/dist/console/index.html +2 -2
  51. package/dist/content-filter.d.ts +7 -0
  52. package/dist/content-filter.js +23 -0
  53. package/dist/decision-cap.d.ts +7 -29
  54. package/dist/decision-cap.js +3 -94
  55. package/dist/docker-daemon.d.ts +2 -2
  56. package/dist/docker-daemon.js +2 -2
  57. package/dist/errors.d.ts +1 -0
  58. package/dist/errors.js +8 -5
  59. package/dist/explain.js +3 -1
  60. package/dist/faux-computers.js +4 -0
  61. package/dist/files.d.ts +1 -9
  62. package/dist/files.js +1 -9
  63. package/dist/github-connection.js +25 -7
  64. package/dist/github-faux.d.ts +26 -0
  65. package/dist/github-faux.js +76 -0
  66. package/dist/github.d.ts +28 -4
  67. package/dist/github.js +46 -10
  68. package/dist/gpu-words.d.ts +14 -0
  69. package/dist/gpu-words.js +21 -0
  70. package/dist/graph-served.d.ts +5 -3
  71. package/dist/graph-served.js +14 -6
  72. package/dist/graph-view.d.ts +2 -0
  73. package/dist/graph-view.js +29 -2
  74. package/dist/handed-values.d.ts +1 -1
  75. package/dist/handed-values.js +1 -1
  76. package/dist/harness-install.d.ts +60 -3
  77. package/dist/harness-install.js +322 -34
  78. package/dist/harness-opencode/harness.js +0 -1
  79. package/dist/harness-opencode/host/policy.js +2 -2
  80. package/dist/harness.js +1 -1
  81. package/dist/host-tools.d.ts +8 -9
  82. package/dist/host-tools.js +7 -7
  83. package/dist/index.d.ts +2 -3
  84. package/dist/index.js +2 -2
  85. package/dist/key-refusal.d.ts +1 -1
  86. package/dist/key-refusal.js +2 -2
  87. package/dist/learn/check.d.ts +10 -2
  88. package/dist/learn/check.js +126 -8
  89. package/dist/learn/commit.d.ts +40 -6
  90. package/dist/learn/commit.js +164 -20
  91. package/dist/learn/folder.d.ts +11 -3
  92. package/dist/learn/folder.js +40 -16
  93. package/dist/learn/grade.d.ts +22 -2
  94. package/dist/learn/grade.js +127 -19
  95. package/dist/learn/index.d.ts +2 -2
  96. package/dist/learn/index.js +2 -2
  97. package/dist/learn/learning.sh +11 -13
  98. package/dist/learn/notes.d.ts +17 -3
  99. package/dist/learn/notes.js +19 -6
  100. package/dist/learn/reflect.d.ts +5 -2
  101. package/dist/learn/reflect.js +48 -32
  102. package/dist/learn/skills.d.ts +52 -5
  103. package/dist/learn/skills.js +104 -21
  104. package/dist/learned-nodes.d.ts +18 -0
  105. package/dist/learned-nodes.js +8 -0
  106. package/dist/learned-workflow.d.ts +27 -13
  107. package/dist/learned-workflow.js +110 -38
  108. package/dist/learning-cost.d.ts +79 -0
  109. package/dist/learning-cost.js +69 -0
  110. package/dist/learning-routes.d.ts +48 -2
  111. package/dist/learning-routes.js +99 -28
  112. package/dist/learning-run.d.ts +7 -5
  113. package/dist/learning-run.js +9 -6
  114. package/dist/learning-words.d.ts +3 -0
  115. package/dist/learning-words.js +6 -2
  116. package/dist/learning.d.ts +13 -28
  117. package/dist/learning.js +4 -18
  118. package/dist/llm.d.ts +4 -1
  119. package/dist/llm.js +4 -2
  120. package/dist/mcp-gateway.d.ts +6 -0
  121. package/dist/mcp-gateway.js +11 -1
  122. package/dist/mcp-probe.d.ts +8 -1
  123. package/dist/mcp-probe.js +62 -20
  124. package/dist/mcp-secret-writes.js +4 -0
  125. package/dist/mcp-servers-store.d.ts +12 -12
  126. package/dist/mcp-servers-store.js +8 -3
  127. package/dist/model.d.ts +8 -5
  128. package/dist/model.js +14 -6
  129. package/dist/openapi.d.ts +2 -0
  130. package/dist/openapi.js +236 -55
  131. package/dist/owner.d.ts +0 -1
  132. package/dist/owner.js +0 -2
  133. package/dist/pause.d.ts +2 -19
  134. package/dist/pause.js +5 -74
  135. package/dist/place-offers.d.ts +97 -0
  136. package/dist/place-offers.js +206 -0
  137. package/dist/place.d.ts +9 -13
  138. package/dist/place.js +22 -32
  139. package/dist/port-models.d.ts +12 -4
  140. package/dist/port-models.js +31 -9
  141. package/dist/print.d.ts +1 -8
  142. package/dist/print.js +1 -14
  143. package/dist/propose.d.ts +3 -0
  144. package/dist/propose.js +25 -19
  145. package/dist/run-cut.d.ts +5 -0
  146. package/dist/run-cut.js +19 -0
  147. package/dist/run-db.js +3 -3
  148. package/dist/run-launch.d.ts +18 -3
  149. package/dist/run-launch.js +11 -5
  150. package/dist/run-learning-served.d.ts +12 -1
  151. package/dist/run-manifest.d.ts +2 -2
  152. package/dist/run-manifest.js +2 -2
  153. package/dist/run-reads-over-store.d.ts +4 -2
  154. package/dist/run-reads-over-store.js +10 -8
  155. package/dist/run-secrets.js +3 -3
  156. package/dist/run-timeline-served.js +60 -38
  157. package/dist/run-view.d.ts +35 -16
  158. package/dist/run-view.js +64 -35
  159. package/dist/runnable.d.ts +6 -3
  160. package/dist/runnable.js +20 -4
  161. package/dist/runner/adapter-loop.d.ts +46 -5
  162. package/dist/runner/adapter-loop.js +381 -56
  163. package/dist/runner/adapter-run-spec.d.ts +46 -4
  164. package/dist/runner/adapter-run-spec.js +200 -45
  165. package/dist/runner/adapters/pi.d.ts +39 -3
  166. package/dist/runner/adapters/pi.js +124 -29
  167. package/dist/runner/beside.d.ts +8 -0
  168. package/dist/runner/beside.js +24 -2
  169. package/dist/runner/claim-secrets.d.ts +6 -0
  170. package/dist/runner/claim-secrets.js +15 -1
  171. package/dist/runner/cli-run-spec.d.ts +10 -0
  172. package/dist/runner/cli-run-spec.js +207 -64
  173. package/dist/runner/commands.d.ts +5 -1
  174. package/dist/runner/commands.js +3 -3
  175. package/dist/runner/conformance/harness.d.ts +1 -1
  176. package/dist/runner/conformance/harness.js +13 -10
  177. package/dist/runner/github-app.d.ts +7 -2
  178. package/dist/runner/github-app.js +46 -15
  179. package/dist/runner/harness-loops.d.ts +6 -1
  180. package/dist/runner/harness-loops.js +24 -1
  181. package/dist/runner/journal-kinds.d.ts +53 -7
  182. package/dist/runner/journal-kinds.js +29 -1
  183. package/dist/runner/learning-end.d.ts +15 -0
  184. package/dist/runner/learning-end.js +113 -20
  185. package/dist/runner/learning-factory.js +6 -2
  186. package/dist/runner/learning-loop.d.ts +75 -1
  187. package/dist/runner/learning-loop.js +215 -22
  188. package/dist/runner/learning-seed.d.ts +8 -0
  189. package/dist/runner/learning-seed.js +7 -1
  190. package/dist/runner/loop-contract.d.ts +12 -0
  191. package/dist/runner/loop-contract.js +6 -0
  192. package/dist/runner/loop.d.ts +5 -1
  193. package/dist/runner/loop.js +20 -0
  194. package/dist/runner/main.d.ts +9 -4
  195. package/dist/runner/main.js +38 -13
  196. package/dist/runner/mcp-claim.d.ts +7 -0
  197. package/dist/runner/mcp-claim.js +35 -2
  198. package/dist/runner/mcp-github.d.ts +15 -4
  199. package/dist/runner/mcp-github.js +55 -11
  200. package/dist/runner/mcp-run.d.ts +2 -0
  201. package/dist/runner/mcp-run.js +2 -0
  202. package/dist/runner/metrics.d.ts +18 -1
  203. package/dist/runner/metrics.js +81 -1
  204. package/dist/runner/model-route.d.ts +6 -0
  205. package/dist/runner/model-route.js +5 -2
  206. package/dist/runner/pr-checkout.d.ts +59 -0
  207. package/dist/runner/pr-checkout.js +176 -0
  208. package/dist/runner/reflect-hook.d.ts +1 -0
  209. package/dist/runner/reflect-hook.js +3 -3
  210. package/dist/runner/runner.js +136 -19
  211. package/dist/runner/spec-holds.d.ts +13 -3
  212. package/dist/runner/spec-holds.js +13 -10
  213. package/dist/runner/store-port.d.ts +4 -1
  214. package/dist/runner/store-secrets.js +17 -1
  215. package/dist/runner/subagent.d.ts +44 -0
  216. package/dist/runner/subagent.js +188 -0
  217. package/dist/runner/workflow-host.d.ts +25 -4
  218. package/dist/runner/workflow-host.js +26 -4
  219. package/dist/runner/workflow-loop.d.ts +9 -3
  220. package/dist/runner/workflow-loop.js +17 -10
  221. package/dist/runner/workflow-spec.d.ts +28 -13
  222. package/dist/runner/workflow-spec.js +247 -102
  223. package/dist/runs-over-store.d.ts +18 -7
  224. package/dist/runs-over-store.js +149 -31
  225. package/dist/seal-key.d.ts +0 -2
  226. package/dist/seal-key.js +0 -2
  227. package/dist/sealing.js +1 -2
  228. package/dist/secret-cut.d.ts +1 -1
  229. package/dist/secret-cut.js +1 -1
  230. package/dist/server-lock.js +4 -5
  231. package/dist/server.d.ts +49 -63
  232. package/dist/server.js +429 -230
  233. package/dist/stop-signals.d.ts +4 -2
  234. package/dist/stop-signals.js +5 -3
  235. package/dist/store/agent-body.d.ts +14 -3
  236. package/dist/store/agent-body.js +22 -8
  237. package/dist/store/deadline.d.ts +18 -0
  238. package/dist/store/deadline.js +49 -0
  239. package/dist/store/index.d.ts +3 -3
  240. package/dist/store/index.js +2 -2
  241. package/dist/store/journal/storage.js +2 -1
  242. package/dist/store/postgres/connection.d.ts +4 -0
  243. package/dist/store/postgres/connection.js +64 -13
  244. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  245. package/dist/store/schema.d.ts +2 -1
  246. package/dist/store/schema.js +11 -8
  247. package/dist/store/seal.d.ts +13 -0
  248. package/dist/store/seal.js +19 -0
  249. package/dist/store/sqlite/connection.d.ts +5 -0
  250. package/dist/store/sqlite/connection.js +88 -82
  251. package/dist/store/sqlite/run-patch.d.ts +18 -2
  252. package/dist/store/sqlite/run-patch.js +31 -2
  253. package/dist/store/sqlite/store.js +65 -11
  254. package/dist/store/store.d.ts +62 -12
  255. package/dist/store/store.js +22 -1
  256. package/dist/store-reads/analytics.js +3 -2
  257. package/dist/store-reads/cap.d.ts +1 -3
  258. package/dist/store-reads/cap.js +8 -6
  259. package/dist/store-reads/decisions.d.ts +2 -2
  260. package/dist/store-reads/decisions.js +3 -6
  261. package/dist/store-reads/journal.js +83 -15
  262. package/dist/store-reads/learning.d.ts +73 -3
  263. package/dist/store-reads/learning.js +232 -9
  264. package/dist/store-reads/runs.d.ts +6 -4
  265. package/dist/store-reads/runs.js +17 -10
  266. package/dist/store-reads/stats.js +5 -1
  267. package/dist/store-view.d.ts +15 -1
  268. package/dist/store-view.js +88 -29
  269. package/dist/template-eval.js +2 -1
  270. package/dist/templates.d.ts +73 -4
  271. package/dist/templates.js +113 -23
  272. package/dist/timeline/timeline.d.ts +11 -1
  273. package/dist/timeline/timeline.js +19 -4
  274. package/dist/tool-blurbs.js +1 -0
  275. package/dist/tool-budget.d.ts +26 -0
  276. package/dist/tool-budget.js +56 -0
  277. package/dist/tool-gate.d.ts +13 -3
  278. package/dist/tool-gate.js +15 -7
  279. package/dist/tool-plane.d.ts +42 -29
  280. package/dist/tool-plane.js +64 -27
  281. package/dist/tools.d.ts +53 -39
  282. package/dist/tools.js +174 -79
  283. package/dist/trigger-signatures.d.ts +1 -0
  284. package/dist/trigger-signatures.js +3 -1
  285. package/dist/triggers.d.ts +3 -3
  286. package/dist/triggers.js +2 -2
  287. package/dist/turn-end.d.ts +0 -3
  288. package/dist/turn-end.js +0 -3
  289. package/dist/uploads.d.ts +28 -5
  290. package/dist/uploads.js +82 -9
  291. package/dist/usage-lines.d.ts +1 -1
  292. package/dist/usage.d.ts +1 -47
  293. package/dist/usage.js +3 -82
  294. package/dist/validate.d.ts +8 -0
  295. package/dist/validate.js +40 -3
  296. package/dist/webhooks.d.ts +2 -1
  297. package/dist/webhooks.js +5 -2
  298. package/dist/workflow/decision-recovery.d.ts +23 -0
  299. package/dist/workflow/decision-recovery.js +80 -0
  300. package/dist/workflow/decisions.d.ts +134 -0
  301. package/dist/workflow/decisions.js +46 -0
  302. package/dist/workflow/host-session.d.ts +5 -0
  303. package/dist/workflow/host-session.js +85 -0
  304. package/dist/workflow/host-tools.d.ts +3 -0
  305. package/dist/workflow/host-tools.js +3 -0
  306. package/dist/workflow/node-runner.d.ts +112 -0
  307. package/dist/workflow/node-runner.js +270 -0
  308. package/dist/workflow/node.d.ts +88 -0
  309. package/dist/workflow/node.js +99 -0
  310. package/dist/workflow/operator-error.d.ts +4 -0
  311. package/dist/workflow/operator-error.js +4 -0
  312. package/dist/workflow/pi-versions.d.ts +9 -0
  313. package/dist/workflow/pi-versions.js +8 -0
  314. package/dist/workflow/readers.d.ts +36 -0
  315. package/dist/workflow/readers.js +145 -0
  316. package/dist/workflow/record-file.d.ts +10 -0
  317. package/dist/workflow/record-file.js +56 -0
  318. package/dist/workflow/record-tool.d.ts +76 -0
  319. package/dist/workflow/record-tool.js +126 -0
  320. package/dist/workflow/record.d.ts +151 -0
  321. package/dist/workflow/record.js +401 -0
  322. package/dist/workflow/run-error.d.ts +16 -0
  323. package/dist/workflow/run-error.js +26 -0
  324. package/dist/workflow/runner.d.ts +6 -0
  325. package/dist/workflow/runner.js +240 -0
  326. package/dist/workflow/store.d.ts +23 -0
  327. package/dist/workflow/store.js +242 -0
  328. package/dist/workflow/task.d.ts +133 -0
  329. package/dist/workflow/task.js +411 -0
  330. package/dist/workflow/thinking.d.ts +3 -0
  331. package/dist/workflow/thinking.js +7 -0
  332. package/dist/workflow/tool-context.d.ts +21 -0
  333. package/dist/workflow/tool-context.js +13 -0
  334. package/dist/workflow/types.d.ts +126 -0
  335. package/dist/workflow/types.js +1 -0
  336. package/dist/workflow/wal.d.ts +11 -0
  337. package/dist/workflow/wal.js +106 -0
  338. package/dist/workflow-run.d.ts +1 -1
  339. package/dist/workspace/agent-computer.d.ts +137 -0
  340. package/dist/workspace/agent-computer.js +292 -0
  341. package/dist/workspace/archil-claim.d.ts +13 -2
  342. package/dist/workspace/archil-claim.js +22 -13
  343. package/dist/workspace/archil-disk.d.ts +10 -1
  344. package/dist/workspace/archil-disk.js +4 -0
  345. package/dist/workspace/archil-disks.d.ts +49 -0
  346. package/dist/workspace/archil-disks.js +185 -0
  347. package/dist/workspace/archil-exec.d.ts +12 -2
  348. package/dist/workspace/archil-exec.js +18 -3
  349. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  350. package/dist/workspace/archil-mount-credential.js +13 -4
  351. package/dist/workspace/archil.d.ts +2 -2
  352. package/dist/workspace/archil.js +25 -5
  353. package/dist/workspace/attach.js +2 -0
  354. package/dist/workspace/computer-deps.d.ts +18 -11
  355. package/dist/workspace/computer-deps.js +64 -40
  356. package/dist/workspace/computer-for-claim.d.ts +47 -9
  357. package/dist/workspace/computer-for-claim.js +236 -24
  358. package/dist/workspace/computer-janitor.d.ts +3 -2
  359. package/dist/workspace/computer-janitor.js +43 -9
  360. package/dist/workspace/computer-ledger.d.ts +3 -8
  361. package/dist/workspace/computer-ledger.js +7 -3
  362. package/dist/workspace/computer-providers.d.ts +5 -3
  363. package/dist/workspace/computer-providers.js +11 -9
  364. package/dist/workspace/hands.d.ts +5 -2
  365. package/dist/workspace/hands.js +4 -3
  366. package/dist/workspace/index.d.ts +5 -4
  367. package/dist/workspace/index.js +2 -1
  368. package/dist/workspace/local.d.ts +3 -0
  369. package/dist/workspace/local.js +9 -0
  370. package/dist/workspace/paths.js +3 -2
  371. package/dist/workspace/pi-env.d.ts +4 -0
  372. package/dist/workspace/pi-env.js +3 -2
  373. package/dist/workspace/resolve-computer.d.ts +48 -12
  374. package/dist/workspace/resolve-computer.js +88 -19
  375. package/dist/workspace/run-disk.d.ts +34 -0
  376. package/dist/workspace/run-disk.js +91 -0
  377. package/dist/workspace/run-tools.d.ts +6 -4
  378. package/dist/workspace/run-tools.js +17 -9
  379. package/dist/workspace/server-run-workspace.d.ts +3 -2
  380. package/dist/workspace/server-run-workspace.js +17 -4
  381. package/dist/workspace/workspace.d.ts +5 -0
  382. package/dist/workspace.d.ts +0 -3
  383. package/dist/workspace.js +2 -15
  384. package/package.json +11 -16
  385. package/skills/agentrun-serve/SKILL.md +1 -1
  386. package/templates/README.md +11 -8
  387. package/templates/code-review/agent.md +27 -11
  388. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  389. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  390. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  391. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  392. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  393. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  394. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  395. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  396. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  397. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  398. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  399. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  400. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  401. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  402. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  404. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  405. package/templates/code-review/evals/re-review/prompt.md +1 -1
  406. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  407. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  408. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  409. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  410. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  411. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  412. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  413. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  414. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  415. package/templates/code-review/findings.schema.json +131 -27
  416. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  417. package/templates/code-review/skills/review/DEEP.md +130 -0
  418. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  419. package/templates/code-review/skills/review/SKILL.md +104 -154
  420. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  421. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  422. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  423. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  424. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  425. package/templates/release-notes/agent.md +11 -0
  426. package/dist/box/record.d.ts +0 -6
  427. package/dist/box/record.js +0 -41
  428. package/dist/box/sweep.d.ts +0 -53
  429. package/dist/box/sweep.js +0 -193
  430. package/dist/box-egress-vm.d.ts +0 -118
  431. package/dist/box-egress-vm.js +0 -354
  432. package/dist/box-egress.d.ts +0 -105
  433. package/dist/box-egress.js +0 -256
  434. package/dist/box-relay-vm.d.ts +0 -84
  435. package/dist/box-relay-vm.js +0 -437
  436. package/dist/box-relay.d.ts +0 -36
  437. package/dist/box-relay.js +0 -207
  438. package/dist/boxes.d.ts +0 -109
  439. package/dist/boxes.js +0 -249
  440. package/dist/budget.d.ts +0 -76
  441. package/dist/budget.js +0 -204
  442. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  443. package/dist/console/assets/index-opTN5Naq.css +0 -1
  444. package/dist/daytona-api.d.ts +0 -10
  445. package/dist/daytona-api.js +0 -20
  446. package/dist/egress-proxy.d.ts +0 -45
  447. package/dist/egress-proxy.js +0 -416
  448. package/dist/egress-table.d.ts +0 -24
  449. package/dist/egress-table.js +0 -165
  450. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -2,25 +2,33 @@ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/conte
2
2
  import { createModels } from "@earendil-works/pi-ai/models";
3
3
  import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
4
4
  import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
5
- import { ASK_PERSON_WAITING, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
- import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "../timeline/index.js";
7
- import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
8
- import { deniedText as setToDenyText, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "../refusal-words.js";
5
+ import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
+ import { endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, RUN_RESUMED } from "../timeline/index.js";
7
+ import { raiseFollowUpId } from "../run-view.js";
8
+ /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
9
+ * takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks whether the run's root ends
10
+ * on its end (a fresh reopen). */
11
+ const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold"]);
12
+ /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
13
+ const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
14
+ import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
15
+ import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
9
16
  import { ADAPTER_API } from "../turn-end.js";
10
17
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
11
- import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
18
+ import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
12
19
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
13
20
  import { isComputerCommand, journalHold } from "./computer-journal.js";
14
21
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
15
22
  import { journalSessions } from "./sessions.js";
16
- import { DECISION_SESSION, overCapOf, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
17
- import { portModels } from "../port-models.js";
23
+ import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
24
+ import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
18
25
  import { bookedIn } from "../paid-calls.js";
19
26
  import { withHostCalls } from "../host-calls.js";
20
27
  import { sideEffect } from "./side-effects.js";
21
28
  import { McpClaimRefused } from "./mcp-claim.js";
22
29
  import { Fenced } from "../store/index.js";
23
30
  import { parkedFollowUp } from "./mcp-run.js";
31
+ import { budgetOf, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
24
32
  /** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
25
33
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
26
34
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
@@ -51,8 +59,34 @@ export function agentConversation(record) {
51
59
  * before the spec's lifecycle was known). Set in the root's creating commit, cleared in the commit that makes them, so a
52
60
  * claim lost in between leaves them to the next claim. */
53
61
  const RootWritesOwed = defineDoc({ kind: "agentrun.root-writes-owed", version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ owed: false }), checkpointWhen: () => false });
62
+ /** pi's retry of a model request that failed in a way it retries (a provider's 429, overload or 5xx, a dropped connection,
63
+ * a stream cut mid-answer): up to 8 more attempts, 2s doubling to at most 30s apart (about two and a half minutes in all),
64
+ * so a provider's capacity outage of a minute or two is waited out, not the run's end. Each wait is the harness's own
65
+ * durable sleep; a subagent's conversation runs on the same settings. */
66
+ export const MODEL_RETRY = { enabled: true, maxRetries: 8, baseDelayMs: 2_000, maxAgentDelayMs: 30_000 };
67
+ /** pi-ai's retries inside one attempt, of a request the provider refused before any output (a 429 or a 5xx, through the
68
+ * session's proxy, which passes on its retry-after): after the wait the provider asked for, up to 30s, else its own short
69
+ * backoff. Each is a new request through the proxy, judged by the cap and booked as any other: a refusal books nothing. */
70
+ export const MODEL_STREAM = { maxRetries: 2, maxRetryDelayMs: 30_000 };
54
71
  /** The most of a harness's own turn error a failed run's summary keeps. */
55
72
  const TURN_ERROR_MAX = 500;
73
+ /** A paid call's refusal an earlier claim kept (KINDS.pausePending) whose pause never landed: the newest one with no
74
+ * pause (KINDS.budget), no end and no park on a person's question (KINDS.personAsked: the turn ended on the ask with no
75
+ * next request, so the refusal is spent, and the person's answer is no retry of the call) after it. Undefined when there
76
+ * is none. */
77
+ export function pendingPauseOf(entries) {
78
+ for (let at = entries.length - 1; at >= 0; at--) {
79
+ const entry = entries[at];
80
+ if (entry.kind === KINDS.budget || entry.kind === KINDS.end || entry.kind === KINDS.personAsked)
81
+ return undefined;
82
+ // A kept refusal, or none: a drop kept as null (the call would since fit, or the turn ended on a question).
83
+ if (entry.kind === KINDS.pausePending)
84
+ return (entry.data ?? undefined);
85
+ }
86
+ return undefined;
87
+ }
88
+ /** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
89
+ const DELIVER_NOW_MS = 5_000;
56
90
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
57
91
  const cutWhole = (text, max) => {
58
92
  const cut = text.slice(0, max);
@@ -122,7 +156,7 @@ const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forG
122
156
  * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
123
157
  * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
124
158
  * message's timestamp: the Timeline dates its rows by them. */
125
- async function openCliRecord(harness, journal, context, now) {
159
+ async function openCliRecord(harness, journal, context, now, cwd) {
126
160
  const root = await harness.root(context);
127
161
  const append = async (kind, data) => {
128
162
  await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
@@ -137,6 +171,8 @@ async function openCliRecord(harness, journal, context, now) {
137
171
  // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
138
172
  const sending = new Set();
139
173
  let personWritten = false;
174
+ // The request ids of the follow-ups written (followUp): each is written once.
175
+ const followUps = new Set();
140
176
  // Each end-of-run turn's prompt the record wrote as it asked the turn, by its request id: a turn asked again (a later
141
177
  // claim, after a crash in the turn) reuses it, never writes a second.
142
178
  const askedAt = new Map();
@@ -158,6 +194,8 @@ async function openCliRecord(harness, journal, context, now) {
158
194
  started.set(data.callId, true);
159
195
  else if ((entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
160
196
  personWritten = true;
197
+ if ((entry.kind === KINDS.message || entry.kind === KINDS.input) && typeof data.requestId === "string")
198
+ followUps.add(data.requestId);
161
199
  }
162
200
  for (const [callId, ended] of started) {
163
201
  if (ended || (parked.has(callId) && !sent.has(callId)))
@@ -210,6 +248,16 @@ async function openCliRecord(harness, journal, context, now) {
210
248
  await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
211
249
  personWritten = true;
212
250
  }),
251
+ followUp: (input, requestId, origin) => inTurn(async () => {
252
+ if (followUps.has(requestId))
253
+ return;
254
+ if (origin)
255
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin, requestId }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
256
+ else
257
+ await append(KINDS.message, { role: "person", text: input, requestId });
258
+ followUps.add(requestId);
259
+ personWritten = true;
260
+ }),
213
261
  message: (input, origin) => inTurn(async () => {
214
262
  if (origin)
215
263
  await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
@@ -239,16 +287,16 @@ async function openCliRecord(harness, journal, context, now) {
239
287
  }
240
288
  return;
241
289
  }
242
- await append(KINDS.callStart, { callId, tool, input, replaySafe });
290
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
243
291
  started.set(callId, false);
244
292
  });
245
293
  },
246
- async park(callId, tool, input, replaySafe) {
294
+ async park(callId, tool, input, replaySafe, bridge) {
247
295
  await flushText();
248
296
  await inTurn(async () => {
249
297
  if (started.has(callId))
250
298
  return;
251
- await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true });
299
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(bridge ? { bridge } : {}), ...(cwd ? { cwd } : {}) });
252
300
  started.set(callId, false);
253
301
  parked.add(callId);
254
302
  });
@@ -321,6 +369,8 @@ export function createAdapterLoop(spec, options = {}) {
321
369
  }
322
370
  function adapterLoop(specOf, options, deps) {
323
371
  const restartLimit = options.restartLimit ?? DEFAULT_RESTART_LIMIT;
372
+ const retry = options.retry ?? MODEL_RETRY;
373
+ const stream = options.stream ?? MODEL_STREAM;
324
374
  const now = options.now ?? Date.now;
325
375
  /** The gate's clock as main's card says a time: ISO. */
326
376
  const isoNow = () => new Date(now()).toISOString();
@@ -390,6 +440,10 @@ function adapterLoop(specOf, options, deps) {
390
440
  * Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
391
441
  * the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
392
442
  let reopen;
443
+ /** A reopen of a run whose session is still new (a person stopped it before its first input was sent): resolved once the
444
+ * person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
445
+ * late the runner hands the message over. */
446
+ let firstInputPlaced;
393
447
  /** The tool hosts' holds while the run waits in its claim on the person's answer (HostLifecycle.personWait): dropped
394
448
  * once the wait is over, whichever way it ends. */
395
449
  let waitHolds = [];
@@ -404,6 +458,11 @@ function adapterLoop(specOf, options, deps) {
404
458
  * it (sendAfterTurn) (#2174: refused here, a message the API had accepted was lost). Kept across a pass's restart; a row still here
405
459
  * when the claim ends is untaken, so the run's next claim takes it again, or the run's end refuses it in the end's words. */
406
460
  const afterTurn = [];
461
+ /** The request ids of the messages placed as steers into a turn in flight (a harness that steers: pi), in order. pi
462
+ * answers one in the turn it steered, or, placed as that turn answered, in a run of its own right after it: the turn's
463
+ * end waits on each one's submission (turnOfRequest) before the run may end, so the run never reads completed with a
464
+ * message it took still unanswered, and its session is never closed under that answer. */
465
+ const steeredIn = [];
407
466
  /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
408
467
  * during the end-of-run turn does. */
409
468
  let turnsOver = false;
@@ -453,6 +512,20 @@ function adapterLoop(specOf, options, deps) {
453
512
  /** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
454
513
  let mcpHosted = () => undefined;
455
514
  let mcpStale = false;
515
+ /** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
516
+ * input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
517
+ * shows the next user entry with exactly this text as "AgentRun: …". Once per follow-up: the marker names its request
518
+ * id, and a re-claim that finds one under it writes none (a second would stay open, and could take a person's later
519
+ * message of the same words for the server's). A CLI's run records its follow-up through its own record, which carries
520
+ * the origin itself. */
521
+ const markServerFollowUp = async (theHarness, theRoot, text, requestId) => {
522
+ if (cliRecord)
523
+ return;
524
+ const marked = (await entriesOf(gate.journal, theRoot.id, context)).some((entry) => entry.kind === MESSAGE_ORIGIN && entry.data?.requestId === requestId);
525
+ if (marked)
526
+ return;
527
+ await theHarness.commit((tx) => tx.appendEntry(theRoot.id, { kind: MESSAGE_ORIGIN, data: { origin: CAP_RAISED_ORIGIN, text, requestId } }), context);
528
+ };
456
529
  /** The run's raise state, read from its root: the newest budget entry with no raise entry after it is the pause it
457
530
  * waits at (its pending cap is the cap a raise is checked against); the newest raise entry is its last raise. */
458
531
  async function raiseStateOf() {
@@ -594,11 +667,12 @@ function adapterLoop(specOf, options, deps) {
594
667
  if (!gate || !session || gate.sealed)
595
668
  return { later: "the run is parking: the steer waits for its resume" };
596
669
  // The run's job has answered and it is looking back before its end: a person's message is not the end-of-run turn's
597
- // to answer. Left untaken, so the run's end says it came after the answer.
670
+ // to answer. Left untaken, the run's end opens a completed run again with it as a new turn (store run-patch.ts
671
+ // refuseLeftovers).
598
672
  if (reflecting)
599
- return { later: "the run has answered and is ending: the steer is not placed in its end-of-run turn" };
673
+ return { later: "the run has answered and is ending: the message opens it again as a new turn once its end is in" };
600
674
  if (handingBack)
601
- return { later: "the run has answered and waits for its computer to be handed back before it ends: the steer is not placed" };
675
+ return { later: "the run has answered and waits for its computer to be handed back before it ends: the message opens it again as a new turn once its end is in" };
602
676
  const text = typeof command.body?.text === "string" ? command.body.text : "";
603
677
  const requestId = commandRequest(command.id);
604
678
  // A message that answers nothing (a trigger's, answers: false) waits for the turn's end and runs as a turn of its
@@ -617,14 +691,36 @@ function adapterLoop(specOf, options, deps) {
617
691
  return { refused: "The run is waiting on a person." };
618
692
  // A reopened run's follow-up, its session idle: sent as a turn of its own, tracked to its end (as the input and a raise's
619
693
  // follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
620
- if (reopen && !reopen.sent && session.state === "idle") {
694
+ if (reopen && !reopen.sent && (session.state === "idle" || session.state === "new")) {
621
695
  const theSession = session;
622
- // The answer to a wait in the claim: the row's waiting summary goes in its commit.
623
- const taken = gate.expect(writesSubmission(requestId), { take: [command.id], ...(reopen === waitTurn ? { run: { summary: null } } : {}) });
696
+ const theRecord = cliRecord;
697
+ // Who wrote it, when the person did not (a trigger's message that reopened the run): its input is that origin's.
698
+ const by = originOf(command.body?.origin);
699
+ // A run a person stopped before its first input was sent (a stop during a harness's first-use install): its session
700
+ // is new. A stop then means "don't start yet", never "forget what I asked": the run's first turn is one request
701
+ // carrying the original input and then the person's message, under the first input's id. The original input is
702
+ // never sent, or answered, as a turn of its own.
703
+ const first = theSession.state === "new" ? specNow : undefined;
704
+ const sendId = first ? INPUT_REQUEST : requestId;
705
+ const content = first ? `${first.input}\n\n${text}` : text;
706
+ // The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
707
+ // writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
708
+ // row. A runner lost between the send and that entry leaves the row untaken, so the next claim sends it again: a
709
+ // follow-up may be sent twice after a crash, never lost. The answer to a wait in the claim: the row's waiting summary
710
+ // goes in that commit too.
711
+ const placedBy = theRecord ? writesEntry(by ? KINDS.input : KINDS.message, (data) => data.requestId === requestId) : writesSubmission(sendId);
712
+ const taken = gate.expect(placedBy, { take: [command.id], ...(reopen === waitTurn ? { run: { summary: null } } : {}) });
624
713
  taken.catch(() => undefined);
625
714
  reopen.sent = (async () => {
626
- await cliRecord?.person(text);
627
- await theSession.send(text, { id: requestId });
715
+ await theSession.send(content, { id: sendId, ...(by ? { origin: by } : {}) });
716
+ // A CLI's record: the original input as its writer's (the launch's origin, else the person's), then the message.
717
+ if (first) {
718
+ if (first.inputOrigin)
719
+ await theRecord?.input(first.input, first.inputOrigin);
720
+ else
721
+ await theRecord?.person(first.input);
722
+ }
723
+ await theRecord?.followUp(text, requestId, by);
628
724
  })();
629
725
  reopen.placed?.();
630
726
  try {
@@ -649,6 +745,10 @@ function adapterLoop(specOf, options, deps) {
649
745
  afterTurn.push({ commandId: command.id, text, requestId, ...(origin ? { origin } : {}) });
650
746
  return { taken: true };
651
747
  }
748
+ // The claim's last turn has ended and nothing more is sent (turnsOver): a steer placed now would start a turn the run's
749
+ // end then cuts, so it waits for the run's end, as a CLI's message does.
750
+ if (turnsOver && !askedLast)
751
+ return { later: "the run has answered and is ending: the message waits for the run's end" };
652
752
  // A person's answer to the question the last turn ended on (a parked ask's, its run claimed again by it): the row's
653
753
  // waiting summary goes in its commit, as an in-claim wait's answer clears it. Left until the end commit, the answer's
654
754
  // turn reads running, held and "Waiting for your reply", and the server tells run.needs_input for that ask again.
@@ -671,6 +771,9 @@ function adapterLoop(specOf, options, deps) {
671
771
  return { later: "the run is parking: the steer waits for its resume" };
672
772
  return { refused: `the steer was not placed: ${error.message}` };
673
773
  }
774
+ // Placed in the turn in flight: the turn's end waits for it to be answered (steeredIn), never ending the run first.
775
+ if (!askedLast)
776
+ steeredIn.push(requestId);
674
777
  await taken.catch(() => { });
675
778
  return { taken: true };
676
779
  };
@@ -730,7 +833,7 @@ function adapterLoop(specOf, options, deps) {
730
833
  /** The root a phase is making, awaited before the owed writes are read. */
731
834
  let rootMaking;
732
835
  harness = await Harness.open(gate.journal, {
733
- models: () => models, registry, settings: { restartLimit }, onReport: () => { },
836
+ models: () => models, registry, settings: { restartLimit, retry, stream }, onReport: () => { },
734
837
  // A tool host's onConversation, in each agent conversation's creating commit (the spec's, once it is known: the
735
838
  // root is created when the session opens, after the spec).
736
839
  conversationCreated: async (tx, record) => {
@@ -787,7 +890,7 @@ function adapterLoop(specOf, options, deps) {
787
890
  },
788
891
  // Lazy, as main's process takes them (portModels(() => sessionPort?.(...))): a spec takes them at its build, and
789
892
  // each request reads the session's port then, there once the session is open.
790
- models: (label) => portModels(() => session?.port?.(label)),
893
+ models: (label, tier) => portModels(() => session?.port?.(label, tier), undefined, tier === undefined ? PORT_PROVIDER : tierProvider(tier)),
791
894
  pause: async (refusal) => {
792
895
  await pauseFor?.(refusal);
793
896
  },
@@ -842,7 +945,7 @@ function adapterLoop(specOf, options, deps) {
842
945
  // A person's stop while the spec was built (it waited on a harness's install): the run ends stopped, in the stop's
843
946
  // words, its row taken; the work it waited on goes on for the next run. A stop wins over the build's own failure.
844
947
  if (stopReason?.kind === "command")
845
- return await writeEnd(harness, await harness.root(context), gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId]);
948
+ return await writeEnd(harness, await harness.root(context), gate, stopEnd(stopReason.cancel), [stopReason.commandId]);
846
949
  // A spec that failed after a phase made the run's root (its computer's image build failed): the end goes on that
847
950
  // root with why (said: cut of every secret the runner holds), as run()'s catch writes it once the session's root
848
951
  // is known, so the timeline keeps the phase row and reads the failure after it.
@@ -916,10 +1019,38 @@ function adapterLoop(specOf, options, deps) {
916
1019
  // bound, and that bound kept, so a possible cache miss pauses the run, never fails it).
917
1020
  return overCapOf(await sessions.read(spec.session.key), others, cap);
918
1021
  };
1022
+ /** A paid call's pending pause as it lands, at the model's next request: said again with the run's spend as it is
1023
+ * now (every session's booked spend; the turn's calls have all ended, so nothing else is held), so the budget card
1024
+ * counts what parallel calls settled since the refusal. Undefined when the call would now fit (one of them settled
1025
+ * for less than it held): no pause, and the request goes to the cap as any does. A refusal with no call named on
1026
+ * it, or a spend unknown, lands as it was. */
1027
+ const landing = async (pending) => {
1028
+ const step = pending.figures?.step;
1029
+ const cap = capNow();
1030
+ if (!step || cap === undefined)
1031
+ return pending;
1032
+ let spent = 0;
1033
+ for (const key of await sessions.keys()) {
1034
+ const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
1035
+ if (spend === null)
1036
+ return pending;
1037
+ spent += spend;
1038
+ }
1039
+ if (spent + step.holdUsd <= cap + FIT_TOLERANCE)
1040
+ return undefined;
1041
+ const { text, figures } = paidRefusal(cap, spent, 0, step.name, step.holdUsd, step.basis);
1042
+ return { ...pending, refuse: text, figures };
1043
+ };
919
1044
  const beforeRequest = async (request) => {
920
1045
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
921
1046
  // whatever else would pause it (a paid call's refusal, pendingPause).
922
1047
  const over = await overCap();
1048
+ if (!over && pendingPause) {
1049
+ pendingPause = await landing(pendingPause);
1050
+ // Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
1051
+ if (pendingPause === undefined)
1052
+ await keepPending(null);
1053
+ }
923
1054
  const answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
924
1055
  if (answer && "refuse" in answer) {
925
1056
  refused = answer;
@@ -927,10 +1058,29 @@ function adapterLoop(specOf, options, deps) {
927
1058
  }
928
1059
  return answer;
929
1060
  };
1061
+ // A paid call's refusal is the call's result first: its pause is journaled at the model's next request (beforeRequest,
1062
+ // pendingPause), once the harness has stored that result, so the run never reads waiting on a raise before its
1063
+ // Timeline says why. The refusal is kept on the root at once (KINDS.pausePending, no run patch, nothing a person
1064
+ // reads), so a claim lost in between restores it (pendingPauseOf) and the next claim's request parks the run.
930
1065
  pauseFor = async (refusal) => {
931
1066
  pendingPause = refusal;
932
- await pauseAt(refusal);
1067
+ await keepPending(refusal);
933
1068
  };
1069
+ /** The pending pause kept on the root (KINDS.pausePending): a refusal, or null once it is dropped for good (the call
1070
+ * would now fit, or the turn ended on a question), which pendingPauseOf reads as none. */
1071
+ async function keepPending(refusal) {
1072
+ if (!harness || !gate || gate.sealed)
1073
+ return;
1074
+ const on = harness;
1075
+ try {
1076
+ const conversation = root ?? (await on.root(context));
1077
+ await on.commit(async (tx) => void (await tx.appendEntry(conversation.id, { kind: KINDS.pausePending, data: refusal })), context);
1078
+ }
1079
+ catch {
1080
+ // Not kept (the journal sealed: the claim lost or the run parking): a refusal still parks this claim's own
1081
+ // request; a drop leaves the next claim to judge the old refusal again when it lands (landing).
1082
+ }
1083
+ }
934
1084
  async function pauseAt(answer) {
935
1085
  {
936
1086
  // A refusal a raise could fix (the cap's rule, parkOf) journals its pause, the run parked, before the refusal
@@ -938,6 +1088,11 @@ function adapterLoop(specOf, options, deps) {
938
1088
  // claim resumes the run parked (an unanswered pause), never ends it as a failed turn. One that cannot land (the
939
1089
  // journal sealed) is left to the turn's end, as before.
940
1090
  const park = spec.cap?.park(refusalOf(answer), raisedCapUsd ?? spec.cap.capUsd);
1091
+ // Parking: every later request of this claim is refused in the same words, so nothing more is sent until a raise
1092
+ // (on the next claim) resumes the run. A run's other conversations (a subagent's children) ask in their own
1093
+ // turns; one refused request parks them all, never one alone.
1094
+ if (park?.outcome === "parked")
1095
+ pendingPause ??= answer;
941
1096
  if (park?.outcome === "parked" && !pausedAtRefusal && harness && gate && !gate.sealed) {
942
1097
  const on = gate;
943
1098
  // From here a raise row waits for the next claim (raise): one taken now would answer no pause this claim
@@ -975,9 +1130,28 @@ function adapterLoop(specOf, options, deps) {
975
1130
  const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
976
1131
  if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
977
1132
  await paidOf();
978
- const gateOf = preIntentGate(spec, hooks);
1133
+ // The cap's wrap-up (tool-budget.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1134
+ // spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
1135
+ // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1136
+ // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
1137
+ const wrapUp = async () => {
1138
+ // A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
1139
+ if (!spec.runCap)
1140
+ return false;
1141
+ const capUsd = capNow();
1142
+ if (capUsd === undefined)
1143
+ return false;
1144
+ let taken = 0;
1145
+ for (const key of await sessions.keys()) {
1146
+ const read = sessionSpendOf(await sessions.read(key));
1147
+ const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
1148
+ taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
1149
+ }
1150
+ return wrappingUp(capUsd, taken);
1151
+ };
1152
+ const gateOf = preIntentGate(spec, hooks, wrapUp);
979
1153
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
980
- const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now) : undefined;
1154
+ const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now, spec.cwd) : undefined;
981
1155
  cliRecord = record;
982
1156
  // Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
983
1157
  // read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
@@ -995,6 +1169,34 @@ function adapterLoop(specOf, options, deps) {
995
1169
  const ended = record?.endOf(toolContext.callId);
996
1170
  if (ended)
997
1171
  return endedAnswer(tool.name, ended);
1172
+ // A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
1173
+ // attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
1174
+ // set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
1175
+ if ((toolContext.attempt ?? 0) > 0 && spec.gate) {
1176
+ // By the name the gate before the intent asks it by: an MCP tool by its catalog name.
1177
+ const name = mcp?.catalogOf(tool.name) ?? tool.name;
1178
+ const asked = spec.gate.askedAs?.(name) ?? name;
1179
+ const now = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
1180
+ if (now === "deny")
1181
+ return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
1182
+ if (typeof now === "object")
1183
+ return { text: now.deny, isError: true };
1184
+ // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
1185
+ // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
1186
+ // the claim lets it go; a deny says the earlier attempt may have taken effect.
1187
+ if (now === "ask") {
1188
+ const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
1189
+ const answer = await answerOf(call, mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null, asked);
1190
+ if (answer === "park")
1191
+ return await heldUntilAborted(toolContext.signal);
1192
+ if (!answer.approved)
1193
+ return { text: refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown"), isError: true };
1194
+ }
1195
+ // pi let this call start before it was asked here: a stop while the gate or a person was asked wins over the
1196
+ // permission that came after it, and the call is never started.
1197
+ if (stopAbort.signal.aborted || toolContext.signal?.aborted)
1198
+ return { text: STOPPED_WHILE_WAITING, isError: true };
1199
+ }
998
1200
  if (record)
999
1201
  await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
1000
1202
  try {
@@ -1083,14 +1285,24 @@ function adapterLoop(specOf, options, deps) {
1083
1285
  };
1084
1286
  // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
1085
1287
  // start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
1086
- // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it).
1288
+ // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it). A call it asks
1289
+ // about goes on the record first, its start marked parked (once per call id), as an MCP call parked at its door does,
1290
+ // and marked the bridge's: the bridge hands the CLI nothing while it waits, so no waiting result shows, as on pi. Its
1291
+ // row shows while it waits, before its approval; the claim that runs it once allowed writes its sent mark on that
1292
+ // one start (start()), and a stop withdraws it never sent (unsentParked). A start refused because another call of the
1293
+ // round parked the run first (the journal sealed) leaves this call held as that one is.
1294
+ const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
1295
+ const askingGate = record
1296
+ ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), true).catch((error) => {
1297
+ if (!gate?.sealed)
1298
+ throw error;
1299
+ }))
1300
+ : gateOf;
1087
1301
  const bridgeGate = record
1088
1302
  ? async (call, hookContext) => {
1089
- const answer = await gateOf(call, hookContext);
1090
- if (answer !== "allow" && "deny" in answer) {
1091
- const tool = tools.find((one) => one.name === call.tool);
1092
- await record.refused(call.callId, call.tool, call.args ?? {}, tool?.replay === "safe", answer.deny);
1093
- }
1303
+ const answer = await askingGate(call, hookContext);
1304
+ if (answer !== "allow" && "deny" in answer)
1305
+ await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
1094
1306
  return answer;
1095
1307
  }
1096
1308
  : gateOf;
@@ -1120,6 +1332,9 @@ function adapterLoop(specOf, options, deps) {
1120
1332
  : undefined;
1121
1333
  session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
1122
1334
  root = await harness.root(context);
1335
+ // The root as the claim found it, before this pass writes anything of its own there (the computer's show-up, a
1336
+ // takeover's note): what the reopen check below reads, so a fresh reopen is told by the run's own last entry.
1337
+ const foundEntries = restarts === 0 ? await entriesOf(gate.journal, root.id, context) : [];
1123
1338
  // The run's desktop or phone: its hold's changes go to the run's journal, through this pass's Harness (under its
1124
1339
  // fence), and the computer shows up, the agent driving.
1125
1340
  computerNow?.detach();
@@ -1133,10 +1348,16 @@ function adapterLoop(specOf, options, deps) {
1133
1348
  // The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
1134
1349
  await computerNow.up(await entriesOf(gate.journal, root.id, context));
1135
1350
  }
1136
- // The cap a raise left the run at, from its root (the newest raise entry), before any request of this claim: a
1137
- // claim that takes over a raised run (a resume, another runner's) holds it to the raise, never the launch's cap.
1351
+ // The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
1352
+ // budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
1353
+ // run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
1138
1354
  if (spec.cap)
1139
- raisedCapUsd = (await raiseStateOf()).lastRaise?.to ?? raisedCapUsd;
1355
+ raisedCapUsd = capNowOf(spec.cap.capUsd, await entriesOf(gate.journal, root.id, context)) ?? raisedCapUsd;
1356
+ // A paid call an earlier claim refused for room whose pause never landed (the claim lost between the call's stored
1357
+ // result and the model's next request): its pending pause, restored, so that request is refused in its words and
1358
+ // the run parks for the raise the call needs.
1359
+ if (spec.cap && pendingPause === undefined)
1360
+ pendingPause = pendingPauseOf(await entriesOf(gate.journal, root.id, context)) ?? pendingPause;
1140
1361
  // A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
1141
1362
  // run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
1142
1363
  // before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
@@ -1147,10 +1368,39 @@ function adapterLoop(specOf, options, deps) {
1147
1368
  // Taken over from a runner whose lease ran out mid-run: said on the run's timeline once, at this claim's first pass.
1148
1369
  if (restarts === 0 && claim.lost)
1149
1370
  await noteTakenOver(harness, root, claim.lost.runner);
1150
- // Reopened by a person's follow-up (runs.reopen): its journal holds an end and its session opens idle. Set before the
1151
- // session is ready, so the follow-up's steer, handed over once it is, is sent as this claim's turn.
1152
- if (restarts === 0 && session.state === "idle" && (await entriesOf(gate.journal, root.id, context)).some((entry) => entry.kind === KINDS.end))
1153
- reopen = {};
1371
+ // What this claim laid of the run's learning seed, once per claim: the newest is what the run was given.
1372
+ if (restarts === 0 && spec.learningLaid) {
1373
+ const [journalOf, rootOf, laid] = [harness, root, spec.learningLaid];
1374
+ await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.learningLaid, data: { skills: [...laid.skills], workflows: [...laid.workflows] } }), context);
1375
+ }
1376
+ // Reopened by a person's follow-up (runs.reopen, or the end's own reopen): a fresh reopen is a claim whose journal's
1377
+ // root ends on an end entry, with no input of the root in flight. Then any turn its session still reads open is one
1378
+ // that end already closed (a person's stop leaves the turn they stopped open in the session: an interrupt writes no
1379
+ // end there), done and never resumed, so it is settled (settleOpenTurn, as a host done with a stopped turn settles
1380
+ // it), and the session, idle, takes the follow-up as this claim's turn: set before the session is ready, so the
1381
+ // follow-up's steer, handed over once it is, is sent as that turn. A claim that finds the follow-up already under way
1382
+ // (anything on the root after the end, or a root input in flight: a takeover or a drain mid follow-up) is no reopen:
1383
+ // its session recovers that turn as any open turn.
1384
+ if (restarts === 0) {
1385
+ const rootId = root.id;
1386
+ // Read before this claim's own writes (foundEntries), and past the bookkeeping any claim writes on the root before
1387
+ // its turn (its session's key, a phase row, a takeover's note, the computer's hold, the learning seed it laid):
1388
+ // none of them is a turn of the follow-up's.
1389
+ const endsRoot = foundEntries.findLast((entry) => !CLAIM_BOOKKEEPING.has(entry.kind))?.kind === KINDS.end;
1390
+ const inFlight = (await harness.inspect(context)).submissions.some((one) => one.conversationId === rootId && one.type === "input");
1391
+ if (endsRoot && !inFlight && session.state === "open_turn")
1392
+ await session.settleOpenTurn();
1393
+ // A session still new (a person stopped the run before its first input was sent): the follow-up is its first
1394
+ // input, and the input the person stopped is never sent.
1395
+ firstInputPlaced = undefined;
1396
+ if (endsRoot && !inFlight && session.state === "idle")
1397
+ reopen = {};
1398
+ else if (endsRoot && !inFlight && session.state === "new") {
1399
+ const mine = {};
1400
+ firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
1401
+ reopen = mine;
1402
+ }
1403
+ }
1154
1404
  opened();
1155
1405
  await reportHeld(harness, root.id);
1156
1406
  if (restarts > restartLimit + 1) {
@@ -1169,7 +1419,7 @@ function adapterLoop(specOf, options, deps) {
1169
1419
  // ends as a stop does mid-turn: in the stop's words, its row taken, with what the end-of-run step keeps of a
1170
1420
  // cut run.
1171
1421
  if (stopReason?.kind === "command") {
1172
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1422
+ return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1173
1423
  }
1174
1424
  const paused = raising.budget;
1175
1425
  const resumes = raising.resumes;
@@ -1177,7 +1427,11 @@ function adapterLoop(specOf, options, deps) {
1177
1427
  if (paused) {
1178
1428
  if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
1179
1429
  return await parkAtCap(harness, root, gate, paused);
1180
- await session.send(spec.cap.followUpOf(raising.capUsd).text, { id: `agentrun:raise:${raising.state?.lastRaise?.pause ?? "follow-up"}` });
1430
+ // The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
1431
+ const followUp = spec.cap.followUpOf(raising.capUsd).text;
1432
+ const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
1433
+ await markServerFollowUp(harness, root, followUp, followUpId);
1434
+ await session.send(followUp, { id: followUpId });
1181
1435
  followedUp = true;
1182
1436
  }
1183
1437
  }
@@ -1188,7 +1442,10 @@ function adapterLoop(specOf, options, deps) {
1188
1442
  // the run's, is the follow-up's, never the first input's.
1189
1443
  const state = await raiseStateOf();
1190
1444
  if (state.pause === undefined && state.lastRaise?.pause !== undefined) {
1191
- await session.send(spec.cap.followUpOf(state.lastRaise.to).text, { id: `agentrun:raise:${state.lastRaise.pause}` });
1445
+ const followUp = spec.cap.followUpOf(state.lastRaise.to).text;
1446
+ const followUpId = raiseFollowUpId(state.lastRaise.pause);
1447
+ await markServerFollowUp(harness, root, followUp, followUpId);
1448
+ await session.send(followUp, { id: followUpId });
1192
1449
  followedUp = true;
1193
1450
  }
1194
1451
  }
@@ -1213,7 +1470,7 @@ function adapterLoop(specOf, options, deps) {
1213
1470
  // A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
1214
1471
  // end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
1215
1472
  if (stopReason?.kind === "command")
1216
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1473
+ return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1217
1474
  gate.seal(new Parked());
1218
1475
  return { state: "parked" };
1219
1476
  }
@@ -1231,6 +1488,12 @@ function adapterLoop(specOf, options, deps) {
1231
1488
  // A steer handed over waits on the session's readiness (resolved above) before it sends: one turn of the event loop
1232
1489
  // lets it get there.
1233
1490
  await new Promise((resolve) => setImmediate(resolve));
1491
+ // A session still new: the message is the run's first input, and nothing else may be sent first. A row the
1492
+ // runner reads on a later poll is waited for (or the run's stop, park or loss).
1493
+ if (firstInputPlaced && !reopen.sent) {
1494
+ const lost = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
1495
+ await Promise.race([firstInputPlaced, stopping, parking, harness.closed.then(() => undefined, () => undefined), lost]);
1496
+ }
1234
1497
  const sent = reopen.sent;
1235
1498
  reopen = undefined;
1236
1499
  if (sent) {
@@ -1240,9 +1503,12 @@ function adapterLoop(specOf, options, deps) {
1240
1503
  }
1241
1504
  // A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
1242
1505
  // open found it, and a CLI adapter reads idle once its turn is sent, so state read after a send says nothing.
1243
- const placed = followedUp || session.state !== "idle";
1244
- if (followedUp) {
1245
- // The follow-up is the turn this claim runs.
1506
+ // A reopen of a session still new whose message was never placed (the run stopped, parked or was lost meanwhile):
1507
+ // nothing is sent, least of all the input the person stopped.
1508
+ const firstUnplaced = firstInputPlaced !== undefined && !followedUp;
1509
+ const placed = followedUp || (session.state !== "idle" && !firstUnplaced);
1510
+ if (followedUp || firstUnplaced) {
1511
+ // The follow-up is the turn this claim runs, or there is none.
1246
1512
  }
1247
1513
  else if (session.state === "new") {
1248
1514
  // A trigger's first input is its origin's (the launch's), never written as the person's.
@@ -1290,12 +1556,12 @@ function adapterLoop(specOf, options, deps) {
1290
1556
  let timer;
1291
1557
  const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
1292
1558
  clearTimeout(timer);
1293
- // A cancel ends the same way, in its own words (main's "cancelled"); the bound is the same.
1294
- const words = endedBy(stopReason.cancel);
1559
+ // A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
1560
+ const stopped = stopEnd(stopReason.cancel);
1295
1561
  const cut = await cutRows(claim, spec, "stopped");
1296
1562
  if (!settled)
1297
- return await writeEnd(harness, root, gate, { state: "failed", summary: `${words}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
1298
- return await writeEnd(harness, root, gate, { state: "stopped", summary: words }, [stopReason.commandId], cut);
1563
+ return await writeEnd(harness, root, gate, { state: "failed", summary: `${stopped.summary}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
1564
+ return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
1299
1565
  }
1300
1566
  // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
1301
1567
  // it kept went): the run parks on its question, as it does with nothing open.
@@ -1349,6 +1615,12 @@ function adapterLoop(specOf, options, deps) {
1349
1615
  // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
1350
1616
  // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
1351
1617
  const callId = endedOnTurnEndingTool(settledEntries);
1618
+ // Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
1619
+ // person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
1620
+ if (pendingPause) {
1621
+ pendingPause = undefined;
1622
+ await keepPending(null);
1623
+ }
1352
1624
  const waited = await waitInClaim(harness, callId);
1353
1625
  if (waited) {
1354
1626
  turn = waited.next;
@@ -1361,12 +1633,34 @@ function adapterLoop(specOf, options, deps) {
1361
1633
  // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
1362
1634
  // the direct loop's rule: the words are loop-contract's cutAtLimit).
1363
1635
  const cut = cutLast(settledEntries);
1636
+ // The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
1637
+ // message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
1638
+ // command that waits on this loop cannot hold its end.
1639
+ if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
1640
+ let bound;
1641
+ await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
1642
+ clearTimeout(bound);
1643
+ // A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
1644
+ // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
1645
+ const cutBy = stopReason;
1646
+ if (cutBy?.kind === "command")
1647
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
1648
+ if (cutBy || deps.signal.aborted)
1649
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
1650
+ }
1364
1651
  // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
1365
1652
  const next = cut ? undefined : afterTurn.shift();
1366
1653
  if (next) {
1367
1654
  turn = sendAfterTurn(gate, next);
1368
1655
  continue;
1369
1656
  }
1657
+ // A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
1658
+ // the run's end. One already answered settles at once.
1659
+ const steered = cut ? undefined : steeredIn.shift();
1660
+ if (steered !== undefined) {
1661
+ turn = turnOfRequest(harness, root, steered);
1662
+ continue;
1663
+ }
1370
1664
  data = cut ? { state: "failed", summary: cut } : { state: "ended" };
1371
1665
  }
1372
1666
  break;
@@ -1386,7 +1680,7 @@ function adapterLoop(specOf, options, deps) {
1386
1680
  // Set by stop() during the wait: read past the narrowing TypeScript did before it.
1387
1681
  const cut = stopReason;
1388
1682
  if (cut?.kind === "command")
1389
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cut.cancel) }, [cut.commandId], await cutRows(claim, spec, "stopped"));
1683
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
1390
1684
  if (cut || deps.signal.aborted)
1391
1685
  return await interrupted(cut?.kind ?? "its claim's signal aborted");
1392
1686
  }
@@ -1394,7 +1688,7 @@ function adapterLoop(specOf, options, deps) {
1394
1688
  // writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
1395
1689
  const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
1396
1690
  if (step.kind === "stopped")
1397
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason?.kind === "command" ? stopReason.cancel : undefined) }, [step.commandId], await cutRows(claim, spec, "stopped-looking"));
1691
+ return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
1398
1692
  if (step.kind === "interrupted")
1399
1693
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
1400
1694
  // The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
@@ -1438,8 +1732,11 @@ function adapterLoop(specOf, options, deps) {
1438
1732
  await closeSession();
1439
1733
  }
1440
1734
  }
1441
- /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park). */
1442
- function preIntentGate(spec, hooks) {
1735
+ /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
1736
+ * `wrapUp`: whether the run has taken its share of the cap, so every call the model makes is refused in its fixed words.
1737
+ * `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
1738
+ * through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
1739
+ function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
1443
1740
  return async (call, _hookContext) => {
1444
1741
  // An MCP tool is asked about by its catalog name (`mcp:<server>/<tool>`), as its settings and its card name it.
1445
1742
  const tool = mcp?.catalogOf(call.tool) ?? call.tool;
@@ -1448,7 +1745,19 @@ function adapterLoop(specOf, options, deps) {
1448
1745
  if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
1449
1746
  return { deny: REFLECT_NOTE_ONLY };
1450
1747
  await hooks.beforeIntent(kernelCall);
1451
- const decision = (await spec.gate?.(kernelCall)) ?? "allow";
1748
+ // The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
1749
+ // asked about.
1750
+ // A conversation's own budget (a subagent's max_tool_calls) narrows the run's, never widens it.
1751
+ const budget = budgetOf(spec.gate?.toolCalls, call.ownBudget ? await call.ownBudget() : undefined);
1752
+ if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
1753
+ return { deny: TOOL_BUDGET_TEXT };
1754
+ // The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
1755
+ // in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
1756
+ if (call.nested !== true && (await wrapUp()))
1757
+ return { deny: WRAP_UP_TEXT };
1758
+ // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
1759
+ const replayed = call.replayed === true;
1760
+ const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
1452
1761
  if (typeof decision === "object")
1453
1762
  return { deny: decision.deny };
1454
1763
  // Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
@@ -1456,7 +1765,7 @@ function adapterLoop(specOf, options, deps) {
1456
1765
  const asked = spec.gate?.askedAs?.(tool) ?? tool;
1457
1766
  // Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
1458
1767
  if (decision === "deny")
1459
- return { deny: setToDenyText(asked) };
1768
+ return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
1460
1769
  if (decision === "allow")
1461
1770
  return "allow";
1462
1771
  // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
@@ -1465,6 +1774,8 @@ function adapterLoop(specOf, options, deps) {
1465
1774
  // Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
1466
1775
  // The gate's own fields win over any of the same name in the call's input, which the model wrote.
1467
1776
  const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
1777
+ // The call on the record before its ask (beforeAsk), with the input its model gave it.
1778
+ await beforeAsk?.(call);
1468
1779
  const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
1469
1780
  if (answer === "park")
1470
1781
  return { park: true };
@@ -1475,7 +1786,9 @@ function adapterLoop(specOf, options, deps) {
1475
1786
  const seen = askedArgs.get(call.callId);
1476
1787
  approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
1477
1788
  }
1478
- return answer.approved ? "allow" : { deny: deniedText(asked, answer.note) };
1789
+ if (answer.approved)
1790
+ return "allow";
1791
+ return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
1479
1792
  };
1480
1793
  }
1481
1794
  /** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
@@ -1540,6 +1853,15 @@ function adapterLoop(specOf, options, deps) {
1540
1853
  await new Promise((resolve) => (wakeInbox = resolve));
1541
1854
  }
1542
1855
  }
1856
+ /** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
1857
+ * park), then thrown, so nothing of it is answered in this pass. */
1858
+ function heldUntilAborted(signal) {
1859
+ return new Promise((_, reject) => {
1860
+ if (signal.aborted)
1861
+ return reject(new Error("parked"));
1862
+ signal.addEventListener("abort", () => reject(new Error("parked")), { once: true });
1863
+ });
1864
+ }
1543
1865
  /** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. `later` when this
1544
1866
  * claim can no longer say: its Harness never opened, or its pass is parking, ending or stopping (the journal sealed,
1545
1867
  * closeSession closing the Harness behind the seal). The row is left untaken and the run's next claim checks it, as a
@@ -1707,6 +2029,9 @@ function adapterLoop(specOf, options, deps) {
1707
2029
  if (done)
1708
2030
  return;
1709
2031
  done = true;
2032
+ if (value === "lapsed")
2033
+ for (const hold of waitHolds)
2034
+ hold.confirmed?.();
1710
2035
  endWait(mine);
1711
2036
  resolve(value);
1712
2037
  };