@parcha/agentrun-serve 0.1.0-beta.35 → 0.1.0-beta.37

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 (522) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +417 -219
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-conformance-cli.d.ts +1 -0
  15. package/dist/attach-conformance-cli.js +18 -0
  16. package/dist/attach-conformance.d.ts +25 -0
  17. package/dist/attach-conformance.js +343 -0
  18. package/dist/attach-images.d.ts +15 -0
  19. package/dist/attach-images.js +59 -0
  20. package/dist/background.d.ts +0 -6
  21. package/dist/background.js +0 -28
  22. package/dist/box-image.d.ts +1 -97
  23. package/dist/box-image.js +4 -284
  24. package/dist/box-paths.d.ts +2 -7
  25. package/dist/box-paths.js +7 -13
  26. package/dist/box-settings.d.ts +0 -11
  27. package/dist/box-settings.js +4 -29
  28. package/dist/browser-commands.js +1 -1
  29. package/dist/browser-computer.d.ts +47 -3
  30. package/dist/browser-computer.js +286 -18
  31. package/dist/browser-cost.d.ts +1 -1
  32. package/dist/browser-live.d.ts +20 -8
  33. package/dist/browser-live.js +50 -27
  34. package/dist/browser-person.d.ts +19 -2
  35. package/dist/browser-person.js +55 -6
  36. package/dist/browser-wait-ended.d.ts +23 -0
  37. package/dist/browser-wait-ended.js +42 -0
  38. package/dist/cap.d.ts +12 -57
  39. package/dist/cap.js +20 -160
  40. package/dist/catalog.d.ts +1 -12
  41. package/dist/catalog.js +3 -33
  42. package/dist/cli.js +17 -26
  43. package/dist/composio-preset.d.ts +36 -0
  44. package/dist/composio-preset.js +179 -0
  45. package/dist/computer-attach.d.ts +125 -0
  46. package/dist/computer-attach.js +330 -0
  47. package/dist/computer-calls.d.ts +48 -0
  48. package/dist/computer-calls.js +126 -0
  49. package/dist/computer-channel.d.ts +57 -0
  50. package/dist/computer-channel.js +115 -0
  51. package/dist/computer-commands.d.ts +1 -1
  52. package/dist/computer-held-routes.d.ts +35 -0
  53. package/dist/computer-held-routes.js +106 -0
  54. package/dist/computer-held.d.ts +48 -0
  55. package/dist/computer-held.js +87 -0
  56. package/dist/computer-keys.d.ts +21 -1
  57. package/dist/computer-keys.js +53 -11
  58. package/dist/computer-live.d.ts +160 -0
  59. package/dist/computer-live.js +643 -0
  60. package/dist/computer-routes.d.ts +1 -4
  61. package/dist/computer-routes.js +3 -5
  62. package/dist/computer-setting.d.ts +2 -0
  63. package/dist/computer-setting.js +38 -1
  64. package/dist/computer-view.d.ts +24 -2
  65. package/dist/computer-view.js +51 -3
  66. package/dist/computer-viewer.d.ts +6 -0
  67. package/dist/computer-viewer.js +297 -0
  68. package/dist/computers.d.ts +79 -12
  69. package/dist/computers.js +147 -28
  70. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  71. package/dist/console/assets/index-DRN62V5v.css +1 -0
  72. package/dist/console/index.html +2 -2
  73. package/dist/docker-daemon.d.ts +2 -2
  74. package/dist/docker-daemon.js +2 -2
  75. package/dist/errors.js +5 -5
  76. package/dist/faux-computers.d.ts +9 -20
  77. package/dist/faux-computers.js +56 -24
  78. package/dist/files.d.ts +1 -9
  79. package/dist/files.js +1 -9
  80. package/dist/github-connection.d.ts +10 -2
  81. package/dist/github-connection.js +65 -2
  82. package/dist/github-faux.js +1 -1
  83. package/dist/github.d.ts +22 -2
  84. package/dist/github.js +42 -8
  85. package/dist/gpu-words.d.ts +14 -0
  86. package/dist/gpu-words.js +21 -0
  87. package/dist/graph-view.d.ts +3 -1
  88. package/dist/graph-view.js +25 -1
  89. package/dist/handed-values.d.ts +1 -1
  90. package/dist/handed-values.js +1 -1
  91. package/dist/harness-install.d.ts +60 -3
  92. package/dist/harness-install.js +322 -34
  93. package/dist/harness.d.ts +1 -0
  94. package/dist/harness.js +36 -2
  95. package/dist/host-tools.d.ts +9 -10
  96. package/dist/host-tools.js +7 -7
  97. package/dist/hosted-search.d.ts +5 -4
  98. package/dist/hosted-search.js +2 -7
  99. package/dist/import-sources.d.ts +10 -0
  100. package/dist/import-sources.js +44 -2
  101. package/dist/import.d.ts +3 -3
  102. package/dist/import.js +37 -6
  103. package/dist/index.d.ts +1 -3
  104. package/dist/index.js +1 -2
  105. package/dist/key-refusal.d.ts +1 -1
  106. package/dist/key-refusal.js +2 -2
  107. package/dist/learn/check.d.ts +11 -2
  108. package/dist/learn/check.js +124 -6
  109. package/dist/learn/commit.d.ts +43 -7
  110. package/dist/learn/commit.js +166 -22
  111. package/dist/learn/folder.d.ts +11 -0
  112. package/dist/learn/folder.js +37 -1
  113. package/dist/learn/general.d.ts +66 -0
  114. package/dist/learn/general.js +73 -0
  115. package/dist/learn/grade.d.ts +22 -1
  116. package/dist/learn/grade.js +107 -16
  117. package/dist/learn/index.d.ts +1 -1
  118. package/dist/learn/index.js +1 -1
  119. package/dist/learn/learning.sh +12 -1
  120. package/dist/learn/notes.d.ts +3 -0
  121. package/dist/learn/notes.js +3 -0
  122. package/dist/learn/reflect.d.ts +14 -2
  123. package/dist/learn/reflect.js +54 -30
  124. package/dist/learn/skills.d.ts +37 -5
  125. package/dist/learn/skills.js +60 -7
  126. package/dist/learned-nodes.d.ts +6 -2
  127. package/dist/learned-workflow.d.ts +43 -9
  128. package/dist/learned-workflow.js +128 -37
  129. package/dist/learning-batch.d.ts +283 -0
  130. package/dist/learning-batch.js +574 -0
  131. package/dist/learning-cost.d.ts +79 -0
  132. package/dist/learning-cost.js +69 -0
  133. package/dist/learning-evals.d.ts +33 -0
  134. package/dist/learning-evals.js +98 -0
  135. package/dist/learning-routes.d.ts +32 -4
  136. package/dist/learning-routes.js +48 -12
  137. package/dist/learning-words.d.ts +9 -0
  138. package/dist/learning-words.js +12 -2
  139. package/dist/learning.d.ts +39 -19
  140. package/dist/learning.js +88 -46
  141. package/dist/live/stream.js +6 -3
  142. package/dist/live/translate.d.ts +4 -3
  143. package/dist/live/translate.js +8 -4
  144. package/dist/live-reach.d.ts +37 -0
  145. package/dist/live-reach.js +62 -0
  146. package/dist/mcp-gateway.d.ts +9 -0
  147. package/dist/mcp-gateway.js +60 -11
  148. package/dist/mcp-oauth.d.ts +57 -7
  149. package/dist/mcp-oauth.js +133 -18
  150. package/dist/mcp-private-hosts.d.ts +4 -4
  151. package/dist/mcp-private-hosts.js +20 -12
  152. package/dist/mcp-probe.d.ts +27 -3
  153. package/dist/mcp-probe.js +106 -29
  154. package/dist/mcp-secret-writes.js +8 -0
  155. package/dist/mcp-servers-store.d.ts +38 -15
  156. package/dist/mcp-servers-store.js +120 -23
  157. package/dist/mcp-store.d.ts +10 -4
  158. package/dist/mcp-store.js +17 -6
  159. package/dist/model-form.d.ts +26 -0
  160. package/dist/model-form.js +80 -0
  161. package/dist/model.d.ts +5 -5
  162. package/dist/model.js +29 -16
  163. package/dist/openapi.d.ts +2 -0
  164. package/dist/openapi.js +586 -64
  165. package/dist/owner.d.ts +0 -1
  166. package/dist/owner.js +0 -2
  167. package/dist/page.d.ts +18 -0
  168. package/dist/page.js +48 -20
  169. package/dist/paid-calls.d.ts +1 -1
  170. package/dist/paid-calls.js +1 -1
  171. package/dist/place-offers.d.ts +96 -0
  172. package/dist/place-offers.js +202 -0
  173. package/dist/place.d.ts +9 -13
  174. package/dist/place.js +21 -32
  175. package/dist/port-models.d.ts +2 -1
  176. package/dist/port-models.js +5 -3
  177. package/dist/print.d.ts +16 -9
  178. package/dist/print.js +15 -17
  179. package/dist/propose.d.ts +4 -0
  180. package/dist/propose.js +34 -11
  181. package/dist/provider.js +3 -2
  182. package/dist/reflect-range.d.ts +8 -1
  183. package/dist/reflect-range.js +1 -1
  184. package/dist/run-cut.d.ts +5 -0
  185. package/dist/run-cut.js +19 -0
  186. package/dist/run-launch.d.ts +28 -3
  187. package/dist/run-launch.js +14 -4
  188. package/dist/run-learning-served.d.ts +2 -2
  189. package/dist/run-manifest.d.ts +2 -2
  190. package/dist/run-manifest.js +2 -2
  191. package/dist/run-reads-over-store.d.ts +1 -1
  192. package/dist/run-repo.d.ts +20 -0
  193. package/dist/run-repo.js +63 -0
  194. package/dist/run-secrets.js +3 -3
  195. package/dist/run-timeline-served.d.ts +1 -1
  196. package/dist/run-timeline-served.js +56 -44
  197. package/dist/run-view.d.ts +8 -5
  198. package/dist/run-view.js +18 -10
  199. package/dist/runnable.d.ts +2 -2
  200. package/dist/runnable.js +6 -2
  201. package/dist/runner/adapter-loop.d.ts +39 -8
  202. package/dist/runner/adapter-loop.js +770 -83
  203. package/dist/runner/adapter-run-spec.d.ts +36 -7
  204. package/dist/runner/adapter-run-spec.js +171 -37
  205. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  206. package/dist/runner/adapters/pi-computer.js +43 -0
  207. package/dist/runner/adapters/pi.d.ts +20 -7
  208. package/dist/runner/adapters/pi.js +111 -26
  209. package/dist/runner/beside.d.ts +7 -3
  210. package/dist/runner/beside.js +26 -12
  211. package/dist/runner/claim-secrets.d.ts +4 -0
  212. package/dist/runner/claim-secrets.js +6 -1
  213. package/dist/runner/cli-run-spec.d.ts +27 -3
  214. package/dist/runner/cli-run-spec.js +198 -74
  215. package/dist/runner/commands.d.ts +8 -2
  216. package/dist/runner/commands.js +31 -6
  217. package/dist/runner/computer-channel.d.ts +34 -0
  218. package/dist/runner/computer-channel.js +61 -0
  219. package/dist/runner/conformance/harness.d.ts +0 -1
  220. package/dist/runner/conformance/harness.js +87 -18
  221. package/dist/runner/conformance/subject.d.ts +1 -1
  222. package/dist/runner/dispatch.js +3 -0
  223. package/dist/runner/end-of-run.d.ts +22 -12
  224. package/dist/runner/end-of-run.js +38 -16
  225. package/dist/runner/github-app.d.ts +2 -1
  226. package/dist/runner/github-app.js +6 -4
  227. package/dist/runner/harness-loops.js +16 -2
  228. package/dist/runner/held-run.d.ts +65 -0
  229. package/dist/runner/held-run.js +158 -0
  230. package/dist/runner/journal-kinds.d.ts +35 -6
  231. package/dist/runner/journal-kinds.js +20 -1
  232. package/dist/runner/journal-reader.d.ts +5 -4
  233. package/dist/runner/journal-reader.js +12 -10
  234. package/dist/runner/learning-ask.d.ts +7 -1
  235. package/dist/runner/learning-ask.js +21 -6
  236. package/dist/runner/learning-dispatch.d.ts +22 -0
  237. package/dist/runner/learning-dispatch.js +77 -10
  238. package/dist/runner/learning-end.d.ts +37 -1
  239. package/dist/runner/learning-end.js +115 -14
  240. package/dist/runner/learning-factory.d.ts +1 -1
  241. package/dist/runner/learning-factory.js +15 -5
  242. package/dist/runner/learning-loop.d.ts +139 -7
  243. package/dist/runner/learning-loop.js +369 -32
  244. package/dist/runner/learning-seed.d.ts +9 -0
  245. package/dist/runner/learning-seed.js +14 -1
  246. package/dist/runner/live-ticker.js +1 -0
  247. package/dist/runner/loop-contract.d.ts +16 -1
  248. package/dist/runner/loop-contract.js +6 -0
  249. package/dist/runner/loop.d.ts +10 -2
  250. package/dist/runner/loop.js +22 -1
  251. package/dist/runner/main.d.ts +13 -1
  252. package/dist/runner/main.js +38 -6
  253. package/dist/runner/mcp-claim.d.ts +11 -4
  254. package/dist/runner/mcp-claim.js +140 -23
  255. package/dist/runner/mcp-github.d.ts +4 -2
  256. package/dist/runner/mcp-github.js +1 -8
  257. package/dist/runner/mcp-run.d.ts +6 -4
  258. package/dist/runner/mcp-run.js +16 -3
  259. package/dist/runner/metrics.d.ts +15 -2
  260. package/dist/runner/metrics.js +21 -2
  261. package/dist/runner/model-route.d.ts +3 -0
  262. package/dist/runner/model-route.js +5 -2
  263. package/dist/runner/pr-checkout.d.ts +60 -0
  264. package/dist/runner/pr-checkout.js +176 -0
  265. package/dist/runner/reflect-hook.d.ts +19 -0
  266. package/dist/runner/reflect-hook.js +20 -8
  267. package/dist/runner/runner.d.ts +26 -0
  268. package/dist/runner/runner.js +231 -27
  269. package/dist/runner/scratch-sweep.d.ts +13 -0
  270. package/dist/runner/scratch-sweep.js +62 -0
  271. package/dist/runner/sessions.d.ts +1 -1
  272. package/dist/runner/spec-holds.d.ts +8 -3
  273. package/dist/runner/spec-holds.js +12 -10
  274. package/dist/runner/store-port.d.ts +7 -2
  275. package/dist/runner/store-secrets.js +21 -4
  276. package/dist/runner/subagent.d.ts +44 -0
  277. package/dist/runner/subagent.js +190 -0
  278. package/dist/runner/workflow-host.d.ts +24 -3
  279. package/dist/runner/workflow-host.js +24 -4
  280. package/dist/runner/workflow-loop.d.ts +6 -3
  281. package/dist/runner/workflow-loop.js +9 -8
  282. package/dist/runner/workflow-spec.d.ts +39 -15
  283. package/dist/runner/workflow-spec.js +143 -40
  284. package/dist/runs-over-store.d.ts +16 -6
  285. package/dist/runs-over-store.js +145 -29
  286. package/dist/seal-key.js +3 -3
  287. package/dist/sealed-settings-store.d.ts +5 -2
  288. package/dist/sealed-settings-store.js +10 -4
  289. package/dist/sealing.js +1 -2
  290. package/dist/secret-cut.d.ts +1 -1
  291. package/dist/secret-cut.js +1 -1
  292. package/dist/secret-writes.d.ts +5 -4
  293. package/dist/secret-writes.js +5 -4
  294. package/dist/server-secrets-store.d.ts +4 -3
  295. package/dist/server-secrets-store.js +15 -9
  296. package/dist/server-secrets.js +3 -2
  297. package/dist/server.d.ts +75 -63
  298. package/dist/server.js +712 -316
  299. package/dist/settings-wake.d.ts +21 -0
  300. package/dist/settings-wake.js +59 -0
  301. package/dist/standard-webhooks.d.ts +4 -1
  302. package/dist/standard-webhooks.js +8 -4
  303. package/dist/store/agent-body.d.ts +9 -2
  304. package/dist/store/agent-body.js +16 -8
  305. package/dist/store/command-wake.d.ts +12 -0
  306. package/dist/store/command-wake.js +37 -0
  307. package/dist/store/deadline.js +9 -5
  308. package/dist/store/dialect.d.ts +6 -0
  309. package/dist/store/dialect.js +5 -0
  310. package/dist/store/index.d.ts +4 -4
  311. package/dist/store/index.js +2 -2
  312. package/dist/store/journal/storage.d.ts +3 -2
  313. package/dist/store/journal/storage.js +15 -6
  314. package/dist/store/postgres/connection.js +9 -4
  315. package/dist/store/postgres/dialect.js +4 -0
  316. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  317. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  318. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  319. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  320. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  321. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  322. package/dist/store/schema.d.ts +2 -1
  323. package/dist/store/schema.js +85 -13
  324. package/dist/store/seal.d.ts +13 -0
  325. package/dist/store/seal.js +19 -0
  326. package/dist/store/sqlite/connection.d.ts +5 -0
  327. package/dist/store/sqlite/connection.js +88 -47
  328. package/dist/store/sqlite/run-patch.d.ts +25 -7
  329. package/dist/store/sqlite/run-patch.js +58 -14
  330. package/dist/store/sqlite/store.js +331 -59
  331. package/dist/store/store.d.ts +330 -21
  332. package/dist/store/store.js +34 -2
  333. package/dist/store-reads/analytics.js +3 -2
  334. package/dist/store-reads/cap.d.ts +2 -4
  335. package/dist/store-reads/cap.js +16 -7
  336. package/dist/store-reads/decisions.d.ts +3 -3
  337. package/dist/store-reads/decisions.js +3 -6
  338. package/dist/store-reads/import-summary.d.ts +1 -1
  339. package/dist/store-reads/journal.d.ts +5 -4
  340. package/dist/store-reads/journal.js +118 -27
  341. package/dist/store-reads/learning.d.ts +34 -4
  342. package/dist/store-reads/learning.js +137 -23
  343. package/dist/store-reads/runs.d.ts +7 -5
  344. package/dist/store-reads/runs.js +17 -10
  345. package/dist/store-reads/stats.js +5 -1
  346. package/dist/store-reads/workflow.d.ts +1 -1
  347. package/dist/store-view.d.ts +5 -0
  348. package/dist/store-view.js +70 -29
  349. package/dist/template-eval.js +8 -5
  350. package/dist/template-github-permissions.d.ts +22 -8
  351. package/dist/template-github-permissions.js +35 -15
  352. package/dist/templates.d.ts +64 -0
  353. package/dist/templates.js +101 -16
  354. package/dist/timeline/timeline.d.ts +30 -1
  355. package/dist/timeline/timeline.js +29 -13
  356. package/dist/timeline/util.d.ts +4 -0
  357. package/dist/timeline/util.js +14 -0
  358. package/dist/tool-blurbs.js +1 -0
  359. package/dist/tool-budget.d.ts +27 -7
  360. package/dist/tool-budget.js +21 -9
  361. package/dist/tool-gate.d.ts +23 -10
  362. package/dist/tool-gate.js +60 -44
  363. package/dist/tool-plane.d.ts +46 -28
  364. package/dist/tool-plane.js +73 -31
  365. package/dist/tools.d.ts +31 -38
  366. package/dist/tools.js +117 -74
  367. package/dist/trigger-adapter.d.ts +4 -0
  368. package/dist/trigger-secrets-shown.d.ts +2 -2
  369. package/dist/trigger-secrets-shown.js +1 -1
  370. package/dist/trigger-signatures.d.ts +26 -6
  371. package/dist/trigger-signatures.js +44 -8
  372. package/dist/trigger-targets.d.ts +2 -0
  373. package/dist/trigger-targets.js +1 -0
  374. package/dist/trigger-webhook.js +5 -2
  375. package/dist/triggers.d.ts +10 -6
  376. package/dist/triggers.js +37 -7
  377. package/dist/turn-end.d.ts +0 -3
  378. package/dist/turn-end.js +0 -3
  379. package/dist/turns.js +16 -1
  380. package/dist/usage-lines.d.ts +1 -1
  381. package/dist/validate.d.ts +6 -0
  382. package/dist/validate.js +41 -4
  383. package/dist/web-fetch.d.ts +1 -1
  384. package/dist/web-search.d.ts +10 -5
  385. package/dist/web-search.js +7 -6
  386. package/dist/webhooks.d.ts +147 -103
  387. package/dist/webhooks.js +564 -324
  388. package/dist/workflow/decision-recovery.d.ts +23 -0
  389. package/dist/workflow/decision-recovery.js +80 -0
  390. package/dist/workflow/decisions.d.ts +134 -0
  391. package/dist/workflow/decisions.js +46 -0
  392. package/dist/workflow/host-session.d.ts +5 -0
  393. package/dist/workflow/host-session.js +85 -0
  394. package/dist/workflow/host-tools.d.ts +3 -0
  395. package/dist/workflow/host-tools.js +3 -0
  396. package/dist/workflow/node-runner.d.ts +113 -0
  397. package/dist/workflow/node-runner.js +270 -0
  398. package/dist/workflow/node.d.ts +89 -0
  399. package/dist/workflow/node.js +101 -0
  400. package/dist/workflow/operator-error.d.ts +4 -0
  401. package/dist/workflow/operator-error.js +4 -0
  402. package/dist/workflow/pi-versions.d.ts +32 -0
  403. package/dist/workflow/pi-versions.js +65 -0
  404. package/dist/workflow/record-file.d.ts +10 -0
  405. package/dist/workflow/record-file.js +56 -0
  406. package/dist/workflow/record-tool.d.ts +77 -0
  407. package/dist/workflow/record-tool.js +126 -0
  408. package/dist/workflow/record.d.ts +151 -0
  409. package/dist/workflow/record.js +401 -0
  410. package/dist/workflow/run-error.d.ts +16 -0
  411. package/dist/workflow/run-error.js +26 -0
  412. package/dist/workflow/runner.d.ts +6 -0
  413. package/dist/workflow/runner.js +240 -0
  414. package/dist/workflow/store.d.ts +23 -0
  415. package/dist/workflow/store.js +242 -0
  416. package/dist/workflow/task.d.ts +133 -0
  417. package/dist/workflow/task.js +412 -0
  418. package/dist/workflow/thinking.d.ts +3 -0
  419. package/dist/workflow/thinking.js +7 -0
  420. package/dist/workflow/tool-context.d.ts +21 -0
  421. package/dist/workflow/tool-context.js +13 -0
  422. package/dist/workflow/types.d.ts +126 -0
  423. package/dist/workflow/types.js +1 -0
  424. package/dist/workflow-run.d.ts +2 -2
  425. package/dist/workspace/agent-computer.d.ts +137 -0
  426. package/dist/workspace/agent-computer.js +292 -0
  427. package/dist/workspace/archil-claim.d.ts +11 -0
  428. package/dist/workspace/archil-claim.js +18 -10
  429. package/dist/workspace/archil-disks.d.ts +49 -0
  430. package/dist/workspace/archil-disks.js +185 -0
  431. package/dist/workspace/archil-exec.js +2 -3
  432. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  433. package/dist/workspace/archil-mount-credential.js +13 -4
  434. package/dist/workspace/attached-computers.d.ts +41 -0
  435. package/dist/workspace/attached-computers.js +114 -0
  436. package/dist/workspace/computer-deps.d.ts +32 -17
  437. package/dist/workspace/computer-deps.js +37 -14
  438. package/dist/workspace/computer-for-claim.d.ts +58 -13
  439. package/dist/workspace/computer-for-claim.js +267 -26
  440. package/dist/workspace/computer-hold.d.ts +11 -27
  441. package/dist/workspace/computer-hold.js +36 -56
  442. package/dist/workspace/computer-janitor.d.ts +3 -2
  443. package/dist/workspace/computer-janitor.js +43 -9
  444. package/dist/workspace/computer-ledger.d.ts +5 -1
  445. package/dist/workspace/computer-ledger.js +11 -0
  446. package/dist/workspace/computer-mcp.d.ts +25 -0
  447. package/dist/workspace/computer-mcp.js +41 -0
  448. package/dist/workspace/computer-ports.d.ts +4 -13
  449. package/dist/workspace/computer-ports.js +4 -107
  450. package/dist/workspace/computer-script.d.ts +37 -0
  451. package/dist/workspace/computer-script.js +138 -0
  452. package/dist/workspace/executors.d.ts +1 -1
  453. package/dist/workspace/index.d.ts +7 -4
  454. package/dist/workspace/index.js +4 -1
  455. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  456. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  457. package/dist/workspace/resolve-computer.d.ts +45 -11
  458. package/dist/workspace/resolve-computer.js +72 -14
  459. package/dist/workspace/run-disk.d.ts +34 -0
  460. package/dist/workspace/run-disk.js +91 -0
  461. package/dist/workspace/run-tools.d.ts +35 -18
  462. package/dist/workspace/run-tools.js +24 -29
  463. package/dist/workspace/server-run-workspace.d.ts +3 -2
  464. package/dist/workspace/server-run-workspace.js +17 -4
  465. package/dist/workspace.js +1 -1
  466. package/package.json +19 -21
  467. package/templates/README.md +9 -6
  468. package/templates/code-review/agent.md +27 -11
  469. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  470. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  471. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  472. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  473. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  474. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  475. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  476. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  477. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  478. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  479. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  480. package/templates/code-review/evals/re-review/prompt.md +1 -1
  481. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  482. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  483. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  484. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  485. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  486. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  487. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  488. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  489. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  490. package/templates/code-review/findings.schema.json +131 -27
  491. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  492. package/templates/code-review/skills/review/DEEP.md +130 -0
  493. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  494. package/templates/code-review/skills/review/SKILL.md +104 -154
  495. package/templates/market-monitor/agent.md +1 -1
  496. package/dist/box/record.d.ts +0 -6
  497. package/dist/box/record.js +0 -41
  498. package/dist/box/sweep.d.ts +0 -53
  499. package/dist/box/sweep.js +0 -193
  500. package/dist/box-egress-vm.d.ts +0 -118
  501. package/dist/box-egress-vm.js +0 -354
  502. package/dist/box-egress.d.ts +0 -105
  503. package/dist/box-egress.js +0 -256
  504. package/dist/box-relay-vm.d.ts +0 -84
  505. package/dist/box-relay-vm.js +0 -437
  506. package/dist/box-relay.d.ts +0 -36
  507. package/dist/box-relay.js +0 -207
  508. package/dist/boxes.d.ts +0 -109
  509. package/dist/boxes.js +0 -249
  510. package/dist/budget.d.ts +0 -71
  511. package/dist/budget.js +0 -199
  512. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  513. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  514. package/dist/daytona-api.d.ts +0 -10
  515. package/dist/daytona-api.js +0 -20
  516. package/dist/egress-proxy.d.ts +0 -45
  517. package/dist/egress-proxy.js +0 -416
  518. package/dist/egress-table.d.ts +0 -24
  519. package/dist/egress-table.js +0 -165
  520. package/dist/run-db.d.ts +0 -53
  521. package/dist/run-db.js +0 -116
  522. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -3,20 +3,30 @@ 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 { CAP_WRAPUP, endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
7
7
  import { raiseFollowUpId } from "../run-view.js";
8
+ import { durableWait } from "../workflow/pi-versions.js";
9
+ /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
10
+ * takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks whether the run's root ends
11
+ * on its end (a fresh reopen). */
12
+ 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]);
8
13
  /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
9
14
  const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
10
- import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
15
+ import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
11
16
  import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
12
17
  import { ADAPTER_API } from "../turn-end.js";
13
18
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
14
- import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
19
+ 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";
15
20
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
16
21
  import { isComputerCommand, journalHold } from "./computer-journal.js";
22
+ import { isHeldCommand, journalHeld } from "./held-run.js";
23
+ import { HELD_KIND, heldWords } from "../computer-held.js";
24
+ import { CALL_KIND, CALL_MS, COMPUTER_CALL } from "../computer-channel.js";
25
+ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
26
+ import { channelCallOf, runChannelCall } from "./computer-channel.js";
17
27
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
18
28
  import { journalSessions } from "./sessions.js";
19
- import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
29
+ import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, previousAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
20
30
  import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
21
31
  import { bookedIn } from "../paid-calls.js";
22
32
  import { withHostCalls } from "../host-calls.js";
@@ -24,7 +34,10 @@ import { sideEffect } from "./side-effects.js";
24
34
  import { McpClaimRefused } from "./mcp-claim.js";
25
35
  import { Fenced } from "../store/index.js";
26
36
  import { parkedFollowUp } from "./mcp-run.js";
27
- import { TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
37
+ import { budgetOf, reserveFor, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
38
+ /** 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,
39
+ * and the harness's next call runs it. */
40
+ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
28
41
  /** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
29
42
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
30
43
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
@@ -55,6 +68,15 @@ export function agentConversation(record) {
55
68
  * before the spec's lifecycle was known). Set in the root's creating commit, cleared in the commit that makes them, so a
56
69
  * claim lost in between leaves them to the next claim. */
57
70
  const RootWritesOwed = defineDoc({ kind: "agentrun.root-writes-owed", version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ owed: false }), checkpointWhen: () => false });
71
+ /** pi's retry of a model request that failed in a way it retries (a provider's 429, overload or 5xx, a dropped connection,
72
+ * a stream cut mid-answer): up to 8 more attempts, 2s doubling to at most 30s apart (about two and a half minutes in all),
73
+ * so a provider's capacity outage of a minute or two is waited out, not the run's end. Each wait is the harness's own
74
+ * durable sleep; a subagent's conversation runs on the same settings. */
75
+ export const MODEL_RETRY = { enabled: true, maxRetries: 8, baseDelayMs: 2_000, maxAgentDelayMs: 30_000 };
76
+ /** pi-ai's retries inside one attempt, of a request the provider refused before any output (a 429 or a 5xx, through the
77
+ * session's proxy, which passes on its retry-after): after the wait the provider asked for, up to 30s, else its own short
78
+ * backoff. Each is a new request through the proxy, judged by the cap and booked as any other: a refusal books nothing. */
79
+ export const MODEL_STREAM = { maxRetries: 2, maxRetryDelayMs: 30_000 };
58
80
  /** The most of a harness's own turn error a failed run's summary keeps. */
59
81
  const TURN_ERROR_MAX = 500;
60
82
  /** A paid call's refusal an earlier claim kept (KINDS.pausePending) whose pause never landed: the newest one with no
@@ -74,6 +96,10 @@ export function pendingPauseOf(entries) {
74
96
  }
75
97
  /** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
76
98
  const DELIVER_NOW_MS = 5_000;
99
+ /** How long the cap's wrap-up note, once a request took it, waits for that request's admission before a later request
100
+ * may take it. A request that leaves before its admission gives it back as it goes (ModelPort.noteReturned): this is
101
+ * only the backstop for a path that never does. A proxy's token count and admission take well under it. */
102
+ const WRAP_UP_OFFER_MS = 30_000;
77
103
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
78
104
  const cutWhole = (text, max) => {
79
105
  const cut = text.slice(0, max);
@@ -148,6 +174,15 @@ async function openCliRecord(harness, journal, context, now, cwd) {
148
174
  const append = async (kind, data) => {
149
175
  await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
150
176
  };
177
+ /** A message that starts a turn: its entry and the turn's start (KINDS.turnStart), one commit, so the turn is open from
178
+ * the commit that holds its message. `entry` is the whole message entry when it is the host's input (with its origin). */
179
+ const startsTurn = async (message) => {
180
+ await harness.commit(async (tx) => {
181
+ await tx.appendEntry(root.id, ("entry" in message ? message.entry : { kind: message.kind, data: { ...message.data, at: now() } }));
182
+ await tx.appendEntry(root.id, { kind: KINDS.turnStart, data: { at: now() } });
183
+ }, context);
184
+ turnsOpen += 1;
185
+ };
151
186
  // Each call started on the record: whether it has its end; and each end, by call id.
152
187
  const started = new Map();
153
188
  const ends = new Map();
@@ -158,6 +193,10 @@ async function openCliRecord(harness, journal, context, now, cwd) {
158
193
  // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
159
194
  const sending = new Set();
160
195
  let personWritten = false;
196
+ // The turns the record opened (KINDS.turnStart) and has not ended (KINDS.turnEnd): what the journal says on open, then kept.
197
+ let turnsOpen = 0;
198
+ // The request ids of the follow-ups written (followUp): each is written once.
199
+ const followUps = new Set();
161
200
  // 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
162
201
  // claim, after a crash in the turn) reuses it, never writes a second.
163
202
  const askedAt = new Map();
@@ -179,6 +218,12 @@ async function openCliRecord(harness, journal, context, now, cwd) {
179
218
  started.set(data.callId, true);
180
219
  else if ((entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
181
220
  personWritten = true;
221
+ if (entry.kind === KINDS.turnStart)
222
+ turnsOpen += 1;
223
+ else if (entry.kind === KINDS.turnEnd && turnsOpen > 0)
224
+ turnsOpen -= 1;
225
+ if ((entry.kind === KINDS.message || entry.kind === KINDS.input) && typeof data.requestId === "string")
226
+ followUps.add(data.requestId);
182
227
  }
183
228
  for (const [callId, ended] of started) {
184
229
  if (ended || (parked.has(callId) && !sent.has(callId)))
@@ -188,19 +233,27 @@ async function openCliRecord(harness, journal, context, now, cwd) {
188
233
  ends.set(callId, { status: "interrupted" });
189
234
  }
190
235
  let text = "";
236
+ /** A model message was written at a request's start (flushSaid) and no other flush has come since. */
237
+ let flushedAtRequest = false;
191
238
  /** The end-of-run turn's answer while that turn runs (answering), else undefined. */
192
239
  let answer;
193
240
  // One write at a time, in the order they were asked for, a failed one never stopping the next.
194
241
  let chain = Promise.resolve();
195
242
  const inTurn = (work) => (chain = chain.then(work, work));
196
243
  /** What was said since the last boundary as a model message; at a turn's end, with the cut its adapter reported. */
197
- const flushText = (cut) => {
244
+ const flushText = (cut, atRequest = false) => {
198
245
  // Taken at the boundary, not when its write's turn comes: text said after it is the next message's.
199
246
  const said = text;
200
247
  text = "";
201
248
  return inTurn(async () => {
202
249
  if (said === "")
203
250
  return;
251
+ // Whitespace after a message flushed at the request before it joined that message's row, as the turn's text up to its
252
+ // call always has: it is no message of its own.
253
+ const joined = flushedAtRequest && said.trim() === "";
254
+ flushedAtRequest = atRequest;
255
+ if (joined)
256
+ return;
204
257
  const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }) } : {};
205
258
  await append(KINDS.message, { role: "model", text: said, ...length });
206
259
  });
@@ -219,24 +272,49 @@ async function openCliRecord(harness, journal, context, now, cwd) {
219
272
  void flushText(event).catch(() => undefined);
220
273
  },
221
274
  flushText,
222
- person: (input) => inTurn(async () => {
275
+ flushSaid: () => (answer === undefined && text.trim() !== "" ? flushText(undefined, true) : Promise.resolve()),
276
+ person: (input, opens = true) => inTurn(async () => {
223
277
  if (personWritten)
224
278
  return;
225
- await append(KINDS.message, { role: "person", text: input });
279
+ if (opens)
280
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
281
+ else
282
+ await append(KINDS.message, { role: "person", text: input });
226
283
  personWritten = true;
227
284
  }),
228
- input: (input, origin) => inTurn(async () => {
285
+ input: (input, origin, opens = true) => inTurn(async () => {
229
286
  if (personWritten)
230
287
  return;
231
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
288
+ const entry = { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] };
289
+ if (opens)
290
+ await startsTurn({ entry });
291
+ else
292
+ await harness.commit((tx) => tx.appendEntry(root.id, entry), context);
293
+ personWritten = true;
294
+ }),
295
+ followUp: (input, requestId, origin) => inTurn(async () => {
296
+ if (followUps.has(requestId))
297
+ return;
298
+ if (origin)
299
+ await startsTurn({ entry: { kind: KINDS.input, data: { origin, requestId }, model: [{ role: "user", content: input, timestamp: now() }] } });
300
+ else
301
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input, requestId } });
302
+ followUps.add(requestId);
232
303
  personWritten = true;
233
304
  }),
234
305
  message: (input, origin) => inTurn(async () => {
235
306
  if (origin)
236
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
307
+ await startsTurn({ entry: { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] } });
237
308
  else
238
- await append(KINDS.message, { role: "person", text: input });
309
+ await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
310
+ }),
311
+ turnEnded: (status, error) => inTurn(async () => {
312
+ if (turnsOpen === 0)
313
+ return;
314
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.turnEnd, data: { status, ...(error === undefined ? {} : { error }) } }), context);
315
+ turnsOpen -= 1;
239
316
  }),
317
+ openTurn: () => turnsOpen > 0,
240
318
  async sending(commandId) {
241
319
  let again = false;
242
320
  await inTurn(async () => {
@@ -342,6 +420,8 @@ export function createAdapterLoop(spec, options = {}) {
342
420
  }
343
421
  function adapterLoop(specOf, options, deps) {
344
422
  const restartLimit = options.restartLimit ?? DEFAULT_RESTART_LIMIT;
423
+ const retry = options.retry ?? MODEL_RETRY;
424
+ const stream = options.stream ?? MODEL_STREAM;
345
425
  const now = options.now ?? Date.now;
346
426
  /** The gate's clock as main's card says a time: ISO. */
347
427
  const isoNow = () => new Date(now()).toISOString();
@@ -356,6 +436,16 @@ function adapterLoop(specOf, options, deps) {
356
436
  };
357
437
  let stopped = () => { };
358
438
  const stopping = new Promise((resolve) => (stopped = resolve));
439
+ /** A cancel, a lost claim or a shutdown that came after a person's stop, and the cut it gives the held computer that
440
+ * stop kept (writeEnd). */
441
+ let laterStop;
442
+ /** Whether the run's first stop kept its computer (keeps), as the runner was told when it chose to go on handing the
443
+ * 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
444
+ * computer go, never waiting for a release no row can bring. */
445
+ let keptAtStop = false;
446
+ const keeps = (reason) => reason.kind === "command" && !reason.cancel && heldNow !== undefined && heldNow.state() !== "released" && !gate?.sealed;
447
+ let cutHeld = () => { };
448
+ const heldCut = new Promise((resolve) => (cutHeld = resolve));
359
449
  /** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal): a host tool call in flight (a CLI's door
360
450
  * 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.
361
451
  * stop() aborts it first, with the stop's Interrupted, so the reason a cut call reads is the stop's. */
@@ -373,6 +463,8 @@ function adapterLoop(specOf, options, deps) {
373
463
  let refusals = 0;
374
464
  /** The claim's first delivery is done (LoopDeps.delivered): every row the runner read is with the loop. */
375
465
  let delivered = false;
466
+ /** The calls this run's journal had asked about and not answered when the claim first read it (askStands). */
467
+ let standing;
376
468
  /** The run is parking at its cap (the early pause, from its commit on): a raise row is left for the next claim. */
377
469
  let pausing = false;
378
470
  /** Resolved once the claim's Harness is open and its root known: a command's check reads the journal through it. */
@@ -381,6 +473,14 @@ function adapterLoop(specOf, options, deps) {
381
473
  let held;
382
474
  /** The run's computer hold's journal side, for the current pass (AdapterRunSpec.computer). */
383
475
  let computerNow;
476
+ /** The run's computer held for its owner, for the current pass (AdapterRunSpec.held). */
477
+ let heldNow;
478
+ /** The current pass's computer for the computer call channel (AdapterRunSpec.computer), and how a call's entry is
479
+ * committed on the run's root through the pass's Harness. */
480
+ let channelNow;
481
+ /** Channel calls done on the computer whose record (and row's take) is still to be written: each answers whether it
482
+ * wrote (settleCalls). */
483
+ const unsettledCalls = new Set();
384
484
  /** This claim's spec, once known: a raise is checked by its cap's rule, and the end's patch is read from it. */
385
485
  let specNow;
386
486
  /** Whether this claim's tool host was let go (its beforeRelease run), once. */
@@ -411,6 +511,15 @@ function adapterLoop(specOf, options, deps) {
411
511
  * Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
412
512
  * the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
413
513
  let reopen;
514
+ /** A reopen of a run whose session is still new (a person stopped it before its first input was sent): resolved once the
515
+ * person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
516
+ * late the runner hands the message over. */
517
+ let firstInputPlaced;
518
+ /** Resolved once a pass of this claim has sent what its session starts on (the run's input, a follow-up, a recovery),
519
+ * or found nothing to send: a message handed over while the session is still new waits for it, so it lands after the
520
+ * run's input, never as the session's first prompt (a message sent as soon as the run's 202 came back). */
521
+ let inputSent = () => { };
522
+ const startSent = new Promise((resolve) => (inputSent = resolve));
414
523
  /** The tool hosts' holds while the run waits in its claim on the person's answer (HostLifecycle.personWait): dropped
415
524
  * once the wait is over, whichever way it ends. */
416
525
  let waitHolds = [];
@@ -603,6 +712,89 @@ function adapterLoop(specOf, options, deps) {
603
712
  handing = turn.catch(() => undefined);
604
713
  return turn;
605
714
  };
715
+ /** The owner's start or release of a held computer (runner/held-run.ts): taken by the commit that writes what came of it
716
+ * (its entry carries the row's id); refused in words when it changed nothing. One at a time, in the take-over's turn. */
717
+ const heldCommand = (command) => {
718
+ const turn = handing.then(async () => {
719
+ await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
720
+ const [theGate, theHeld] = [gate, heldNow];
721
+ if (!theGate || theGate.sealed)
722
+ return { later: "the run is parking or ending: the row waits for its next claim" };
723
+ if (!theHeld)
724
+ return { refused: "This run does not hold its computer: start it with hold: true." };
725
+ const decided = theHeld.decide(command);
726
+ if ("refused" in decided)
727
+ return decided;
728
+ const madeBy = (data) => theHeld.madeBy(data, command.id);
729
+ const landed = theGate.expect(writesEntry(HELD_KIND, madeBy), { take: [command.id] });
730
+ landed.catch(() => undefined);
731
+ await decided.write();
732
+ await landed;
733
+ return { taken: true };
734
+ });
735
+ handing = turn.catch(() => undefined);
736
+ return turn;
737
+ };
738
+ /**
739
+ * A call through the computer call channel (runner/computer-channel.ts): run on the pass's computer, behind the
740
+ * person's hold, and taken with its answer by the commit that writes its computer.call entry. It runs off the take-over's
741
+ * 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,
742
+ * 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
743
+ * (settleCalls): a fault's restart meanwhile writes it through the claim's next pass, and a claim that ends first leaves
744
+ * the row untaken for the run's end, or its next claim, to settle. Refused in words when the run has no
745
+ * computer that takes calls, is parking or ending, or held its computer and let it go.
746
+ */
747
+ const channelCommand = async (command) => {
748
+ await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
749
+ const [theGate, pass, theHeld] = [gate, channelNow, heldNow];
750
+ if (!theGate || theGate.sealed)
751
+ return { refused: "The run's computer is not up now: the run is starting, parking or ending." };
752
+ if (!pass)
753
+ 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." };
754
+ const refusal = theHeld?.refusesCall();
755
+ if (refusal)
756
+ return { refused: refusal };
757
+ const call = channelCallOf(command);
758
+ if ("refused" in call)
759
+ return call;
760
+ void (async () => {
761
+ // The hold's idle count stands still while the call runs, and starts again when the last one ends.
762
+ theHeld?.callStarted();
763
+ let done;
764
+ try {
765
+ done = await runChannelCall(pass.computer, call, AbortSignal.any([deps.signal, AbortSignal.timeout(CALL_MS)]), now);
766
+ }
767
+ finally {
768
+ theHeld?.callEnded(now());
769
+ }
770
+ unsettledCalls.add(async () => {
771
+ // Written through the pass open now: the one the call ran in, or, when a fault closed that one meanwhile, the
772
+ // claim's next. None open (between passes): it waits for the next pass to open.
773
+ const [liveGate, livePass] = [gate, channelNow];
774
+ if (!liveGate || liveGate.sealed || !livePass)
775
+ return false;
776
+ const landed = liveGate.expect(writesEntry(CALL_KIND, (data) => data.by === command.id), { take: [command.id], answer: { command: command.id, value: done.answer } });
777
+ landed.catch(() => undefined);
778
+ await livePass.commit([{ kind: CALL_KIND, data: { by: command.id, at: done.at, ...done.record } }]);
779
+ await landed;
780
+ return true;
781
+ });
782
+ settleCalls();
783
+ })().catch(() => undefined);
784
+ return { taken: true };
785
+ };
786
+ /** Writes each finished channel call whose record is not written yet, through the pass open now. One the pass's seal
787
+ * failed stays for the next pass; one the claim ends with stays untaken, and the run's end (or its next claim) settles
788
+ * its row. */
789
+ function settleCalls() {
790
+ for (const settle of [...unsettledCalls]) {
791
+ unsettledCalls.delete(settle);
792
+ settle().then((written) => {
793
+ if (!written)
794
+ unsettledCalls.add(settle);
795
+ }, () => unsettledCalls.add(settle));
796
+ }
797
+ }
606
798
  /** The raise entry, taking every raise row this claim has in its one commit (each take keyed to the entry). */
607
799
  async function takeRaises() {
608
800
  const takes = raising.takes.splice(0);
@@ -627,18 +819,28 @@ function adapterLoop(specOf, options, deps) {
627
819
  }
628
820
  const steer = async (command) => {
629
821
  // Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
630
- if (!gate || !session)
631
- await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
822
+ // Awaited even with a session there: until the claim is ready it has not said whether this message reopens the run.
823
+ const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
824
+ await Promise.race([ready, over()]);
632
825
  // The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
633
826
  // untaken for the next claim, which hands it on again; never refused for good.
634
827
  if (!gate || !session || gate.sealed)
635
828
  return { later: "the run is parking: the steer waits for its resume" };
829
+ // The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
830
+ // the message would be the session's first prompt and the input would follow it; it waits for the input instead, then
831
+ // goes into that turn as any message does.
832
+ if (!reopen && session.state === "new") {
833
+ await Promise.race([startSent, over()]);
834
+ if (!gate || !session || gate.sealed)
835
+ return { later: "the run is parking: the steer waits for its resume" };
836
+ }
636
837
  // 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
637
- // to answer. Left untaken, so the run's end says it came after the answer.
838
+ // to answer. Left untaken, the run's end opens a completed run again with it as a new turn (store run-patch.ts
839
+ // refuseLeftovers).
638
840
  if (reflecting)
639
- return { later: "the run has answered and is ending: the steer is not placed in its end-of-run turn" };
841
+ return { later: "the run has answered and is ending: the message opens it again as a new turn once its end is in" };
640
842
  if (handingBack)
641
- return { later: "the run has answered and waits for its computer to be handed back before it ends: the steer is not placed" };
843
+ return { later: "the run has answered and waits for its computer to be handed back before it ends: the message opens it again as a new turn once its end is in" };
642
844
  const text = typeof command.body?.text === "string" ? command.body.text : "";
643
845
  const requestId = commandRequest(command.id);
644
846
  // A message that answers nothing (a trigger's, answers: false) waits for the turn's end and runs as a turn of its
@@ -647,7 +849,9 @@ function adapterLoop(specOf, options, deps) {
647
849
  // The session idle with no wait taking messages yet: whether the last turn ended on a question to the person, read
648
850
  // first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
649
851
  // between that choice and the message's placing.
650
- const askedLast = !reopen && session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
852
+ const reopenedBefore = reopen;
853
+ const endedOnAsk = session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
854
+ const askedLast = !reopenedBefore && endedOnAsk;
651
855
  if (!gate || !session || gate.sealed)
652
856
  return { later: "the run is parking: the steer waits for its resume" };
653
857
  // A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
@@ -657,14 +861,38 @@ function adapterLoop(specOf, options, deps) {
657
861
  return { refused: "The run is waiting on a person." };
658
862
  // 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
659
863
  // follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
660
- if (reopen && !reopen.sent && session.state === "idle") {
864
+ if (reopen && !reopen.sent && (session.state === "idle" || session.state === "new")) {
661
865
  const theSession = session;
662
- // The answer to a wait in the claim: the row's waiting summary goes in its commit.
663
- const taken = gate.expect(writesSubmission(requestId), { take: [command.id], ...(reopen === waitTurn ? { run: { summary: null } } : {}) });
866
+ const theRecord = cliRecord;
867
+ // Who wrote it, when the person did not (a trigger's message that reopened the run): its input is that origin's.
868
+ const by = originOf(command.body?.origin);
869
+ // A run a person stopped before its first input was sent (a stop during a harness's first-use install): its session
870
+ // is new. A stop then means "don't start yet", never "forget what I asked": the run's first turn is one request
871
+ // carrying the original input and then the person's message, under the first input's id. The original input is
872
+ // never sent, or answered, as a turn of its own.
873
+ const first = theSession.state === "new" ? specNow : undefined;
874
+ const sendId = first ? INPUT_REQUEST : requestId;
875
+ const content = first ? `${first.input}\n\n${text}` : text;
876
+ // The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
877
+ // writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
878
+ // row. A runner lost between the send and that entry leaves the row untaken, so the next claim sends it again: a
879
+ // follow-up may be sent twice after a crash, never lost. The answer to an ask: the row's waiting summary goes in
880
+ // that commit too, for a wait in the claim and for a question a reopened run parked on (its journal holds its earlier
881
+ // end, so its claim reads as reopened). Left until the end commit, the answer's turn reads running, held and "Waiting
882
+ // for your reply", and the server tells that ask again.
883
+ const placedBy = theRecord ? writesEntry(by ? KINDS.input : KINDS.message, (data) => data.requestId === requestId) : writesSubmission(sendId);
884
+ const taken = gate.expect(placedBy, { take: [command.id], ...(reopen === waitTurn || endedOnAsk ? { run: { summary: null } } : {}) });
664
885
  taken.catch(() => undefined);
665
886
  reopen.sent = (async () => {
666
- await cliRecord?.person(text);
667
- await theSession.send(text, { id: requestId });
887
+ await theSession.send(content, { id: sendId, ...(by ? { origin: by } : {}) });
888
+ // A CLI's record: the original input as its writer's (the launch's origin, else the person's), then the message.
889
+ if (first) {
890
+ if (first.inputOrigin)
891
+ await theRecord?.input(first.input, first.inputOrigin, false);
892
+ else
893
+ await theRecord?.person(first.input, false);
894
+ }
895
+ await theRecord?.followUp(text, requestId, by);
668
896
  })();
669
897
  reopen.placed?.();
670
898
  try {
@@ -777,7 +1005,7 @@ function adapterLoop(specOf, options, deps) {
777
1005
  /** The root a phase is making, awaited before the owed writes are read. */
778
1006
  let rootMaking;
779
1007
  harness = await Harness.open(gate.journal, {
780
- models: () => models, registry, settings: { restartLimit }, onReport: () => { },
1008
+ models: () => models, registry, settings: { restartLimit, retry, stream }, onReport: () => { },
781
1009
  // A tool host's onConversation, in each agent conversation's creating commit (the spec's, once it is known: the
782
1010
  // root is created when the session opens, after the spec).
783
1011
  conversationCreated: async (tx, record) => {
@@ -800,13 +1028,38 @@ function adapterLoop(specOf, options, deps) {
800
1028
  // made here, before the spec, so the spec's tool host binds them at its bind (a browser release's charge comes
801
1029
  // outside any call). Each session is opened at its first step: a run that makes none writes nothing for it. A
802
1030
  // handle not opened on this claim reads what the run's records held when the claim began.
803
- const sessions = journalSessions(harness, context, { flush: () => deps.flush() });
1031
+ // What was spent beside them on the run's behalf (its spec's runCap.beside) is read with them at each admission
1032
+ // (runBooking), the spec's once it is known.
1033
+ const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
1034
+ const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush() }), { beside: besideNow });
804
1035
  let capBuilt;
1036
+ /** The session's previous request, as the cap's `expected` pricing reads it (the kernel's Previous): the last of the
1037
+ * harness's own requests on this claim that answered, its input as its usage reported it (read from or written to
1038
+ * the cache, and the rest) and its input bound, and when it ended. None before one has: priced as a cache miss. */
1039
+ let previous;
1040
+ /** Each of this claim's requests as the cap was asked about it, by its turn, until it ends. */
1041
+ const askedFor = new Map();
805
1042
  const theCap = () => {
806
1043
  if (!specNow?.runCap)
807
1044
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
808
1045
  // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
809
- return (capBuilt ??= runCap({ sessions, ...specNow.runCap, capUsd: capNow }));
1046
+ // Its previous request is the session's own (requestEnded), unless the spec names one (a test's warm cache).
1047
+ const { beside: _beside, ...config } = specNow.runCap;
1048
+ return (capBuilt ??= runCap({ sessions, previousOf: (model) => (previous?.model === model ? previous : undefined), ...config, capUsd: capNow }));
1049
+ };
1050
+ /** A request of this claim ended (`request_end`): one of the harness's own (no host label, no side call) that
1051
+ * answered with its input reported is the session's previous request from now. */
1052
+ const requestEnded = (turn, usage, how) => {
1053
+ const asked = askedFor.get(turn);
1054
+ askedFor.delete(turn);
1055
+ if (!asked?.own || asked.bound === undefined || usage.cut || (how !== undefined && how.end !== "answered"))
1056
+ return;
1057
+ const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1058
+ if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
1059
+ return;
1060
+ // A smaller request than the previous on the same model is a compaction or another conversation's (a child of the
1061
+ // run, whose requests the proxy cannot tell from the root's): history resets (previousAfter), never sticks.
1062
+ previous = previousAfter(previous, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
810
1063
  };
811
1064
  const flushed = { flush: () => deps.flush() };
812
1065
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -889,7 +1142,7 @@ function adapterLoop(specOf, options, deps) {
889
1142
  // A person's stop while the spec was built (it waited on a harness's install): the run ends stopped, in the stop's
890
1143
  // words, its row taken; the work it waited on goes on for the next run. A stop wins over the build's own failure.
891
1144
  if (stopReason?.kind === "command")
892
- return await writeEnd(harness, await harness.root(context), gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId]);
1145
+ return await writeEnd(harness, await harness.root(context), gate, stopEnd(stopReason.cancel), [stopReason.commandId]);
893
1146
  // A spec that failed after a phase made the run's root (its computer's image build failed): the end goes on that
894
1147
  // root with why (said: cut of every secret the runner holds), as run()'s catch writes it once the session's root
895
1148
  // is known, so the timeline keeps the phase row and reads the failure after it.
@@ -950,7 +1203,11 @@ function adapterLoop(specOf, options, deps) {
950
1203
  const cap = capNow();
951
1204
  if (cap === undefined)
952
1205
  return undefined;
953
- let others = 0;
1206
+ // What was spent beside the run on its behalf counts as its other sessions' spend does.
1207
+ const beside = await besideNow();
1208
+ if (beside === null)
1209
+ return undefined;
1210
+ let others = beside;
954
1211
  for (const key of await sessions.keys()) {
955
1212
  if (key === spec.session.key)
956
1213
  continue;
@@ -973,7 +1230,10 @@ function adapterLoop(specOf, options, deps) {
973
1230
  const cap = capNow();
974
1231
  if (!step || cap === undefined)
975
1232
  return pending;
976
- let spent = 0;
1233
+ const beside = await besideNow();
1234
+ if (beside === null)
1235
+ return pending;
1236
+ let spent = beside;
977
1237
  for (const key of await sessions.keys()) {
978
1238
  const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
979
1239
  if (spend === null)
@@ -986,6 +1246,8 @@ function adapterLoop(specOf, options, deps) {
986
1246
  return { ...pending, refuse: text, figures };
987
1247
  };
988
1248
  const beforeRequest = async (request) => {
1249
+ // Kept until it ends, so its answer can be the session's previous request (requestEnded).
1250
+ askedFor.set(request.turn, { model: request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
989
1251
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
990
1252
  // whatever else would pause it (a paid call's refusal, pendingPause).
991
1253
  const over = await overCap();
@@ -1032,6 +1294,11 @@ function adapterLoop(specOf, options, deps) {
1032
1294
  // claim resumes the run parked (an unanswered pause), never ends it as a failed turn. One that cannot land (the
1033
1295
  // journal sealed) is left to the turn's end, as before.
1034
1296
  const park = spec.cap?.park(refusalOf(answer), raisedCapUsd ?? spec.cap.capUsd);
1297
+ // Parking: every later request of this claim is refused in the same words, so nothing more is sent until a raise
1298
+ // (on the next claim) resumes the run. A run's other conversations (a subagent's children) ask in their own
1299
+ // turns; one refused request parks them all, never one alone.
1300
+ if (park?.outcome === "parked")
1301
+ pendingPause ??= answer;
1035
1302
  if (park?.outcome === "parked" && !pausedAtRefusal && harness && gate && !gate.sealed) {
1036
1303
  const on = gate;
1037
1304
  // From here a raise row waits for the next claim (raise): one taken now would answer no pause this claim
@@ -1047,6 +1314,108 @@ function adapterLoop(specOf, options, deps) {
1047
1314
  }
1048
1315
  }
1049
1316
  }
1317
+ // The cap's wrap-up note (#2080): near its cap the run's next main-model request is told once, inside its own body
1318
+ // (the session's model proxy places it: ModelPort.note), to finish now, by the kernel cap's rule (noteFor) over the
1319
+ // run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
1320
+ // (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
1321
+ // cap is told again when it too comes near; written as the server's row only once a request carrying the note is
1322
+ // admitted with it.
1323
+ const wrapUpHarness = harness;
1324
+ const wrapUpRoot = root ?? (await harness.root(context));
1325
+ const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
1326
+ .filter((entry) => entry.kind === CAP_WRAPUP)
1327
+ .map((entry) => entry.data?.capUsd)
1328
+ .filter((capUsd) => typeof capUsd === "number");
1329
+ const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
1330
+ // What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
1331
+ // earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
1332
+ // after each request is admitted (the note is placed before its own request's admission, so it reads the last).
1333
+ const restOf = async () => {
1334
+ // And what was spent beside the run on its behalf (its learning runs' grades).
1335
+ const beside = await besideNow();
1336
+ if (beside === null)
1337
+ return null;
1338
+ let rest = beside;
1339
+ for (const key of await sessions.keys()) {
1340
+ if (key === spec.session.key || key === DECISION_SESSION || key === TOOL_SESSION)
1341
+ continue;
1342
+ const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
1343
+ if (spent === null)
1344
+ return null;
1345
+ rest += spent;
1346
+ }
1347
+ return rest;
1348
+ };
1349
+ // The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
1350
+ // them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
1351
+ // (booked at its hold and bound, the worst case), one never sent, given back, owed or stopped.
1352
+ const claimRecords = await writer.read();
1353
+ const claimHosts = sessionSpendOf(claimRecords).hosts;
1354
+ /** The turns of requests that are no main-model request of the harness's own: read from the records, then each
1355
+ * admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
1356
+ const notOwn = new Set(claimHosts.keys());
1357
+ for (const record of claimRecords) {
1358
+ const data = (record.data ?? {});
1359
+ if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
1360
+ notOwn.add(data.turn);
1361
+ }
1362
+ const capNote = {
1363
+ costs: claimRecords.flatMap((record) => {
1364
+ if (record.kind !== RUNNER_RECORDS.turn)
1365
+ return [];
1366
+ const data = (record.data ?? {});
1367
+ const own = typeof data.usd === "number" && data.usd > 0 && !data.cut && !data.unsent && !data.givenBack && !data.stopped && data.rule !== "owed";
1368
+ return own && (data.turn === undefined || !notOwn.has(data.turn)) ? [data.usd] : [];
1369
+ }),
1370
+ restUsd: await restOf(),
1371
+ };
1372
+ /** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
1373
+ const figuresOf = (model, asked) => {
1374
+ const config = specNow?.runCap;
1375
+ const capModel = config?.modelOf(model);
1376
+ if (!config || !capModel)
1377
+ return undefined;
1378
+ return requestFigures({ kind: "model", id: "reserve", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, config.mode ?? "expected", Date.now());
1379
+ };
1380
+ /** What the run keeps back to answer (tool-budget.ts reserveFor), its typical step the run's own priced answers'. */
1381
+ const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
1382
+ let bookingNow;
1383
+ const wrapUpNote = (model, asked) => {
1384
+ const config = specNow?.runCap;
1385
+ const capModel = config?.modelOf(model);
1386
+ const sessionSpent = bookingNow?.spentUsd();
1387
+ const decided = ledger.decisions.spentUsd();
1388
+ const paidSpent = ledger.paid.spentUsd();
1389
+ const rest = capNote.restUsd;
1390
+ // The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
1391
+ const inFlight = bookingNow?.heldUsd();
1392
+ const capUsd = capNow();
1393
+ // One request at a time carries it: while one offered it waits for its admission, an overlapping request is not
1394
+ // offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
1395
+ // took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
1396
+ // refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
1397
+ // only the backstop for a path that never gives it back: past it, a later request is offered it.
1398
+ if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
1399
+ return undefined;
1400
+ if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
1401
+ return undefined;
1402
+ const spentUsd = sessionSpent + decided + paidSpent + rest;
1403
+ // The tools' gate counts a request in flight at its hold and its bound (sessionSpendOf: a cache miss adds the bound),
1404
+ // so the note counts it the same: it never comes later than the gate's first refusal.
1405
+ const heldUsd = inFlight + (bookingNow?.boundUsd() ?? 0) + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
1406
+ const due = noteFor({ kind: "model", id: "wrap-up", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: Date.now() });
1407
+ // The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
1408
+ // answer (tool-budget.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
1409
+ // its own has not made it due before: told on the request whose tool call would be refused now, no later than the
1410
+ // first refusal. The rule's figure here is the run's spend and holds as they stand at this take, and this request's
1411
+ // own reserve. (The gate's reader, wrapUp, reads the records at each call and is async; a reading kept from an
1412
+ // admission would count that request's own hold as taken after it answered.)
1413
+ const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
1414
+ const leftUsd = capUsd - spentUsd - heldUsd;
1415
+ const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
1416
+ capNote.offered = note ? { ...note, capUsd, at: Date.now() } : undefined;
1417
+ return note?.words;
1418
+ };
1050
1419
  // The rule before a side effect for every paid model request, on the path every adapter's requests take: the
1051
1420
  // booking writes the request's record, then awaits request_start before the request leaves, so the flush here
1052
1421
  // makes that record and everything before it durable first (each send, a retry's included).
@@ -1054,15 +1423,56 @@ function adapterLoop(specOf, options, deps) {
1054
1423
  key: spec.session.key,
1055
1424
  label: spec.session.label,
1056
1425
  beforeRequest,
1426
+ note: wrapUpNote,
1427
+ // A request that took it and left before its admission gives it back: the next request may take it at once.
1428
+ noteReturned: (note) => {
1429
+ if (capNote.offered?.words === note)
1430
+ capNote.offered = undefined;
1431
+ },
1057
1432
  onEvent: async (event) => {
1058
- if (event.type === "request_start")
1433
+ // The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
1434
+ // the harness's own is not one of them).
1435
+ // (A price from the host's table, `estimated`, is a cost; what bookCut tells of an earlier claim's requests, owed
1436
+ // at their hold or cut, comes before `capNote.live` and is never one.)
1437
+ 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)
1438
+ capNote.costs.push(event.usage.usd);
1439
+ if (event.type === "request_end")
1440
+ requestEnded(event.turn, event.usage, event.ended);
1441
+ if (event.type === "request_start") {
1442
+ // A new request means the model's last message is over: what it said so far is on the record before the request,
1443
+ // so an answer shows while the turn goes on (a CLI that answers, then makes another request).
1444
+ await cliRecord?.flushSaid().catch(() => undefined);
1445
+ // A pi run's answers are its own entries, so a request that leaves is marked on the root before it does: one
1446
+ // with no answer by the time the run settles (a stop or cancel cut it mid-answer) was cut, and a cut request's
1447
+ // cost is unknown, never the $0 an unmarked one reads (timeline REQUEST_STARTED). The other harnesses' requests
1448
+ // are read from the booking (spec.record "loop"), and a host's own side request (event.host: a learned node's, a
1449
+ // web search's) is marked and costed by its own path, never as one of the run's answers.
1450
+ if (spec.record !== "loop" && event.host === undefined && event.label === spec.session.label && harness && gate && !gate.sealed) {
1451
+ const on = harness;
1452
+ const conversation = root ?? (await on.root(context));
1453
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_STARTED, data: {} }), context);
1454
+ }
1059
1455
  await deps.flush();
1456
+ }
1457
+ // Its end, when the request did not answer at a price: the stream ended with no answer or none priced (a stop cut
1458
+ // 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.
1459
+ 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) {
1460
+ const on = harness;
1461
+ const conversation = root ?? (await on.root(context));
1462
+ const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
1463
+ // Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
1464
+ // mark cut all the same.
1465
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: (unsent ? { unsent: true } : {}) }), context).catch(() => undefined);
1466
+ }
1060
1467
  },
1061
1468
  });
1469
+ bookingNow = booking;
1062
1470
  // A paid request an earlier claim admitted and never saw answered (its runner lost while the request was out): the
1063
1471
  // provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
1064
1472
  // is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
1065
1473
  await booking.bookCut();
1474
+ // This claim's own answers count toward the typical cost from here (bookCut's owed and cut bookings came before).
1475
+ capNote.live = true;
1066
1476
  // A paid tool call an earlier claim admitted and never saw settled is booked the same way, cut, at its hold, its
1067
1477
  // charge unknown: it may have run and been charged before the claim was lost. Its session opens only for a paid call
1068
1478
  // of this claim, and a replay the gate refuses makes none, so it is opened here for the cut alone, never read as free.
@@ -1080,13 +1490,16 @@ function adapterLoop(specOf, options, deps) {
1080
1490
  const capUsd = capNow();
1081
1491
  if (capUsd === undefined)
1082
1492
  return false;
1083
- let taken = 0;
1493
+ // What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
1494
+ let taken = await besideNow();
1084
1495
  for (const key of await sessions.keys()) {
1085
1496
  const read = sessionSpendOf(await sessions.read(key));
1086
1497
  const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
1087
1498
  taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
1088
1499
  }
1089
- return wrappingUp(capUsd, taken);
1500
+ // What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
1501
+ // is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
1502
+ return wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures));
1090
1503
  };
1091
1504
  const gateOf = preIntentGate(spec, hooks, wrapUp);
1092
1505
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
@@ -1094,6 +1507,13 @@ function adapterLoop(specOf, options, deps) {
1094
1507
  cliRecord = record;
1095
1508
  // Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
1096
1509
  // read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
1510
+ /** A tool call's computer calls (computer-calls.ts), kept on the run's root beside the call, by its id. */
1511
+ const keepCalls = async (call, calls, dropped) => {
1512
+ const [journalOf, rootOf] = [harness, root];
1513
+ if (!journalOf || !rootOf || gate?.sealed)
1514
+ return;
1515
+ await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: COMPUTER_CALLS, data: { call, calls, ...(dropped > 0 ? { dropped } : {}) } }), context);
1516
+ };
1097
1517
  const hosted = (tool) => ({
1098
1518
  ...tool,
1099
1519
  // The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
@@ -1122,10 +1542,13 @@ function adapterLoop(specOf, options, deps) {
1122
1542
  return { text: now.deny, isError: true };
1123
1543
  // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
1124
1544
  // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
1125
- // the claim lets it go; a deny says the earlier attempt may have taken effect.
1126
- if (now === "ask") {
1545
+ // the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
1546
+ // the setting at allow now: the setting answers the ask (allowedBySetting).
1547
+ const bySetting = now === "allow" && (await askStands(toolContext.callId));
1548
+ if (now === "ask" || bySetting) {
1127
1549
  const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
1128
- const answer = await answerOf(call, mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null, asked);
1550
+ const price = mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null;
1551
+ const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
1129
1552
  if (answer === "park")
1130
1553
  return await heldUntilAborted(toolContext.signal);
1131
1554
  if (!answer.approved)
@@ -1146,7 +1569,9 @@ function adapterLoop(specOf, options, deps) {
1146
1569
  // refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
1147
1570
  // The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
1148
1571
  // loop wrapped it, and whether a person approved this call.
1149
- 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 }))),
1572
+ // The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
1573
+ // row's computer_calls, before its result is written.
1574
+ route: () => bookedIn({ call: toolContext.callId, record: async () => { }, 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)))),
1150
1575
  beforeResult: async (answer) => {
1151
1576
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
1152
1577
  try {
@@ -1191,8 +1616,41 @@ function adapterLoop(specOf, options, deps) {
1191
1616
  mcpStale = false;
1192
1617
  await mcp.fresh();
1193
1618
  }
1619
+ // The wrap-up this request carries, taken off the offer now: its admission tells it; a refusal (the throw below)
1620
+ // or a dropped note leaves it untold, to be offered to a later request.
1621
+ const offer = request.noted ? capNote.offered : undefined;
1622
+ if (offer)
1623
+ capNote.offered = undefined;
1194
1624
  const ticket = await port.beforeRequest(request);
1195
1625
  unbooked += 1;
1626
+ // The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
1627
+ if (ticket && request.side)
1628
+ notOwn.add(ticket.turn);
1629
+ // The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
1630
+ if (!request.side && request.host === undefined)
1631
+ capNote.lastFigures = figuresOf(request.model, request) ?? capNote.lastFigures;
1632
+ // What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
1633
+ // the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
1634
+ try {
1635
+ capNote.restUsd = await restOf();
1636
+ }
1637
+ catch (error) {
1638
+ capNote.restUsd = null;
1639
+ console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
1640
+ }
1641
+ // Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
1642
+ // row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
1643
+ if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
1644
+ const { words, leftUsd, capUsd } = offer;
1645
+ toldCaps.push(capUsd);
1646
+ try {
1647
+ await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
1648
+ await deps.flush();
1649
+ }
1650
+ catch (error) {
1651
+ console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
1652
+ }
1653
+ }
1196
1654
  return ticket;
1197
1655
  },
1198
1656
  afterRequest: async (...args) => {
@@ -1209,6 +1667,7 @@ function adapterLoop(specOf, options, deps) {
1209
1667
  },
1210
1668
  ...(port.responded ? { responded: port.responded.bind(port) } : {}),
1211
1669
  ...(port.note ? { note: port.note.bind(port) } : {}),
1670
+ ...(port.noteReturned ? { noteReturned: port.noteReturned.bind(port) } : {}),
1212
1671
  };
1213
1672
  // What the request that just answered cost, once the session's requests are booked (bookingOfAnswer): its own
1214
1673
  // booking's figure, null when unknown; a side request's is given and never read. A refused request's record is its $0.
@@ -1242,10 +1701,17 @@ function adapterLoop(specOf, options, deps) {
1242
1701
  const answer = await askingGate(call, hookContext);
1243
1702
  if (answer !== "allow" && "deny" in answer)
1244
1703
  await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
1704
+ // A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
1705
+ // run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
1706
+ else if (answer === "allow" && approvedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
1707
+ await record.end(call.callId, "done", OWN_TOOL_RELEASED);
1245
1708
  return answer;
1246
1709
  }
1247
1710
  : gateOf;
1248
- const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, hostTool: hosted, bookedCost };
1711
+ // A tool no call of which reaches the gate before it runs (Codex's live search, inside its model requests): its
1712
+ // setting now, read again at each request, so a deny or ask set mid-run reaches the next one.
1713
+ const permission = spec.gate?.permission;
1714
+ const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost };
1249
1715
  // The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
1250
1716
  // MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
1251
1717
  const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
@@ -1271,19 +1737,44 @@ function adapterLoop(specOf, options, deps) {
1271
1737
  : undefined;
1272
1738
  session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
1273
1739
  root = await harness.root(context);
1740
+ // The root as the claim found it, before this pass writes anything of its own there (the computer's show-up, a
1741
+ // takeover's note): what the reopen check below reads, so a fresh reopen is told by the run's own last entry.
1742
+ const foundEntries = restarts === 0 ? await entriesOf(gate.journal, root.id, context) : [];
1274
1743
  // The run's desktop or phone: its hold's changes go to the run's journal, through this pass's Harness (under its
1275
1744
  // fence), and the computer shows up, the agent driving.
1276
1745
  computerNow?.detach();
1277
1746
  computerNow = undefined;
1747
+ channelNow = undefined;
1278
1748
  if (spec.computer) {
1279
1749
  const [journalOf, rootOf] = [harness, root];
1280
- computerNow = journalHold(claim.runId, spec.computer, (entries) => journalOf.commit(async (tx) => {
1750
+ channelNow = { computer: spec.computer, commit: (entries) => journalOf.commit(async (tx) => {
1751
+ for (const entry of entries)
1752
+ await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
1753
+ }, context) };
1754
+ }
1755
+ if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
1756
+ const [journalOf, rootOf] = [harness, root];
1757
+ computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
1281
1758
  for (const entry of entries)
1282
1759
  await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
1283
1760
  }, context), now);
1284
1761
  // The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
1285
1762
  await computerNow.up(await entriesOf(gate.journal, root.id, context));
1286
1763
  }
1764
+ // The run's computer held for its owner: the hold starts waiting on the run's first pass. A later pass's computer
1765
+ // (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,
1766
+ // nor has what the owner set up on it: the run ends in those words.
1767
+ heldNow = undefined;
1768
+ if (spec.held) {
1769
+ const [journalOf, rootOf] = [harness, root];
1770
+ heldNow = journalHeld(spec.held, (entries) => journalOf.commit(async (tx) => {
1771
+ for (const entry of entries)
1772
+ await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
1773
+ }, context), now);
1774
+ if ((await heldNow.up(await entriesOf(gate.journal, root.id, context))) === "lost") {
1775
+ return await writeEnd(harness, root, gate, { state: "failed", summary: heldWords.lost }, []);
1776
+ }
1777
+ }
1287
1778
  // The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
1288
1779
  // budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
1289
1780
  // run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
@@ -1309,15 +1800,58 @@ function adapterLoop(specOf, options, deps) {
1309
1800
  const [journalOf, rootOf, laid] = [harness, root, spec.learningLaid];
1310
1801
  await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.learningLaid, data: { skills: [...laid.skills], workflows: [...laid.workflows] } }), context);
1311
1802
  }
1312
- // Reopened by a person's follow-up (runs.reopen): its journal holds an end and its session opens idle. Set before the
1313
- // session is ready, so the follow-up's steer, handed over once it is, is sent as this claim's turn.
1314
- if (restarts === 0 && session.state === "idle" && (await entriesOf(gate.journal, root.id, context)).some((entry) => entry.kind === KINDS.end))
1315
- reopen = {};
1803
+ // Reopened by a person's follow-up (runs.reopen, or the end's own reopen): a fresh reopen is a claim whose journal's
1804
+ // root ends on an end entry, with no input of the root in flight. Then any turn its session still reads open is one
1805
+ // that end already closed (a person's stop leaves the turn they stopped open in the session: an interrupt writes no
1806
+ // end there), done and never resumed, so it is settled (settleOpenTurn, as a host done with a stopped turn settles
1807
+ // it), and the session, idle, takes the follow-up as this claim's turn: set before the session is ready, so the
1808
+ // follow-up's steer, handed over once it is, is sent as that turn. A claim that finds the follow-up already under way
1809
+ // (anything on the root after the end, or a root input in flight: a takeover or a drain mid follow-up) is no reopen:
1810
+ // its session recovers that turn as any open turn.
1811
+ if (restarts === 0) {
1812
+ const rootId = root.id;
1813
+ // Read before this claim's own writes (foundEntries), and past the bookkeeping any claim writes on the root before
1814
+ // its turn (its session's key, a phase row, a takeover's note, the computer's hold, the learning seed it laid):
1815
+ // none of them is a turn of the follow-up's.
1816
+ const endsRoot = foundEntries.findLast((entry) => !CLAIM_BOOKKEEPING.has(entry.kind))?.kind === KINDS.end;
1817
+ const inFlight = (await harness.inspect(context)).submissions.some((one) => one.conversationId === rootId && one.type === "input");
1818
+ if (endsRoot && !inFlight && session.state === "open_turn")
1819
+ await session.settleOpenTurn();
1820
+ // A session still new (a person stopped the run before its first input was sent): the follow-up is its first
1821
+ // input, and the input the person stopped is never sent.
1822
+ firstInputPlaced = undefined;
1823
+ if (endsRoot && !inFlight && session.state === "idle")
1824
+ reopen = {};
1825
+ else if (endsRoot && !inFlight && session.state === "new") {
1826
+ const mine = {};
1827
+ firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
1828
+ reopen = mine;
1829
+ }
1830
+ }
1316
1831
  opened();
1832
+ // A channel call a fault's restart cut off from its pass: its record is written through this one.
1833
+ settleCalls();
1317
1834
  await reportHeld(harness, root.id);
1318
1835
  if (restarts > restartLimit + 1) {
1319
1836
  return await writeEnd(harness, root, gate, { state: "failed", summary: `the kernel faulted on every restart (${restarts} restarts)` }, [], await cutRows(claim, spec, "faulted"));
1320
1837
  }
1838
+ // A held computer waits for its owner's start before the agent's first input; the owner's calls set the task up
1839
+ // meanwhile. A release, or no call for the hold's minutes, ends the run before its agent ever ran. A stop ends it
1840
+ // stopped, and a lost claim leaves it for the next claim.
1841
+ if (heldNow?.state() === "waiting") {
1842
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
1843
+ const waited = await heldNow.untilStarted(Promise.race([stopping, aborted, harness.closed]));
1844
+ // Set by stop() during the wait: read past the narrowing TypeScript did before it.
1845
+ const cut = stopReason;
1846
+ if (cut?.kind === "command")
1847
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
1848
+ if (cut || deps.signal.aborted || waited === "cut")
1849
+ return await interrupted(cut?.kind ?? "its claim's signal aborted");
1850
+ if (heldNow.state() === "released") {
1851
+ const why = heldNow.lapse() === "timeout" ? heldWords.timeout(spec.held.minutes) : "The owner released the computer before the agent started";
1852
+ return await writeEnd(harness, root, gate, { state: "stopped", outcome: "cancelled", summary: why }, []);
1853
+ }
1854
+ }
1321
1855
  let followedUp = false;
1322
1856
  if (raising.resuming) {
1323
1857
  // Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
@@ -1331,7 +1865,7 @@ function adapterLoop(specOf, options, deps) {
1331
1865
  // ends as a stop does mid-turn: in the stop's words, its row taken, with what the end-of-run step keeps of a
1332
1866
  // cut run.
1333
1867
  if (stopReason?.kind === "command") {
1334
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1868
+ return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1335
1869
  }
1336
1870
  const paused = raising.budget;
1337
1871
  const resumes = raising.resumes;
@@ -1368,7 +1902,13 @@ function adapterLoop(specOf, options, deps) {
1368
1902
  const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
1369
1903
  const follow = await parkedFollowUp(mcp, {
1370
1904
  entries: await entriesOf(gate.journal, root.id, context),
1371
- answer: (call, price) => answerOf(call, price),
1905
+ // As the gate before an intent does: a call still waiting on its person whose tool now reads allow is answered by
1906
+ // the setting (allowedBySetting); any other waits for the person's answer.
1907
+ answer: async (call, price) => {
1908
+ const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
1909
+ const bySetting = now === "allow" && (await askStands(call.callId));
1910
+ return bySetting ? allowedBySetting(call, price, call.tool) : answerOf(call, price);
1911
+ },
1372
1912
  deniedNow: async (call) => {
1373
1913
  // The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
1374
1914
  const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
@@ -1382,7 +1922,7 @@ function adapterLoop(specOf, options, deps) {
1382
1922
  // A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
1383
1923
  // end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
1384
1924
  if (stopReason?.kind === "command")
1385
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1925
+ return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1386
1926
  gate.seal(new Parked());
1387
1927
  return { state: "parked" };
1388
1928
  }
@@ -1400,6 +1940,12 @@ function adapterLoop(specOf, options, deps) {
1400
1940
  // A steer handed over waits on the session's readiness (resolved above) before it sends: one turn of the event loop
1401
1941
  // lets it get there.
1402
1942
  await new Promise((resolve) => setImmediate(resolve));
1943
+ // A session still new: the message is the run's first input, and nothing else may be sent first. A row the
1944
+ // runner reads on a later poll is waited for (or the run's stop, park or loss).
1945
+ if (firstInputPlaced && !reopen.sent) {
1946
+ const lost = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
1947
+ await Promise.race([firstInputPlaced, stopping, parking, harness.closed.then(() => undefined, () => undefined), lost]);
1948
+ }
1403
1949
  const sent = reopen.sent;
1404
1950
  reopen = undefined;
1405
1951
  if (sent) {
@@ -1409,9 +1955,12 @@ function adapterLoop(specOf, options, deps) {
1409
1955
  }
1410
1956
  // A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
1411
1957
  // open found it, and a CLI adapter reads idle once its turn is sent, so state read after a send says nothing.
1412
- const placed = followedUp || session.state !== "idle";
1413
- if (followedUp) {
1414
- // The follow-up is the turn this claim runs.
1958
+ // A reopen of a session still new whose message was never placed (the run stopped, parked or was lost meanwhile):
1959
+ // nothing is sent, least of all the input the person stopped.
1960
+ const firstUnplaced = firstInputPlaced !== undefined && !followedUp;
1961
+ const placed = followedUp || (session.state !== "idle" && !firstUnplaced);
1962
+ if (followedUp || firstUnplaced) {
1963
+ // The follow-up is the turn this claim runs, or there is none.
1415
1964
  }
1416
1965
  else if (session.state === "new") {
1417
1966
  // A trigger's first input is its origin's (the launch's), never written as the person's.
@@ -1423,6 +1972,8 @@ function adapterLoop(specOf, options, deps) {
1423
1972
  }
1424
1973
  else if (session.state === "open_turn")
1425
1974
  await session.recover();
1975
+ // A message handed over while the session was new is placed from here on, after what was just sent.
1976
+ inputSent();
1426
1977
  // The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
1427
1978
  // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
1428
1979
  let turn = placed ? session.turnEnd() : idleTurnOf(harness, root);
@@ -1459,12 +2010,12 @@ function adapterLoop(specOf, options, deps) {
1459
2010
  let timer;
1460
2011
  const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
1461
2012
  clearTimeout(timer);
1462
- // A cancel ends the same way, in its own words (main's "cancelled"); the bound is the same.
1463
- const words = endedBy(stopReason.cancel);
2013
+ // A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
2014
+ const stopped = stopEnd(stopReason.cancel);
1464
2015
  const cut = await cutRows(claim, spec, "stopped");
1465
2016
  if (!settled)
1466
- return await writeEnd(harness, root, gate, { state: "failed", summary: `${words}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
1467
- return await writeEnd(harness, root, gate, { state: "stopped", summary: words }, [stopReason.commandId], cut);
2017
+ 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);
2018
+ return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
1468
2019
  }
1469
2020
  // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
1470
2021
  // it kept went): the run parks on its question, as it does with nothing open.
@@ -1475,6 +2026,8 @@ function adapterLoop(specOf, options, deps) {
1475
2026
  const outcome = (await turn);
1476
2027
  // What the model said last, on the record before the run's end.
1477
2028
  await record?.flushText();
2029
+ // The turn's end on the record, after its last text: a CLI run reads working until here.
2030
+ await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
1478
2031
  await harness.waitForIdle(context);
1479
2032
  const settledEntries = await entriesOf(gate.journal, root.id, context);
1480
2033
  const cutOff = restartLimited(settledEntries);
@@ -1482,6 +2035,20 @@ function adapterLoop(specOf, options, deps) {
1482
2035
  // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
1483
2036
  await bookingsSettled();
1484
2037
  const over = cutOff ? undefined : await overCap();
2038
+ // A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
2039
+ // 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.
2040
+ if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
2041
+ let bound;
2042
+ await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
2043
+ clearTimeout(bound);
2044
+ // A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
2045
+ // narrowing TypeScript did before the delivery.
2046
+ const cutBy = stopReason;
2047
+ if (cutBy?.kind === "command")
2048
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2049
+ if (cutBy || deps.signal.aborted)
2050
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2051
+ }
1485
2052
  if (cutOff)
1486
2053
  data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
1487
2054
  else if (over)
@@ -1501,6 +2068,22 @@ function adapterLoop(specOf, options, deps) {
1501
2068
  return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
1502
2069
  data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
1503
2070
  }
2071
+ else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
2072
+ // A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
2073
+ // queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
2074
+ // answer (the same row the run's end would have written).
2075
+ const said = outcome.error?.trim() ?? "";
2076
+ const rootId = root.id;
2077
+ 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);
2078
+ turn = sendAfterTurn(gate, afterTurn.shift());
2079
+ continue;
2080
+ }
2081
+ else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
2082
+ // A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
2083
+ // turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
2084
+ // with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
2085
+ data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
2086
+ }
1504
2087
  else if (outcome.status !== "completed") {
1505
2088
  // A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
1506
2089
  // the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
@@ -1547,7 +2130,7 @@ function adapterLoop(specOf, options, deps) {
1547
2130
  // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
1548
2131
  const cutBy = stopReason;
1549
2132
  if (cutBy?.kind === "command")
1550
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cutBy.cancel) }, [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2133
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
1551
2134
  if (cutBy || deps.signal.aborted)
1552
2135
  return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
1553
2136
  }
@@ -1583,15 +2166,33 @@ function adapterLoop(specOf, options, deps) {
1583
2166
  // Set by stop() during the wait: read past the narrowing TypeScript did before it.
1584
2167
  const cut = stopReason;
1585
2168
  if (cut?.kind === "command")
1586
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cut.cancel) }, [cut.commandId], await cutRows(claim, spec, "stopped"));
2169
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
1587
2170
  if (cut || deps.signal.aborted)
1588
2171
  return await interrupted(cut?.kind ?? "its claim's signal aborted");
1589
2172
  }
2173
+ // A held computer stays the owner's after the agent's end, for their checks: the run's end, and its computer's
2174
+ // release after it, wait for the owner's release or the hold's lapse. A person's stop keeps waiting (writeEnd), the
2175
+ // run then ending stopped; a cancel ends it at once, and a lost claim leaves it for the next claim.
2176
+ if (heldNow) {
2177
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
2178
+ handingBack = true;
2179
+ const waited = await heldNow.heldAtEnd(Promise.race([stopping, aborted, harness.closed]));
2180
+ const cut = stopReason;
2181
+ if (cut?.kind === "command")
2182
+ return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
2183
+ if (cut || deps.signal.aborted || waited === "cut")
2184
+ return await interrupted(cut?.kind ?? "its claim's signal aborted");
2185
+ }
2186
+ // A stop or cancel the runner handed on as the turn was failing (it hands rows on as they are written) is taken by
2187
+ // this end, which is the stop's own: with the turn's failure the end, its row would be handed on and never taken.
2188
+ const failingStop = data.state === "failed" ? stopReason : undefined;
2189
+ if (failingStop?.kind === "command")
2190
+ return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
1590
2191
  // The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
1591
2192
  // writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
1592
2193
  const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
1593
2194
  if (step.kind === "stopped")
1594
- return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason?.kind === "command" ? stopReason.cancel : undefined) }, [step.commandId], await cutRows(claim, spec, "stopped-looking"));
2195
+ return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
1595
2196
  if (step.kind === "interrupted")
1596
2197
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
1597
2198
  // The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
@@ -1627,6 +2228,8 @@ function adapterLoop(specOf, options, deps) {
1627
2228
  held?.detach();
1628
2229
  computerNow?.detach();
1629
2230
  computerNow = undefined;
2231
+ heldNow = undefined;
2232
+ channelNow = undefined;
1630
2233
  handingBack = false;
1631
2234
  deps.live?.(() => undefined);
1632
2235
  // A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
@@ -1650,7 +2253,8 @@ function adapterLoop(specOf, options, deps) {
1650
2253
  await hooks.beforeIntent(kernelCall);
1651
2254
  // The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
1652
2255
  // asked about.
1653
- const budget = spec.gate?.toolCalls;
2256
+ // A conversation's own budget (a subagent's max_tool_calls) narrows the run's, never widens it.
2257
+ const budget = budgetOf(spec.gate?.toolCalls, call.ownBudget ? await call.ownBudget() : undefined);
1654
2258
  if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
1655
2259
  return { deny: TOOL_BUDGET_TEXT };
1656
2260
  // 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
@@ -1668,7 +2272,10 @@ function adapterLoop(specOf, options, deps) {
1668
2272
  // Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
1669
2273
  if (decision === "deny")
1670
2274
  return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
1671
- if (decision === "allow")
2275
+ // A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
2276
+ // (allowedBySetting), and the call runs without asking the person again.
2277
+ const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
2278
+ if (decision === "allow" && !bySetting)
1672
2279
  return "allow";
1673
2280
  // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
1674
2281
  // (a learned workflow's MCP calls set to ask: askedFor).
@@ -1678,7 +2285,8 @@ function adapterLoop(specOf, options, deps) {
1678
2285
  const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
1679
2286
  // The call on the record before its ask (beforeAsk), with the input its model gave it.
1680
2287
  await beforeAsk?.(call);
1681
- const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
2288
+ const price = mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null;
2289
+ const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked);
1682
2290
  if (answer === "park")
1683
2291
  return { park: true };
1684
2292
  // A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
@@ -1709,23 +2317,7 @@ function adapterLoop(specOf, options, deps) {
1709
2317
  // The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
1710
2318
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
1711
2319
  const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
1712
- // Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
1713
- // of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on.
1714
- const entryLands = async (kind, data, staged) => {
1715
- const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
1716
- // A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
1717
- landed.catch(() => undefined);
1718
- try {
1719
- await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
1720
- await landed;
1721
- return true;
1722
- }
1723
- catch (error) {
1724
- if (gate.sealed)
1725
- return false;
1726
- throw error;
1727
- }
1728
- };
2320
+ const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
1729
2321
  if (first === undefined) {
1730
2322
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
1731
2323
  if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
@@ -1755,6 +2347,67 @@ function adapterLoop(specOf, options, deps) {
1755
2347
  await new Promise((resolve) => (wakeInbox = resolve));
1756
2348
  }
1757
2349
  }
2350
+ /** Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
2351
+ * of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on. */
2352
+ async function landEntry(conversation, kind, data, staged) {
2353
+ const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
2354
+ // A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
2355
+ landed.catch(() => undefined);
2356
+ try {
2357
+ await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
2358
+ await landed;
2359
+ return true;
2360
+ }
2361
+ catch (error) {
2362
+ if (gate.sealed)
2363
+ return false;
2364
+ throw error;
2365
+ }
2366
+ }
2367
+ /** The answer to an ask a person was shown and has not answered, once its tool's setting reads allow: the setting
2368
+ * answers it. The ask closes with an allow row of its own (by "setting": "Allowed by the tool's setting"), the call
2369
+ * runs, and the person is never asked again. A person's answer already in the inbox for the call stands over it when it
2370
+ * is a deny; an allow of theirs is taken with the setting's answer, so no row is left untaken. */
2371
+ async function allowedBySetting(call, price, asked) {
2372
+ // Decided only once the claim's stored commands are with the loop (deps.delivered): pi's recovery starts tool tasks while
2373
+ // the session opens, before command() can put a person's stored deny into the inbox, and the setting must not win over it.
2374
+ await (deps.delivered ?? Promise.resolve());
2375
+ const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
2376
+ if (row?.kind === "deny")
2377
+ return answerOf(call, price, asked);
2378
+ const conversation = await harness.root(context);
2379
+ const data = { callId: call.callId, approved: true, decision: "allow", answeredAt: isoNow(), by: "setting" };
2380
+ if (row)
2381
+ inbox.splice(inbox.indexOf(row), 1);
2382
+ if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
2383
+ return "park";
2384
+ // The call's ask, as journaled: kept for the caller, which scopes an approval to it.
2385
+ const first = findData(await entriesOf(gate.journal, conversation.id, context), KINDS.ask, (ask) => ask.callId === call.callId);
2386
+ if (first)
2387
+ askedArgs.set(call.callId, first.args);
2388
+ return data;
2389
+ }
2390
+ /** Whether a person was asked about this call and has not answered yet (an ask in the journal, no answer): its card is
2391
+ * theirs, so the call waits for that answer (answerOf) even when its tool's setting reads allow by now, and runs on
2392
+ * their allow, its rows reading so. Let through on the setting alone, it ran with its ask unanswered, which the run's
2393
+ * end reads withdrawn: its rows said "Not run: the run ended while it waited" of a call that ran. A deny set since still
2394
+ * refuses it first. Read from the journal once a claim: an ask written later in the claim parks it, and an answer
2395
+ * written later is read by answerOf itself. */
2396
+ async function askStands(callId) {
2397
+ standing ??= (async () => {
2398
+ const conversation = await harness.root(context);
2399
+ const entries = await entriesOf(gate.journal, conversation.id, context);
2400
+ const answered = new Set(entries.filter((entry) => entry.kind === KINDS.answer).map((entry) => entry.data.callId));
2401
+ return new Set(entries.filter((entry) => entry.kind === KINDS.ask).map((entry) => entry.data.callId).filter((id) => !answered.has(id)));
2402
+ })();
2403
+ // A read that failed (a seal while it ran) is read again by the next call, never kept.
2404
+ const read = standing;
2405
+ return (await read.catch((error) => {
2406
+ if (standing === read)
2407
+ standing = undefined;
2408
+ throw error;
2409
+ })).has(callId);
2410
+ }
1758
2411
  /** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
1759
2412
  * park), then thrown, so nothing of it is answered in this pass. */
1760
2413
  function heldUntilAborted(signal) {
@@ -1866,7 +2519,8 @@ function adapterLoop(specOf, options, deps) {
1866
2519
  return { status: "completed" };
1867
2520
  }
1868
2521
  const submission = await on.submission(found.id, context);
1869
- const record = submission ? await submission.wait(context) : undefined;
2522
+ // Never on the claim's signal (durableWait): an abort while it registers is this wait's rejection, never one unhandled.
2523
+ const record = submission ? await durableWait((at) => submission.wait(at), context) : undefined;
1870
2524
  return { status: !record || record.status === "done" ? "completed" : "failed" };
1871
2525
  }
1872
2526
  /** The run waits in its claim on the person's answer to its question (ask_person `callId` ended its turn) when a tool
@@ -1931,6 +2585,9 @@ function adapterLoop(specOf, options, deps) {
1931
2585
  if (done)
1932
2586
  return;
1933
2587
  done = true;
2588
+ if (value === "lapsed")
2589
+ for (const hold of waitHolds)
2590
+ hold.confirmed?.();
1934
2591
  endWait(mine);
1935
2592
  resolve(value);
1936
2593
  };
@@ -1996,7 +2653,7 @@ function adapterLoop(specOf, options, deps) {
1996
2653
  if (!spec.agentId)
1997
2654
  throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
1998
2655
  try {
1999
- 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) });
2656
+ 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) });
2000
2657
  return cut() ?? { kind: "rows", also: rows?.also ?? [] };
2001
2658
  }
2002
2659
  catch (error) {
@@ -2029,17 +2686,17 @@ function adapterLoop(specOf, options, deps) {
2029
2686
  clearTimeout(timer);
2030
2687
  }
2031
2688
  }
2032
- /** The end-of-run turn: one more turn through the run's session, its request id one per run (a repeat is answered from
2033
- * its submission, so a later claim never asks the model again), its writes under work/.learning/ refused while it runs.
2034
- * `again`: its re-ask, a request of its own (one per run too). Aborted at `deadlineMs`. A stop or a lost claim cuts it:
2035
- * it throws, and the step sees why. */
2036
- async function askEndOfRun(claim, prompt, deadlineMs, again = false) {
2689
+ /** 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
2690
+ * answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
2691
+ * asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
2692
+ * per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. */
2693
+ async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1) {
2037
2694
  if (!session || !harness || !gate || !root)
2038
2695
  throw new Error("the run's session is not open");
2039
2696
  const on = harness;
2040
2697
  const conversation = root;
2041
2698
  const theSession = session;
2042
- const requestId = reflectRequestId(claim.runId, again);
2699
+ const requestId = reflectRequestId(claim.runId, again, round);
2043
2700
  const theRecord = cliRecord;
2044
2701
  reflecting = true;
2045
2702
  let timer;
@@ -2149,6 +2806,20 @@ function adapterLoop(specOf, options, deps) {
2149
2806
  /** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
2150
2807
  * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
2151
2808
  async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
2809
+ // A person's stop of a run that holds its computer ends its agent, not the hold (computer-held.ts): the end, and the
2810
+ // computer's release after it, wait for the owner's release or the hold's lapse, the owner's calls still answered.
2811
+ // A cancel, a lost claim or a shutdown meanwhile ends the wait; a cancel's end is then the run's, taking both rows.
2812
+ const stop = stopReason;
2813
+ if (stop?.kind === "command" && keptAtStop && take.includes(stop.commandId) && heldNow && heldNow.state() !== "released" && !theGate.sealed) {
2814
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
2815
+ handingBack = true;
2816
+ await heldNow.heldAtEnd(Promise.race([heldCut, aborted, on.closed]), heldWords.stopped(heldNow.minutes));
2817
+ const later = laterStop;
2818
+ if (later?.kind === "command" && later.cancel) {
2819
+ base = { ...base, ...stopEnd(true) };
2820
+ take = [...take, later.commandId];
2821
+ }
2822
+ }
2152
2823
  // 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
2153
2824
  // their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
2154
2825
  await releaseHost(on);
@@ -2183,6 +2854,9 @@ function adapterLoop(specOf, options, deps) {
2183
2854
  await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
2184
2855
  for (const callId of recordEnds)
2185
2856
  await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
2857
+ // 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.
2858
+ if (cliRecord?.openTurn())
2859
+ await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
2186
2860
  if (failedWith !== undefined)
2187
2861
  await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
2188
2862
  return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
@@ -2232,12 +2906,25 @@ function adapterLoop(specOf, options, deps) {
2232
2906
  return handBack(command);
2233
2907
  if (isComputerCommand(command))
2234
2908
  return computerCommand(command);
2909
+ if (isHeldCommand(command))
2910
+ return heldCommand(command);
2911
+ if (command.kind === COMPUTER_CALL)
2912
+ return channelCommand(command);
2235
2913
  // A pause is a workflow run's: an agentic run's turn is stopped instead, in main's words (runs.ts pause).
2236
2914
  if (command.kind === "pause" || command.kind === "resume")
2237
2915
  return { refused: AGENTIC_PAUSE_REFUSED };
2238
2916
  return { refused: `an adapter loop takes no ${command.kind} command` };
2239
2917
  },
2918
+ keepsComputer: keeps,
2240
2919
  async stop(reason) {
2920
+ // The runner asked keepsComputer right before this call: the first stop's answer is the one its end keeps to.
2921
+ if (stopReason === undefined)
2922
+ keptAtStop = keeps(reason);
2923
+ // A cancel, a lost claim or a shutdown after a stop that kept the run's computer: the hold ends with it (writeEnd).
2924
+ if (stopReason && stopReason !== reason && (reason.kind !== "command" || reason.cancel)) {
2925
+ laterStop ??= reason;
2926
+ cutHeld();
2927
+ }
2241
2928
  stopReason ??= reason;
2242
2929
  if (reason.kind !== "command")
2243
2930
  gate?.seal(new Interrupted(reason.kind));