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

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 (568) hide show
  1. package/CHANGELOG.md +452 -0
  2. package/README.md +311 -142
  3. package/dist/agent-rows.d.ts +1 -1
  4. package/dist/agents-store.d.ts +35 -3
  5. package/dist/agents-store.js +39 -14
  6. package/dist/answer-json.d.ts +34 -1
  7. package/dist/answer-json.js +91 -9
  8. package/dist/api-only.d.ts +1 -1
  9. package/dist/api-only.js +2 -2
  10. package/dist/attach-conformance-cli.d.ts +1 -0
  11. package/dist/attach-conformance-cli.js +18 -0
  12. package/dist/attach-conformance.d.ts +25 -0
  13. package/dist/attach-conformance.js +343 -0
  14. package/dist/browser-cost.d.ts +1 -1
  15. package/dist/browser-cost.js +52 -93
  16. package/dist/browser-live.d.ts +20 -8
  17. package/dist/browser-live.js +50 -27
  18. package/dist/cap.d.ts +0 -407
  19. package/dist/cap.js +4 -1028
  20. package/dist/catalog.d.ts +1 -12
  21. package/dist/catalog.js +4 -34
  22. package/dist/cli.js +13 -4
  23. package/dist/composio-preset.d.ts +53 -0
  24. package/dist/composio-preset.js +221 -0
  25. package/dist/computer-attach.d.ts +125 -0
  26. package/dist/computer-attach.js +330 -0
  27. package/dist/computer-calls.d.ts +60 -0
  28. package/dist/computer-calls.js +209 -0
  29. package/dist/computer-channel.d.ts +57 -0
  30. package/dist/computer-channel.js +115 -0
  31. package/dist/computer-commands.d.ts +1 -1
  32. package/dist/computer-held-routes.d.ts +35 -0
  33. package/dist/computer-held-routes.js +106 -0
  34. package/dist/computer-held.d.ts +48 -0
  35. package/dist/computer-held.js +87 -0
  36. package/dist/computer-keys.d.ts +21 -1
  37. package/dist/computer-keys.js +53 -11
  38. package/dist/computer-live.d.ts +165 -0
  39. package/dist/computer-live.js +655 -0
  40. package/dist/computer-setting.d.ts +15 -2
  41. package/dist/computer-setting.js +20 -4
  42. package/dist/computer-view.d.ts +14 -0
  43. package/dist/computer-view.js +51 -3
  44. package/dist/computer-viewer.d.ts +6 -0
  45. package/dist/computer-viewer.js +311 -0
  46. package/dist/computers.d.ts +37 -8
  47. package/dist/computers.js +62 -14
  48. package/dist/console/assets/index-CjqQirbo.css +1 -0
  49. package/dist/console/assets/index-b6-XY5A9.js +576 -0
  50. package/dist/console/index.html +2 -2
  51. package/dist/console-links.d.ts +2 -0
  52. package/dist/console-links.js +3 -0
  53. package/dist/decisions.js +4 -0
  54. package/dist/faux-computers.d.ts +9 -20
  55. package/dist/faux-computers.js +56 -26
  56. package/dist/github-connection.d.ts +10 -2
  57. package/dist/github-connection.js +65 -2
  58. package/dist/github-faux.js +1 -1
  59. package/dist/graph-view.d.ts +1 -1
  60. package/dist/harness-opencode/adapter.js +7 -3
  61. package/dist/harness-opencode/facts.js +0 -2
  62. package/dist/harness-opencode/host/policy.d.ts +2 -5
  63. package/dist/harness-opencode/host/policy.js +8 -32
  64. package/dist/harness-table.d.ts +0 -2
  65. package/dist/harness-table.js +0 -2
  66. package/dist/harness.d.ts +1 -0
  67. package/dist/harness.js +35 -1
  68. package/dist/host-tools.d.ts +2 -6
  69. package/dist/host-tools.js +7 -10
  70. package/dist/hosted-search.d.ts +5 -6
  71. package/dist/hosted-search.js +2 -28
  72. package/dist/import-sources.d.ts +10 -0
  73. package/dist/import-sources.js +44 -2
  74. package/dist/import.d.ts +3 -3
  75. package/dist/import.js +37 -6
  76. package/dist/key-words.d.ts +3 -2
  77. package/dist/key-words.js +4 -2
  78. package/dist/learn/check.d.ts +10 -2
  79. package/dist/learn/check.js +13 -5
  80. package/dist/learn/commit.d.ts +14 -2
  81. package/dist/learn/commit.js +23 -9
  82. package/dist/learn/compile.d.ts +243 -0
  83. package/dist/learn/compile.js +471 -0
  84. package/dist/learn/folder.d.ts +6 -0
  85. package/dist/learn/folder.js +4 -1
  86. package/dist/learn/general.d.ts +69 -0
  87. package/dist/learn/general.js +75 -0
  88. package/dist/learn/grade.d.ts +5 -1
  89. package/dist/learn/grade.js +29 -7
  90. package/dist/learn/notes.d.ts +8 -0
  91. package/dist/learn/notes.js +18 -0
  92. package/dist/learn/promote.d.ts +253 -0
  93. package/dist/learn/promote.js +428 -0
  94. package/dist/learn/refit.d.ts +39 -0
  95. package/dist/learn/refit.js +236 -0
  96. package/dist/learn/reflect.d.ts +9 -20
  97. package/dist/learn/reflect.js +18 -125
  98. package/dist/learn/replay-calls.d.ts +63 -0
  99. package/dist/learn/replay-calls.js +158 -0
  100. package/dist/learn/skills.d.ts +50 -14
  101. package/dist/learn/skills.js +183 -47
  102. package/dist/learn/workflow-nodes.d.ts +15 -0
  103. package/dist/learn/workflow-nodes.js +44 -0
  104. package/dist/learned-nodes.d.ts +50 -2
  105. package/dist/learned-nodes.js +41 -2
  106. package/dist/learned-workflow.d.ts +43 -3
  107. package/dist/learned-workflow.js +170 -28
  108. package/dist/learning-batch.d.ts +283 -0
  109. package/dist/learning-batch.js +574 -0
  110. package/dist/learning-cost.d.ts +18 -6
  111. package/dist/learning-cost.js +15 -7
  112. package/dist/learning-evals.d.ts +33 -0
  113. package/dist/learning-evals.js +98 -0
  114. package/dist/learning-routes.d.ts +37 -2
  115. package/dist/learning-routes.js +52 -8
  116. package/dist/learning-words.d.ts +13 -0
  117. package/dist/learning-words.js +13 -0
  118. package/dist/learning.d.ts +55 -17
  119. package/dist/learning.js +91 -48
  120. package/dist/live/stream.js +6 -3
  121. package/dist/live/translate.d.ts +4 -3
  122. package/dist/live/translate.js +8 -4
  123. package/dist/live-reach.d.ts +37 -0
  124. package/dist/live-reach.js +62 -0
  125. package/dist/llm.js +0 -3
  126. package/dist/mcp-gateway.d.ts +21 -20
  127. package/dist/mcp-gateway.js +76 -55
  128. package/dist/mcp-oauth.d.ts +62 -7
  129. package/dist/mcp-oauth.js +134 -19
  130. package/dist/mcp-pin-first.d.ts +37 -0
  131. package/dist/mcp-pin-first.js +107 -0
  132. package/dist/mcp-private-hosts.d.ts +4 -4
  133. package/dist/mcp-private-hosts.js +20 -12
  134. package/dist/mcp-probe.d.ts +27 -11
  135. package/dist/mcp-probe.js +60 -42
  136. package/dist/mcp-secret-writes.js +4 -0
  137. package/dist/mcp-servers-store.d.ts +115 -25
  138. package/dist/mcp-servers-store.js +241 -43
  139. package/dist/mcp-sources.d.ts +39 -0
  140. package/dist/mcp-sources.js +74 -0
  141. package/dist/mcp-store.d.ts +21 -4
  142. package/dist/mcp-store.js +33 -8
  143. package/dist/mcp-wire.d.ts +22 -0
  144. package/dist/mcp-wire.js +36 -0
  145. package/dist/mcp.js +3 -3
  146. package/dist/meta-tool-names.d.ts +1 -0
  147. package/dist/meta-tool-names.js +3 -0
  148. package/dist/model-form.d.ts +26 -0
  149. package/dist/model-form.js +80 -0
  150. package/dist/model.d.ts +13 -0
  151. package/dist/model.js +69 -25
  152. package/dist/monid.d.ts +51 -25
  153. package/dist/monid.js +226 -140
  154. package/dist/openapi.js +694 -59
  155. package/dist/page.d.ts +18 -0
  156. package/dist/page.js +48 -20
  157. package/dist/paid-calls.d.ts +26 -29
  158. package/dist/paid-calls.js +46 -102
  159. package/dist/place-offers.d.ts +2 -3
  160. package/dist/place-offers.js +3 -7
  161. package/dist/place.js +1 -2
  162. package/dist/print.d.ts +15 -1
  163. package/dist/print.js +14 -3
  164. package/dist/propose.d.ts +10 -1
  165. package/dist/propose.js +30 -10
  166. package/dist/provider.js +12 -4
  167. package/dist/reflect-range.d.ts +8 -1
  168. package/dist/reflect-range.js +3 -2
  169. package/dist/rows.d.ts +5 -3
  170. package/dist/rows.js +15 -4
  171. package/dist/run-launch.d.ts +27 -2
  172. package/dist/run-launch.js +15 -4
  173. package/dist/run-learning-served.d.ts +13 -2
  174. package/dist/run-manifest.d.ts +5 -0
  175. package/dist/run-manifest.js +20 -0
  176. package/dist/run-reads-over-store.d.ts +1 -1
  177. package/dist/run-repo.d.ts +20 -0
  178. package/dist/run-repo.js +63 -0
  179. package/dist/run-secrets.js +2 -3
  180. package/dist/run-timeline-served.d.ts +1 -1
  181. package/dist/run-timeline-served.js +5 -2
  182. package/dist/run-view.d.ts +19 -8
  183. package/dist/run-view.js +62 -26
  184. package/dist/runnable.d.ts +0 -3
  185. package/dist/runnable.js +37 -29
  186. package/dist/runner/adapter-loop.d.ts +47 -17
  187. package/dist/runner/adapter-loop.js +1427 -303
  188. package/dist/runner/adapter-run-spec.d.ts +23 -9
  189. package/dist/runner/adapter-run-spec.js +162 -56
  190. package/dist/runner/adapters/pi-computer.d.ts +9 -0
  191. package/dist/runner/adapters/pi-computer.js +51 -0
  192. package/dist/runner/adapters/pi.d.ts +25 -11
  193. package/dist/runner/adapters/pi.js +168 -45
  194. package/dist/runner/beside.d.ts +7 -3
  195. package/dist/runner/beside.js +21 -11
  196. package/dist/runner/claim-secrets.d.ts +4 -0
  197. package/dist/runner/claim-secrets.js +6 -1
  198. package/dist/runner/cli-run-spec.d.ts +20 -3
  199. package/dist/runner/cli-run-spec.js +174 -64
  200. package/dist/runner/commands.d.ts +3 -1
  201. package/dist/runner/commands.js +28 -3
  202. package/dist/runner/computer-channel.d.ts +34 -0
  203. package/dist/runner/computer-channel.js +62 -0
  204. package/dist/runner/conformance/harness.d.ts +3 -0
  205. package/dist/runner/conformance/harness.js +224 -17
  206. package/dist/runner/conformance/subject.d.ts +12 -5
  207. package/dist/runner/dispatch.js +3 -0
  208. package/dist/runner/end-of-run.d.ts +23 -12
  209. package/dist/runner/end-of-run.js +41 -16
  210. package/dist/runner/feedback-round.d.ts +52 -0
  211. package/dist/runner/feedback-round.js +79 -0
  212. package/dist/runner/github-app.d.ts +2 -1
  213. package/dist/runner/github-app.js +4 -2
  214. package/dist/runner/harness-loops.js +15 -1
  215. package/dist/runner/held-run.d.ts +65 -0
  216. package/dist/runner/held-run.js +158 -0
  217. package/dist/runner/journal-kinds.d.ts +44 -7
  218. package/dist/runner/journal-kinds.js +29 -0
  219. package/dist/runner/journal-reader.d.ts +5 -4
  220. package/dist/runner/journal-reader.js +12 -10
  221. package/dist/runner/learning-ask.d.ts +7 -1
  222. package/dist/runner/learning-ask.js +21 -6
  223. package/dist/runner/learning-dispatch.d.ts +22 -0
  224. package/dist/runner/learning-dispatch.js +77 -10
  225. package/dist/runner/learning-end.d.ts +69 -13
  226. package/dist/runner/learning-end.js +340 -87
  227. package/dist/runner/learning-factory.d.ts +1 -1
  228. package/dist/runner/learning-factory.js +11 -5
  229. package/dist/runner/learning-loop.d.ts +86 -8
  230. package/dist/runner/learning-loop.js +178 -23
  231. package/dist/runner/learning-seed.d.ts +11 -0
  232. package/dist/runner/learning-seed.js +27 -0
  233. package/dist/runner/live-ticker.js +1 -0
  234. package/dist/runner/loop-contract.d.ts +26 -3
  235. package/dist/runner/loop.d.ts +21 -2
  236. package/dist/runner/loop.js +23 -2
  237. package/dist/runner/main.d.ts +13 -1
  238. package/dist/runner/main.js +27 -5
  239. package/dist/runner/mcp-claim.d.ts +15 -8
  240. package/dist/runner/mcp-claim.js +176 -71
  241. package/dist/runner/mcp-github.js +1 -1
  242. package/dist/runner/mcp-run.d.ts +21 -57
  243. package/dist/runner/mcp-run.js +25 -85
  244. package/dist/runner/meta-tools.d.ts +37 -0
  245. package/dist/runner/meta-tools.js +268 -0
  246. package/dist/runner/metrics.d.ts +11 -2
  247. package/dist/runner/metrics.js +26 -5
  248. package/dist/runner/model-route.js +12 -3
  249. package/dist/runner/monid-run.d.ts +16 -0
  250. package/dist/runner/monid-run.js +96 -0
  251. package/dist/runner/pr-checkout.d.ts +1 -0
  252. package/dist/runner/pr-checkout.js +1 -1
  253. package/dist/runner/promotion.d.ts +80 -0
  254. package/dist/runner/promotion.js +562 -0
  255. package/dist/runner/reflect-hook.d.ts +46 -13
  256. package/dist/runner/reflect-hook.js +149 -48
  257. package/dist/runner/runner.d.ts +26 -0
  258. package/dist/runner/runner.js +208 -17
  259. package/dist/runner/scratch-sweep.d.ts +13 -0
  260. package/dist/runner/scratch-sweep.js +62 -0
  261. package/dist/runner/sessions.d.ts +9 -4
  262. package/dist/runner/sessions.js +5 -1
  263. package/dist/runner/step-guard.d.ts +62 -0
  264. package/dist/runner/step-guard.js +93 -0
  265. package/dist/runner/store-port.d.ts +4 -2
  266. package/dist/runner/store-secrets.js +4 -3
  267. package/dist/runner/subagent.d.ts +0 -3
  268. package/dist/runner/subagent.js +10 -13
  269. package/dist/runner/workflow-first.d.ts +216 -0
  270. package/dist/runner/workflow-first.js +303 -0
  271. package/dist/runner/workflow-host.d.ts +6 -1
  272. package/dist/runner/workflow-host.js +1 -1
  273. package/dist/runner/workflow-loop.d.ts +1 -1
  274. package/dist/runner/workflow-loop.js +17 -10
  275. package/dist/runner/workflow-spec.d.ts +15 -2
  276. package/dist/runner/workflow-spec.js +63 -23
  277. package/dist/runs-over-store.d.ts +17 -3
  278. package/dist/runs-over-store.js +59 -20
  279. package/dist/seal-key.js +3 -3
  280. package/dist/sealed-settings-store.d.ts +5 -2
  281. package/dist/sealed-settings-store.js +10 -4
  282. package/dist/secret-writes.d.ts +5 -4
  283. package/dist/secret-writes.js +5 -4
  284. package/dist/server-secrets-store.d.ts +4 -3
  285. package/dist/server-secrets-store.js +15 -9
  286. package/dist/server-secrets.js +3 -2
  287. package/dist/server.d.ts +119 -18
  288. package/dist/server.js +841 -202
  289. package/dist/settings-wake.d.ts +23 -0
  290. package/dist/settings-wake.js +65 -0
  291. package/dist/standard-webhooks.d.ts +4 -1
  292. package/dist/standard-webhooks.js +8 -4
  293. package/dist/store/agent-body.d.ts +14 -3
  294. package/dist/store/agent-body.js +14 -10
  295. package/dist/store/command-wake.d.ts +13 -0
  296. package/dist/store/command-wake.js +37 -0
  297. package/dist/store/dialect.d.ts +6 -0
  298. package/dist/store/dialect.js +5 -0
  299. package/dist/store/index.d.ts +1 -1
  300. package/dist/store/journal/storage.d.ts +3 -2
  301. package/dist/store/journal/storage.js +13 -5
  302. package/dist/store/postgres/connection.js +3 -1
  303. package/dist/store/postgres/dialect.js +4 -0
  304. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  305. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  306. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  307. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  308. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  309. package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
  310. package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
  311. package/dist/store/schema.d.ts +10 -1
  312. package/dist/store/schema.js +104 -15
  313. package/dist/store/sqlite/connection.d.ts +2 -2
  314. package/dist/store/sqlite/connection.js +2 -2
  315. package/dist/store/sqlite/run-patch.d.ts +7 -5
  316. package/dist/store/sqlite/run-patch.js +45 -18
  317. package/dist/store/sqlite/store.js +331 -72
  318. package/dist/store/store.d.ts +312 -21
  319. package/dist/store/store.js +12 -1
  320. package/dist/store-reads/cap.d.ts +1 -1
  321. package/dist/store-reads/cap.js +8 -1
  322. package/dist/store-reads/decisions.d.ts +2 -2
  323. package/dist/store-reads/decisions.js +1 -1
  324. package/dist/store-reads/import-summary.d.ts +1 -1
  325. package/dist/store-reads/journal.d.ts +30 -5
  326. package/dist/store-reads/journal.js +128 -56
  327. package/dist/store-reads/learning.d.ts +114 -12
  328. package/dist/store-reads/learning.js +238 -48
  329. package/dist/store-reads/loop.d.ts +61 -0
  330. package/dist/store-reads/loop.js +111 -0
  331. package/dist/store-reads/runs.d.ts +1 -1
  332. package/dist/store-reads/workflow.d.ts +1 -1
  333. package/dist/store-view.d.ts +6 -0
  334. package/dist/store-view.js +59 -26
  335. package/dist/template-eval.d.ts +18 -9
  336. package/dist/template-eval.js +95 -68
  337. package/dist/template-github-permissions.d.ts +24 -10
  338. package/dist/template-github-permissions.js +36 -15
  339. package/dist/template-import.d.ts +31 -0
  340. package/dist/template-import.js +121 -0
  341. package/dist/template-source.d.ts +51 -0
  342. package/dist/template-source.js +371 -0
  343. package/dist/templates.d.ts +218 -46
  344. package/dist/templates.js +493 -181
  345. package/dist/timeline/computer.d.ts +48 -0
  346. package/dist/timeline/computer.js +169 -0
  347. package/dist/timeline/index.d.ts +4 -3
  348. package/dist/timeline/index.js +4 -3
  349. package/dist/timeline/labels.d.ts +6 -2
  350. package/dist/timeline/labels.js +93 -2
  351. package/dist/timeline/origin.d.ts +19 -5
  352. package/dist/timeline/origin.js +11 -4
  353. package/dist/timeline/timeline.d.ts +22 -1
  354. package/dist/timeline/timeline.js +34 -18
  355. package/dist/timeline/util.d.ts +4 -0
  356. package/dist/timeline/util.js +14 -0
  357. package/dist/tool-gate.d.ts +84 -50
  358. package/dist/tool-gate.js +179 -101
  359. package/dist/tool-keys.d.ts +4 -1
  360. package/dist/tool-keys.js +8 -3
  361. package/dist/tool-list.d.ts +26 -0
  362. package/dist/tool-list.js +43 -0
  363. package/dist/tool-names.d.ts +71 -0
  364. package/dist/tool-names.js +99 -0
  365. package/dist/tool-plane.d.ts +33 -27
  366. package/dist/tool-plane.js +72 -39
  367. package/dist/tools.d.ts +32 -7
  368. package/dist/tools.js +37 -24
  369. package/dist/trigger-adapter.d.ts +4 -0
  370. package/dist/trigger-secrets-shown.d.ts +2 -2
  371. package/dist/trigger-secrets-shown.js +1 -1
  372. package/dist/trigger-signatures.d.ts +25 -6
  373. package/dist/trigger-signatures.js +41 -7
  374. package/dist/trigger-targets.d.ts +2 -0
  375. package/dist/trigger-targets.js +1 -0
  376. package/dist/trigger-webhook.js +5 -2
  377. package/dist/triggers.d.ts +7 -3
  378. package/dist/triggers.js +35 -5
  379. package/dist/turns.js +16 -1
  380. package/dist/validate.d.ts +15 -7
  381. package/dist/validate.js +102 -45
  382. package/dist/web-fetch.d.ts +2 -8
  383. package/dist/web-fetch.js +2 -22
  384. package/dist/web-search.d.ts +10 -5
  385. package/dist/web-search.js +7 -6
  386. package/dist/webhooks.d.ts +145 -102
  387. package/dist/webhooks.js +559 -322
  388. package/dist/workflow/decisions.d.ts +1 -1
  389. package/dist/workflow/node-runner.d.ts +2 -1
  390. package/dist/workflow/node.d.ts +2 -1
  391. package/dist/workflow/node.js +3 -1
  392. package/dist/workflow/pi-versions.d.ts +23 -0
  393. package/dist/workflow/pi-versions.js +57 -0
  394. package/dist/workflow/record-tool.d.ts +2 -1
  395. package/dist/workflow/store.d.ts +1 -1
  396. package/dist/workflow/task.js +3 -2
  397. package/dist/workflow-run.d.ts +1 -1
  398. package/dist/workspace/attached-computers.d.ts +41 -0
  399. package/dist/workspace/attached-computers.js +114 -0
  400. package/dist/workspace/computer-deps.d.ts +19 -9
  401. package/dist/workspace/computer-deps.js +24 -9
  402. package/dist/workspace/computer-for-claim.d.ts +23 -8
  403. package/dist/workspace/computer-for-claim.js +92 -33
  404. package/dist/workspace/computer-hold.d.ts +11 -27
  405. package/dist/workspace/computer-hold.js +41 -55
  406. package/dist/workspace/computer-ledger.d.ts +3 -1
  407. package/dist/workspace/computer-ledger.js +4 -0
  408. package/dist/workspace/computer-mcp.d.ts +25 -0
  409. package/dist/workspace/computer-mcp.js +41 -0
  410. package/dist/workspace/computer-ports.d.ts +4 -13
  411. package/dist/workspace/computer-ports.js +4 -107
  412. package/dist/workspace/computer-script.d.ts +53 -0
  413. package/dist/workspace/computer-script.js +172 -0
  414. package/dist/workspace/executors.d.ts +1 -1
  415. package/dist/workspace/index.d.ts +4 -2
  416. package/dist/workspace/index.js +3 -1
  417. package/dist/workspace/kind-skills/desktop/SKILL.md +132 -84
  418. package/dist/workspace/kind-skills/phone/SKILL.md +104 -85
  419. package/dist/workspace/local.js +2 -2
  420. package/dist/workspace/resolve-computer.d.ts +24 -1
  421. package/dist/workspace/resolve-computer.js +40 -16
  422. package/dist/workspace/run-tools.d.ts +56 -21
  423. package/dist/workspace/run-tools.js +55 -34
  424. package/dist/wrap-up.d.ts +21 -0
  425. package/dist/wrap-up.js +21 -0
  426. package/launcher/agentrun-serve +4 -2
  427. package/package.json +19 -16
  428. package/templates/README.md +111 -45
  429. package/templates/code-review/agent.md +30 -14
  430. package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
  431. package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
  432. package/templates/code-review/evals/injection/case.yaml +2 -1
  433. package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
  434. package/templates/code-review/evals/mentions-defused/case.yaml +2 -2
  435. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
  436. package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
  437. package/templates/code-review/evals/never-flag/case.yaml +2 -1
  438. package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
  439. package/templates/code-review/evals/null-name/case.yaml +2 -1
  440. package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
  441. package/templates/code-review/evals/off-by-one/case.yaml +2 -1
  442. package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
  443. package/templates/code-review/evals/other-repo/case.yaml +16 -0
  444. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
  445. package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
  446. package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
  447. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
  448. package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
  449. package/templates/code-review/evals/other-repo/prompt.md +10 -0
  450. package/templates/code-review/evals/re-review/case.yaml +2 -1
  451. package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
  452. package/templates/code-review/evals/re-review-open/case.yaml +2 -1
  453. package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
  454. package/templates/code-review/evals/repo-rule/case.yaml +2 -1
  455. package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
  456. package/templates/code-review/evals/two-defects/case.yaml +2 -1
  457. package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
  458. package/templates/code-review/rules/CODEREVIEW.md +1 -1
  459. package/templates/code-review/skills/review/DEEP.md +3 -2
  460. package/templates/code-review/skills/review/REVIEWER.md +3 -2
  461. package/templates/code-review/skills/review/SKILL.md +4 -3
  462. package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
  463. package/templates/inbound-lead/agent.md +26 -16
  464. package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
  465. package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
  466. package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
  467. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
  468. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
  469. package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
  470. package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
  471. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
  472. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
  473. package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
  474. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
  475. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
  476. package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
  477. package/templates/kyb/agent.md +15 -5
  478. package/templates/kyb/evals/adverse-media/prompt.md +2 -7
  479. package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
  480. package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
  481. package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
  482. package/templates/kyb/evals/name-collision/prompt.md +2 -6
  483. package/templates/kyb/evals/no-invention/prompt.md +2 -6
  484. package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
  485. package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
  486. package/templates/kyb/kyb.schema.json +8 -7
  487. package/templates/kyb/skills/kyb/SKILL.md +9 -6
  488. package/templates/market-monitor/agent.md +19 -12
  489. package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
  490. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
  491. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
  492. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
  493. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  494. package/templates/release-notes/agent.md +32 -10
  495. package/templates/release-notes/evals/draft-not-publish/case.yaml +4 -3
  496. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
  497. package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
  498. package/templates/release-notes/evals/issue-write-refused/case.yaml +4 -3
  499. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
  500. package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
  501. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
  502. package/templates/release-notes/evals/learned-style/case.yaml +2 -1
  503. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
  504. package/templates/release-notes/evals/other-repo/case.yaml +24 -0
  505. package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
  506. package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
  507. package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
  508. package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
  509. package/templates/release-notes/evals/other-repo/prompt.md +32 -0
  510. package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
  511. package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
  512. package/templates/release-notes/notes.schema.json +1 -1
  513. package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
  514. package/dist/console/assets/index-BI4Byidu.js +0 -550
  515. package/dist/console/assets/index-C19gUF2n.css +0 -1
  516. package/dist/run-db.d.ts +0 -53
  517. package/dist/run-db.js +0 -116
  518. package/dist/tool-blurbs.d.ts +0 -4
  519. package/dist/tool-blurbs.js +0 -28
  520. package/dist/tool-budget.d.ts +0 -26
  521. package/dist/tool-budget.js +0 -56
  522. package/dist/workflow/readers.d.ts +0 -36
  523. package/dist/workflow/readers.js +0 -145
  524. package/dist/workflow/wal.d.ts +0 -11
  525. package/dist/workflow/wal.js +0 -106
  526. package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
  527. package/templates/code-review/evals/injection/graders/schema.md +0 -5
  528. package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
  529. package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
  530. package/templates/code-review/evals/null-name/graders/schema.md +0 -5
  531. package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
  532. package/templates/code-review/evals/re-review/graders/schema.md +0 -5
  533. package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
  534. package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
  535. package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
  536. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
  537. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
  538. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
  539. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
  540. package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
  541. package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
  542. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
  543. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
  544. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
  545. package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
  546. package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
  547. package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
  548. package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
  549. package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
  550. package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
  551. package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
  552. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
  553. package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
  554. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
  555. package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
  556. package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
  557. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
  558. package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
  559. package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
  560. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
  561. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
  562. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
  563. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
  564. package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
  565. package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
  566. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
  567. package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
  568. package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
@@ -3,36 +3,94 @@ 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
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";
6
+ import { turnEndedOnAsk } from "../store-reads/journal.js";
7
+ import { CAP_WRAPUP, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
7
8
  import { raiseFollowUpId } from "../run-view.js";
9
+ import { durableWait } from "../workflow/pi-versions.js";
8
10
  /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
9
11
  * 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
12
  * on its end (a fresh reopen). */
11
- const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold"]);
13
+ const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
14
+ /** A learned workflow's handback is the server's message to the agent, never the person's. */
15
+ const HANDED_BACK_ORIGIN = { kind: "server", reason: "handed_back" };
12
16
  /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
13
17
  const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
18
+ /** The output contract's one retry turn is the server's message too, under one request id per run: pi places it once from
19
+ * its submission, a CLI's record writes it once, and a claim that finds it on the record never asks again. */
20
+ const OUTPUT_RETRY_ORIGIN = { kind: "server", reason: "output_retry" };
21
+ const OUTPUT_RETRY_REQUEST = "agentrun:output-retry";
22
+ /** Whether the run had its one retry: the input entry the retry wrote (pi's submission, a CLI's record) with the model's
23
+ * answer after it. One written and never answered (a runner lost between a CLI's record and its send) is not had: the
24
+ * claim that opens the session again sends it, under the same request id, so it is written once. */
25
+ const outputRetried = (entries) => {
26
+ const at = entries.findLastIndex((entry) => entry.kind === KINDS.input && originOf(entry.data?.origin)?.reason === OUTPUT_RETRY_ORIGIN.reason);
27
+ return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
+ };
14
29
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
15
30
  import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
16
31
  import { ADAPTER_API } from "../turn-end.js";
17
32
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.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";
33
+ import { approvalOf, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
34
+ import { outputMiss, outputRetryWords } from "../answer-json.js";
19
35
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
20
36
  import { isComputerCommand, journalHold } from "./computer-journal.js";
37
+ import { isHeldCommand, journalHeld } from "./held-run.js";
38
+ import { HELD_KIND, heldWords } from "../computer-held.js";
39
+ import { CALL_KIND, CALL_MS, COMPUTER_CALL } from "../computer-channel.js";
40
+ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
41
+ import { channelCallOf, runChannelCall } from "./computer-channel.js";
21
42
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
22
43
  import { journalSessions } from "./sessions.js";
23
- import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
44
+ import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, recentAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
24
45
  import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
25
46
  import { bookedIn } from "../paid-calls.js";
26
47
  import { withHostCalls } from "../host-calls.js";
27
48
  import { sideEffect } from "./side-effects.js";
28
49
  import { McpClaimRefused } from "./mcp-claim.js";
50
+ import { CODEMODE, defersCatalog, isCatalogName, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
51
+ import { metaTools } from "./meta-tools.js";
52
+ import { builtinHarness } from "../harness-table.js";
29
53
  import { Fenced } from "../store/index.js";
30
- import { parkedFollowUp } from "./mcp-run.js";
31
- import { budgetOf, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
54
+ import { answerAsServed } from "../answer-json.js";
55
+ import { reserveFor, WRAP_UP_TEXT, wrappingUp } from "../wrap-up.js";
56
+ import { LEARNED_CLIP, LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
57
+ import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
58
+ import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
59
+ /** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
60
+ * and the harness's next call runs it. */
61
+ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
32
62
  /** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
33
63
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
34
64
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
35
65
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
66
+ /** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
67
+ const TURN_CUT_AT_QUESTION = "the turn ended at its question to the person";
68
+ function turnCut() {
69
+ let armedAt;
70
+ let ask;
71
+ let asked = new Promise((resolve) => (ask = resolve));
72
+ const held = [];
73
+ return {
74
+ arm: (callId) => void (armedAt = callId),
75
+ disarm: () => void (armedAt = undefined),
76
+ get armed() {
77
+ return armedAt !== undefined;
78
+ },
79
+ hold() {
80
+ ask();
81
+ return new Promise((_, reject) => held.push(reject));
82
+ },
83
+ get asked() {
84
+ return asked;
85
+ },
86
+ done() {
87
+ armedAt = undefined;
88
+ for (const reject of held.splice(0))
89
+ reject(new Error(TURN_CUT_AT_QUESTION));
90
+ asked = new Promise((resolve) => (ask = resolve));
91
+ },
92
+ };
93
+ }
36
94
  /** A HostLifecycle and the ToolHost members that fill it: what a spec's ToolHost takes, and hands the loop. */
37
95
  export function hostLifecycle() {
38
96
  const onConversation = [];
@@ -87,6 +145,10 @@ export function pendingPauseOf(entries) {
87
145
  }
88
146
  /** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
89
147
  const DELIVER_NOW_MS = 5_000;
148
+ /** How long the cap's wrap-up note, once a request took it, waits for that request's admission before a later request
149
+ * may take it. A request that leaves before its admission gives it back as it goes (ModelPort.noteReturned): this is
150
+ * only the backstop for a path that never does. A proxy's token count and admission take well under it. */
151
+ const WRAP_UP_OFFER_MS = 30_000;
90
152
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
91
153
  const cutWhole = (text, max) => {
92
154
  const cut = text.slice(0, max);
@@ -107,6 +169,21 @@ const cliErrorAnswer = (harness, error, at) => ({
107
169
  timestamp: at,
108
170
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
109
171
  });
172
+ /** The session's recent requests as its newest KINDS.capRecent record kept them: each that reads as one (a model, and each
173
+ * figure a finite number of 0 or more); none without a record. One that does not read is left out: a request is then
174
+ * priced from another or uncached, never under its worst. */
175
+ export function recentIn(records) {
176
+ const kept = records.findLast((record) => record.kind === KINDS.capRecent)?.data;
177
+ if (!Array.isArray(kept))
178
+ return [];
179
+ const figure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
180
+ return kept.flatMap((data) => {
181
+ const one = (data ?? {});
182
+ if (typeof one !== "object" || typeof one.model !== "string" || !figure(one.cachedTokens) || !figure(one.inputTokens) || !figure(one.boundTokens) || !figure(one.endedAt))
183
+ return [];
184
+ return [{ model: one.model, cachedTokens: one.cachedTokens, inputTokens: one.inputTokens, boundTokens: one.boundTokens, endedAt: one.endedAt, ...(typeof one.counted === "boolean" ? { counted: one.counted } : {}) }];
185
+ });
186
+ }
110
187
  /** The turns a session's records booked (its runner.turn records), in order. */
111
188
  export function turnsOf(records) {
112
189
  return records.filter((record) => record.kind === RUNNER_RECORDS.turn).map((record) => record.data.turn).filter((turn) => typeof turn === "number");
@@ -155,12 +232,23 @@ const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forG
155
232
  /** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
156
233
  * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
157
234
  * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
158
- * message's timestamp: the Timeline dates its rows by them. */
159
- async function openCliRecord(harness, journal, context, now, cwd) {
235
+ * message's timestamp: the Timeline dates its rows by them. `endsItsCalls`: a harness that says each call's end itself
236
+ * (pi, of the calls its tools nest: it reruns a replay-safe one a crash cut), so none is ended interrupted here. */
237
+ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls = false) {
160
238
  const root = await harness.root(context);
161
239
  const append = async (kind, data) => {
162
240
  await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
163
241
  };
242
+ /** A message that starts a turn: its entry and the turn's start (KINDS.turnStart), one commit, so the turn is open from
243
+ * the commit that holds its message. `entry` is the whole message entry when it is the host's input (with its origin). */
244
+ const startsTurn = async (message) => {
245
+ await harness.commit(async (tx) => {
246
+ await tx.appendEntry(root.id, ("entry" in message ? message.entry : { kind: message.kind, data: { ...message.data, at: now() } }));
247
+ await tx.appendEntry(root.id, { kind: KINDS.turnStart, data: { at: now() } });
248
+ }, context);
249
+ turnsOpen += 1;
250
+ lastAsked = undefined;
251
+ };
164
252
  // Each call started on the record: whether it has its end; and each end, by call id.
165
253
  const started = new Map();
166
254
  const ends = new Map();
@@ -168,24 +256,39 @@ async function openCliRecord(harness, journal, context, now, cwd) {
168
256
  // is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
169
257
  const parked = new Set();
170
258
  const sent = new Set();
259
+ // A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
260
+ const nesting = new Set();
171
261
  // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
172
262
  const sending = new Set();
173
263
  let personWritten = false;
264
+ // The turns the record opened (KINDS.turnStart) and has not ended (KINDS.turnEnd): what the journal says on open, then kept.
265
+ let turnsOpen = 0;
174
266
  // The request ids of the follow-ups written (followUp): each is written once.
175
267
  const followUps = new Set();
176
268
  // 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
177
- // claim, after a crash in the turn) reuses it, never writes a second.
269
+ // claim, after a crash in the turn) reuses it, never writes a second. And what each kept as it was first asked.
178
270
  const askedAt = new Map();
271
+ const askedKept = new Map();
272
+ // The end-of-run turn asked last, while no turn of the job's (its input, a message, a follow-up) opened after it.
273
+ let lastAsked;
179
274
  for (const entry of await entriesOf(journal, root.id, context)) {
180
275
  const data = (entry.data ?? {});
181
276
  if (entry.kind === KINDS.messageSending && typeof data.commandId === "number")
182
277
  sending.add(data.commandId);
183
- if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string")
278
+ if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string") {
184
279
  askedAt.set(data.requestId, entry.id);
280
+ lastAsked = data.requestId;
281
+ if (data.kept && typeof data.kept === "object" && !Array.isArray(data.kept))
282
+ askedKept.set(data.requestId, data.kept);
283
+ }
284
+ if (entry.kind === KINDS.turnStart || (entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
285
+ lastAsked = undefined;
185
286
  if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
186
287
  ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
187
288
  if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.parked === true)
188
289
  parked.add(data.callId);
290
+ if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.nests === true)
291
+ nesting.add(data.callId);
189
292
  if (entry.kind === KINDS.callSent && typeof data.callId === "string")
190
293
  sent.add(data.callId);
191
294
  if (entry.kind === KINDS.callStart && typeof data.callId === "string")
@@ -194,30 +297,42 @@ async function openCliRecord(harness, journal, context, now, cwd) {
194
297
  started.set(data.callId, true);
195
298
  else if ((entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
196
299
  personWritten = true;
300
+ if (entry.kind === KINDS.turnStart)
301
+ turnsOpen += 1;
302
+ else if (entry.kind === KINDS.turnEnd && turnsOpen > 0)
303
+ turnsOpen -= 1;
197
304
  if ((entry.kind === KINDS.message || entry.kind === KINDS.input) && typeof data.requestId === "string")
198
305
  followUps.add(data.requestId);
199
306
  }
200
307
  for (const [callId, ended] of started) {
201
- if (ended || (parked.has(callId) && !sent.has(callId)))
308
+ if (endsItsCalls || ended || (parked.has(callId) && !sent.has(callId)) || nesting.has(callId))
202
309
  continue;
203
310
  await append(KINDS.callEnd, { callId, status: "interrupted" });
204
311
  started.set(callId, true);
205
312
  ends.set(callId, { status: "interrupted" });
206
313
  }
207
314
  let text = "";
315
+ /** A model message was written at a request's start (flushSaid) and no other flush has come since. */
316
+ let flushedAtRequest = false;
208
317
  /** The end-of-run turn's answer while that turn runs (answering), else undefined. */
209
318
  let answer;
210
319
  // One write at a time, in the order they were asked for, a failed one never stopping the next.
211
320
  let chain = Promise.resolve();
212
321
  const inTurn = (work) => (chain = chain.then(work, work));
213
322
  /** What was said since the last boundary as a model message; at a turn's end, with the cut its adapter reported. */
214
- const flushText = (cut) => {
323
+ const flushText = (cut, atRequest = false) => {
215
324
  // Taken at the boundary, not when its write's turn comes: text said after it is the next message's.
216
325
  const said = text;
217
326
  text = "";
218
327
  return inTurn(async () => {
219
328
  if (said === "")
220
329
  return;
330
+ // Whitespace after a message flushed at the request before it joined that message's row, as the turn's text up to its
331
+ // call always has: it is no message of its own.
332
+ const joined = flushedAtRequest && said.trim() === "";
333
+ flushedAtRequest = atRequest;
334
+ if (joined)
335
+ return;
221
336
  const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }) } : {};
222
337
  await append(KINDS.message, { role: "model", text: said, ...length });
223
338
  });
@@ -236,34 +351,51 @@ async function openCliRecord(harness, journal, context, now, cwd) {
236
351
  void flushText(event).catch(() => undefined);
237
352
  },
238
353
  flushText,
239
- person: (input) => inTurn(async () => {
354
+ flushSaid: () => (answer === undefined && text.trim() !== "" ? flushText(undefined, true) : Promise.resolve()),
355
+ person: (input, opens = true) => inTurn(async () => {
240
356
  if (personWritten)
241
357
  return;
242
- await append(KINDS.message, { role: "person", text: input });
358
+ if (opens)
359
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
360
+ else
361
+ await append(KINDS.message, { role: "person", text: input });
362
+ lastAsked = undefined;
243
363
  personWritten = true;
244
364
  }),
245
- input: (input, origin) => inTurn(async () => {
365
+ input: (input, origin, opens = true) => inTurn(async () => {
246
366
  if (personWritten)
247
367
  return;
248
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
368
+ const entry = { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] };
369
+ if (opens)
370
+ await startsTurn({ entry });
371
+ else
372
+ await harness.commit((tx) => tx.appendEntry(root.id, entry), context);
373
+ lastAsked = undefined;
249
374
  personWritten = true;
250
375
  }),
251
376
  followUp: (input, requestId, origin) => inTurn(async () => {
252
377
  if (followUps.has(requestId))
253
378
  return;
254
379
  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);
380
+ await startsTurn({ entry: { kind: KINDS.input, data: { origin, requestId }, model: [{ role: "user", content: input, timestamp: now() }] } });
256
381
  else
257
- await append(KINDS.message, { role: "person", text: input, requestId });
382
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input, requestId } });
258
383
  followUps.add(requestId);
259
384
  personWritten = true;
260
385
  }),
261
386
  message: (input, origin) => inTurn(async () => {
262
387
  if (origin)
263
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
388
+ await startsTurn({ entry: { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] } });
264
389
  else
265
- await append(KINDS.message, { role: "person", text: input });
390
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
391
+ }),
392
+ turnEnded: (status, error) => inTurn(async () => {
393
+ if (turnsOpen === 0)
394
+ return;
395
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.turnEnd, data: { status, ...(error === undefined ? {} : { error }) } }), context);
396
+ turnsOpen -= 1;
266
397
  }),
398
+ openTurn: () => turnsOpen > 0,
267
399
  async sending(commandId) {
268
400
  let again = false;
269
401
  await inTurn(async () => {
@@ -276,7 +408,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
276
408
  });
277
409
  return again;
278
410
  },
279
- async start(callId, tool, input, replaySafe) {
411
+ async start(callId, tool, input, replaySafe, nests) {
280
412
  await flushText();
281
413
  await inTurn(async () => {
282
414
  if (started.has(callId)) {
@@ -287,16 +419,16 @@ async function openCliRecord(harness, journal, context, now, cwd) {
287
419
  }
288
420
  return;
289
421
  }
290
- await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
422
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...(cwd ? { cwd } : {}) });
291
423
  started.set(callId, false);
292
424
  });
293
425
  },
294
- async park(callId, tool, input, replaySafe, bridge) {
426
+ async park(callId, tool, input, replaySafe) {
295
427
  await flushText();
296
428
  await inTurn(async () => {
297
429
  if (started.has(callId))
298
430
  return;
299
- await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(bridge ? { bridge } : {}), ...(cwd ? { cwd } : {}) });
431
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(cwd ? { cwd } : {}) });
300
432
  started.set(callId, false);
301
433
  parked.add(callId);
302
434
  });
@@ -331,18 +463,29 @@ async function openCliRecord(harness, journal, context, now, cwd) {
331
463
  started.set(callId, true);
332
464
  ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
333
465
  }),
334
- answering: (requestId, prompt) => {
466
+ answering: async (requestId, prompt, keep) => {
335
467
  answer = "";
336
- return inTurn(async () => {
468
+ await inTurn(async () => {
337
469
  if (askedAt.has(requestId))
338
470
  return;
339
471
  await harness.commit(async (tx) => {
340
472
  if (await tx.submissionByRequest(root.id, requestId))
341
473
  return;
342
- const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
474
+ // What the step keeps as the turn is first asked, with its prompt: durable before the turn's first request leaves
475
+ // (that request's flush), so a later claim that asks the turn again reads the first ask's, never its own.
476
+ const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId, ...(keep ? { kept: keep } : {}) }, model: [{ role: "user", content: prompt, timestamp: now() }] });
343
477
  askedAt.set(requestId, asked.id);
478
+ lastAsked = requestId;
479
+ if (keep)
480
+ askedKept.set(requestId, keep);
344
481
  }, context);
345
482
  });
483
+ return askedKept.get(requestId);
484
+ },
485
+ keptOf: (requestId) => askedKept.get(requestId),
486
+ async lookingBack() {
487
+ const requestId = lastAsked;
488
+ return requestId !== undefined && !(await harness.commit((tx) => tx.submissionByRequest(root.id, requestId), context));
346
489
  },
347
490
  answered: (requestId, prompt, status) => inTurn(async () => {
348
491
  const said = answer ?? "";
@@ -385,6 +528,16 @@ function adapterLoop(specOf, options, deps) {
385
528
  };
386
529
  let stopped = () => { };
387
530
  const stopping = new Promise((resolve) => (stopped = resolve));
531
+ /** A cancel, a lost claim or a shutdown that came after a person's stop, and the cut it gives the held computer that
532
+ * stop kept (writeEnd). */
533
+ let laterStop;
534
+ /** Whether the run's first stop kept its computer (keeps), as the runner was told when it chose to go on handing the
535
+ * run's rows on: a stop that came before the hold was up (the computer still coming up) did not, so its end lets the
536
+ * computer go, never waiting for a release no row can bring. */
537
+ let keptAtStop = false;
538
+ const keeps = (reason) => reason.kind === "command" && !reason.cancel && heldNow !== undefined && heldNow.state() !== "released" && !gate?.sealed;
539
+ let cutHeld = () => { };
540
+ const heldCut = new Promise((resolve) => (cutHeld = resolve));
388
541
  /** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal): a host tool call in flight (a CLI's door
389
542
  * call among them, whose own request signal its CLI may never abort) is cut with it, as pi's own abort cuts pi's calls.
390
543
  * stop() aborts it first, with the stop's Interrupted, so the reason a cut call reads is the stop's. */
@@ -402,6 +555,8 @@ function adapterLoop(specOf, options, deps) {
402
555
  let refusals = 0;
403
556
  /** The claim's first delivery is done (LoopDeps.delivered): every row the runner read is with the loop. */
404
557
  let delivered = false;
558
+ /** The calls this run's journal had asked about and not answered when the claim first read it (askStands). */
559
+ let standing;
405
560
  /** The run is parking at its cap (the early pause, from its commit on): a raise row is left for the next claim. */
406
561
  let pausing = false;
407
562
  /** Resolved once the claim's Harness is open and its root known: a command's check reads the journal through it. */
@@ -410,6 +565,14 @@ function adapterLoop(specOf, options, deps) {
410
565
  let held;
411
566
  /** The run's computer hold's journal side, for the current pass (AdapterRunSpec.computer). */
412
567
  let computerNow;
568
+ /** The run's computer held for its owner, for the current pass (AdapterRunSpec.held). */
569
+ let heldNow;
570
+ /** The current pass's computer for the computer call channel (AdapterRunSpec.computer), and how a call's entry is
571
+ * committed on the run's root through the pass's Harness. */
572
+ let channelNow;
573
+ /** Channel calls done on the computer whose record (and row's take) is still to be written: each answers whether it
574
+ * wrote (settleCalls). */
575
+ const unsettledCalls = new Set();
413
576
  /** This claim's spec, once known: a raise is checked by its cap's rule, and the end's patch is read from it. */
414
577
  let specNow;
415
578
  /** Whether this claim's tool host was let go (its beforeRelease run), once. */
@@ -440,15 +603,27 @@ function adapterLoop(specOf, options, deps) {
440
603
  * Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
441
604
  * the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
442
605
  let reopen;
606
+ /** A grade's feedback round this claim closes (runner/feedback-round.ts): the run opened again on a grade's words (its
607
+ * steer, taken with a FEEDBACK entry and never sent as a turn), or a claim that finds such an entry with no end after it.
608
+ * The agent is asked no turn of the job's: the run goes to its end-of-run turn, told the grade first (feedbackAsk). */
609
+ let feedbackNow;
443
610
  /** A reopen of a run whose session is still new (a person stopped it before its first input was sent): resolved once the
444
611
  * person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
445
612
  * late the runner hands the message over. */
446
613
  let firstInputPlaced;
614
+ /** Resolved once a pass of this claim has sent what its session starts on (the run's input, a follow-up, a recovery),
615
+ * or found nothing to send: a message handed over while the session is still new waits for it, so it lands after the
616
+ * run's input, never as the session's first prompt (a message sent as soon as the run's 202 came back). */
617
+ let inputSent = () => { };
618
+ const startSent = new Promise((resolve) => (inputSent = resolve));
447
619
  /** The tool hosts' holds while the run waits in its claim on the person's answer (HostLifecycle.personWait): dropped
448
620
  * once the wait is over, whichever way it ends. */
449
621
  let waitHolds = [];
450
622
  /** The wait's own `reopen`, while it is set. */
451
623
  let waitTurn;
624
+ /** The `reopen` of a CLI run parked on its question (its turn cut there: no steer reaches its idle session), while it is
625
+ * set: the person's answer is the claim's turn, and a trigger's message is no answer. */
626
+ let askReopen;
452
627
  /** A person's message placed as a steer while the session was idle and no wait took it (its turn tracked by no one): the
453
628
  * answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
454
629
  * answer (waitInClaim), once. */
@@ -466,6 +641,14 @@ function adapterLoop(specOf, options, deps) {
466
641
  /** 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
467
642
  * during the end-of-run turn does. */
468
643
  let turnsOver = false;
644
+ /** While the run's learned workflow runs first (AdapterRunSpec.workflowFirst): a message waits for it, then goes the way
645
+ * any message goes once the workflow answered (the run is ending) or handed the job back (the agent's turn runs). */
646
+ let servingFirst;
647
+ /** The messages waiting for the run's first input (steer: the session still new, or its learned workflow running first),
648
+ * placed one after another, in the order they came, once it is sent; `waitingFirst` counts those not placed yet, so a
649
+ * message after them waits its turn behind them. */
650
+ let afterFirst = Promise.resolve();
651
+ let waitingFirst = 0;
469
652
  /** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
470
653
  * only while it is that wait's (a wait that settles late never ends a later one). */
471
654
  const endWait = (of) => {
@@ -485,6 +668,10 @@ function adapterLoop(specOf, options, deps) {
485
668
  };
486
669
  /** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
487
670
  let cliRecord;
671
+ /** A CLI's turn cut at its question to the person (TurnCut): armed by the call's end, asked for by the next request. */
672
+ const askCut = turnCut();
673
+ /** Whether this loop sent the run its output retry (sendOutputRetry): never a second, even when its turn gave no answer. */
674
+ let outputRetrySent = false;
488
675
  /** The session's paid requests admitted and not yet booked (its model port's beforeRequest, then its afterRequest), and
489
676
  * who waits for none: the run's end waits for them, since a booking written after the end (the run's release) is
490
677
  * fenced and lost, and its request read back at its hold. */
@@ -636,6 +823,89 @@ function adapterLoop(specOf, options, deps) {
636
823
  handing = turn.catch(() => undefined);
637
824
  return turn;
638
825
  };
826
+ /** The owner's start or release of a held computer (runner/held-run.ts): taken by the commit that writes what came of it
827
+ * (its entry carries the row's id); refused in words when it changed nothing. One at a time, in the take-over's turn. */
828
+ const heldCommand = (command) => {
829
+ const turn = handing.then(async () => {
830
+ await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
831
+ const [theGate, theHeld] = [gate, heldNow];
832
+ if (!theGate || theGate.sealed)
833
+ return { later: "the run is parking or ending: the row waits for its next claim" };
834
+ if (!theHeld)
835
+ return { refused: "This run does not hold its computer: start it with hold: true." };
836
+ const decided = theHeld.decide(command);
837
+ if ("refused" in decided)
838
+ return decided;
839
+ const madeBy = (data) => theHeld.madeBy(data, command.id);
840
+ const landed = theGate.expect(writesEntry(HELD_KIND, madeBy), { take: [command.id] });
841
+ landed.catch(() => undefined);
842
+ await decided.write();
843
+ await landed;
844
+ return { taken: true };
845
+ });
846
+ handing = turn.catch(() => undefined);
847
+ return turn;
848
+ };
849
+ /**
850
+ * A call through the computer call channel (runner/computer-channel.ts): run on the pass's computer, behind the
851
+ * person's hold, and taken with its answer by the commit that writes its computer.call entry. It runs off the take-over's
852
+ * turn and off the runner's delivery, which goes on to the next row at once: a call may wait for a person's hand-back,
853
+ * and the hand-back is a later row. So `taken` here means its take rides on that entry's commit once the call is done
854
+ * (settleCalls): a fault's restart meanwhile writes it through the claim's next pass, and a claim that ends first leaves
855
+ * the row untaken for the run's end, or its next claim, to settle. Refused in words when the run has no
856
+ * computer that takes calls, is parking or ending, or held its computer and let it go.
857
+ */
858
+ const channelCommand = async (command) => {
859
+ await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
860
+ const [theGate, pass, theHeld] = [gate, channelNow, heldNow];
861
+ if (!theGate || theGate.sealed)
862
+ return { refused: "The run's computer is not up now: the run is starting, parking or ending." };
863
+ if (!pass)
864
+ return { refused: specNow?.computer ? "The run's computer is not up now: the run is starting, parking or ending." : "This run has no computer that takes protocol calls: none, or a browser." };
865
+ const refusal = theHeld?.refusesCall();
866
+ if (refusal)
867
+ return { refused: refusal };
868
+ const call = channelCallOf(command);
869
+ if ("refused" in call)
870
+ return call;
871
+ void (async () => {
872
+ // The hold's idle count stands still while the call runs, and starts again when the last one ends.
873
+ theHeld?.callStarted();
874
+ let done;
875
+ try {
876
+ done = await runChannelCall(pass.computer, call, AbortSignal.any([deps.signal, AbortSignal.timeout(CALL_MS)]), now);
877
+ }
878
+ finally {
879
+ theHeld?.callEnded(now());
880
+ }
881
+ unsettledCalls.add(async () => {
882
+ // Written through the pass open now: the one the call ran in, or, when a fault closed that one meanwhile, the
883
+ // claim's next. None open (between passes): it waits for the next pass to open.
884
+ const [liveGate, livePass] = [gate, channelNow];
885
+ if (!liveGate || liveGate.sealed || !livePass)
886
+ return false;
887
+ const landed = liveGate.expect(writesEntry(CALL_KIND, (data) => data.by === command.id), { take: [command.id], answer: { command: command.id, value: done.answer } });
888
+ landed.catch(() => undefined);
889
+ await livePass.commit([{ kind: CALL_KIND, data: { by: command.id, at: done.at, ...done.record } }]);
890
+ await landed;
891
+ return true;
892
+ });
893
+ settleCalls();
894
+ })().catch(() => undefined);
895
+ return { taken: true };
896
+ };
897
+ /** Writes each finished channel call whose record is not written yet, through the pass open now. One the pass's seal
898
+ * failed stays for the next pass; one the claim ends with stays untaken, and the run's end (or its next claim) settles
899
+ * its row. */
900
+ function settleCalls() {
901
+ for (const settle of [...unsettledCalls]) {
902
+ unsettledCalls.delete(settle);
903
+ settle().then((written) => {
904
+ if (!written)
905
+ unsettledCalls.add(settle);
906
+ }, () => unsettledCalls.add(settle));
907
+ }
908
+ }
639
909
  /** The raise entry, taking every raise row this claim has in its one commit (each take keyed to the entry). */
640
910
  async function takeRaises() {
641
911
  const takes = raising.takes.splice(0);
@@ -658,12 +928,49 @@ function adapterLoop(specOf, options, deps) {
658
928
  if (data.capUsd > 0)
659
929
  raisedCapUsd = data.capUsd;
660
930
  }
931
+ const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
661
932
  const steer = async (command) => {
662
933
  // Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
663
- if (!gate || !session)
664
- await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
934
+ // Awaited even with a session there: until the claim is ready it has not said whether this message reopens the run.
935
+ await Promise.race([ready, over()]);
665
936
  // The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
666
937
  // untaken for the next claim, which hands it on again; never refused for good.
938
+ if (!gate || !session || gate.sealed)
939
+ return { later: "the run is parking: the steer waits for its resume" };
940
+ // The session is still new and this is no reopen's message (the claim has yet to send the run's input), or the run's
941
+ // learned workflow runs first, or a message before it still waits for either: it waits for the input, off the runner's
942
+ // delivery, as a computer channel's call does (channelCommand). The runner hands the run's rows on one at a time, each
943
+ // once the one before it answered: held here for a workflow that runs long, this message would hold every row after it,
944
+ // and a person's stop or cancel (the stop that cuts the workflow's call, its spend and custody), a raise or a hand-back
945
+ // would never reach the run. `taken` here means its take rides on the commit that places it once the input is sent; a
946
+ // claim that ends first (a stop, a park, the workflow's answer) leaves the row untaken, for the run's end or its next
947
+ // claim to settle, as any message the run's end finds untaken.
948
+ if (waitingFirst > 0 || (!reopen && session.state === "new") || servingFirst) {
949
+ waitingFirst += 1;
950
+ const placing = afterFirst.then(() => placeSteer(command));
951
+ afterFirst = placing.then(() => void (waitingFirst -= 1), (error) => {
952
+ waitingFirst -= 1;
953
+ console.warn(`[runner] a message that waited for the run's first input was not placed: ${said(error)}`);
954
+ });
955
+ return { taken: true };
956
+ }
957
+ return placeSteer(command);
958
+ };
959
+ /** A person's message placed (steer): as the run's next turn, into the turn in flight, or after it. */
960
+ const placeSteer = async (command) => {
961
+ if (!gate || !session || gate.sealed)
962
+ return { later: "the run is parking: the steer waits for its resume" };
963
+ // The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
964
+ // the message would be the session's first prompt and the input would follow it; it waits for the input instead, then
965
+ // goes into that turn as any message does.
966
+ if (!reopen && session.state === "new") {
967
+ await Promise.race([startSent, over()]);
968
+ if (!gate || !session || gate.sealed)
969
+ return { later: "the run is parking: the steer waits for its resume" };
970
+ }
971
+ // The run's learned workflow is running first: nothing is sent to the agent until it answered or handed the job back.
972
+ if (servingFirst)
973
+ await servingFirst;
667
974
  if (!gate || !session || gate.sealed)
668
975
  return { later: "the run is parking: the steer waits for its resume" };
669
976
  // 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
@@ -681,14 +988,41 @@ function adapterLoop(specOf, options, deps) {
681
988
  // The session idle with no wait taking messages yet: whether the last turn ended on a question to the person, read
682
989
  // first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
683
990
  // between that choice and the message's placing.
684
- const askedLast = !reopen && session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
991
+ const reopenedBefore = reopen;
992
+ const endedOnAsk = session.state === "idle" && root !== undefined && turnEndedOnAsk((await entriesOf(gate.journal, root.id, context))) !== undefined;
993
+ const askedLast = !reopenedBefore && endedOnAsk;
994
+ // A reopen of a run its learned workflow answered alone (its session new: the agent never took the job): what the
995
+ // workflow answered, said to the agent between the job and the message, which is a word on that answer.
996
+ const servedAnswer = reopen && !reopen.sent && session.state === "new" && root !== undefined ? servedAnswerOf(await entriesOf(gate.journal, root.id, context)) : undefined;
685
997
  if (!gate || !session || gate.sealed)
686
998
  return { later: "the run is parking: the steer waits for its resume" };
687
999
  // A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
688
- // between the question's turn end and that wait): never the wait's answer, never placed, refused in the words the
689
- // server refuses one with while the run waits (runs-over-store.ts WAITS_ON_A_PERSON).
690
- if (followUp && (askedLast || (reopen !== undefined && reopen === waitTurn)))
691
- return { refused: "The run is waiting on a person." };
1000
+ // between the question's turn end and that wait): never the wait's answer, never placed now. Its firing reads sent (the
1001
+ // door took the row), so it is never refused either: left untaken, it runs as a turn of its own after the person's
1002
+ // answer, as a parked run's does (the store's park takes no wake from it; the run's end opens the run again with it).
1003
+ if (followUp && (askedLast || (reopen !== undefined && (reopen === waitTurn || reopen === askReopen))))
1004
+ return { later: "the run is waiting on a person: the message runs as a turn of its own after the answer" };
1005
+ // A grade's feedback round (feedback-round.ts): the run opened again on the grade's words, which are never a turn of
1006
+ // the job's. Kept on the root as a FEEDBACK entry, whose commit takes the row; the claim goes to its end-of-run turn.
1007
+ const fed = reopen && !reopen.sent && (session.state === "idle" || session.state === "new") ? feedbackOf(command.body) : undefined;
1008
+ if (fed && reopen && harness && root) {
1009
+ const [on, theRoot, mine] = [harness, root, reopen];
1010
+ const taken = gate.expect(writesEntry(KINDS.feedback, (data) => data.requestId === requestId), { take: [command.id] });
1011
+ taken.catch(() => undefined);
1012
+ mine.feedback = fed;
1013
+ mine.sent = on.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.feedback, data: { ...fed, requestId, at: now() } }), context).then(() => undefined);
1014
+ mine.placed?.();
1015
+ try {
1016
+ await mine.sent;
1017
+ }
1018
+ catch (error) {
1019
+ if (gate.sealed)
1020
+ return { later: "the run is parking: the feedback waits for its resume" };
1021
+ return { refused: `the feedback was not kept: ${error.message}` };
1022
+ }
1023
+ await taken.catch(() => { });
1024
+ return { taken: true };
1025
+ }
692
1026
  // 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
693
1027
  // follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
694
1028
  if (reopen && !reopen.sent && (session.state === "idle" || session.state === "new")) {
@@ -702,23 +1036,28 @@ function adapterLoop(specOf, options, deps) {
702
1036
  // never sent, or answered, as a turn of its own.
703
1037
  const first = theSession.state === "new" ? specNow : undefined;
704
1038
  const sendId = first ? INPUT_REQUEST : requestId;
705
- const content = first ? `${first.input}\n\n${text}` : text;
1039
+ // A run its learned workflow answered alone: the job, what the workflow answered (cut of the runner's secrets, as a
1040
+ // handback is), then the message.
1041
+ const answered = first && servedAnswer ? servedAnswerText(servedAnswer.workflow, deps.redact ? deps.redact(servedAnswer.answer) : servedAnswer.answer) : undefined;
1042
+ const content = first ? [first.input, ...(answered ? [answered] : []), text].join("\n\n") : text;
706
1043
  // The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
707
1044
  // writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
708
1045
  // 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.
1046
+ // follow-up may be sent twice after a crash, never lost. The answer to an ask: the row's waiting summary goes in
1047
+ // that commit too, for a wait in the claim and for a question a reopened run parked on (its journal holds its earlier
1048
+ // end, so its claim reads as reopened). Left until the end commit, the answer's turn reads running, held and "Waiting
1049
+ // for your reply", and the server tells that ask again.
711
1050
  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 } } : {}) });
1051
+ const taken = gate.expect(placedBy, { take: [command.id], ...(reopen === waitTurn || endedOnAsk ? { run: { summary: null } } : {}) });
713
1052
  taken.catch(() => undefined);
714
1053
  reopen.sent = (async () => {
715
1054
  await theSession.send(content, { id: sendId, ...(by ? { origin: by } : {}) });
716
1055
  // A CLI's record: the original input as its writer's (the launch's origin, else the person's), then the message.
717
1056
  if (first) {
718
1057
  if (first.inputOrigin)
719
- await theRecord?.input(first.input, first.inputOrigin);
1058
+ await theRecord?.input(first.input, first.inputOrigin, false);
720
1059
  else
721
- await theRecord?.person(first.input);
1060
+ await theRecord?.person(first.input, false);
722
1061
  }
723
1062
  await theRecord?.followUp(text, requestId, by);
724
1063
  })();
@@ -802,6 +1141,19 @@ function adapterLoop(specOf, options, deps) {
802
1141
  await cliRecord?.message(next.text, next.origin);
803
1142
  return session.turnEnd();
804
1143
  };
1144
+ /** The output contract's one retry (AdapterRunSpec.outputSchema): the server's message saying why the answer missed the
1145
+ * schema, sent as a turn of its own on the same session, its requests admitted and booked by the run's one cap as any
1146
+ * turn's. A CLI's record writes it first (once, under its request id); pi's submission carries its origin and is placed
1147
+ * once under that id. Sent at most once by this loop (outputRetrySent), and by a later claim only when the record has
1148
+ * it unanswered (outputRetried). Its turn's end is what this gives. */
1149
+ const sendOutputRetry = async (why) => {
1150
+ outputRetrySent = true;
1151
+ const text = outputRetryWords(deps.redact ? deps.redact(why) : why);
1152
+ await cliRecord?.followUp(text, OUTPUT_RETRY_REQUEST, OUTPUT_RETRY_ORIGIN);
1153
+ await session.send(text, { id: OUTPUT_RETRY_REQUEST, origin: OUTPUT_RETRY_ORIGIN });
1154
+ await specNow?.hooks?.afterMessageSent?.();
1155
+ return session.turnEnd();
1156
+ };
805
1157
  async function run(claim) {
806
1158
  context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
807
1159
  // Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
@@ -856,13 +1208,48 @@ function adapterLoop(specOf, options, deps) {
856
1208
  // made here, before the spec, so the spec's tool host binds them at its bind (a browser release's charge comes
857
1209
  // outside any call). Each session is opened at its first step: a run that makes none writes nothing for it. A
858
1210
  // handle not opened on this claim reads what the run's records held when the claim began.
859
- const sessions = journalSessions(harness, context, { flush: () => deps.flush() });
1211
+ // What was spent beside them on the run's behalf (its spec's runCap.beside) is read with them at each admission
1212
+ // (runBooking), the spec's once it is known.
1213
+ const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
1214
+ const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush(), claim }), { beside: besideNow });
860
1215
  let capBuilt;
1216
+ /** The session's recent requests, as the cap's `expected` pricing reads them (the kernel's recentAfter and
1217
+ * warmFrom): the harness's own requests that answered under CACHE_WARM_MS ago, each one's input as its usage
1218
+ * reported it (read from or written to the cache, and the rest), its input bound and when it ended. Kept on the
1219
+ * session (KINDS.capRecent), so a new claim after an approval, a deny or a park starts from them (seeded below,
1220
+ * once the session's records are read), and its first request is warm or cold by when they ended, as within a
1221
+ * claim. None before one has: a cache miss. */
1222
+ let recent = [];
1223
+ /** What the run keeps back beside a request of its own session while it streams (RunCapOptions.keepBackUsd), set
1224
+ * once the wrap-up's reserve is known (below): a tool call it makes mid-stream finds room for the steps after it. */
1225
+ let keepBackOf;
1226
+ /** Each of this claim's requests as the cap was asked about it, by its turn, until it ends. */
1227
+ const askedFor = new Map();
861
1228
  const theCap = () => {
862
1229
  if (!specNow?.runCap)
863
1230
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
864
1231
  // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
865
- return (capBuilt ??= runCap({ sessions, ...specNow.runCap, capUsd: capNow }));
1232
+ // Its recent requests are the session's own (requestEnded), unless the spec names them (a test's warm cache).
1233
+ const { beside: _beside, ...config } = specNow.runCap;
1234
+ return (capBuilt ??= runCap({ sessions, recentOf: (model) => recent.filter((one) => one.model === model), keepBackUsd: (request, asked) => keepBackOf?.(request, asked), ...config, capUsd: capNow }));
1235
+ };
1236
+ /** A request of this claim ended (`request_end`): one of the harness's own (no host label, no side call) that
1237
+ * answered with its input reported is one of the session's recent requests from now, kept on the session
1238
+ * (`keep`, the model session's writer) for a later claim. A write that fails leaves the later claim the older
1239
+ * ones, or none: priced from them or uncached, never under the worst. */
1240
+ const requestEnded = async (turn, usage, how, keep) => {
1241
+ const asked = askedFor.get(turn);
1242
+ askedFor.delete(turn);
1243
+ if (!asked?.own || asked.bound === undefined || usage.cut || (how !== undefined && how.end !== "answered"))
1244
+ return;
1245
+ const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1246
+ if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
1247
+ return;
1248
+ // A smaller request than the last (a CLI's own while a tool runs, a compaction's, a child's that the proxy cannot
1249
+ // tell from the root's) is kept beside the others, never in their place: each request is priced from the one
1250
+ // whose bound fits it best (warmFrom), so none resets the conversation's history.
1251
+ recent = recentAfter(recent, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
1252
+ await keep.append([{ kind: KINDS.capRecent, data: recent }]).catch(() => undefined);
866
1253
  };
867
1254
  const flushed = { flush: () => deps.flush() };
868
1255
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -1006,7 +1393,11 @@ function adapterLoop(specOf, options, deps) {
1006
1393
  const cap = capNow();
1007
1394
  if (cap === undefined)
1008
1395
  return undefined;
1009
- let others = 0;
1396
+ // What was spent beside the run on its behalf counts as its other sessions' spend does.
1397
+ const beside = await besideNow();
1398
+ if (beside === null)
1399
+ return undefined;
1400
+ let others = beside;
1010
1401
  for (const key of await sessions.keys()) {
1011
1402
  if (key === spec.session.key)
1012
1403
  continue;
@@ -1029,7 +1420,10 @@ function adapterLoop(specOf, options, deps) {
1029
1420
  const cap = capNow();
1030
1421
  if (!step || cap === undefined)
1031
1422
  return pending;
1032
- let spent = 0;
1423
+ const beside = await besideNow();
1424
+ if (beside === null)
1425
+ return pending;
1426
+ let spent = beside;
1033
1427
  for (const key of await sessions.keys()) {
1034
1428
  const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
1035
1429
  if (spend === null)
@@ -1042,9 +1436,13 @@ function adapterLoop(specOf, options, deps) {
1042
1436
  return { ...pending, refuse: text, figures };
1043
1437
  };
1044
1438
  const beforeRequest = async (request) => {
1439
+ // Kept until it ends, so its answer can be one of the session's recent requests (requestEnded): on its model as the cap
1440
+ // prices it (RunCap.asked), which a CLI's request names as its provider does, so the next request finds it.
1441
+ askedFor.set(request.turn, { model: specNow?.runCap ? theCap().asked(request).model.id : request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
1045
1442
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
1046
- // whatever else would pause it (a paid call's refusal, pendingPause).
1047
- const over = await overCap();
1443
+ // whatever else would pause it (a paid call's refusal, pendingPause). One a paid call stopped for good
1444
+ // (paid-calls.ts stopRun) ends in that call's words, which say why, past its cap too.
1445
+ const over = pendingPause?.forGood ? undefined : await overCap();
1048
1446
  if (!over && pendingPause) {
1049
1447
  pendingPause = await landing(pendingPause);
1050
1448
  // Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
@@ -1108,6 +1506,126 @@ function adapterLoop(specOf, options, deps) {
1108
1506
  }
1109
1507
  }
1110
1508
  }
1509
+ // The cap's wrap-up note (#2080): near its cap the run's next main-model request is told once, inside its own body
1510
+ // (the session's model proxy places it: ModelPort.note), to finish now, by the kernel cap's rule (noteFor) over the
1511
+ // run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
1512
+ // (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
1513
+ // cap is told again when it too comes near; written as the server's row only once a request carrying the note is
1514
+ // admitted with it.
1515
+ const wrapUpHarness = harness;
1516
+ const wrapUpRoot = root ?? (await harness.root(context));
1517
+ const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
1518
+ .filter((entry) => entry.kind === CAP_WRAPUP)
1519
+ .map((entry) => entry.data?.capUsd)
1520
+ .filter((capUsd) => typeof capUsd === "number");
1521
+ const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
1522
+ // What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
1523
+ // earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
1524
+ // after each request is admitted (the note is placed before its own request's admission, so it reads the last).
1525
+ const restOf = async () => {
1526
+ // And what was spent beside the run on its behalf (its learning runs' grades).
1527
+ const beside = await besideNow();
1528
+ if (beside === null)
1529
+ return null;
1530
+ let rest = beside;
1531
+ for (const key of await sessions.keys()) {
1532
+ if (key === spec.session.key || key === DECISION_SESSION || key === TOOL_SESSION)
1533
+ continue;
1534
+ const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
1535
+ if (spent === null)
1536
+ return null;
1537
+ rest += spent;
1538
+ }
1539
+ return rest;
1540
+ };
1541
+ // The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
1542
+ // them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
1543
+ // (booked at its hold and bound, the worst case), one never sent, given back, owed or stopped.
1544
+ const claimRecords = await writer.read();
1545
+ // The recent requests an earlier claim or pass kept (KINDS.capRecent): this claim's first request is priced from
1546
+ // them, warm or cold by when they ended, never as if the session had no history.
1547
+ recent = recentIn(claimRecords);
1548
+ const claimHosts = sessionSpendOf(claimRecords).hosts;
1549
+ /** The turns of requests that are no main-model request of the harness's own: read from the records, then each
1550
+ * admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
1551
+ const notOwn = new Set(claimHosts.keys());
1552
+ for (const record of claimRecords) {
1553
+ const data = (record.data ?? {});
1554
+ if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
1555
+ notOwn.add(data.turn);
1556
+ }
1557
+ const capNote = {
1558
+ costs: claimRecords.flatMap((record) => {
1559
+ if (record.kind !== RUNNER_RECORDS.turn)
1560
+ return [];
1561
+ const data = (record.data ?? {});
1562
+ const own = typeof data.usd === "number" && data.usd > 0 && !data.cut && !data.unsent && !data.givenBack && !data.stopped && data.rule !== "owed";
1563
+ return own && (data.turn === undefined || !notOwn.has(data.turn)) ? [data.usd] : [];
1564
+ }),
1565
+ restUsd: await restOf(),
1566
+ };
1567
+ /** A main-model request as the run's cap prices it at admission (RunCap.asked: its model and the session's previous
1568
+ * request, so its input reads the cache that request left warm), for the wrap-up's note and what the run keeps back
1569
+ * to answer. A request the note takes is measured as its client sent it (NoteRequest), by its bytes. */
1570
+ const pricedOf = (model, asked) => theCap().asked({ ...asked, model });
1571
+ /** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
1572
+ const figuresOf = (model, asked) => {
1573
+ const config = specNow?.runCap;
1574
+ if (!config?.modelOf(model))
1575
+ return undefined;
1576
+ return requestFigures(pricedOf(model, asked), config.mode ?? "expected", (config.now ?? Date.now)());
1577
+ };
1578
+ /** What the run keeps back to answer (wrap-up.ts reserveFor), its typical step the run's own priced answers'. */
1579
+ const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
1580
+ // A CLI harness's request of the session's own (no side call, no host's, no unanswered one, no paid step) keeps
1581
+ // back that same reserve, priced on itself as the wrap-up's gate prices it once it is admitted
1582
+ // (capNote.lastFigures): admitted at an output whose worst case leaves it free, a tool call it makes while it
1583
+ // streams is not refused for the reserve (the kernel rule's keepUsd says when it cannot be kept, and why the cap
1584
+ // holds either way). A CLI may start a call with its response still open (Codex) or book its cost after its calls
1585
+ // (Claude Code); pi starts a tool once its response is complete, so its requests keep none back.
1586
+ keepBackOf = (request, asked) => {
1587
+ const config = specNow?.runCap;
1588
+ if (!config || spec.record !== "loop" || request.key !== spec.session.key || request.host !== undefined || request.side || request.unanswered || request.paid)
1589
+ return undefined;
1590
+ return reserveOf(requestFigures(asked, config.mode ?? "expected", (config.now ?? Date.now)()));
1591
+ };
1592
+ let bookingNow;
1593
+ const wrapUpNote = (model, asked) => {
1594
+ const config = specNow?.runCap;
1595
+ const capModel = config?.modelOf(model);
1596
+ const sessionSpent = bookingNow?.spentUsd();
1597
+ const decided = ledger.decisions.spentUsd();
1598
+ const paidSpent = ledger.paid.spentUsd();
1599
+ const rest = capNote.restUsd;
1600
+ // The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
1601
+ const inFlight = bookingNow?.heldUsd();
1602
+ const capUsd = capNow();
1603
+ // One request at a time carries it: while one offered it waits for its admission, an overlapping request is not
1604
+ // offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
1605
+ // took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
1606
+ // refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
1607
+ // only the backstop for a path that never gives it back: past it, a later request is offered it.
1608
+ if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
1609
+ return undefined;
1610
+ if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
1611
+ return undefined;
1612
+ const spentUsd = sessionSpent + decided + paidSpent + rest;
1613
+ // The tools' gate counts a request in flight at its hold and its bound (sessionSpendOf: a cache miss adds the bound),
1614
+ // so the note counts it the same: it never comes later than the gate's first refusal.
1615
+ const heldUsd = inFlight + (bookingNow?.boundUsd() ?? 0) + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
1616
+ const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: (config.now ?? Date.now)() });
1617
+ // The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
1618
+ // answer (wrap-up.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
1619
+ // its own has not made it due before: told on the request whose tool call would be refused now, no later than the
1620
+ // first refusal. The rule's figure here is the run's spend and holds as they stand at this take, and this request's
1621
+ // own reserve. (The gate's reader, wrapUp, reads the records at each call and is async; a reading kept from an
1622
+ // admission would count that request's own hold as taken after it answered.)
1623
+ const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
1624
+ const leftUsd = capUsd - spentUsd - heldUsd;
1625
+ const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
1626
+ capNote.offered = note ? { ...note, capUsd, at: Date.now() } : undefined;
1627
+ return note?.words;
1628
+ };
1111
1629
  // The rule before a side effect for every paid model request, on the path every adapter's requests take: the
1112
1630
  // booking writes the request's record, then awaits request_start before the request leaves, so the flush here
1113
1631
  // makes that record and everything before it durable first (each send, a retry's included).
@@ -1115,22 +1633,63 @@ function adapterLoop(specOf, options, deps) {
1115
1633
  key: spec.session.key,
1116
1634
  label: spec.session.label,
1117
1635
  beforeRequest,
1636
+ note: wrapUpNote,
1637
+ // A request that took it and left before its admission gives it back: the next request may take it at once.
1638
+ noteReturned: (note) => {
1639
+ if (capNote.offered?.words === note)
1640
+ capNote.offered = undefined;
1641
+ },
1118
1642
  onEvent: async (event) => {
1119
- if (event.type === "request_start")
1643
+ // The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
1644
+ // the harness's own is not one of them).
1645
+ // (A price from the host's table, `estimated`, is a cost; what bookCut tells of an earlier claim's requests, owed
1646
+ // at their hold or cut, comes before `capNote.live` and is never one.)
1647
+ if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
1648
+ capNote.costs.push(event.usage.usd);
1649
+ if (event.type === "request_end")
1650
+ await requestEnded(event.turn, event.usage, event.ended, writer);
1651
+ if (event.type === "request_start") {
1652
+ // A new request means the model's last message is over: what it said so far is on the record before the request,
1653
+ // so an answer shows while the turn goes on (a CLI that answers, then makes another request).
1654
+ await cliRecord?.flushSaid().catch(() => undefined);
1655
+ // A pi run's answers are its own entries, so a request that leaves is marked on the root before it does: one
1656
+ // with no answer by the time the run settles (a stop or cancel cut it mid-answer) was cut, and a cut request's
1657
+ // cost is unknown, never the $0 an unmarked one reads (timeline REQUEST_STARTED). The other harnesses' requests
1658
+ // are read from the booking (spec.record "loop"), and a host's own side request (event.host: a learned node's, a
1659
+ // web search's) is marked and costed by its own path, never as one of the run's answers.
1660
+ if (spec.record !== "loop" && event.host === undefined && event.label === spec.session.label && harness && gate && !gate.sealed) {
1661
+ const on = harness;
1662
+ const conversation = root ?? (await on.root(context));
1663
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_STARTED, data: {} }), context);
1664
+ }
1120
1665
  await deps.flush();
1666
+ }
1667
+ // Its end, when the request did not answer at a price: the stream ended with no answer or none priced (a stop cut
1668
+ // it), which reads cut and unknown once the run's answer entries are counted; or it never left (a stop landed as it was marked), which withdraws the mark (`unsent`), at no cost.
1669
+ if (event.type === "request_end" && event.ended && (event.ended.end !== "answered" || event.ended.usd === null) && spec.record !== "loop" && event.host === undefined && event.label === spec.session.label && harness && gate && !gate.sealed) {
1670
+ const on = harness;
1671
+ const conversation = root ?? (await on.root(context));
1672
+ const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
1673
+ // Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
1674
+ // mark cut all the same.
1675
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: (unsent ? { unsent: true } : {}) }), context).catch(() => undefined);
1676
+ }
1121
1677
  },
1122
1678
  });
1679
+ bookingNow = booking;
1123
1680
  // A paid request an earlier claim admitted and never saw answered (its runner lost while the request was out): the
1124
1681
  // provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
1125
1682
  // is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
1126
1683
  await booking.bookCut();
1684
+ // This claim's own answers count toward the typical cost from here (bookCut's owed and cut bookings came before).
1685
+ capNote.live = true;
1127
1686
  // A paid tool call an earlier claim admitted and never saw settled is booked the same way, cut, at its hold, its
1128
1687
  // charge unknown: it may have run and been charged before the claim was lost. Its session opens only for a paid call
1129
1688
  // of this claim, and a replay the gate refuses makes none, so it is opened here for the cut alone, never read as free.
1130
1689
  const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
1131
1690
  if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
1132
1691
  await paidOf();
1133
- // The cap's wrap-up (tool-budget.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1692
+ // The cap's wrap-up (wrap-up.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1134
1693
  // 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
1694
  // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1136
1695
  // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
@@ -1141,13 +1700,16 @@ function adapterLoop(specOf, options, deps) {
1141
1700
  const capUsd = capNow();
1142
1701
  if (capUsd === undefined)
1143
1702
  return false;
1144
- let taken = 0;
1703
+ // What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
1704
+ let taken = await besideNow();
1145
1705
  for (const key of await sessions.keys()) {
1146
1706
  const read = sessionSpendOf(await sessions.read(key));
1147
1707
  const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
1148
1708
  taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
1149
1709
  }
1150
- return wrappingUp(capUsd, taken);
1710
+ // What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
1711
+ // is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
1712
+ return wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures));
1151
1713
  };
1152
1714
  const gateOf = preIntentGate(spec, hooks, wrapUp);
1153
1715
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
@@ -1155,6 +1717,13 @@ function adapterLoop(specOf, options, deps) {
1155
1717
  cliRecord = record;
1156
1718
  // Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
1157
1719
  // read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
1720
+ /** A tool call's computer calls (computer-calls.ts), kept on the run's root beside the call, by its id. */
1721
+ const keepCalls = async (call, calls, dropped) => {
1722
+ const [journalOf, rootOf] = [harness, root];
1723
+ if (!journalOf || !rootOf || gate?.sealed)
1724
+ return;
1725
+ await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: COMPUTER_CALLS, data: { call, calls, ...(dropped > 0 ? { dropped } : {}) } }), context);
1726
+ };
1158
1727
  const hosted = (tool) => ({
1159
1728
  ...tool,
1160
1729
  // The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
@@ -1164,11 +1733,19 @@ function adapterLoop(specOf, options, deps) {
1164
1733
  // bridge asks first; one refused is on the record from the gate, bridgeGate), so its record's start is written
1165
1734
  // here, before the flush and the call, and its end after.
1166
1735
  call: async (args, toolContext) => {
1736
+ // A tool that only nests calls (tools_call, codemode) has its row on a CLI's record as pi's does, its start marked
1737
+ // `nests`; each call it makes is on the record after it as its own tool's (its id `<callId>/<key>`). It runs again
1738
+ // whole after a crash, its recorded calls answered from their records, so its own end never answers it.
1739
+ const record = cliRecord;
1167
1740
  // A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
1168
1741
  // from that end, never run again.
1169
- const ended = record?.endOf(toolContext.callId);
1742
+ const ended = tool.nests ? undefined : record?.endOf(toolContext.callId);
1170
1743
  if (ended)
1171
1744
  return endedAnswer(tool.name, ended);
1745
+ // A run a paid call stopped for good (paid-calls.ts stopRun) runs no tool after it, a script's own calls
1746
+ // included: each is refused in the stop's words, never run.
1747
+ if (pendingPause?.forGood)
1748
+ return { text: pendingPause.refuse, isError: true };
1172
1749
  // A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
1173
1750
  // attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
1174
1751
  // set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
@@ -1183,10 +1760,13 @@ function adapterLoop(specOf, options, deps) {
1183
1760
  return { text: now.deny, isError: true };
1184
1761
  // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
1185
1762
  // 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") {
1763
+ // the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
1764
+ // the setting at allow now: the setting answers the ask (allowedBySetting).
1765
+ const bySetting = now === "allow" && (await askStands(toolContext.callId));
1766
+ if (now === "ask" || bySetting) {
1188
1767
  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);
1768
+ const price = mcp?.priceOf(name) ?? null;
1769
+ const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
1190
1770
  if (answer === "park")
1191
1771
  return await heldUntilAborted(toolContext.signal);
1192
1772
  if (!answer.approved)
@@ -1197,8 +1777,11 @@ function adapterLoop(specOf, options, deps) {
1197
1777
  if (stopAbort.signal.aborted || toolContext.signal?.aborted)
1198
1778
  return { text: STOPPED_WHILE_WAITING, isError: true };
1199
1779
  }
1780
+ // Another call after a turn-ending one: the turn goes on (TurnCut).
1781
+ if (record)
1782
+ askCut.disarm();
1200
1783
  if (record)
1201
- await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
1784
+ await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe", tool.nests);
1202
1785
  try {
1203
1786
  const answer = await sideEffect({
1204
1787
  replaySafe: tool.replay === "safe",
@@ -1207,7 +1790,9 @@ function adapterLoop(specOf, options, deps) {
1207
1790
  // refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
1208
1791
  // The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
1209
1792
  // loop wrapped it, and whether a person approved this call.
1210
- route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }))),
1793
+ // The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
1794
+ // row's computer_calls, before its result is written.
1795
+ route: () => bookedIn({ call: toolContext.callId, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped)))),
1211
1796
  beforeResult: async (answer) => {
1212
1797
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
1213
1798
  try {
@@ -1223,6 +1808,12 @@ function adapterLoop(specOf, options, deps) {
1223
1808
  // A call a stop cut answers whatever its tool said of the abort: it ends interrupted, never as its outcome.
1224
1809
  if (record)
1225
1810
  await record.end(toolContext.callId, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
1811
+ // A CLI's question to the person (a turn-ending tool's call, answered): its turn is cut at its next request,
1812
+ // as pi's ends here (TurnCut). Any other call's end after it lets the turn go on.
1813
+ if (record && endsTurn(tool.name) && !answer.isError && !stopAbort.signal.aborted)
1814
+ askCut.arm(toolContext.callId);
1815
+ else if (record)
1816
+ askCut.disarm();
1226
1817
  return answer;
1227
1818
  }
1228
1819
  catch (error) {
@@ -1234,7 +1825,40 @@ function adapterLoop(specOf, options, deps) {
1234
1825
  }
1235
1826
  },
1236
1827
  });
1237
- const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1828
+ const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1829
+ // tools_search, tools_call and codemode over the session's tools (meta-tools.ts), on every harness (codemode on
1830
+ // each but one that runs scripts of its own): what they call is called nested, each call asked about and recorded
1831
+ // as its own tool's. A search finds a tool whose setting is not deny; an MCP tool's setting is its catalog name's.
1832
+ const settingOf = spec.gate?.permission;
1833
+ // The harness's own tools beside them (pi's subagent, its browser's): found and called by name as the host's are,
1834
+ // run by the harness as its own nested calls. Never called here: a nested call reaches them through the harness.
1835
+ const native = (spec.adapter.ownTools ?? []).filter((one) => !own.some((tool) => tool.name === one.name)).map((one) => ({
1836
+ name: one.name,
1837
+ description: one.description,
1838
+ inputSchema: one.inputSchema,
1839
+ replay: "never",
1840
+ call: async () => ({ text: `${one.name} is run by the harness itself, as a nested call of tools_call or a script.`, isError: true }),
1841
+ }));
1842
+ // One discovery system (tool-deferral.ts): a run whose catalog tools pass DEFER_CATALOG_OVER does not list them; the
1843
+ // model finds them with tools_search and runs them with tools_call (still the tool's own call at the gate). Claude
1844
+ // Code defers them itself (its ToolSearch, on under the same test), so it is offered neither. Under the threshold
1845
+ // every tool is listed and there is no search or call. codemode is offered as it always was.
1846
+ const facts = builtinHarness(spec.adapter.id)?.facts;
1847
+ // A meta tool whose setting is deny is not offered at all, rather than offered and refused.
1848
+ const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
1849
+ // Deferred only when the model can both find and run what it hid: with either helper denied every tool stays listed,
1850
+ // so denying a helper never takes an otherwise allowed tool out of reach.
1851
+ // The one verdict for every harness: one with a tool search of its own (Claude Code's) follows it too, handed it as
1852
+ // `deferCatalog` below, and so lists every tool when either helper is set to deny.
1853
+ const deferred = defersCatalog(own.map((one) => one.name)) && (await allowed(TOOLS_SEARCH)) && (await allowed(TOOLS_CALL));
1854
+ const offered = deferred && !facts?.ownToolSearch;
1855
+ const metas = metaTools({
1856
+ tools: () => [...own, ...native],
1857
+ granted: async (name) => !settingOf || (await settingOf(mcp?.catalogOf(name) ?? name).catch(() => "deny")) !== "deny",
1858
+ codemode: facts?.ownCodemode !== true && (await allowed(CODEMODE)),
1859
+ discovery: { search: offered, call: offered },
1860
+ }).filter((meta) => ![...own, ...native].some((one) => one.name === meta.name));
1861
+ const tools = [...own.map((one) => (offered && isCatalogName(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
1238
1862
  // An MCP tool of the run by its catalog name, as wrapped above: what a learned workflow's MCP node calls.
1239
1863
  mcpHosted = (catalog) => {
1240
1864
  const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
@@ -1247,13 +1871,50 @@ function adapterLoop(specOf, options, deps) {
1247
1871
  unbooked = 0;
1248
1872
  const counted = {
1249
1873
  beforeRequest: async (request) => {
1874
+ // The CLI's next request of its main model after its question to the person: never admitted, it asks for the
1875
+ // turn's cut (TurnCut). Its side calls and the host's own requests go on.
1876
+ if (askCut.armed && !request.side && request.host === undefined)
1877
+ return askCut.hold();
1250
1878
  // A command row since the MCP credentials were made fresh: made fresh again before this request.
1251
1879
  if (mcpStale && mcp) {
1252
1880
  mcpStale = false;
1253
1881
  await mcp.fresh();
1254
1882
  }
1883
+ // The wrap-up this request carries, taken off the offer now: its admission tells it; a refusal (the throw below)
1884
+ // or a dropped note leaves it untold, to be offered to a later request.
1885
+ const offer = request.noted ? capNote.offered : undefined;
1886
+ if (offer)
1887
+ capNote.offered = undefined;
1255
1888
  const ticket = await port.beforeRequest(request);
1256
1889
  unbooked += 1;
1890
+ // The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
1891
+ if (ticket && request.side)
1892
+ notOwn.add(ticket.turn);
1893
+ // The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
1894
+ if (!request.side && request.host === undefined)
1895
+ capNote.lastFigures = figuresOf(request.model, request) ?? capNote.lastFigures;
1896
+ // What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
1897
+ // the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
1898
+ try {
1899
+ capNote.restUsd = await restOf();
1900
+ }
1901
+ catch (error) {
1902
+ capNote.restUsd = null;
1903
+ console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
1904
+ }
1905
+ // Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
1906
+ // row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
1907
+ if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
1908
+ const { words, leftUsd, capUsd } = offer;
1909
+ toldCaps.push(capUsd);
1910
+ try {
1911
+ await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
1912
+ await deps.flush();
1913
+ }
1914
+ catch (error) {
1915
+ console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
1916
+ }
1917
+ }
1257
1918
  return ticket;
1258
1919
  },
1259
1920
  afterRequest: async (...args) => {
@@ -1270,6 +1931,7 @@ function adapterLoop(specOf, options, deps) {
1270
1931
  },
1271
1932
  ...(port.responded ? { responded: port.responded.bind(port) } : {}),
1272
1933
  ...(port.note ? { note: port.note.bind(port) } : {}),
1934
+ ...(port.noteReturned ? { noteReturned: port.noteReturned.bind(port) } : {}),
1273
1935
  };
1274
1936
  // What the request that just answered cost, once the session's requests are booked (bookingOfAnswer): its own
1275
1937
  // booking's figure, null when unknown; a side request's is given and never read. A refused request's record is its $0.
@@ -1286,51 +1948,82 @@ function adapterLoop(specOf, options, deps) {
1286
1948
  // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
1287
1949
  // start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
1288
1950
  // 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.
1951
+ // about goes on the record first, its start marked parked (once per call id): the bridge hands the CLI nothing while it
1952
+ // waits, so no waiting result shows, as on pi. Its row shows while it waits, before its approval; the claim that runs
1953
+ // it once allowed writes its sent mark on that one start (start()), and a stop withdraws it never sent
1954
+ // (unsentParked). A start refused because another call of the round parked the run first (the journal sealed) leaves
1955
+ // this call held as that one is.
1294
1956
  const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
1957
+ // A call a tool of pi's nests (a script's, tools_call's) is pi's own tool task, of which pi's record keeps no row: it
1958
+ // goes on the loop's record as a CLI's call does, so the Timeline shows it as its own call, and an ask for it beside
1959
+ // it. Its start at its gate (marked parked while it waits for a person; refused, with its end, in the gate's words),
1960
+ // its end once pi has its outcome (nestedEnded). The record opens at the claim's first such call, and never ends a
1961
+ // call itself: pi says each one's end, a replay-safe one a crash cut run again first (endsItsCalls).
1962
+ const [nestedOn, nestedJournal] = [harness, gate.journal];
1963
+ let nestedOpen;
1964
+ const nestedRecord = () => (nestedOpen ??= openCliRecord(nestedOn, nestedJournal, context, now, undefined, true));
1965
+ const unlessSealed = (error) => {
1966
+ if (!gate?.sealed)
1967
+ throw error;
1968
+ };
1969
+ const nestedAsking = preIntentGate(spec, hooks, wrapUp, async (call) => (await nestedRecord()).park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed));
1970
+ const nestedGate = async (call, hookContext) => {
1971
+ if (call.nested !== true)
1972
+ return gateOf(call, hookContext);
1973
+ const answer = await nestedAsking(call, hookContext);
1974
+ const nests = await nestedRecord();
1975
+ if (answer === "allow")
1976
+ await nests.start(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed);
1977
+ else if ("deny" in answer)
1978
+ await nests.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny).catch(unlessSealed);
1979
+ return answer;
1980
+ };
1981
+ const nestedEnded = async (callId, status, output) => (await nestedRecord()).end(callId, status, output).catch(unlessSealed);
1295
1982
  const askingGate = record
1296
- ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), true).catch((error) => {
1983
+ ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
1297
1984
  if (!gate?.sealed)
1298
1985
  throw error;
1299
1986
  }))
1300
1987
  : gateOf;
1301
1988
  const bridgeGate = record
1302
1989
  ? async (call, hookContext) => {
1990
+ askCut.disarm();
1991
+ // An MCP call is on the record before its gate answers, its start marked parked (once per call id), so its
1992
+ // sent mark is committed before it is sent. A fault before the bridge writes its intent leaves no intent: the
1993
+ // CLI's re-issue asks again and sends it once. One after the intent is any bridged host tool's: told interrupted,
1994
+ // never run twice.
1995
+ if (mcp?.catalogOf(call.tool) !== undefined) {
1996
+ await record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
1997
+ if (!gate?.sealed)
1998
+ throw error;
1999
+ });
2000
+ }
1303
2001
  const answer = await askingGate(call, hookContext);
1304
2002
  if (answer !== "allow" && "deny" in answer)
1305
2003
  await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
2004
+ // A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
2005
+ // run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
2006
+ else if (answer === "allow" && approvedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
2007
+ await record.end(call.callId, "done", OWN_TOOL_RELEASED);
1306
2008
  return answer;
1307
2009
  }
1308
- : gateOf;
1309
- const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, hostTool: hosted, bookedCost };
1310
- // The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
1311
- // MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
1312
- const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
1313
- const ownClient = mcp !== undefined && spec.adapter.capabilities().mcpClient !== undefined;
1314
- const sessionMcp = ownClient
1315
- ? mcp.session(new Map(tools.filter((tool) => mcpNames.has(tool.name)).map((tool) => [tool.name, tool])), async (call) => {
1316
- // A call through the door is on the run's record before its gate answers (once per call id; the gate's park
1317
- // seals the journal): its row, and an approval read beside it, show while it waits. A refused one ends there;
1318
- // a parked one runs, or is refused, on the claim that resumes it (parkedFollowUp); an allowed one runs now.
1319
- const wire = mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool);
1320
- if (record)
1321
- await record.park(call.callId, wire?.name ?? call.tool, call.args ?? {}, wire?.replay === "safe");
1322
- const answer = await gateOf(call, context);
1323
- if (answer === "allow")
1324
- return undefined;
1325
- if ("deny" in answer) {
1326
- if (record)
1327
- await record.end(call.callId, "refused", answer.deny);
1328
- return { refused: answer.deny };
1329
- }
1330
- return { parked: true };
1331
- })
1332
- : undefined;
1333
- session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
2010
+ : nestedGate;
2011
+ // A tool no call of which reaches the gate before it runs (Codex's live search, inside its model requests): its
2012
+ // setting now, read again at each request, so a deny or ask set mid-run reaches the next one.
2013
+ const permission = spec.gate?.permission;
2014
+ // After a CLI's question to the person (TurnCut armed): what its model says is not on the record, as pi's turn says
2015
+ // nothing after the question; a call of another tool lets the turn go on.
2016
+ const onEvent = (theRecord) => (event) => {
2017
+ if (askCut.armed && event.type === "text")
2018
+ return;
2019
+ if (askCut.armed && event.type === "tool_start")
2020
+ askCut.disarm();
2021
+ theRecord.onEvent(event);
2022
+ };
2023
+ const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
2024
+ // The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
2025
+ // for host tools, each call through the gate before its intent.
2026
+ session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
1334
2027
  root = await harness.root(context);
1335
2028
  // The root as the claim found it, before this pass writes anything of its own there (the computer's show-up, a
1336
2029
  // takeover's note): what the reopen check below reads, so a fresh reopen is told by the run's own last entry.
@@ -1339,15 +2032,37 @@ function adapterLoop(specOf, options, deps) {
1339
2032
  // fence), and the computer shows up, the agent driving.
1340
2033
  computerNow?.detach();
1341
2034
  computerNow = undefined;
2035
+ channelNow = undefined;
1342
2036
  if (spec.computer) {
1343
2037
  const [journalOf, rootOf] = [harness, root];
1344
- computerNow = journalHold(claim.runId, spec.computer, (entries) => journalOf.commit(async (tx) => {
2038
+ channelNow = { computer: spec.computer, commit: (entries) => journalOf.commit(async (tx) => {
2039
+ for (const entry of entries)
2040
+ await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
2041
+ }, context) };
2042
+ }
2043
+ if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
2044
+ const [journalOf, rootOf] = [harness, root];
2045
+ computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
1345
2046
  for (const entry of entries)
1346
2047
  await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
1347
2048
  }, context), now);
1348
2049
  // The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
1349
2050
  await computerNow.up(await entriesOf(gate.journal, root.id, context));
1350
2051
  }
2052
+ // The run's computer held for its owner: the hold starts waiting on the run's first pass. A later pass's computer
2053
+ // (a new claim's, or a restart's after a fault: closeSession let the last one go) is not the one an open hold held,
2054
+ // nor has what the owner set up on it: the run ends in those words.
2055
+ heldNow = undefined;
2056
+ if (spec.held) {
2057
+ const [journalOf, rootOf] = [harness, root];
2058
+ heldNow = journalHeld(spec.held, (entries) => journalOf.commit(async (tx) => {
2059
+ for (const entry of entries)
2060
+ await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
2061
+ }, context), now);
2062
+ if ((await heldNow.up(await entriesOf(gate.journal, root.id, context))) === "lost") {
2063
+ return await writeEnd(harness, root, gate, { state: "failed", summary: heldWords.lost }, []);
2064
+ }
2065
+ }
1351
2066
  // The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
1352
2067
  // budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
1353
2068
  // run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
@@ -1393,6 +2108,8 @@ function adapterLoop(specOf, options, deps) {
1393
2108
  // A session still new (a person stopped the run before its first input was sent): the follow-up is its first
1394
2109
  // input, and the input the person stopped is never sent.
1395
2110
  firstInputPlaced = undefined;
2111
+ // A feedback round an earlier claim took and never ended (its runner lost): this claim closes it, asking no turn.
2112
+ feedbackNow = endsRoot ? undefined : pendingFeedbackOf(foundEntries);
1396
2113
  if (endsRoot && !inFlight && session.state === "idle")
1397
2114
  reopen = {};
1398
2115
  else if (endsRoot && !inFlight && session.state === "new") {
@@ -1400,13 +2117,43 @@ function adapterLoop(specOf, options, deps) {
1400
2117
  firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
1401
2118
  reopen = mine;
1402
2119
  }
2120
+ // A CLI run parked on its question (its turn cut there, TurnCut): its session takes no steer, so the person's
2121
+ // answer is this claim's turn, sent as a reopened run's follow-up is (steer, through `reopen`), the row's waiting
2122
+ // summary going in its take. A turn the session still reads open is the one the cut stopped: settled first,
2123
+ // never recovered (recovered, the CLI would go on past its question).
2124
+ if (!endsRoot && !inFlight && spec.record === "loop" && !session.steer && turnEndedOnAsk(foundEntries) !== undefined) {
2125
+ if (session.state === "open_turn")
2126
+ await session.settleOpenTurn();
2127
+ if (session.state === "idle")
2128
+ reopen = askReopen = {};
2129
+ }
1403
2130
  }
1404
2131
  opened();
2132
+ // A channel call a fault's restart cut off from its pass: its record is written through this one.
2133
+ settleCalls();
1405
2134
  await reportHeld(harness, root.id);
1406
2135
  if (restarts > restartLimit + 1) {
1407
2136
  return await writeEnd(harness, root, gate, { state: "failed", summary: `the kernel faulted on every restart (${restarts} restarts)` }, [], await cutRows(claim, spec, "faulted"));
1408
2137
  }
1409
- let followedUp = false;
2138
+ // A held computer waits for its owner's start before the agent's first input; the owner's calls set the task up
2139
+ // meanwhile. A release, or no call for the hold's minutes, ends the run before its agent ever ran. A stop ends it
2140
+ // stopped, and a lost claim leaves it for the next claim.
2141
+ if (heldNow?.state() === "waiting") {
2142
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
2143
+ const waited = await heldNow.untilStarted(Promise.race([stopping, aborted, harness.closed]));
2144
+ // Set by stop() during the wait: read past the narrowing TypeScript did before it.
2145
+ const cut = stopReason;
2146
+ if (cut?.kind === "command")
2147
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
2148
+ if (cut || deps.signal.aborted || waited === "cut")
2149
+ return await interrupted(cut?.kind ?? "its claim's signal aborted");
2150
+ if (heldNow.state() === "released") {
2151
+ const why = heldNow.lapse() === "timeout" ? heldWords.timeout(spec.held.minutes) : "The owner released the computer before the agent started";
2152
+ return await writeEnd(harness, root, gate, { state: "stopped", outcome: "cancelled", summary: why }, []);
2153
+ }
2154
+ }
2155
+ // A feedback round an earlier claim took (feedbackNow): its words are this claim's turn, never the job's input.
2156
+ let followedUp = feedbackNow !== undefined;
1410
2157
  if (raising.resuming) {
1411
2158
  // Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
1412
2159
  // together: one raise entry, and the run resumes once, at the latest cap, with one follow-up in the server's
@@ -1449,38 +2196,6 @@ function adapterLoop(specOf, options, deps) {
1449
2196
  followedUp = true;
1450
2197
  }
1451
2198
  }
1452
- if (!followedUp && ownClient) {
1453
- // MCP calls a harness with its own client parked through the door: each answered once (an allow runs it, a deny
1454
- // is told), then the session goes on with main's resume message for them, written on the record before it is
1455
- // sent (as the person's input is). A call still waiting parks the run again.
1456
- const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
1457
- const follow = await parkedFollowUp(mcp, {
1458
- entries: await entriesOf(gate.journal, root.id, context),
1459
- answer: (call, price) => answerOf(call, price),
1460
- deniedNow: async (call) => {
1461
- // The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
1462
- const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
1463
- return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
1464
- },
1465
- run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
1466
- // A parked call refused ends on the run's record (its start was written at its park), in the refusal's words.
1467
- refused: async (call, text) => cliRecord?.end(call.callId, "refused", text),
1468
- });
1469
- if (follow === "park") {
1470
- // A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
1471
- // end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
1472
- if (stopReason?.kind === "command")
1473
- return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1474
- gate.seal(new Parked());
1475
- return { state: "parked" };
1476
- }
1477
- if (follow) {
1478
- const theRoot = root;
1479
- await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" }, at: now() } }), context);
1480
- await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
1481
- followedUp = true;
1482
- }
1483
- }
1484
2199
  if (reopen) {
1485
2200
  // Every row the runner read for this claim has reached its command() (deps.delivered): the follow-up's steer, sent
1486
2201
  // by steer() as a turn, is the turn this claim runs. With none (a claim after that turn's answer), it ends again.
@@ -1495,10 +2210,13 @@ function adapterLoop(specOf, options, deps) {
1495
2210
  await Promise.race([firstInputPlaced, stopping, parking, harness.closed.then(() => undefined, () => undefined), lost]);
1496
2211
  }
1497
2212
  const sent = reopen.sent;
2213
+ const fed = reopen.feedback;
1498
2214
  reopen = undefined;
1499
2215
  if (sent) {
1500
2216
  await sent.catch(() => undefined);
1501
2217
  followedUp = true;
2218
+ if (fed)
2219
+ feedbackNow = fed;
1502
2220
  }
1503
2221
  }
1504
2222
  // A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
@@ -1506,9 +2224,161 @@ function adapterLoop(specOf, options, deps) {
1506
2224
  // A reopen of a session still new whose message was never placed (the run stopped, parked or was lost meanwhile):
1507
2225
  // nothing is sent, least of all the input the person stopped.
1508
2226
  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.
2227
+ // A CLI's end-of-run turn an earlier claim sent and never saw end (its prompt the last turn on the record, no
2228
+ // submission): the job's turn had ended before it, so the session's open turn is that look-back. One a person
2229
+ // stopped with a follow-up after it is not: the open turn is the follow-up's, recovered as the job's. It is settled, never recovered:
2230
+ // recovered, it ran as the job's turn, its answer lost, and the end-of-run step then asked the CLI again, a paid
2231
+ // look-back twice on one claim. The step asks it again once, under the run's cap (an earlier request of it booked
2232
+ // at its hold, bookCut), or skips it, reading what the first ask kept (EndOfRunTurn ask's `kept`). A feedback round
2233
+ // (feedbackNow) sends no turn of its own before its look-back, so its open look-back is settled the same way.
2234
+ if ((!followedUp || feedbackNow !== undefined) && !firstUnplaced && session.state === "open_turn" && (await record?.lookingBack()))
2235
+ await session.settleOpenTurn();
2236
+ /** The run's learned workflow, run first (AdapterRunSpec.workflowFirst), once for the run: the person's input on the
2237
+ * record, then the workflow's call through the session's own learned_workflow tool as the loop wrapped it (its gate
2238
+ * with its ask, its record, its flush and booking, the stop's abort), under one call id (replay never: a call a
2239
+ * crash cut is ended interrupted and handed back, never run again), then the WORKFLOW_FIRST entry saying how it
2240
+ * ended, with its answer as the model's message when it answered, in one commit. pi keeps no record of the loop's
2241
+ * (its own entries are its record): its call goes on a record of its own for this step, the same entries. A claim
2242
+ * that finds the entry or the call's end takes it as it is. Undefined: the run is its agent's (the tool is not the
2243
+ * run's, or the gate denies it before anything is written); "park": the call waits for a person's approval. */
2244
+ const serveFirst = async (first) => {
2245
+ const learned = tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
2246
+ if (!learned)
2247
+ return undefined;
2248
+ const [on, theRoot, theGate] = [harness, root, gate];
2249
+ const args = { name: first.name, input: first.input };
2250
+ const call = { callId: WORKFLOW_FIRST_CALL, tool: LEARNED_WORKFLOW_TOOL, args };
2251
+ const job = (text) => ({ outcome: "handed_back", text: handbackText(first.name, text, spec.input) });
2252
+ const kept = findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true);
2253
+ const rec = record ?? (await openCliRecord(on, theGate.journal, context, now, spec.cwd));
2254
+ const ended = rec.endOf(WORKFLOW_FIRST_CALL);
2255
+ /** The call's answer as the run takes it: one the agent could not stand behind goes back to it, either one the
2256
+ * tool cut (learnedText: no agent turn could recover its ending) or, for an agent with an output schema, one that
2257
+ * cannot be shaped to it (answerAsServed: the answer as the run serves it, the one replay and grading read; why
2258
+ * goes back with it). Pure in the call's end, so a claim that recovers a handback rebuilds the same words. */
2259
+ const taken = (got) => {
2260
+ if (got.isError)
2261
+ return got;
2262
+ if (got.text.length > LEARNED_CLIP)
2263
+ return { ...got, isError: true };
2264
+ const asServed = answerAsServed(got.text, first.outputSchema);
2265
+ return "why" in asServed ? { text: `${got.text}\n\n[${asServed.why}]`, isError: true } : { ...got, text: asServed.text };
2266
+ };
2267
+ const recorded = (end) => ({ text: end.output ?? (end.status === "interrupted" ? endedAnswer(LEARNED_WORKFLOW_TOOL, end).text : ""), isError: end.status !== "done" });
2268
+ if (kept?.outcome === "answered")
2269
+ return { outcome: "answered", text: ended?.output ?? "" };
2270
+ // Handed back on an earlier claim whose handback never reached the agent (the session is still new): sent now, in
2271
+ // the words that claim would have sent (its why included).
2272
+ if (kept)
2273
+ return job(ended ? taken(recorded(ended)).text : "");
2274
+ if (!ended) {
2275
+ // A deny before anything is written leaves the run its agent's, as if the workflow were not there.
2276
+ const before = await spec.gate?.({ callId: call.callId, tool: call.tool, args });
2277
+ if (before === "deny" || typeof before === "object")
2278
+ return undefined;
2279
+ if (spec.inputOrigin)
2280
+ await rec.input(spec.input, spec.inputOrigin);
2281
+ else
2282
+ await rec.person(spec.input);
2283
+ }
2284
+ let answer;
2285
+ if (ended)
2286
+ answer = recorded(ended);
2287
+ else {
2288
+ const verdict = await preIntentGate(spec, hooks, wrapUp, (asked) => rec.park(asked.callId, asked.tool, asked.args ?? {}, false))(call, context);
2289
+ if (verdict !== "allow" && "park" in verdict)
2290
+ return "park";
2291
+ if (verdict !== "allow") {
2292
+ // Refused at its gate once the job was on the record (its ask declined, the cap's wrap-up): handed back in
2293
+ // the gate's words, the call ended refused.
2294
+ if (rec.unsentParked().includes(WORKFLOW_FIRST_CALL))
2295
+ await rec.end(WORKFLOW_FIRST_CALL, "refused", verdict.deny);
2296
+ else
2297
+ await rec.refused(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false, verdict.deny);
2298
+ answer = { text: verdict.deny, isError: true };
2299
+ }
2300
+ else {
2301
+ // A CLI's record takes the call's start and end inside the wrapper; pi's step record here.
2302
+ if (!record)
2303
+ await rec.start(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false);
2304
+ const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal });
2305
+ answer = { text: got.text, isError: got.isError === true };
2306
+ if (!record)
2307
+ await rec.end(WORKFLOW_FIRST_CALL, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
2308
+ }
2309
+ }
2310
+ if (stopAbort.signal.aborted)
2311
+ return undefined;
2312
+ answer = taken(answer);
2313
+ const outcome = answer.isError ? "handed_back" : "answered";
2314
+ const data = { workflow: first.name, digest: first.digest, revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
2315
+ await on.commit(async (tx) => {
2316
+ if (outcome === "answered")
2317
+ await tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "model", text: answer.text, at: now() } });
2318
+ await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
2319
+ }, context);
2320
+ return outcome === "answered" ? { outcome, text: answer.text } : job(answer.text);
2321
+ };
2322
+ // The run's learned workflow first, before anything is sent to its agent (runner/workflow-first.ts): its answer is
2323
+ // the run's, or its handback is the agent's first input. Only while the session is new: a claim that finds a turn
2324
+ // under way (the handback sent) never runs it again.
2325
+ let served;
2326
+ // A workflow this run already served or handed back on an earlier claim (its end on the root): recovered whatever the
2327
+ // money rule says now, so a crash before the handback never makes the agent redo finished work.
2328
+ const keptFirst = spec.workflowFirst || !spec.workflowRevise || followedUp || firstUnplaced || session.state !== "new" ? undefined : findData(await entriesOf(gate.journal, root.id, context), WORKFLOW_FIRST, () => true);
2329
+ const recovered = keptFirst && keptFirst.outcome !== "needs_revision" ? { name: keptFirst.workflow, digest: keptFirst.digest, revision: keptFirst.revision, input: {}, ...(spec.workflowRevise?.outputSchema !== undefined ? { outputSchema: spec.workflowRevise.outputSchema } : {}) } : undefined;
2330
+ const firstToServe = spec.workflowFirst ?? recovered;
2331
+ // A fitting workflow the money rule stopped: why, on the root, once for the run, as the agent takes it.
2332
+ if (spec.workflowRevise && !followedUp && !firstUnplaced && session.state === "new") {
2333
+ const [on, theRoot, theGate] = [harness, root, gate];
2334
+ if (!findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true)) {
2335
+ const { workflow, digest, revision, served_usd, by_hand_usd, runs } = spec.workflowRevise;
2336
+ const data = { workflow, digest, revision, outcome: "needs_revision", served_usd, by_hand_usd, runs };
2337
+ await on.commit(async (tx) => {
2338
+ await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
2339
+ }, context);
2340
+ }
2341
+ }
2342
+ if (firstToServe && !followedUp && !firstUnplaced && session.state === "new") {
2343
+ let release;
2344
+ servingFirst = new Promise((resolve) => (release = resolve));
2345
+ try {
2346
+ const step = await serveFirst(firstToServe);
2347
+ // A stop while it ran, or while it was asked, ends the run stopped, its call ended interrupted (or its ask
2348
+ // withdrawn) on the record: given back parked with its stop untaken, the run would be claimed again only to end
2349
+ // then. A lost claim leaves it.
2350
+ const cutBy = stopReason;
2351
+ if (step === "park" && cutBy?.kind !== "command") {
2352
+ await releaseHost(harness);
2353
+ gate.seal(new Parked());
2354
+ return { state: "parked" };
2355
+ }
2356
+ if (cutBy?.kind === "command")
2357
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2358
+ if (cutBy || deps.signal.aborted || step === "park")
2359
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2360
+ served = step;
2361
+ // A replay run (runner/promotion.ts) ends on its workflow's step whichever way it ended: its hand-back is the
2362
+ // agent's recorded answer for that input, read from the graded run, never asked of the agent again.
2363
+ if (served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay))
2364
+ turnsOver = true;
2365
+ else if (served?.outcome === "handed_back") {
2366
+ // The agent's first input: the handback, the server's (its row "AgentRun: …"), the job whole after it. Cut of
2367
+ // every secret the runner holds: the workflow's words may quote what its steps read.
2368
+ const text = deps.redact ? deps.redact(served.text) : served.text;
2369
+ await record?.message(text, HANDED_BACK_ORIGIN);
2370
+ await session.send(text, { origin: HANDED_BACK_ORIGIN });
2371
+ }
2372
+ }
2373
+ finally {
2374
+ servingFirst = undefined;
2375
+ release();
2376
+ }
2377
+ }
2378
+ const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
2379
+ if (served || followedUp || firstUnplaced) {
2380
+ // The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
2381
+ // or there is none.
1512
2382
  }
1513
2383
  else if (session.state === "new") {
1514
2384
  // A trigger's first input is its origin's (the launch's), never written as the person's.
@@ -1520,9 +2390,14 @@ function adapterLoop(specOf, options, deps) {
1520
2390
  }
1521
2391
  else if (session.state === "open_turn")
1522
2392
  await session.recover();
2393
+ // A message handed over while the session was new is placed from here on, after what was just sent.
2394
+ inputSent();
1523
2395
  // The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
1524
- // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
1525
- let turn = placed ? session.turnEnd() : idleTurnOf(harness, root);
2396
+ // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold. None
2397
+ // when the workflow answered: the run ends on its answer.
2398
+ // A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn.
2399
+ const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined;
2400
+ let turn = alone ? new Promise(() => { }) : placed ? session.turnEnd() : idleTurnOf(harness, root);
1526
2401
  // Set on every way out of the loop below but parkOn's, which returns before it is read.
1527
2402
  let data;
1528
2403
  let failedWith;
@@ -1530,141 +2405,189 @@ function adapterLoop(specOf, options, deps) {
1530
2405
  let parkOn;
1531
2406
  /** The ask_person call the run waits on in its claim, while it does. */
1532
2407
  let waitingOn;
1533
- for (;;) {
1534
- const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed")]);
1535
- if (end === "parked") {
1536
- // Let the tool host go first (a browser's release, booked under the live claim), then seal.
1537
- await releaseHost(harness);
1538
- gate.seal(new Parked());
1539
- return { state: "parked" };
1540
- }
1541
- if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
1542
- await closeSession();
1543
- continue passes;
1544
- }
1545
- if (end === "closed" || (stopReason && stopReason.kind !== "command"))
1546
- return await interrupted(stopReason?.kind ?? "the Session closed");
1547
- if (end === "stop" && stopReason?.kind === "command") {
1548
- // Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
1549
- // is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
1550
- const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
1551
- const settling = (async () => {
1552
- await session.interrupt().catch(() => { });
1553
- await harness.waitForIdle(context).catch(() => { });
1554
- return true;
1555
- })();
1556
- let timer;
1557
- const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
1558
- clearTimeout(timer);
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);
1561
- const cut = await cutRows(claim, spec, "stopped");
1562
- if (!settled)
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);
1565
- }
1566
- // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
1567
- // it kept went): the run parks on its question, as it does with nothing open.
1568
- if (end === "lapsed") {
1569
- parkOn = waitingOn;
1570
- break;
1571
- }
1572
- const outcome = (await turn);
1573
- // What the model said last, on the record before the run's end.
1574
- await record?.flushText();
1575
- await harness.waitForIdle(context);
1576
- const settledEntries = await entriesOf(gate.journal, root.id, context);
1577
- const cutOff = restartLimited(settledEntries);
1578
- // A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
1579
- // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
1580
- await bookingsSettled();
1581
- const over = cutOff ? undefined : await overCap();
1582
- if (cutOff)
1583
- data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
1584
- else if (over)
1585
- data = { state: "failed", summary: over };
1586
- else if (outcome.status !== "completed" && refused) {
1587
- // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
1588
- // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
1589
- // check's own words, never as a run with no answer.
1590
- const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
1591
- if (park?.outcome === "parked" && pausedAtRefusal) {
1592
- // Its pause and the run parked landed before pi heard of the refusal.
1593
- await releaseHost(harness);
1594
- gate.seal(new Parked());
1595
- return { state: "parked" };
2408
+ if (alone)
2409
+ data = { state: "ended" };
2410
+ else
2411
+ for (;;) {
2412
+ const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
2413
+ // Parked on a call held at the gate (a CLI's at its tool bridge): the answer that made the call may still be
2414
+ // streaming, and its booking lands before the claim goes (parkClaim).
2415
+ if (end === "parked")
2416
+ return await parkClaim(harness, gate);
2417
+ if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
2418
+ await closeSession();
2419
+ continue passes;
1596
2420
  }
1597
- if (park?.outcome === "parked")
1598
- return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
1599
- data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
1600
- }
1601
- else if (outcome.status !== "completed") {
1602
- // A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
1603
- // the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
1604
- // the loop's own words.
1605
- const said = outcome.error?.trim();
1606
- data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
1607
- // A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
1608
- // end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
1609
- if (said && spec.record === "loop")
1610
- failedWith = deps.redact ? deps.redact(said) : said;
1611
- }
1612
- else if (endedOnTurnEndingTool(settledEntries) !== undefined) {
1613
- // The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
1614
- // open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
1615
- // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
1616
- // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
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);
2421
+ if (end === "closed" || (stopReason && stopReason.kind !== "command"))
2422
+ return await interrupted(stopReason?.kind ?? "the Session closed");
2423
+ if (end === "stop" && stopReason?.kind === "command") {
2424
+ // Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
2425
+ // is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
2426
+ const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
2427
+ const settling = (async () => {
2428
+ const interrupting = session.interrupt().catch(() => { });
2429
+ // A request held after a question to the person (TurnCut) is refused once the stop is under way.
2430
+ askCut.done();
2431
+ await interrupting;
2432
+ await harness.waitForIdle(context).catch(() => { });
2433
+ return true;
2434
+ })();
2435
+ let timer;
2436
+ const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
2437
+ clearTimeout(timer);
2438
+ // A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
2439
+ const stopped = stopEnd(stopReason.cancel);
2440
+ const cut = await cutRows(claim, spec, "stopped");
2441
+ if (!settled)
2442
+ 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);
2443
+ return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
1623
2444
  }
1624
- const waited = await waitInClaim(harness, callId);
1625
- if (waited) {
1626
- turn = waited.next;
1627
- waitingOn = callId;
1628
- continue;
2445
+ // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
2446
+ // it kept went): the run parks on its question, as it does with nothing open.
2447
+ if (end === "lapsed") {
2448
+ parkOn = waitingOn;
2449
+ break;
1629
2450
  }
1630
- parkOn = callId;
1631
- }
1632
- else {
1633
- // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
1634
- // the direct loop's rule: the words are loop-contract's cutAtLimit).
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) {
2451
+ const outcome = end === "cut" ? await cutAtQuestion(session, turn, spec.stopSettleMs ?? STOP_SETTLE_MS) : (await turn);
2452
+ // A turn that ended with no cut (its CLI asked nothing more after its question): nothing armed past it.
2453
+ askCut.done();
2454
+ // What the model said last, on the record before the run's end.
2455
+ await record?.flushText();
2456
+ // The turn's end on the record, after its last text: a CLI run reads working until here.
2457
+ await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
2458
+ await harness.waitForIdle(context);
2459
+ const settledEntries = await entriesOf(gate.journal, root.id, context);
2460
+ const cutOff = restartLimited(settledEntries);
2461
+ // A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
2462
+ // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
2463
+ await bookingsSettled();
2464
+ // A run a paid call stopped for good (paid-calls.ts stopRun) ends in that call's words, past its cap too.
2465
+ const stoppedBy = pendingPause?.forGood ? pendingPause : undefined;
2466
+ const over = cutOff || stoppedBy ? undefined : await overCap();
2467
+ // A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
2468
+ // poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
2469
+ if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
1640
2470
  let bound;
1641
2471
  await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
1642
2472
  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.
2473
+ // A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
2474
+ // narrowing TypeScript did before the delivery.
1645
2475
  const cutBy = stopReason;
1646
2476
  if (cutBy?.kind === "command")
1647
2477
  return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
1648
2478
  if (cutBy || deps.signal.aborted)
1649
2479
  return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
1650
2480
  }
1651
- // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
1652
- const next = cut ? undefined : afterTurn.shift();
1653
- if (next) {
1654
- turn = sendAfterTurn(gate, next);
1655
- continue;
2481
+ if (cutOff)
2482
+ data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
2483
+ else if (over)
2484
+ data = { state: "failed", summary: over };
2485
+ else if (stoppedBy)
2486
+ data = { state: "failed", summary: stoppedBy.refuse };
2487
+ else if (outcome.status !== "completed" && refused) {
2488
+ // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
2489
+ // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
2490
+ // check's own words, never as a run with no answer.
2491
+ const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
2492
+ // Its pause and the run parked landed before pi heard of the refusal.
2493
+ if (park?.outcome === "parked" && pausedAtRefusal)
2494
+ return await parkClaim(harness, gate);
2495
+ if (park?.outcome === "parked")
2496
+ return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
2497
+ data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
1656
2498
  }
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);
2499
+ else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
2500
+ // A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
2501
+ // queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
2502
+ // answer (the same row the run's end would have written).
2503
+ const said = outcome.error?.trim() ?? "";
2504
+ const rootId = root.id;
2505
+ await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
2506
+ turn = sendAfterTurn(gate, afterTurn.shift());
1662
2507
  continue;
1663
2508
  }
1664
- data = cut ? { state: "failed", summary: cut } : { state: "ended" };
2509
+ else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
2510
+ // A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
2511
+ // turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
2512
+ // with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
2513
+ data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
2514
+ }
2515
+ else if (outcome.status !== "completed") {
2516
+ // A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
2517
+ // the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
2518
+ // the loop's own words.
2519
+ const said = outcome.error?.trim();
2520
+ data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
2521
+ // A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
2522
+ // end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
2523
+ if (said && spec.record === "loop")
2524
+ failedWith = deps.redact ? deps.redact(said) : said;
2525
+ }
2526
+ else if (turnEndedOnAsk(settledEntries) !== undefined) {
2527
+ // The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
2528
+ // open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
2529
+ // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
2530
+ // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
2531
+ const callId = turnEndedOnAsk(settledEntries);
2532
+ // Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
2533
+ // person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
2534
+ if (pendingPause) {
2535
+ pendingPause = undefined;
2536
+ await keepPending(null);
2537
+ }
2538
+ const waited = await waitInClaim(harness, callId);
2539
+ if (waited) {
2540
+ turn = waited.next;
2541
+ waitingOn = callId;
2542
+ continue;
2543
+ }
2544
+ parkOn = callId;
2545
+ }
2546
+ else {
2547
+ // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
2548
+ // the direct loop's rule: the words are loop-contract's cutAtLimit).
2549
+ const cut = cutLast(settledEntries);
2550
+ // The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
2551
+ // message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
2552
+ // command that waits on this loop cannot hold its end.
2553
+ if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
2554
+ let bound;
2555
+ await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
2556
+ clearTimeout(bound);
2557
+ // A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
2558
+ // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
2559
+ const cutBy = stopReason;
2560
+ if (cutBy?.kind === "command")
2561
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2562
+ if (cutBy || deps.signal.aborted)
2563
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2564
+ }
2565
+ // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
2566
+ const next = cut ? undefined : afterTurn.shift();
2567
+ if (next) {
2568
+ turn = sendAfterTurn(gate, next);
2569
+ continue;
2570
+ }
2571
+ // A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
2572
+ // the run's end. One already answered settles at once.
2573
+ const steered = cut ? undefined : steeredIn.shift();
2574
+ if (steered !== undefined) {
2575
+ turn = turnOfRequest(harness, root, steered);
2576
+ continue;
2577
+ }
2578
+ // The output contract: an answer whose last json block misses the agent's output schema is asked again, once,
2579
+ // in the same session, never a second time (outputRetried reads the record, so a later claim does not ask
2580
+ // either), and not once the run is wrapping up at its cap (the room left is its answer's, and a retry that
2581
+ // could not fit would park the run for the retry's sake). The run's result then says why (output_error).
2582
+ const miss = cut || spec.outputSchema === undefined || outputRetrySent || outputRetried(settledEntries) ? undefined : outputMiss(lastAnswerText(settledEntries), spec.outputSchema);
2583
+ if (miss !== undefined && !(await wrapUp())) {
2584
+ turn = sendOutputRetry(miss);
2585
+ continue;
2586
+ }
2587
+ data = cut ? { state: "failed", summary: cut } : { state: "ended" };
2588
+ }
2589
+ break;
1665
2590
  }
1666
- break;
1667
- }
1668
2591
  // No turn is sent after this one: a message from here on waits for the run's end (steer).
1669
2592
  turnsOver = true;
1670
2593
  if (parkOn !== undefined)
@@ -1684,6 +2607,24 @@ function adapterLoop(specOf, options, deps) {
1684
2607
  if (cut || deps.signal.aborted)
1685
2608
  return await interrupted(cut?.kind ?? "its claim's signal aborted");
1686
2609
  }
2610
+ // A held computer stays the owner's after the agent's end, for their checks: the run's end, and its computer's
2611
+ // release after it, wait for the owner's release or the hold's lapse. A person's stop keeps waiting (writeEnd), the
2612
+ // run then ending stopped; a cancel ends it at once, and a lost claim leaves it for the next claim.
2613
+ if (heldNow) {
2614
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
2615
+ handingBack = true;
2616
+ const waited = await heldNow.heldAtEnd(Promise.race([stopping, aborted, harness.closed]));
2617
+ const cut = stopReason;
2618
+ if (cut?.kind === "command")
2619
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
2620
+ if (cut || deps.signal.aborted || waited === "cut")
2621
+ return await interrupted(cut?.kind ?? "its claim's signal aborted");
2622
+ }
2623
+ // A stop or cancel the runner handed on as the turn was failing (it hands rows on as they are written) is taken by
2624
+ // this end, which is the stop's own: with the turn's failure the end, its row would be handed on and never taken.
2625
+ const failingStop = data.state === "failed" ? stopReason : undefined;
2626
+ if (failingStop?.kind === "command")
2627
+ return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
1687
2628
  // The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
1688
2629
  // writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
1689
2630
  const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
@@ -1724,6 +2665,8 @@ function adapterLoop(specOf, options, deps) {
1724
2665
  held?.detach();
1725
2666
  computerNow?.detach();
1726
2667
  computerNow = undefined;
2668
+ heldNow = undefined;
2669
+ channelNow = undefined;
1727
2670
  handingBack = false;
1728
2671
  deps.live?.(() => undefined);
1729
2672
  // A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
@@ -1745,12 +2688,6 @@ function adapterLoop(specOf, options, deps) {
1745
2688
  if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
1746
2689
  return { deny: REFLECT_NOTE_ONLY };
1747
2690
  await hooks.beforeIntent(kernelCall);
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
2691
  // 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
2692
  // 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
2693
  if (call.nested !== true && (await wrapUp()))
@@ -1758,15 +2695,28 @@ function adapterLoop(specOf, options, deps) {
1758
2695
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
1759
2696
  const replayed = call.replayed === true;
1760
2697
  const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
1761
- if (typeof decision === "object")
1762
- return { deny: decision.deny };
1763
2698
  // Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
1764
2699
  // an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
1765
2700
  const asked = spec.gate?.askedAs?.(tool) ?? tool;
1766
- // Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
2701
+ // A call a person was asked about and has not answered, refused now because its tool is set to deny (a bare "deny",
2702
+ // or the gate's own words for it): the deny answers the ask first (deniedBySetting), a deny of theirs standing. The
2703
+ // model reads the gate's words (main's, from refusal-words.ts) either way.
2704
+ // The ask is read first: it is the claim's one journal read, the setting a store read.
2705
+ if (decision !== "allow" && decision !== "ask" && spec.gate && (await askStands(call.callId)) && (decision === "deny" || (await spec.gate.permission?.(tool)) === "deny")) {
2706
+ const answer = await deniedBySetting({ ...call, tool }, asked);
2707
+ if (answer === "park")
2708
+ return { park: true };
2709
+ if (answer.by !== "setting")
2710
+ return { deny: deniedText(asked, answer.note) };
2711
+ }
2712
+ if (typeof decision === "object")
2713
+ return { deny: decision.deny };
1767
2714
  if (decision === "deny")
1768
2715
  return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
1769
- if (decision === "allow")
2716
+ // A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
2717
+ // (allowedBySetting), and the call runs without asking the person again.
2718
+ const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
2719
+ if (decision === "allow" && !bySetting)
1770
2720
  return "allow";
1771
2721
  // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
1772
2722
  // (a learned workflow's MCP calls set to ask: askedFor).
@@ -1776,7 +2726,13 @@ function adapterLoop(specOf, options, deps) {
1776
2726
  const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
1777
2727
  // The call on the record before its ask (beforeAsk), with the input its model gave it.
1778
2728
  await beforeAsk?.(call);
1779
- const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
2729
+ // Its price on the card: a catalog tool's (an MCP tool's, a monid endpoint's pinned price), else none.
2730
+ const price = mcp?.priceOf(tool) ?? null;
2731
+ // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the gate's `mcp_calls`, a
2732
+ // learned workflow's MCP calls set to ask): that allow takes the second confirm too.
2733
+ const covered = Array.isArray(shown?.mcp_calls) ? shown.mcp_calls.filter((name) => typeof name === "string") : [];
2734
+ const destructive = [asked, ...covered].some((name) => mcp?.effectOf(name) === "destructive");
2735
+ const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
1780
2736
  if (answer === "park")
1781
2737
  return { park: true };
1782
2738
  // A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
@@ -1794,7 +2750,7 @@ function adapterLoop(specOf, options, deps) {
1794
2750
  /** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
1795
2751
  * park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
1796
2752
  * was asked and its `price`; asked again on a resume, it is the same request. */
1797
- async function answerOf(call, price, asked = call.tool) {
2753
+ async function answerOf(call, price, asked = call.tool, destructive = mcp?.effectOf(asked) === "destructive") {
1798
2754
  const conversation = await harness.root(context);
1799
2755
  const entries = await entriesOf(gate.journal, conversation.id, context);
1800
2756
  const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
@@ -1806,24 +2762,10 @@ function adapterLoop(specOf, options, deps) {
1806
2762
  return known;
1807
2763
  // The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
1808
2764
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
1809
- const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
1810
- // Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
1811
- // of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on.
1812
- const entryLands = async (kind, data, staged) => {
1813
- const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
1814
- // A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
1815
- landed.catch(() => undefined);
1816
- try {
1817
- await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
1818
- await landed;
1819
- return true;
1820
- }
1821
- catch (error) {
1822
- if (gate.sealed)
1823
- return false;
1824
- throw error;
1825
- }
1826
- };
2765
+ // An MCP tool its run's pin marks destructive (ClaimMcp.effectOf), or a call whose allow covers one (`destructive`):
2766
+ // its card asks a second confirm of an allow.
2767
+ const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
2768
+ const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
1827
2769
  if (first === undefined) {
1828
2770
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
1829
2771
  if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
@@ -1853,6 +2795,86 @@ function adapterLoop(specOf, options, deps) {
1853
2795
  await new Promise((resolve) => (wakeInbox = resolve));
1854
2796
  }
1855
2797
  }
2798
+ /** Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
2799
+ * of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on. */
2800
+ async function landEntry(conversation, kind, data, staged) {
2801
+ const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
2802
+ // A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
2803
+ landed.catch(() => undefined);
2804
+ try {
2805
+ await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
2806
+ await landed;
2807
+ return true;
2808
+ }
2809
+ catch (error) {
2810
+ if (gate.sealed)
2811
+ return false;
2812
+ throw error;
2813
+ }
2814
+ }
2815
+ /** The answer to an ask a person was shown and has not answered, once its tool's setting reads allow: the setting
2816
+ * answers it. The ask closes with an allow row of its own (by "setting": "Allowed by the tool's setting"), the call
2817
+ * runs, and the person is never asked again. A person's answer already in the inbox for the call stands over it when it
2818
+ * is a deny; an allow of theirs is taken with the setting's answer, so no row is left untaken. */
2819
+ async function allowedBySetting(call, price, asked) {
2820
+ // Decided only once the claim's stored commands are with the loop (deps.delivered): pi's recovery starts tool tasks while
2821
+ // the session opens, before command() can put a person's stored deny into the inbox, and the setting must not win over it.
2822
+ await (deps.delivered ?? Promise.resolve());
2823
+ const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
2824
+ if (row?.kind === "deny")
2825
+ return answerOf(call, price, asked);
2826
+ const conversation = await harness.root(context);
2827
+ const data = { callId: call.callId, approved: true, decision: "allow", answeredAt: isoNow(), by: "setting" };
2828
+ if (row)
2829
+ inbox.splice(inbox.indexOf(row), 1);
2830
+ if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
2831
+ return "park";
2832
+ // The call's ask, as journaled: kept for the caller, which scopes an approval to it.
2833
+ const first = findData(await entriesOf(gate.journal, conversation.id, context), KINDS.ask, (ask) => ask.callId === call.callId);
2834
+ if (first)
2835
+ askedArgs.set(call.callId, first.args);
2836
+ return data;
2837
+ }
2838
+ /** The answer to an ask a person was shown and has not answered, once its tool's setting reads deny: the deny answers it
2839
+ * (by "setting"), so its rows say it was refused for that deny and the run's end never reads it withdrawn. A person's
2840
+ * allow already in the inbox for the call is taken with it and kept as the allow the deny overrode (`superseded`); a
2841
+ * deny of theirs stands, answered as any (answerOf). */
2842
+ async function deniedBySetting(call, asked) {
2843
+ // As allowedBySetting: decided only once the claim's stored commands are with the loop.
2844
+ await (deps.delivered ?? Promise.resolve());
2845
+ const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
2846
+ if (row?.kind === "deny")
2847
+ return answerOf(call, null, asked);
2848
+ const conversation = await harness.root(context);
2849
+ const answeredAt = isoNow();
2850
+ const data = { callId: call.callId, approved: false, decision: "deny", answeredAt, by: "setting", ...(row ? { superseded: { decision: "allow", answeredAt } } : {}) };
2851
+ if (row)
2852
+ inbox.splice(inbox.indexOf(row), 1);
2853
+ if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
2854
+ return "park";
2855
+ return data;
2856
+ }
2857
+ /** Whether a person was asked about this call and has not answered yet (an ask in the journal, no answer): its card is
2858
+ * theirs, so the call waits for that answer (answerOf) even when its tool's setting reads allow by now, and runs on
2859
+ * their allow, its rows reading so. Let through on the setting alone, it ran with its ask unanswered, which the run's
2860
+ * end reads withdrawn: its rows said "Not run: the run ended while it waited" of a call that ran. A deny set since still
2861
+ * refuses it first. Read from the journal once a claim: an ask written later in the claim parks it, and an answer
2862
+ * written later is read by answerOf itself. */
2863
+ async function askStands(callId) {
2864
+ standing ??= (async () => {
2865
+ const conversation = await harness.root(context);
2866
+ const entries = await entriesOf(gate.journal, conversation.id, context);
2867
+ const answered = new Set(entries.filter((entry) => entry.kind === KINDS.answer).map((entry) => entry.data.callId));
2868
+ return new Set(entries.filter((entry) => entry.kind === KINDS.ask).map((entry) => entry.data.callId).filter((id) => !answered.has(id)));
2869
+ })();
2870
+ // A read that failed (a seal while it ran) is read again by the next call, never kept.
2871
+ const read = standing;
2872
+ return (await read.catch((error) => {
2873
+ if (standing === read)
2874
+ standing = undefined;
2875
+ throw error;
2876
+ })).has(callId);
2877
+ }
1856
2878
  /** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
1857
2879
  * park), then thrown, so nothing of it is answered in this pass. */
1858
2880
  function heldUntilAborted(signal) {
@@ -1934,9 +2956,29 @@ function adapterLoop(specOf, options, deps) {
1934
2956
  parkedAt.catch(() => undefined);
1935
2957
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
1936
2958
  await parkedAt;
1937
- await releaseHost(on);
1938
- theGate.seal(new Parked());
1939
- return { state: "parked" };
2959
+ return parkClaim(on, theGate);
2960
+ }
2961
+ /** A CLI's turn cut at its question to the person (TurnCut): its request after the question held, the turn is stopped
2962
+ * (interrupt), the held request refused once the stop is under way, and the turn the session still reads open settled,
2963
+ * as a host done with a stopped turn settles it. The turn reads completed, ended on the question, as pi's does. Bounded
2964
+ * as a stop is: a turn that does not settle in time fails the run in words. */
2965
+ async function cutAtQuestion(theSession, turn, settleMs) {
2966
+ const settling = (async () => {
2967
+ const stopped = theSession.interrupt().catch(() => { });
2968
+ askCut.done();
2969
+ await stopped;
2970
+ await turn.catch(() => undefined);
2971
+ if (theSession.state === "open_turn")
2972
+ await theSession.settleOpenTurn();
2973
+ return true;
2974
+ })().catch((error) => {
2975
+ console.warn(`[runner] the turn cut at its question did not settle: ${said(error)}`);
2976
+ return false;
2977
+ });
2978
+ let timer;
2979
+ const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
2980
+ clearTimeout(timer);
2981
+ return settled ? { status: "completed" } : { status: "failed", error: `the turn did not stop at its question to the person within ${settleMs / 1000} s` };
1940
2982
  }
1941
2983
  /** The row's waiting summary of a wait in the claim, gone: its answer came by a way whose commit did not clear it. */
1942
2984
  async function notWaiting(on, theGate, conversation, callId) {
@@ -1964,7 +3006,8 @@ function adapterLoop(specOf, options, deps) {
1964
3006
  return { status: "completed" };
1965
3007
  }
1966
3008
  const submission = await on.submission(found.id, context);
1967
- const record = submission ? await submission.wait(context) : undefined;
3009
+ // Never on the claim's signal (durableWait): an abort while it registers is this wait's rejection, never one unhandled.
3010
+ const record = submission ? await durableWait((at) => submission.wait(at), context) : undefined;
1968
3011
  return { status: !record || record.status === "done" ? "completed" : "failed" };
1969
3012
  }
1970
3013
  /** The run waits in its claim on the person's answer to its question (ask_person `callId` ended its turn) when a tool
@@ -2065,6 +3108,8 @@ function adapterLoop(specOf, options, deps) {
2065
3108
  async function closeSession() {
2066
3109
  gate?.seal(new Interrupted("the Session is closing"));
2067
3110
  endWait();
3111
+ // A request held at a cut turn goes with its session, refused, never left pending.
3112
+ askCut.done();
2068
3113
  const closing = Promise.all([session?.close().catch(() => { }), harness?.close(BACKGROUND_CONTEXT).catch(() => { })]);
2069
3114
  let timer;
2070
3115
  await Promise.race([closing, new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
@@ -2078,6 +3123,8 @@ function adapterLoop(specOf, options, deps) {
2078
3123
  releaseNow = undefined;
2079
3124
  await release?.().catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
2080
3125
  }
3126
+ /** What round `round`'s end-of-run turn kept as it was first asked (EndOfRunTurn's keptOf), on the CLI's record. */
3127
+ const keptOf = (claim) => (round) => cliRecord?.keptOf(reflectRequestId(claim.runId, false, round));
2081
3128
  /** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
2082
3129
  const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
2083
3130
  /** The end-of-run step (stepOf: the spec's, else LoopDeps.endOfRun), asked once: the rows to stage with the end; `stopped` when a person's stop
@@ -2097,7 +3144,7 @@ function adapterLoop(specOf, options, deps) {
2097
3144
  if (!spec.agentId)
2098
3145
  throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
2099
3146
  try {
2100
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true) });
3147
+ const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: keptOf(claim) });
2101
3148
  return cut() ?? { kind: "rows", also: rows?.also ?? [] };
2102
3149
  }
2103
3150
  catch (error) {
@@ -2115,7 +3162,7 @@ function adapterLoop(specOf, options, deps) {
2115
3162
  let timer;
2116
3163
  const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
2117
3164
  try {
2118
- const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse }), late]);
3165
+ const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: keptOf(claim) }), late]);
2119
3166
  if (rows === "late") {
2120
3167
  console.warn(`[runner] ${claim.runId}: its end-of-run step gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
2121
3168
  return [];
@@ -2130,18 +3177,41 @@ function adapterLoop(specOf, options, deps) {
2130
3177
  clearTimeout(timer);
2131
3178
  }
2132
3179
  }
2133
- /** The end-of-run turn: one more turn through the run's session, its request id one per run (a repeat is answered from
2134
- * its submission, so a later claim never asks the model again), its writes under work/.learning/ refused while it runs.
2135
- * `again`: its re-ask, a request of its own (one per run too). Aborted at `deadlineMs`. A stop or a lost claim cuts it:
2136
- * it throws, and the step sees why. */
2137
- async function askEndOfRun(claim, prompt, deadlineMs, again = false) {
3180
+ /** What end-of-run turn `requestId` kept as it was first asked, for a harness that keeps its own record (pi): the first
3181
+ * ask's `keep` on the run's root (KINDS.endOfRunKept), an earlier claim's when it asked first, else `keep`, written
3182
+ * there now, before the turn's first request leaves. A CLI's record keeps it with the turn's prompt (answering). */
3183
+ async function keptOnRoot(on, journal, conversation, requestId, keep) {
3184
+ const first = (await entriesOf(journal, conversation.id, context)).find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
3185
+ if (first) {
3186
+ const kept = first.data.kept;
3187
+ return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
3188
+ }
3189
+ if (!keep)
3190
+ return undefined;
3191
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.endOfRunKept, data: { requestId, kept: keep } }), context);
3192
+ return keep;
3193
+ }
3194
+ /** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
3195
+ * answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
3196
+ * asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
3197
+ * per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. */
3198
+ async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1, keep, step) {
2138
3199
  if (!session || !harness || !gate || !root)
2139
3200
  throw new Error("the run's session is not open");
2140
3201
  const on = harness;
2141
3202
  const conversation = root;
2142
3203
  const theSession = session;
2143
- const requestId = reflectRequestId(claim.runId, again);
3204
+ const requestId = reflectRequestId(claim.runId, again, round, step);
2144
3205
  const theRecord = cliRecord;
3206
+ // A grade's feedback round (feedbackNow): its first ask is told the grade first (feedback-round.ts feedbackAsk), and,
3207
+ // when the agent never took the job (its learned workflow answered alone: its session is new), the job and the
3208
+ // workflow's answer before it, cut of every secret the runner holds, as a follow-up's are.
3209
+ if (feedbackNow && !again && step === undefined) {
3210
+ const cut = (text) => (deps.redact ? deps.redact(text) : text);
3211
+ const servedNow = theSession.state === "new" ? servedAnswerOf(await entriesOf(gate.journal, conversation.id, context)) : undefined;
3212
+ const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
3213
+ prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
3214
+ }
2145
3215
  reflecting = true;
2146
3216
  let timer;
2147
3217
  try {
@@ -2149,8 +3219,11 @@ function adapterLoop(specOf, options, deps) {
2149
3219
  const known = theRecord ? await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context) : undefined;
2150
3220
  // How this claim's turn ended; a turn answered before reads as its submission says.
2151
3221
  let turnStatus = "completed";
3222
+ // What the turn's first ask kept (`keep`), an earlier claim's when it asked first: every answer carries it.
3223
+ let kept = theRecord?.keptOf(requestId);
3224
+ const withKept = (answer) => (kept ? { ...answer, kept } : answer);
2152
3225
  if (!known) {
2153
- await theRecord?.answering(requestId, prompt);
3226
+ kept = theRecord ? await theRecord.answering(requestId, prompt, keep) : await keptOnRoot(on, gate.journal, conversation, requestId, keep);
2154
3227
  await theSession.send(prompt, { id: requestId });
2155
3228
  const turn = theSession.turnEnd();
2156
3229
  const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
@@ -2161,7 +3234,7 @@ function adapterLoop(specOf, options, deps) {
2161
3234
  await theSession.interrupt().catch(() => { });
2162
3235
  await on.waitForIdle(context).catch(() => { });
2163
3236
  await theRecord?.answered(requestId, prompt, "timed out");
2164
- return { timedOut: true };
3237
+ return withKept({ timedOut: true });
2165
3238
  }
2166
3239
  // The CLI's turn, as the submission pi's adapter writes: what the step reads next, one reader for both.
2167
3240
  turnStatus = end.status;
@@ -2169,32 +3242,34 @@ function adapterLoop(specOf, options, deps) {
2169
3242
  }
2170
3243
  const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
2171
3244
  if (turnStatus !== "completed" || record?.status !== "done")
2172
- return { failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } };
3245
+ return withKept({ failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } });
2173
3246
  const answer = (await entriesOf(gate.journal, conversation.id, context)).find((entry) => entry.id === record.answer);
2174
- return { ended: true, answer: answerText(answer) };
3247
+ return withKept({ ended: true, answer: answerText(answer) });
2175
3248
  }
2176
3249
  finally {
2177
3250
  clearTimeout(timer);
2178
3251
  reflecting = false;
2179
3252
  }
2180
3253
  }
2181
- /** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded like the cut step: late or failing, none. */
3254
+ /** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded (END_PATCH_MS): late or failing, the end says
3255
+ * its cost and metrics are unknown (END_PATCH_UNKNOWN). */
2182
3256
  async function endPatchOf(data) {
2183
3257
  if (!specNow?.endPatch)
2184
3258
  return {};
2185
3259
  let timer;
2186
- const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
3260
+ const boundMs = specNow.endPatchMs ?? END_PATCH_MS;
3261
+ const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), boundMs)));
2187
3262
  try {
2188
3263
  const patch = await Promise.race([specNow.endPatch(data), late]);
2189
3264
  if (patch === "late") {
2190
- console.warn(`[runner] its end's patch gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
2191
- return {};
3265
+ console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its cost and metrics unknown`);
3266
+ return END_PATCH_UNKNOWN;
2192
3267
  }
2193
3268
  return patch ?? {};
2194
3269
  }
2195
3270
  catch (error) {
2196
- console.warn(`[runner] its end's patch failed: ${said(error)}`);
2197
- return {};
3271
+ console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its cost and metrics unknown`);
3272
+ return END_PATCH_UNKNOWN;
2198
3273
  }
2199
3274
  finally {
2200
3275
  clearTimeout(timer);
@@ -2204,7 +3279,15 @@ function adapterLoop(specOf, options, deps) {
2204
3279
  * cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. */
2205
3280
  async function parkAtCap(on, conversation, theGate, data) {
2206
3281
  await pauseAtCap(on, conversation, theGate, data);
3282
+ return parkClaim(on, theGate);
3283
+ }
3284
+ /** A park's release of the claim, as the end's: the tool host let go first (a browser's release, booked under the live
3285
+ * claim), then every paid request the session admitted booked (bookingsSettled), then the journal sealed. A CLI turn
3286
+ * the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
3287
+ * would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
3288
+ async function parkClaim(on, theGate) {
2207
3289
  await releaseHost(on);
3290
+ await bookingsSettled();
2208
3291
  theGate.seal(new Parked());
2209
3292
  return { state: "parked" };
2210
3293
  }
@@ -2250,12 +3333,34 @@ function adapterLoop(specOf, options, deps) {
2250
3333
  /** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
2251
3334
  * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
2252
3335
  async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
3336
+ // A person's stop of a run that holds its computer ends its agent, not the hold (computer-held.ts): the end, and the
3337
+ // computer's release after it, wait for the owner's release or the hold's lapse, the owner's calls still answered.
3338
+ // A cancel, a lost claim or a shutdown meanwhile ends the wait; a cancel's end is then the run's, taking both rows.
3339
+ const stop = stopReason;
3340
+ if (stop?.kind === "command" && keptAtStop && take.includes(stop.commandId) && heldNow && heldNow.state() !== "released" && !theGate.sealed) {
3341
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
3342
+ handingBack = true;
3343
+ await heldNow.heldAtEnd(Promise.race([heldCut, aborted, on.closed]), heldWords.stopped(heldNow.minutes));
3344
+ const later = laterStop;
3345
+ if (later?.kind === "command" && later.cancel) {
3346
+ base = { ...base, ...stopEnd(true) };
3347
+ take = [...take, later.commandId];
3348
+ }
3349
+ }
2253
3350
  // The end is the run's release: nothing of this claim lands after it, so the tool host is let go first (its writes in
2254
3351
  // their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
2255
3352
  await releaseHost(on);
2256
3353
  await bookingsSettled();
2257
3354
  const patch = await endPatchOf(base);
2258
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}) };
3355
+ // A person's stop that came while the end waited (its host's release, its bookings, its patch's reads, up to
3356
+ // END_PATCH_MS on a busy store) is this end's, as a stop during any earlier await of the end path is: the run ends
3357
+ // stopped and the end takes its row, never written completed with the stop left to be refused (refuseLeftovers).
3358
+ // Set by stop() during those awaits: read past the narrowing TypeScript did before them.
3359
+ const late = stopReason;
3360
+ const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
3361
+ if (lateStop)
3362
+ take = [...take, lateStop.commandId];
3363
+ const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
2259
3364
  const run = {
2260
3365
  state: data.state,
2261
3366
  // An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
@@ -2272,8 +3377,11 @@ function adapterLoop(specOf, options, deps) {
2272
3377
  // A cancel's calls read cancelled with their run; a stop's, withdrawn.
2273
3378
  const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
2274
3379
  // A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
2275
- // with the run's, in the same commit, saying it was not run (never interrupted: it never left).
2276
- const recordEnds = cliRecord?.unsentParked() ?? [];
3380
+ // with the run's, in the same commit, saying it was not run (never interrupted: it never left). pi's nested calls
3381
+ // (nestedGate) are on a record of their own, read here from the journal: a stop can end a parked run before this claim
3382
+ // opened a session.
3383
+ const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
3384
+ const recordEnds = ends.unsentParked();
2277
3385
  const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
2278
3386
  const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
2279
3387
  // A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
@@ -2284,6 +3392,9 @@ function adapterLoop(specOf, options, deps) {
2284
3392
  await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
2285
3393
  for (const callId of recordEnds)
2286
3394
  await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
3395
+ // A turn the run ends while it is open (a stop or cancel cut it, or the run failed in it) ends with the run.
3396
+ if (cliRecord?.openTurn())
3397
+ await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
2287
3398
  if (failedWith !== undefined)
2288
3399
  await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
2289
3400
  return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
@@ -2296,7 +3407,7 @@ function adapterLoop(specOf, options, deps) {
2296
3407
  }
2297
3408
  await ended;
2298
3409
  for (const callId of recordEnds)
2299
- cliRecord?.noteEnd(callId, "refused", notRun);
3410
+ ends.noteEnd(callId, "refused", notRun);
2300
3411
  return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
2301
3412
  }
2302
3413
  return {
@@ -2333,12 +3444,25 @@ function adapterLoop(specOf, options, deps) {
2333
3444
  return handBack(command);
2334
3445
  if (isComputerCommand(command))
2335
3446
  return computerCommand(command);
3447
+ if (isHeldCommand(command))
3448
+ return heldCommand(command);
3449
+ if (command.kind === COMPUTER_CALL)
3450
+ return channelCommand(command);
2336
3451
  // A pause is a workflow run's: an agentic run's turn is stopped instead, in main's words (runs.ts pause).
2337
3452
  if (command.kind === "pause" || command.kind === "resume")
2338
3453
  return { refused: AGENTIC_PAUSE_REFUSED };
2339
3454
  return { refused: `an adapter loop takes no ${command.kind} command` };
2340
3455
  },
3456
+ keepsComputer: keeps,
2341
3457
  async stop(reason) {
3458
+ // The runner asked keepsComputer right before this call: the first stop's answer is the one its end keeps to.
3459
+ if (stopReason === undefined)
3460
+ keptAtStop = keeps(reason);
3461
+ // A cancel, a lost claim or a shutdown after a stop that kept the run's computer: the hold ends with it (writeEnd).
3462
+ if (stopReason && stopReason !== reason && (reason.kind !== "command" || reason.cancel)) {
3463
+ laterStop ??= reason;
3464
+ cutHeld();
3465
+ }
2342
3466
  stopReason ??= reason;
2343
3467
  if (reason.kind !== "command")
2344
3468
  gate?.seal(new Interrupted(reason.kind));