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

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 (444) hide show
  1. package/CHANGELOG.md +270 -0
  2. package/README.md +343 -246
  3. package/dist/adapters.d.ts +0 -7
  4. package/dist/adapters.js +11 -22
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +14 -0
  14. package/dist/api-only.js +33 -0
  15. package/dist/archil-routes.d.ts +1 -1
  16. package/dist/bash-read-only.d.ts +22 -0
  17. package/dist/bash-read-only.js +701 -0
  18. package/dist/box-egress-vm.d.ts +0 -8
  19. package/dist/box-egress-vm.js +0 -10
  20. package/dist/box-egress.d.ts +0 -4
  21. package/dist/box-egress.js +1 -16
  22. package/dist/box-paths.d.ts +25 -2
  23. package/dist/box-paths.js +79 -11
  24. package/dist/box-relay.d.ts +0 -11
  25. package/dist/box-relay.js +0 -20
  26. package/dist/box-settings.d.ts +26 -0
  27. package/dist/box-settings.js +63 -0
  28. package/dist/boxes.d.ts +21 -1
  29. package/dist/boxes.js +27 -20
  30. package/dist/browser-commands.d.ts +5 -2
  31. package/dist/browser-commands.js +4 -4
  32. package/dist/browser-computer.d.ts +5 -0
  33. package/dist/browser-computer.js +21 -0
  34. package/dist/browser-cost.d.ts +9 -6
  35. package/dist/browser-cost.js +94 -51
  36. package/dist/browser-live.d.ts +7 -20
  37. package/dist/browser-live.js +15 -93
  38. package/dist/browser-person.d.ts +18 -53
  39. package/dist/browser-person.js +94 -279
  40. package/dist/budget.d.ts +0 -4
  41. package/dist/budget.js +0 -7
  42. package/dist/cap.d.ts +8 -12
  43. package/dist/cap.js +12 -27
  44. package/dist/cli.js +61 -20
  45. package/dist/closed-pipes.d.ts +2 -0
  46. package/dist/closed-pipes.js +13 -0
  47. package/dist/computer-commands.d.ts +2 -0
  48. package/dist/computer-commands.js +2 -0
  49. package/dist/computer-keys.js +5 -2
  50. package/dist/computer-setting.d.ts +20 -4
  51. package/dist/computer-setting.js +25 -5
  52. package/dist/computers.d.ts +31 -3
  53. package/dist/computers.js +70 -11
  54. package/dist/confine.d.ts +120 -0
  55. package/dist/confine.js +436 -0
  56. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  57. package/dist/console/assets/index-opTN5Naq.css +1 -0
  58. package/dist/console/index.html +2 -2
  59. package/dist/daytona-api.d.ts +0 -11
  60. package/dist/daytona-api.js +1 -82
  61. package/dist/decision-rows.d.ts +1 -1
  62. package/dist/decision-rows.js +1 -1
  63. package/dist/docker-daemon.d.ts +31 -0
  64. package/dist/docker-daemon.js +56 -0
  65. package/dist/docker-host-addresses.d.ts +37 -0
  66. package/dist/docker-host-addresses.js +110 -0
  67. package/dist/effort-guidance.js +4 -3
  68. package/dist/environment.d.ts +0 -3
  69. package/dist/environment.js +3 -5
  70. package/dist/errors.d.ts +0 -2
  71. package/dist/errors.js +6 -9
  72. package/dist/filed-answer.d.ts +32 -0
  73. package/dist/filed-answer.js +160 -0
  74. package/dist/files.d.ts +1 -11
  75. package/dist/files.js +2 -21
  76. package/dist/github-connection.d.ts +2 -2
  77. package/dist/github-connection.js +1 -1
  78. package/dist/graph-view.d.ts +3 -5
  79. package/dist/graph-view.js +4 -14
  80. package/dist/handed-values.d.ts +9 -0
  81. package/dist/handed-values.js +26 -0
  82. package/dist/harness-install.d.ts +22 -5
  83. package/dist/harness-install.js +98 -20
  84. package/dist/harness-opencode/adapter.d.ts +7 -0
  85. package/dist/harness-opencode/adapter.js +23 -6
  86. package/dist/harness-opencode/index.d.ts +1 -1
  87. package/dist/harness-opencode/index.js +1 -1
  88. package/dist/harness-opencode/verify.d.ts +17 -0
  89. package/dist/harness-opencode/verify.js +30 -10
  90. package/dist/harness-table.js +6 -1
  91. package/dist/harness.d.ts +4 -3
  92. package/dist/harness.js +16 -1
  93. package/dist/heard.js +1 -1
  94. package/dist/held-fd.d.ts +5 -0
  95. package/dist/held-fd.js +14 -0
  96. package/dist/host-calls.d.ts +20 -0
  97. package/dist/host-calls.js +12 -0
  98. package/dist/host-tools.d.ts +4 -21
  99. package/dist/host-tools.js +4 -61
  100. package/dist/host.d.ts +2 -4
  101. package/dist/host.js +2 -7
  102. package/dist/import-summary.d.ts +1 -5
  103. package/dist/import-summary.js +0 -21
  104. package/dist/import.d.ts +6 -6
  105. package/dist/import.js +62 -24
  106. package/dist/key-refusal.d.ts +5 -1
  107. package/dist/key-refusal.js +19 -4
  108. package/dist/learn/check.d.ts +6 -2
  109. package/dist/learn/check.js +83 -29
  110. package/dist/learn/folder.d.ts +5 -1
  111. package/dist/learn/folder.js +10 -3
  112. package/dist/learn/grade.d.ts +14 -0
  113. package/dist/learn/grade.js +68 -12
  114. package/dist/learn/index.d.ts +4 -4
  115. package/dist/learn/index.js +4 -4
  116. package/dist/learn/reflect.d.ts +31 -2
  117. package/dist/learn/reflect.js +79 -4
  118. package/dist/learn/relevance.d.ts +24 -0
  119. package/dist/learn/relevance.js +91 -0
  120. package/dist/learn/secrets.d.ts +8 -1
  121. package/dist/learn/secrets.js +95 -15
  122. package/dist/learn/skills.d.ts +112 -14
  123. package/dist/learn/skills.js +556 -52
  124. package/dist/learned-workflow.d.ts +37 -5
  125. package/dist/learned-workflow.js +106 -12
  126. package/dist/learning-routes.d.ts +16 -49
  127. package/dist/learning-routes.js +46 -36
  128. package/dist/learning-run.d.ts +6 -250
  129. package/dist/learning-run.js +11 -665
  130. package/dist/learning-words.d.ts +12 -5
  131. package/dist/learning-words.js +18 -9
  132. package/dist/learning.d.ts +93 -77
  133. package/dist/learning.js +176 -304
  134. package/dist/live/stream.js +1 -1
  135. package/dist/live/translate.js +13 -3
  136. package/dist/local-models.d.ts +11 -5
  137. package/dist/local-models.js +13 -8
  138. package/dist/mcp-gateway.d.ts +11 -52
  139. package/dist/mcp-gateway.js +44 -148
  140. package/dist/mcp-oauth.d.ts +10 -14
  141. package/dist/mcp-oauth.js +14 -32
  142. package/dist/mcp-probe.d.ts +0 -7
  143. package/dist/mcp-probe.js +4 -10
  144. package/dist/mcp-servers-store.d.ts +6 -6
  145. package/dist/mcp-servers-store.js +13 -15
  146. package/dist/mcp-store.js +3 -4
  147. package/dist/mcp.js +4 -3
  148. package/dist/model.d.ts +6 -7
  149. package/dist/model.js +43 -27
  150. package/dist/monid.d.ts +0 -2
  151. package/dist/monid.js +3 -6
  152. package/dist/openapi.d.ts +8 -1
  153. package/dist/openapi.js +124 -50
  154. package/dist/page.d.ts +1 -3
  155. package/dist/page.js +9 -19
  156. package/dist/paid-calls.d.ts +21 -27
  157. package/dist/paid-calls.js +28 -62
  158. package/dist/pause.d.ts +0 -2
  159. package/dist/pause.js +1 -8
  160. package/dist/place.d.ts +0 -5
  161. package/dist/place.js +0 -10
  162. package/dist/print.d.ts +2 -1
  163. package/dist/print.js +4 -2
  164. package/dist/propose.js +83 -39
  165. package/dist/push-handler.d.ts +1 -1
  166. package/dist/reflect-range.d.ts +25 -0
  167. package/dist/reflect-range.js +30 -0
  168. package/dist/refusal-words.d.ts +5 -1
  169. package/dist/refusal-words.js +5 -1
  170. package/dist/rows.d.ts +1 -1
  171. package/dist/run-cut.d.ts +0 -6
  172. package/dist/run-cut.js +0 -6
  173. package/dist/run-db.d.ts +2 -13
  174. package/dist/run-db.js +2 -41
  175. package/dist/run-launch.d.ts +19 -2
  176. package/dist/run-launch.js +13 -5
  177. package/dist/run-learning-served.d.ts +46 -2
  178. package/dist/run-learning-served.js +26 -7
  179. package/dist/run-reads-over-store.d.ts +1 -1
  180. package/dist/run-reads-over-store.js +15 -6
  181. package/dist/run-secrets.d.ts +33 -0
  182. package/dist/run-secrets.js +53 -0
  183. package/dist/run-timeline-served.d.ts +5 -1
  184. package/dist/run-timeline-served.js +19 -5
  185. package/dist/run-view.d.ts +12 -17
  186. package/dist/run-view.js +29 -28
  187. package/dist/runnable.d.ts +18 -10
  188. package/dist/runnable.js +21 -10
  189. package/dist/runner/adapter-loop.d.ts +14 -3
  190. package/dist/runner/adapter-loop.js +464 -62
  191. package/dist/runner/adapter-run-spec.d.ts +29 -8
  192. package/dist/runner/adapter-run-spec.js +96 -37
  193. package/dist/runner/adapters/index.js +11 -1
  194. package/dist/runner/adapters/pi.d.ts +15 -1
  195. package/dist/runner/adapters/pi.js +19 -5
  196. package/dist/runner/beside.d.ts +30 -3
  197. package/dist/runner/beside.js +54 -12
  198. package/dist/runner/claim-secrets.d.ts +10 -1
  199. package/dist/runner/claim-secrets.js +49 -15
  200. package/dist/runner/cli-run-spec.d.ts +2 -0
  201. package/dist/runner/cli-run-spec.js +60 -17
  202. package/dist/runner/commands.js +1 -1
  203. package/dist/runner/computer-journal.d.ts +15 -2
  204. package/dist/runner/computer-journal.js +41 -5
  205. package/dist/runner/conformance/harness.js +118 -8
  206. package/dist/runner/conformance/subject.d.ts +4 -1
  207. package/dist/runner/dispatch.d.ts +8 -1
  208. package/dist/runner/dispatch.js +81 -7
  209. package/dist/runner/end-of-run.d.ts +8 -2
  210. package/dist/runner/end-of-run.js +10 -4
  211. package/dist/runner/github-app.js +1 -1
  212. package/dist/runner/harness-loops.d.ts +9 -1
  213. package/dist/runner/harness-loops.js +15 -2
  214. package/dist/runner/journal-kinds.d.ts +30 -6
  215. package/dist/runner/journal-kinds.js +20 -5
  216. package/dist/runner/journal-reader.d.ts +1 -1
  217. package/dist/runner/journal-reader.js +2 -2
  218. package/dist/runner/learning-ask.d.ts +4 -0
  219. package/dist/runner/learning-ask.js +15 -1
  220. package/dist/runner/learning-end.d.ts +18 -3
  221. package/dist/runner/learning-end.js +113 -11
  222. package/dist/runner/learning-loop.d.ts +5 -0
  223. package/dist/runner/learning-loop.js +26 -6
  224. package/dist/runner/live-ticker.d.ts +1 -1
  225. package/dist/runner/live-ticker.js +28 -4
  226. package/dist/runner/loop-contract.d.ts +3 -2
  227. package/dist/runner/main.d.ts +64 -10
  228. package/dist/runner/main.js +165 -27
  229. package/dist/runner/mcp-claim.d.ts +1 -1
  230. package/dist/runner/mcp-claim.js +2 -3
  231. package/dist/runner/mcp-run.d.ts +2 -0
  232. package/dist/runner/mcp-run.js +15 -5
  233. package/dist/runner/memory-claim.d.ts +9 -0
  234. package/dist/runner/memory-claim.js +25 -0
  235. package/dist/runner/metrics.d.ts +33 -1
  236. package/dist/runner/metrics.js +85 -1
  237. package/dist/runner/model-route.d.ts +13 -0
  238. package/dist/runner/model-route.js +154 -11
  239. package/dist/runner/redact.d.ts +8 -2
  240. package/dist/runner/redact.js +11 -2
  241. package/dist/runner/reflect-hook.d.ts +12 -1
  242. package/dist/runner/reflect-hook.js +33 -3
  243. package/dist/runner/runner.d.ts +20 -0
  244. package/dist/runner/runner.js +56 -10
  245. package/dist/runner/store-port.d.ts +1 -1
  246. package/dist/runner/store-secrets.d.ts +3 -3
  247. package/dist/runner/store-secrets.js +8 -12
  248. package/dist/runner/text-tools.d.ts +44 -0
  249. package/dist/runner/text-tools.js +237 -0
  250. package/dist/runner/workflow-loop.d.ts +6 -0
  251. package/dist/runner/workflow-loop.js +6 -4
  252. package/dist/runner/workflow-spec.d.ts +18 -0
  253. package/dist/runner/workflow-spec.js +68 -26
  254. package/dist/runs-over-store.d.ts +8 -3
  255. package/dist/runs-over-store.js +76 -19
  256. package/dist/seal-key.d.ts +54 -15
  257. package/dist/seal-key.js +232 -82
  258. package/dist/sealed-settings-store.d.ts +19 -4
  259. package/dist/sealed-settings-store.js +9 -9
  260. package/dist/sealing.d.ts +4 -0
  261. package/dist/sealing.js +20 -0
  262. package/dist/secret-cut.d.ts +1 -1
  263. package/dist/secret-cut.js +1 -1
  264. package/dist/secret-name.d.ts +9 -0
  265. package/dist/secret-name.js +15 -0
  266. package/dist/secret-writes.d.ts +0 -1
  267. package/dist/secret-writes.js +0 -1
  268. package/dist/secrets.d.ts +2 -10
  269. package/dist/secrets.js +21 -17
  270. package/dist/server-fs.d.ts +4 -0
  271. package/dist/server-fs.js +8 -2
  272. package/dist/server-lock.d.ts +0 -24
  273. package/dist/server-lock.js +1 -80
  274. package/dist/server-secrets-store.d.ts +4 -4
  275. package/dist/server-secrets-store.js +10 -32
  276. package/dist/server-secrets.d.ts +4 -9
  277. package/dist/server-secrets.js +12 -33
  278. package/dist/server.d.ts +26 -44
  279. package/dist/server.js +229 -142
  280. package/dist/sign-ins-store.d.ts +34 -36
  281. package/dist/sign-ins-store.js +27 -38
  282. package/dist/sign-ins.d.ts +2 -119
  283. package/dist/sign-ins.js +5 -311
  284. package/dist/standard-webhooks.d.ts +1 -1
  285. package/dist/standard-webhooks.js +1 -1
  286. package/dist/stats.d.ts +3 -2
  287. package/dist/stats.js +1 -1
  288. package/dist/store/agent-body.d.ts +8 -2
  289. package/dist/store/agent-body.js +16 -4
  290. package/dist/store/index.d.ts +3 -3
  291. package/dist/store/index.js +3 -3
  292. package/dist/store/open.d.ts +18 -5
  293. package/dist/store/open.js +23 -3
  294. package/dist/store/postgres/connection.d.ts +18 -2
  295. package/dist/store/postgres/connection.js +156 -32
  296. package/dist/store/postgres/migrate.d.ts +4 -0
  297. package/dist/store/postgres/migrate.js +27 -3
  298. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  299. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  300. package/dist/store/postgres/store.d.ts +9 -2
  301. package/dist/store/postgres/store.js +9 -0
  302. package/dist/store/schema.js +1 -1
  303. package/dist/store/seal.js +2 -2
  304. package/dist/store/sqlite/connection.js +49 -5
  305. package/dist/store/sqlite/run-patch.d.ts +3 -0
  306. package/dist/store/sqlite/run-patch.js +3 -0
  307. package/dist/store/sqlite/store.js +64 -20
  308. package/dist/store/store.d.ts +38 -6
  309. package/dist/store/store.js +12 -2
  310. package/dist/store-reads/cap.d.ts +1 -1
  311. package/dist/store-reads/cap.js +22 -4
  312. package/dist/store-reads/journal.d.ts +25 -6
  313. package/dist/store-reads/journal.js +173 -21
  314. package/dist/store-reads/learning.d.ts +26 -8
  315. package/dist/store-reads/learning.js +12 -4
  316. package/dist/store-reads/workflow.d.ts +1 -1
  317. package/dist/store-reads/workflow.js +1 -1
  318. package/dist/store-view.d.ts +5 -1
  319. package/dist/store-view.js +91 -23
  320. package/dist/template-eval.d.ts +60 -4
  321. package/dist/template-eval.js +120 -54
  322. package/dist/templates.d.ts +24 -10
  323. package/dist/templates.js +69 -38
  324. package/dist/timeline/group.d.ts +33 -0
  325. package/dist/timeline/group.js +77 -0
  326. package/dist/timeline/index.d.ts +7 -0
  327. package/dist/timeline/index.js +7 -0
  328. package/dist/timeline/labels.d.ts +79 -0
  329. package/dist/timeline/labels.js +150 -0
  330. package/dist/timeline/origin.d.ts +56 -0
  331. package/dist/timeline/origin.js +92 -0
  332. package/dist/timeline/render-text.d.ts +11 -0
  333. package/dist/timeline/render-text.js +62 -0
  334. package/dist/timeline/timeline.d.ts +274 -0
  335. package/dist/timeline/timeline.js +1308 -0
  336. package/dist/timeline/util.d.ts +17 -0
  337. package/dist/timeline/util.js +49 -0
  338. package/dist/tool-gate.d.ts +41 -216
  339. package/dist/tool-gate.js +79 -540
  340. package/dist/tool-keys-store.d.ts +11 -12
  341. package/dist/tool-keys-store.js +24 -31
  342. package/dist/tool-keys.d.ts +9 -104
  343. package/dist/tool-keys.js +15 -271
  344. package/dist/tool-plane.d.ts +14 -42
  345. package/dist/tool-plane.js +23 -81
  346. package/dist/tool-settings-store.d.ts +1 -2
  347. package/dist/tool-settings-store.js +5 -8
  348. package/dist/tools.d.ts +31 -19
  349. package/dist/tools.js +101 -108
  350. package/dist/trigger-adapter.d.ts +2 -2
  351. package/dist/trigger-schedule.js +2 -1
  352. package/dist/trigger-secrets-shown.js +5 -1
  353. package/dist/trigger-targets.d.ts +13 -1
  354. package/dist/trigger-targets.js +31 -1
  355. package/dist/triggers.d.ts +2 -2
  356. package/dist/triggers.js +3 -3
  357. package/dist/turn-end.d.ts +1 -1
  358. package/dist/turn-end.js +1 -1
  359. package/dist/turns.d.ts +0 -6
  360. package/dist/turns.js +0 -19
  361. package/dist/uploads.js +1 -1
  362. package/dist/usage.d.ts +0 -2
  363. package/dist/usage.js +0 -2
  364. package/dist/validate.d.ts +2 -0
  365. package/dist/validate.js +23 -14
  366. package/dist/webhooks.d.ts +102 -76
  367. package/dist/webhooks.js +266 -233
  368. package/dist/workflow-run.d.ts +114 -0
  369. package/dist/workflow-run.js +144 -0
  370. package/dist/workspace/beneath.d.ts +19 -0
  371. package/dist/workspace/beneath.js +106 -0
  372. package/dist/workspace/computer-deps.d.ts +52 -5
  373. package/dist/workspace/computer-deps.js +154 -19
  374. package/dist/workspace/computer-for-claim.d.ts +19 -14
  375. package/dist/workspace/computer-for-claim.js +77 -16
  376. package/dist/workspace/computer-hold.d.ts +6 -1
  377. package/dist/workspace/computer-hold.js +6 -1
  378. package/dist/workspace/computer-janitor.d.ts +47 -0
  379. package/dist/workspace/computer-janitor.js +182 -0
  380. package/dist/workspace/computer-providers.d.ts +6 -2
  381. package/dist/workspace/computer-providers.js +1 -1
  382. package/dist/workspace/grep-worker.d.ts +5 -0
  383. package/dist/workspace/grep-worker.js +9 -6
  384. package/dist/workspace/index.d.ts +4 -3
  385. package/dist/workspace/index.js +4 -4
  386. package/dist/workspace/local.d.ts +11 -2
  387. package/dist/workspace/local.js +161 -43
  388. package/dist/workspace/resolve-computer.d.ts +50 -10
  389. package/dist/workspace/resolve-computer.js +46 -11
  390. package/dist/workspace/run-tools.d.ts +13 -31
  391. package/dist/workspace/run-tools.js +10 -27
  392. package/dist/workspace-paths.d.ts +0 -17
  393. package/dist/workspace-paths.js +1 -41
  394. package/dist/workspace.d.ts +0 -17
  395. package/dist/workspace.js +3 -99
  396. package/launcher/agentrun-serve +6 -33
  397. package/package.json +14 -14
  398. package/templates/README.md +9 -3
  399. package/templates/inbound-lead/agent.md +1 -1
  400. package/templates/kyb/agent.md +1 -1
  401. package/templates/market-monitor/agent.md +2 -2
  402. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  403. package/dist/app.d.ts +0 -5
  404. package/dist/app.js +0 -514
  405. package/dist/bound-files.d.ts +0 -4
  406. package/dist/bound-files.js +0 -164
  407. package/dist/bounds.d.ts +0 -26
  408. package/dist/bounds.js +0 -137
  409. package/dist/coding-tools.d.ts +0 -47
  410. package/dist/coding-tools.js +0 -189
  411. package/dist/computer-adb.d.ts +0 -12
  412. package/dist/computer-adb.js +0 -14
  413. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  414. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  415. package/dist/content-filter.d.ts +0 -7
  416. package/dist/content-filter.js +0 -23
  417. package/dist/disk.d.ts +0 -33
  418. package/dist/disk.js +0 -85
  419. package/dist/door-line.d.ts +0 -23
  420. package/dist/door-line.js +0 -83
  421. package/dist/grade.d.ts +0 -63
  422. package/dist/grade.js +0 -150
  423. package/dist/harness-app.d.ts +0 -69
  424. package/dist/harness-app.js +0 -1162
  425. package/dist/mcp-servers.d.ts +0 -269
  426. package/dist/mcp-servers.js +0 -456
  427. package/dist/packs.d.ts +0 -71
  428. package/dist/packs.js +0 -180
  429. package/dist/request-start.d.ts +0 -27
  430. package/dist/request-start.js +0 -381
  431. package/dist/run-box.d.ts +0 -205
  432. package/dist/run-box.js +0 -661
  433. package/dist/run-holder.d.ts +0 -52
  434. package/dist/run-holder.js +0 -139
  435. package/dist/runs.d.ts +0 -1200
  436. package/dist/runs.js +0 -4103
  437. package/dist/sealed-settings.d.ts +0 -60
  438. package/dist/sealed-settings.js +0 -178
  439. package/dist/served-only.d.ts +0 -5
  440. package/dist/served-only.js +0 -12
  441. package/dist/sessions.d.ts +0 -6
  442. package/dist/sessions.js +0 -109
  443. package/dist/workspace/computer-serves.d.ts +0 -12
  444. package/dist/workspace/computer-serves.js +0 -15
@@ -1,11 +1,11 @@
1
1
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
2
  import { createModels } from "@earendil-works/pi-ai/models";
3
- import { createRegistry, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
4
- import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
5
- import { ASK_PERSON_WAITING, endedAnswer, KINDS, withdrawnAnswers } from "./journal-kinds.js";
6
- import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "@parcha/pi-durable-agent/timeline";
3
+ import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
4
+ import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
5
+ import { ASK_PERSON_WAITING, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
+ import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "../timeline/index.js";
7
7
  import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
8
- import { deniedText as setToDenyText } from "../refusal-words.js";
8
+ import { deniedText as setToDenyText, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "../refusal-words.js";
9
9
  import { ADAPTER_API } from "../turn-end.js";
10
10
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
11
11
  import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
@@ -13,9 +13,10 @@ import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
13
13
  import { isComputerCommand, journalHold } from "./computer-journal.js";
14
14
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
15
15
  import { journalSessions } from "./sessions.js";
16
- import { DECISION_SESSION, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
16
+ import { DECISION_SESSION, overCapOf, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
17
17
  import { portModels } from "../port-models.js";
18
18
  import { bookedIn } from "../paid-calls.js";
19
+ import { withHostCalls } from "../host-calls.js";
19
20
  import { sideEffect } from "./side-effects.js";
20
21
  import { McpClaimRefused } from "./mcp-claim.js";
21
22
  import { Fenced } from "../store/index.js";
@@ -46,6 +47,10 @@ export function hostLifecycle() {
46
47
  export function agentConversation(record) {
47
48
  return Number(record.id) === Number(ROOT_CONVERSATION_ID) || record.owner !== undefined;
48
49
  }
50
+ /** On the run's root: the spec's onConversation writes for it are owed (a phase made the root while the spec was built,
51
+ * before the spec's lifecycle was known). Set in the root's creating commit, cleared in the commit that makes them, so a
52
+ * claim lost in between leaves them to the next claim. */
53
+ const RootWritesOwed = defineDoc({ kind: "agentrun.root-writes-owed", version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ owed: false }), checkpointWhen: () => false });
49
54
  /** The most of a harness's own turn error a failed run's summary keeps. */
50
55
  const TURN_ERROR_MAX = 500;
51
56
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
@@ -105,7 +110,8 @@ export function bookingOfAnswer(records, given) {
105
110
  turns.push(turn.turn);
106
111
  if (side.has(turn.turn))
107
112
  continue;
108
- const figure = turn.bookedUsd !== undefined ? turn.bookedUsd : turn.usd;
113
+ // An answer with no price of its own is unknown, never the hold it was booked at for the cap (answeredUnpriced).
114
+ const figure = answeredUnpriced(turn) ? null : turn.bookedUsd !== undefined ? turn.bookedUsd : turn.usd;
109
115
  usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
110
116
  }
111
117
  return { turns, usd };
@@ -113,20 +119,39 @@ export function bookingOfAnswer(records, given) {
113
119
  /** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
114
120
  const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
115
121
  /** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
116
- * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). */
117
- async function openCliRecord(harness, journal, context) {
122
+ * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
123
+ * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
124
+ * message's timestamp: the Timeline dates its rows by them. */
125
+ async function openCliRecord(harness, journal, context, now) {
118
126
  const root = await harness.root(context);
119
127
  const append = async (kind, data) => {
120
- await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: data }), context);
128
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
121
129
  };
122
130
  // Each call started on the record: whether it has its end; and each end, by call id.
123
131
  const started = new Map();
124
132
  const ends = new Map();
133
+ // A call parked at its gate (its start marked parked) and its sent mark: one parked and never marked never left, so it
134
+ // is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
135
+ const parked = new Set();
136
+ const sent = new Set();
137
+ // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
138
+ const sending = new Set();
125
139
  let personWritten = false;
140
+ // Each end-of-run turn's prompt the record wrote as it asked the turn, by its request id: a turn asked again (a later
141
+ // claim, after a crash in the turn) reuses it, never writes a second.
142
+ const askedAt = new Map();
126
143
  for (const entry of await entriesOf(journal, root.id, context)) {
127
144
  const data = (entry.data ?? {});
145
+ if (entry.kind === KINDS.messageSending && typeof data.commandId === "number")
146
+ sending.add(data.commandId);
147
+ if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string")
148
+ askedAt.set(data.requestId, entry.id);
128
149
  if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
129
150
  ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
151
+ if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.parked === true)
152
+ parked.add(data.callId);
153
+ if (entry.kind === KINDS.callSent && typeof data.callId === "string")
154
+ sent.add(data.callId);
130
155
  if (entry.kind === KINDS.callStart && typeof data.callId === "string")
131
156
  started.set(data.callId, started.get(data.callId) ?? false);
132
157
  else if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
@@ -135,7 +160,7 @@ async function openCliRecord(harness, journal, context) {
135
160
  personWritten = true;
136
161
  }
137
162
  for (const [callId, ended] of started) {
138
- if (ended)
163
+ if (ended || (parked.has(callId) && !sent.has(callId)))
139
164
  continue;
140
165
  await append(KINDS.callEnd, { callId, status: "interrupted" });
141
166
  started.set(callId, true);
@@ -182,18 +207,74 @@ async function openCliRecord(harness, journal, context) {
182
207
  input: (input, origin) => inTurn(async () => {
183
208
  if (personWritten)
184
209
  return;
185
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input }] }), context);
210
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
186
211
  personWritten = true;
187
212
  }),
213
+ message: (input, origin) => inTurn(async () => {
214
+ if (origin)
215
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
216
+ else
217
+ await append(KINDS.message, { role: "person", text: input });
218
+ }),
219
+ async sending(commandId) {
220
+ let again = false;
221
+ await inTurn(async () => {
222
+ again = sending.has(commandId);
223
+ if (again)
224
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: HOST_PHASE, data: { summary: MESSAGE_SENT_AGAIN, at: now() } }), context);
225
+ else
226
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.messageSending, data: { commandId, at: now() } }), context);
227
+ sending.add(commandId);
228
+ });
229
+ return again;
230
+ },
188
231
  async start(callId, tool, input, replaySafe) {
189
232
  await flushText();
190
233
  await inTurn(async () => {
191
- if (started.has(callId))
234
+ if (started.has(callId)) {
235
+ // Parked at its gate and now sent: its mark first, in its own commit (the flush before the send makes it last).
236
+ if (parked.has(callId) && !sent.has(callId) && started.get(callId) === false) {
237
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.callSent, data: { callId } }), context);
238
+ sent.add(callId);
239
+ }
192
240
  return;
241
+ }
193
242
  await append(KINDS.callStart, { callId, tool, input, replaySafe });
194
243
  started.set(callId, false);
195
244
  });
196
245
  },
246
+ async park(callId, tool, input, replaySafe) {
247
+ await flushText();
248
+ await inTurn(async () => {
249
+ if (started.has(callId))
250
+ return;
251
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true });
252
+ started.set(callId, false);
253
+ parked.add(callId);
254
+ });
255
+ },
256
+ async refused(callId, tool, input, replaySafe, words) {
257
+ await flushText();
258
+ await inTurn(async () => {
259
+ if (started.get(callId) === true)
260
+ return;
261
+ const at = now();
262
+ const start = { callId, tool, input, replaySafe, at };
263
+ const end = { callId, status: "refused", output: words, at };
264
+ await harness.commit(async (tx) => {
265
+ if (!started.has(callId))
266
+ await tx.appendEntry(root.id, { kind: KINDS.callStart, data: start });
267
+ await tx.appendEntry(root.id, { kind: KINDS.callEnd, data: end });
268
+ }, context);
269
+ started.set(callId, true);
270
+ ends.set(callId, { status: "refused", output: words });
271
+ });
272
+ },
273
+ unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
274
+ noteEnd(callId, status, output) {
275
+ started.set(callId, true);
276
+ ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
277
+ },
197
278
  endOf: (callId) => ends.get(callId),
198
279
  end: (callId, status, output) => inTurn(async () => {
199
280
  if (started.get(callId) !== false)
@@ -202,8 +283,18 @@ async function openCliRecord(harness, journal, context) {
202
283
  started.set(callId, true);
203
284
  ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
204
285
  }),
205
- answering() {
286
+ answering: (requestId, prompt) => {
206
287
  answer = "";
288
+ return inTurn(async () => {
289
+ if (askedAt.has(requestId))
290
+ return;
291
+ await harness.commit(async (tx) => {
292
+ if (await tx.submissionByRequest(root.id, requestId))
293
+ return;
294
+ const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
295
+ askedAt.set(requestId, asked.id);
296
+ }, context);
297
+ });
207
298
  },
208
299
  answered: (requestId, prompt, status) => inTurn(async () => {
209
300
  const said = answer ?? "";
@@ -211,12 +302,14 @@ async function openCliRecord(harness, journal, context) {
211
302
  await harness.commit(async (tx) => {
212
303
  if (await tx.submissionByRequest(root.id, requestId))
213
304
  return;
214
- const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt }, model: [{ role: "user", content: prompt }] });
305
+ // The prompt answering wrote as the turn was asked, else written now.
306
+ const written = askedAt.get(requestId);
307
+ const asked = written !== undefined ? { id: written } : await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
215
308
  if (status !== "completed") {
216
309
  await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "unanswered", entry: asked.id, reason: `the end-of-run turn ended ${status}` });
217
310
  return;
218
311
  }
219
- const answered = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "model", text: said }, model: [{ role: "assistant", content: [{ type: "text", text: said }] }] });
312
+ const answered = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "model", text: said }, model: [{ role: "assistant", content: [{ type: "text", text: said }], timestamp: now() }] });
220
313
  await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "done", entry: asked.id, answer: answered.id });
221
314
  }, context);
222
315
  }),
@@ -242,6 +335,11 @@ function adapterLoop(specOf, options, deps) {
242
335
  };
243
336
  let stopped = () => { };
244
337
  const stopping = new Promise((resolve) => (stopped = resolve));
338
+ /** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal): a host tool call in flight (a CLI's door
339
+ * 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.
340
+ * stop() aborts it first, with the stop's Interrupted, so the reason a cut call reads is the stop's. */
341
+ const stopAbort = new AbortController();
342
+ void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
245
343
  let parked = () => { };
246
344
  const parking = new Promise((resolve) => (parked = resolve));
247
345
  let finished;
@@ -283,6 +381,9 @@ function adapterLoop(specOf, options, deps) {
283
381
  /** While the end-of-run turn runs: a steer is left for the end, and its writes and edits under work/.learning/ are
284
382
  * refused (REFLECT_NOTE_ONLY). */
285
383
  let reflecting = false;
384
+ /** While the run's end waits for a person to hand its desktop or phone back (#2134): a steer is left for the end, as
385
+ * in the end-of-run turn, so no turn starts that the end, written after the hand-back, would cut. */
386
+ let handingBack = false;
286
387
  /** A run a person's follow-up reopened (the store's runs.reopen: its journal holds the end of its last turn, its session
287
388
  * opens idle): the follow-up's steer is this claim's turn, sent by steer() as a tracked turn (`sent`), and the claim waits
288
389
  * for it, so the run's next end comes after that turn's answer. Undefined once the claim has read its delivered rows.
@@ -298,6 +399,14 @@ function adapterLoop(specOf, options, deps) {
298
399
  * answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
299
400
  * answer (waitInClaim), once. */
300
401
  let idleSteer;
402
+ /** The messages a harness with no mid-turn steer (a CLI's: claude-agent, codex, opencode) took while its turn ran, in the
403
+ * order they came: each is sent as a turn of its own once the turn in flight ends, its row taken once the session holds
404
+ * it (sendAfterTurn) (#2174: refused here, a message the API had accepted was lost). Kept across a pass's restart; a row still here
405
+ * when the claim ends is untaken, so the run's next claim takes it again, or the run's end refuses it in the end's words. */
406
+ const afterTurn = [];
407
+ /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
408
+ * during the end-of-run turn does. */
409
+ let turnsOver = false;
301
410
  /** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
302
411
  * only while it is that wait's (a wait that settles late never ends a later one). */
303
412
  const endWait = (of) => {
@@ -325,9 +434,24 @@ function adapterLoop(specOf, options, deps) {
325
434
  /** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
326
435
  * to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
327
436
  const raising = { takes: [], resumes: false, resuming: false };
437
+ /** The cap the run is held to after a raise: the newest raise entry's (read from the run's root when a claim opens, then
438
+ * each one this claim's raise commit lands), else none and the spec's figure (its launch's) holds. The spec gives the
439
+ * launch's cap and nothing more (a raise is a command row, all the server writes), so this is the one place a raise
440
+ * reaches every admission (runCap's capUsd) and every park (the pending budget's cap), on this claim and any later
441
+ * one, another runner's included. */
442
+ let raisedCapUsd;
443
+ /** The run's cap now: the newest raise's, else the spec's. */
444
+ const capNow = () => raisedCapUsd ?? specNow?.runCap.capUsd();
328
445
  /** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
329
446
  * fresh (a parked token may have expired meanwhile). */
330
447
  let mcp;
448
+ /** The calls of this run a person approved (an ask answered allow, on this claim or read from the journal on a resume),
449
+ * each with the arguments its approval card showed (its journaled ask's): an approval covers what that card named. */
450
+ const approvedCalls = new Map();
451
+ /** Each answered call's ask as journaled (the card the person saw), set by answerOf as it reads or writes the answer. */
452
+ const askedArgs = new Map();
453
+ /** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
454
+ let mcpHosted = () => undefined;
331
455
  let mcpStale = false;
332
456
  /** The run's raise state, read from its root: the newest budget entry with no raise entry after it is the pause it
333
457
  * waits at (its pending cap is the cap a raise is checked against); the newest raise entry is its last raise. */
@@ -375,33 +499,48 @@ function adapterLoop(specOf, options, deps) {
375
499
  await takeRaises();
376
500
  return { taken: true };
377
501
  };
502
+ /** A hand-back that reaches a loop whose pass is over, or never opened, waits for the run's next claim. */
503
+ const HAND_BACK_LATER = "the run is parking or ending: the hand-back waits for its next claim";
378
504
  /** Hand-backs one at a time: each decides on the journal the one before it left, so a second answer meets the first. */
379
505
  let handing = Promise.resolve();
380
506
  /** A person's answer to the agent's browser hand-over (hand-back.ts): the first for an ask is its answer, committed as
381
507
  * the answered hand-over entry at the row's own time, the row taken in that commit. A row after the ask lapsed writes
382
- * the expiry (at the expiry's time) and is refused; one for an ask answered already, or never made, is refused. */
508
+ * the expiry (at the expiry's time) and is refused; one for an ask answered already, or never made, is refused. `later`
509
+ * when this claim can no longer say, as an approval's (waitsFor): its Harness never opened, or its pass is over. */
383
510
  const handBack = (command) => {
384
511
  const turn = handing.then(async () => {
385
512
  await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
386
513
  const [theGate, theHarness, theRoot] = [gate, harness, root];
387
- if (!theGate || !theHarness || !theRoot)
388
- return { refused: handBackOf([], command.body, command.createdAt).refused };
389
- // The person's answer takes its row in the commit that writes it: staged for the answer this row would write (its ask,
390
- // its outcome, at its own time). Decided and written in one commit (answerOnce), so no other writer's answer (the
391
- // browser host's give or expiry) lands between: a row whose commit writes nothing, or the ask's expiry, takes none,
392
- // and the staging matches nothing (an answered ask is never answered again).
393
- const { ask, outcome } = (command.body ?? {});
394
- const at = new Date(command.createdAt).toISOString();
395
- const landed = typeof ask === "string" ? theGate.expect(writesEntry(KINDS.handover, (data) => data.id === ask && data.state === outcome && data.at === at), { take: [command.id] }) : undefined;
396
- landed?.catch(() => undefined);
397
- const { write, refused } = await answerOnce((change) => theHarness.commit(change, context), theRoot.id, (entries) => handBackOf(entries, command.body, command.createdAt));
398
- if (write && refused === undefined)
399
- await landed;
400
- return refused === undefined ? { taken: true } : { refused };
514
+ if (!theGate || !theHarness || !theRoot || theGate.sealed)
515
+ return { later: HAND_BACK_LATER };
516
+ try {
517
+ return await handBackThrough(command, theGate, theHarness, theRoot);
518
+ }
519
+ catch (error) {
520
+ // Sealed while it read or wrote: closeSession seals, then closes the Harness the answer went through.
521
+ if (theGate.sealed)
522
+ return { later: HAND_BACK_LATER };
523
+ throw error;
524
+ }
401
525
  });
402
526
  handing = turn.catch(() => undefined);
403
527
  return turn;
404
528
  };
529
+ /** A hand-back's answer, decided and written through the pass's open Harness. */
530
+ const handBackThrough = async (command, theGate, theHarness, theRoot) => {
531
+ // The person's answer takes its row in the commit that writes it: staged for the answer this row would write (its ask,
532
+ // its outcome, at its own time). Decided and written in one commit (answerOnce), so no other writer's answer (the
533
+ // browser host's give or expiry) lands between: a row whose commit writes nothing, or the ask's expiry, takes none,
534
+ // and the staging matches nothing (an answered ask is never answered again).
535
+ const { ask, outcome } = (command.body ?? {});
536
+ const at = new Date(command.createdAt).toISOString();
537
+ const landed = typeof ask === "string" ? theGate.expect(writesEntry(KINDS.handover, (data) => data.id === ask && data.state === outcome && data.at === at), { take: [command.id] }) : undefined;
538
+ landed?.catch(() => undefined);
539
+ const { write, refused } = await answerOnce((change) => theHarness.commit(change, context), theRoot.id, (entries) => handBackOf(entries, command.body, command.createdAt));
540
+ if (write && refused === undefined)
541
+ await landed;
542
+ return refused === undefined ? { taken: true } : { refused };
543
+ };
405
544
  /** A person's take-over or hand-back of the run's desktop or phone (computer-journal.ts): applied to the hold, and taken
406
545
  * by the commit that writes the change it made (its entries carry the row's id); refused in words when it changed
407
546
  * nothing. One at a time, behind the browser's hand-backs' turn: each meets the hold the one before it left. */
@@ -442,6 +581,9 @@ function adapterLoop(specOf, options, deps) {
442
581
  throw error;
443
582
  }
444
583
  await landed;
584
+ // The raise holds from here, at every admission and park: once its entry is in, never before.
585
+ if (data.capUsd > 0)
586
+ raisedCapUsd = data.capUsd;
445
587
  }
446
588
  const steer = async (command) => {
447
589
  // Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
@@ -455,6 +597,8 @@ function adapterLoop(specOf, options, deps) {
455
597
  // to answer. Left untaken, so the run's end says it came after the answer.
456
598
  if (reflecting)
457
599
  return { later: "the run has answered and is ending: the steer is not placed in its end-of-run turn" };
600
+ if (handingBack)
601
+ return { later: "the run has answered and waits for its computer to be handed back before it ends: the steer is not placed" };
458
602
  const text = typeof command.body?.text === "string" ? command.body.text : "";
459
603
  const requestId = commandRequest(command.id);
460
604
  // A message that answers nothing (a trigger's, answers: false) waits for the turn's end and runs as a turn of its
@@ -494,11 +638,21 @@ function adapterLoop(specOf, options, deps) {
494
638
  await taken.catch(() => { });
495
639
  return { taken: true };
496
640
  }
497
- if (!session.steer)
498
- return { refused: "this harness takes no steer mid-turn" };
499
641
  // Who wrote it, when the person did not (a trigger's message): carried on its input, as the Timeline shows it.
500
642
  const origin = originOf(command.body?.origin);
501
- const taken = gate.expect(writesSubmission(requestId), { take: [command.id] });
643
+ if (!session.steer) {
644
+ // A harness that takes no message mid-turn: the API answered it `follow_up` (it waits for the turn's end), so it is
645
+ // the run's next turn, after any taken before it (afterTurn). Taken now as the dispatch takes a row it buffers: the
646
+ // store's take is the commit of its submission, once sent.
647
+ if (turnsOver)
648
+ return { later: "the run has answered and is ending: the message waits for the run's end" };
649
+ afterTurn.push({ commandId: command.id, text, requestId, ...(origin ? { origin } : {}) });
650
+ return { taken: true };
651
+ }
652
+ // A person's answer to the question the last turn ended on (a parked ask's, its run claimed again by it): the row's
653
+ // waiting summary goes in its commit, as an in-claim wait's answer clears it. Left until the end commit, the answer's
654
+ // turn reads running, held and "Waiting for your reply", and the server tells run.needs_input for that ask again.
655
+ const taken = gate.expect(writesSubmission(requestId), { take: [command.id], ...(askedLast ? { run: { summary: null } } : {}) });
502
656
  // A seal while the steer is placed fails it before it is awaited: handled here.
503
657
  taken.catch(() => undefined);
504
658
  const theGate = gate;
@@ -520,6 +674,31 @@ function adapterLoop(specOf, options, deps) {
520
674
  await taken.catch(() => { });
521
675
  return { taken: true };
522
676
  };
677
+ /** A message the turn in flight could not take (afterTurn), sent as a turn of its own. Its row is taken only once the
678
+ * session holds the prompt (send resolves once it is placed): in the commit that writes it on the run's record, right
679
+ * after the send (a CLI's session writes no submission to the run's journal), or, for an adapter keeping its own record,
680
+ * in its submission's commit. A runner lost before that leaves the row untaken, so the next claim sends it again: a
681
+ * message may be sent twice after a crash, never lost. Its turn's end is what this gives. */
682
+ const sendAfterTurn = async (theGate, next) => {
683
+ // Its intent mark, durable before the send (the flush): a runner lost between the send and the take leaves the mark,
684
+ // and the next claim's send of the same row says it is sent again (CliRecord.sending), never silently paid twice.
685
+ if (cliRecord) {
686
+ await cliRecord.sending(next.commandId);
687
+ await deps.flush();
688
+ }
689
+ const origin = next.origin === undefined ? undefined : JSON.stringify(next.origin);
690
+ const match = !cliRecord
691
+ ? writesSubmission(next.requestId)
692
+ : origin !== undefined
693
+ ? writesEntry(KINDS.input, (data) => JSON.stringify(data.origin) === origin)
694
+ : writesEntry(KINDS.message, (data) => data.role === "person" && data.text === next.text);
695
+ const taken = theGate.expect(match, { take: [next.commandId] });
696
+ taken.catch(() => undefined);
697
+ await session.send(next.text, { id: next.requestId, ...(next.origin ? { origin: next.origin } : {}) });
698
+ await specNow?.hooks?.afterMessageSent?.();
699
+ await cliRecord?.message(next.text, next.origin);
700
+ return session.turnEnd();
701
+ };
523
702
  async function run(claim) {
524
703
  context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
525
704
  // Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
@@ -545,6 +724,11 @@ function adapterLoop(specOf, options, deps) {
545
724
  // The spec's phases said before the run's root exists (AdapterRun.phase), written in the root's creating commit.
546
725
  const phasesBeforeRoot = [];
547
726
  let rootMade = false;
727
+ // A root made by a phase while the spec was built (below), before the spec's own lifecycle was known: its
728
+ // onConversation writes for the root are owed (RootWritesOwed, on the root), made once the spec is (after specOf).
729
+ let specKnown = false;
730
+ /** The root a phase is making, awaited before the owed writes are read. */
731
+ let rootMaking;
548
732
  harness = await Harness.open(gate.journal, {
549
733
  models: () => models, registry, settings: { restartLimit }, onReport: () => { },
550
734
  // A tool host's onConversation, in each agent conversation's creating commit (the spec's, once it is known: the
@@ -556,6 +740,10 @@ function adapterLoop(specOf, options, deps) {
556
740
  rootMade = true;
557
741
  for (const data of phasesBeforeRoot.splice(0))
558
742
  await tx.appendEntry(record.id, { kind: HOST_PHASE, data });
743
+ if (!specKnown) {
744
+ (await tx.doc(RootWritesOwed, record.id)).owed = true;
745
+ return;
746
+ }
559
747
  }
560
748
  for (const write of specNow?.lifecycle?.onConversation ?? [])
561
749
  await write(tx, Number(record.id));
@@ -570,7 +758,8 @@ function adapterLoop(specOf, options, deps) {
570
758
  const theCap = () => {
571
759
  if (!specNow?.runCap)
572
760
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
573
- return (capBuilt ??= runCap({ sessions, ...specNow.runCap }));
761
+ // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
762
+ return (capBuilt ??= runCap({ sessions, ...specNow.runCap, capUsd: capNow }));
574
763
  };
575
764
  const flushed = { flush: () => deps.flush() };
576
765
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -602,14 +791,28 @@ function adapterLoop(specOf, options, deps) {
602
791
  pause: async (refusal) => {
603
792
  await pauseFor?.(refusal);
604
793
  },
794
+ flush: () => deps.flush(),
605
795
  };
606
- // A phase of the host's: queued until the root exists (written in its creating commit, above), else written at once.
796
+ // A phase of the host's, on the run's timeline while its step runs. Said before the root exists (the claim's computer
797
+ // waiting on its image build, inside specOf), it makes the root then, the row in its creating commit (above), so a
798
+ // person sees the row during the wait, and a failed step keeps it (run()'s catch writes the end on that root). The
799
+ // session opens onto that root later and sets its agent there (pi.ts configures it on every open). Else at once.
607
800
  const phasing = harness;
608
801
  const phase = (summary) => {
609
802
  const data = { summary, at: Date.now() };
610
803
  void (async () => {
611
804
  if (!rootMade && !(await phasing.conversation(ROOT_CONVERSATION_ID, context)) && !rootMade) {
612
805
  phasesBeforeRoot.push(data);
806
+ rootMaking = phasing.root(context);
807
+ await rootMaking;
808
+ // The root was made by another write meanwhile (its creating commit took none of these): written now.
809
+ const left = phasesBeforeRoot.splice(0);
810
+ if (left.length === 0)
811
+ return;
812
+ await phasing.commit(async (tx) => {
813
+ for (const one of left)
814
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data: one });
815
+ }, context);
613
816
  return;
614
817
  }
615
818
  await phasing.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data }), context);
@@ -621,7 +824,7 @@ function adapterLoop(specOf, options, deps) {
621
824
  return;
622
825
  passGate.expect(writesEntry(kind, test), { run: { summary } }).catch(() => undefined);
623
826
  };
624
- const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, phase, rowSummaryOn };
827
+ const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn };
625
828
  // The spec, its MCP claim step among it (mcpForClaim, before the session opens). A refusal there ends the run in its
626
829
  // words with nothing sent; a claim lost during its refresh ends the loop with nothing more written. A claim the spec
627
830
  // refuses (ClaimRefused: a handed sign-in that won't read back) ends the run in its words too.
@@ -636,11 +839,40 @@ function adapterLoop(specOf, options, deps) {
636
839
  return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
637
840
  if (error instanceof ClaimRefused)
638
841
  return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
842
+ // A person's stop while the spec was built (it waited on a harness's install): the run ends stopped, in the stop's
843
+ // words, its row taken; the work it waited on goes on for the next run. A stop wins over the build's own failure.
844
+ if (stopReason?.kind === "command")
845
+ return await writeEnd(harness, await harness.root(context), gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId]);
846
+ // A spec that failed after a phase made the run's root (its computer's image build failed): the end goes on that
847
+ // root with why (said: cut of every secret the runner holds), as run()'s catch writes it once the session's root
848
+ // is known, so the timeline keeps the phase row and reads the failure after it.
849
+ await rootMaking?.catch(() => undefined);
850
+ if (rootMade && claim.from !== "parked" && !gate.sealed && !deps.signal.aborted) {
851
+ const ended = await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: said(error) }, []).catch(() => undefined);
852
+ if (ended)
853
+ return ended;
854
+ }
639
855
  throw error;
640
856
  }
641
857
  mcp = spec.mcp;
642
858
  specNow = spec;
859
+ specKnown = true;
860
+ // The spec's resources are the pass's from here: a claim lost in any write below still lets them go (closeSession).
643
861
  releaseNow = spec.release;
862
+ // A root a phase made while the spec was built (on this claim or an earlier one lost before this point) took none
863
+ // of the spec's onConversation writes: they are made now, in a commit of their own, before anything of the
864
+ // session's. A root still being made is waited for first (made from here on, its creating commit takes them itself).
865
+ await rootMaking?.catch(() => undefined);
866
+ if (await harness.conversation(ROOT_CONVERSATION_ID, context)) {
867
+ await harness.commit(async (tx) => {
868
+ const owed = await tx.doc(RootWritesOwed, ROOT_CONVERSATION_ID);
869
+ if (!owed.owed)
870
+ return;
871
+ owed.owed = false;
872
+ for (const write of spec.lifecycle?.onConversation ?? [])
873
+ await write(tx, Number(ROOT_CONVERSATION_ID));
874
+ }, context);
875
+ }
644
876
  // A mark of the run's commits through its own Harness, under its fence.
645
877
  const opened_ = harness;
646
878
  spec.harnessReady?.((change, ctx) => opened_.commit(change, ctx));
@@ -660,8 +892,35 @@ function adapterLoop(specOf, options, deps) {
660
892
  let pausedAtRefusal = false;
661
893
  /** A paid call's refusal that pauses the run (ledger.pause): the run's next request is refused in its words. */
662
894
  let pendingPause;
895
+ /** How the run ends once its booked spend passed its cap (the kernel's overCapEnd, main's run end): every session's
896
+ * booked spend summed, as the cap reads it; the bound, its model session's requests' since the cost last fit, so a
897
+ * cache miss within that bound pauses the run at its next request instead. Undefined while it fits, with no cap, or
898
+ * with a spend unknown. */
899
+ const overCap = async () => {
900
+ // A run whose spec gives no cap (no runCap, or no cap's rule) has none to pass.
901
+ if (!spec.cap || !spec.runCap)
902
+ return undefined;
903
+ const cap = capNow();
904
+ if (cap === undefined)
905
+ return undefined;
906
+ let others = 0;
907
+ for (const key of await sessions.keys()) {
908
+ if (key === spec.session.key)
909
+ continue;
910
+ const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
911
+ if (spent === null)
912
+ return undefined;
913
+ others += spent;
914
+ }
915
+ // Its model session read as the cap reads it (the kernel's overCapOf: a request cut by a crash at its hold plus its
916
+ // bound, and that bound kept, so a possible cache miss pauses the run, never fails it).
917
+ return overCapOf(await sessions.read(spec.session.key), others, cap);
918
+ };
663
919
  const beforeRequest = async (request) => {
664
- const answer = pendingPause ?? (await theCap().before(request));
920
+ // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
921
+ // whatever else would pause it (a paid call's refusal, pendingPause).
922
+ const over = await overCap();
923
+ const answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
665
924
  if (answer && "refuse" in answer) {
666
925
  refused = answer;
667
926
  await pauseAt(answer);
@@ -678,7 +937,7 @@ function adapterLoop(specOf, options, deps) {
678
937
  // reaches pi: pi stores the refused turn only after it, so a claim lost in between leaves the pause, and the next
679
938
  // claim resumes the run parked (an unanswered pause), never ends it as a failed turn. One that cannot land (the
680
939
  // journal sealed) is left to the turn's end, as before.
681
- const park = spec.cap?.park(refusalOf(answer));
940
+ const park = spec.cap?.park(refusalOf(answer), raisedCapUsd ?? spec.cap.capUsd);
682
941
  if (park?.outcome === "parked" && !pausedAtRefusal && harness && gate && !gate.sealed) {
683
942
  const on = gate;
684
943
  // From here a raise row waits for the next claim (raise): one taken now would answer no pause this claim
@@ -710,17 +969,26 @@ function adapterLoop(specOf, options, deps) {
710
969
  // provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
711
970
  // is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
712
971
  await booking.bookCut();
972
+ // A paid tool call an earlier claim admitted and never saw settled is booked the same way, cut, at its hold, its
973
+ // charge unknown: it may have run and been charged before the claim was lost. Its session opens only for a paid call
974
+ // of this claim, and a replay the gate refuses makes none, so it is opened here for the cut alone, never read as free.
975
+ const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
976
+ if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
977
+ await paidOf();
713
978
  const gateOf = preIntentGate(spec, hooks);
714
979
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
715
- const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context) : undefined;
980
+ const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now) : undefined;
716
981
  cliRecord = record;
717
- const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => ({
982
+ // Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
983
+ // read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
984
+ const hosted = (tool) => ({
718
985
  ...tool,
719
986
  // The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
720
987
  // flush unless the tool is replay-safe, the call, then the beforeResult point. A throw there is the kernel's own
721
988
  // fault: the journal is sealed before the harness's result commit, so the Session fails with the call before
722
989
  // its result, and the loop restarts it. A CLI's call reaches here only once the gate allowed it (its tool
723
- // bridge asks first), so its record's start is written here, before the flush and the call, and its end after.
990
+ // bridge asks first; one refused is on the record from the gate, bridgeGate), so its record's start is written
991
+ // here, before the flush and the call, and its end after.
724
992
  call: async (args, toolContext) => {
725
993
  // A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
726
994
  // from that end, never run again.
@@ -735,7 +1003,9 @@ function adapterLoop(specOf, options, deps) {
735
1003
  flush: () => deps.flush(),
736
1004
  // Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
737
1005
  // refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
738
- route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => tool.call(args, toolContext)),
1006
+ // The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
1007
+ // loop wrapped it, and whether a person approved this call.
1008
+ 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 }))),
739
1009
  beforeResult: async (answer) => {
740
1010
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
741
1011
  try {
@@ -748,8 +1018,9 @@ function adapterLoop(specOf, options, deps) {
748
1018
  }
749
1019
  },
750
1020
  });
1021
+ // A call a stop cut answers whatever its tool said of the abort: it ends interrupted, never as its outcome.
751
1022
  if (record)
752
- await record.end(toolContext.callId, answer.isError ? "failed" : "done", answer.text);
1023
+ await record.end(toolContext.callId, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
753
1024
  return answer;
754
1025
  }
755
1026
  catch (error) {
@@ -760,7 +1031,14 @@ function adapterLoop(specOf, options, deps) {
760
1031
  throw error;
761
1032
  }
762
1033
  },
763
- }));
1034
+ });
1035
+ const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1036
+ // An MCP tool of the run by its catalog name, as wrapped above: what a learned workflow's MCP node calls.
1037
+ mcpHosted = (catalog) => {
1038
+ const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
1039
+ const host = wire && tools.find((one) => one.name === wire.name);
1040
+ return host && ((args, ctx) => host.call(args, ctx));
1041
+ };
764
1042
  // The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
765
1043
  // session's proxy sees its upstream end, which can be after pi went idle).
766
1044
  const port = booking.models;
@@ -803,15 +1081,41 @@ function adapterLoop(specOf, options, deps) {
803
1081
  given.add(turn);
804
1082
  return booking.usd;
805
1083
  };
806
- const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: gateOf, bookedCost };
1084
+ // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
1085
+ // start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
1086
+ // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it).
1087
+ const bridgeGate = record
1088
+ ? async (call, hookContext) => {
1089
+ const answer = await gateOf(call, hookContext);
1090
+ if (answer !== "allow" && "deny" in answer) {
1091
+ const tool = tools.find((one) => one.name === call.tool);
1092
+ await record.refused(call.callId, call.tool, call.args ?? {}, tool?.replay === "safe", answer.deny);
1093
+ }
1094
+ return answer;
1095
+ }
1096
+ : gateOf;
1097
+ const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, hostTool: hosted, bookedCost };
807
1098
  // The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
808
1099
  // MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
809
1100
  const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
810
1101
  const ownClient = mcp !== undefined && spec.adapter.capabilities().mcpClient !== undefined;
811
1102
  const sessionMcp = ownClient
812
1103
  ? mcp.session(new Map(tools.filter((tool) => mcpNames.has(tool.name)).map((tool) => [tool.name, tool])), async (call) => {
1104
+ // A call through the door is on the run's record before its gate answers (once per call id; the gate's park
1105
+ // seals the journal): its row, and an approval read beside it, show while it waits. A refused one ends there;
1106
+ // a parked one runs, or is refused, on the claim that resumes it (parkedFollowUp); an allowed one runs now.
1107
+ const wire = mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool);
1108
+ if (record)
1109
+ await record.park(call.callId, wire?.name ?? call.tool, call.args ?? {}, wire?.replay === "safe");
813
1110
  const answer = await gateOf(call, context);
814
- return answer === "allow" ? undefined : "deny" in answer ? { refused: answer.deny } : { parked: true };
1111
+ if (answer === "allow")
1112
+ return undefined;
1113
+ if ("deny" in answer) {
1114
+ if (record)
1115
+ await record.end(call.callId, "refused", answer.deny);
1116
+ return { refused: answer.deny };
1117
+ }
1118
+ return { parked: true };
815
1119
  })
816
1120
  : undefined;
817
1121
  session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
@@ -826,8 +1130,13 @@ function adapterLoop(specOf, options, deps) {
826
1130
  for (const entry of entries)
827
1131
  await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
828
1132
  }, context), now);
829
- await computerNow.up();
1133
+ // The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
1134
+ await computerNow.up(await entriesOf(gate.journal, root.id, context));
830
1135
  }
1136
+ // The cap a raise left the run at, from its root (the newest raise entry), before any request of this claim: a
1137
+ // claim that takes over a raised run (a resume, another runner's) holds it to the raise, never the launch's cap.
1138
+ if (spec.cap)
1139
+ raisedCapUsd = (await raiseStateOf()).lastRaise?.to ?? raisedCapUsd;
831
1140
  // A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
832
1141
  // run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
833
1142
  // before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
@@ -855,6 +1164,13 @@ function adapterLoop(specOf, options, deps) {
855
1164
  // again on the same budget; its next refusal (a raise short of the need) parks it anew through the cap's rule.
856
1165
  await deps.delivered;
857
1166
  raising.resuming = false;
1167
+ // A person's stop or cancel that woke the parked run is its end, before any park again: given back parked on
1168
+ // the same budget, its stop untaken, the run would be claimed again at every poll and never end (#2204). It
1169
+ // ends as a stop does mid-turn: in the stop's words, its row taken, with what the end-of-run step keeps of a
1170
+ // cut run.
1171
+ if (stopReason?.kind === "command") {
1172
+ return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1173
+ }
858
1174
  const paused = raising.budget;
859
1175
  const resumes = raising.resumes;
860
1176
  await takeRaises();
@@ -890,14 +1206,20 @@ function adapterLoop(specOf, options, deps) {
890
1206
  return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
891
1207
  },
892
1208
  run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
1209
+ // A parked call refused ends on the run's record (its start was written at its park), in the refusal's words.
1210
+ refused: async (call, text) => cliRecord?.end(call.callId, "refused", text),
893
1211
  });
894
1212
  if (follow === "park") {
1213
+ // A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
1214
+ // end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
1215
+ if (stopReason?.kind === "command")
1216
+ return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
895
1217
  gate.seal(new Parked());
896
1218
  return { state: "parked" };
897
1219
  }
898
1220
  if (follow) {
899
1221
  const theRoot = root;
900
- await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" } } }), context);
1222
+ await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" }, at: now() } }), context);
901
1223
  await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
902
1224
  followedUp = true;
903
1225
  }
@@ -987,13 +1309,19 @@ function adapterLoop(specOf, options, deps) {
987
1309
  await harness.waitForIdle(context);
988
1310
  const settledEntries = await entriesOf(gate.journal, root.id, context);
989
1311
  const cutOff = restartLimited(settledEntries);
1312
+ // A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
1313
+ // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
1314
+ await bookingsSettled();
1315
+ const over = cutOff ? undefined : await overCap();
990
1316
  if (cutOff)
991
1317
  data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
1318
+ else if (over)
1319
+ data = { state: "failed", summary: over };
992
1320
  else if (outcome.status !== "completed" && refused) {
993
1321
  // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
994
1322
  // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
995
1323
  // check's own words, never as a run with no answer.
996
- const park = spec.cap?.park(refusalOf(refused));
1324
+ const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
997
1325
  if (park?.outcome === "parked" && pausedAtRefusal) {
998
1326
  // Its pause and the run parked landed before pi heard of the refusal.
999
1327
  await releaseHost(harness);
@@ -1033,12 +1361,35 @@ function adapterLoop(specOf, options, deps) {
1033
1361
  // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
1034
1362
  // the direct loop's rule: the words are loop-contract's cutAtLimit).
1035
1363
  const cut = cutLast(settledEntries);
1364
+ // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
1365
+ const next = cut ? undefined : afterTurn.shift();
1366
+ if (next) {
1367
+ turn = sendAfterTurn(gate, next);
1368
+ continue;
1369
+ }
1036
1370
  data = cut ? { state: "failed", summary: cut } : { state: "ended" };
1037
1371
  }
1038
1372
  break;
1039
1373
  }
1374
+ // No turn is sent after this one: a message from here on waits for the run's end (steer).
1375
+ turnsOver = true;
1040
1376
  if (parkOn !== undefined)
1041
1377
  return await parkOnAsk(harness, root, gate, parkOn);
1378
+ // A person who holds the run's desktop or phone keeps it (#2134): the run's end, and its computer's release after
1379
+ // it, wait for the hand-back or the hold's idle bound, the Timeline saying why. A stop ends the run stopped at
1380
+ // once, and a lost claim or a closing runner leaves it for the next claim, as during the end-of-run step.
1381
+ if (computerNow) {
1382
+ const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
1383
+ // Until the run returns: a steer after the hand-back would start a turn its end then cuts, too.
1384
+ handingBack = true;
1385
+ await computerNow.heldAtEnd(Promise.race([stopping, aborted, harness.closed]));
1386
+ // Set by stop() during the wait: read past the narrowing TypeScript did before it.
1387
+ const cut = stopReason;
1388
+ if (cut?.kind === "command")
1389
+ return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cut.cancel) }, [cut.commandId], await cutRows(claim, spec, "stopped"));
1390
+ if (cut || deps.signal.aborted)
1391
+ return await interrupted(cut?.kind ?? "its claim's signal aborted");
1392
+ }
1042
1393
  // The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
1043
1394
  // writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
1044
1395
  const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
@@ -1046,6 +1397,15 @@ function adapterLoop(specOf, options, deps) {
1046
1397
  return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason?.kind === "command" ? stopReason.cancel : undefined) }, [step.commandId], await cutRows(claim, spec, "stopped-looking"));
1047
1398
  if (step.kind === "interrupted")
1048
1399
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
1400
+ // The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
1401
+ // read again once its booking settled), as a job's answer that passed it does, never completed. An end already
1402
+ // failed keeps its own words.
1403
+ if (data.state !== "failed") {
1404
+ await bookingsSettled();
1405
+ const overAtEnd = await overCap();
1406
+ if (overAtEnd)
1407
+ data = { state: "failed", summary: overAtEnd };
1408
+ }
1049
1409
  return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
1050
1410
  }
1051
1411
  }
@@ -1070,6 +1430,7 @@ function adapterLoop(specOf, options, deps) {
1070
1430
  held?.detach();
1071
1431
  computerNow?.detach();
1072
1432
  computerNow = undefined;
1433
+ handingBack = false;
1073
1434
  deps.live?.(() => undefined);
1074
1435
  // A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
1075
1436
  // A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
@@ -1098,9 +1459,22 @@ function adapterLoop(specOf, options, deps) {
1098
1459
  return { deny: setToDenyText(asked) };
1099
1460
  if (decision === "allow")
1100
1461
  return "allow";
1101
- const answer = await answerOf({ ...call, tool }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
1462
+ // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
1463
+ // (a learned workflow's MCP calls set to ask: askedFor).
1464
+ const shown = await spec.gate?.askedFor?.(tool, call.args);
1465
+ // Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
1466
+ // The gate's own fields win over any of the same name in the call's input, which the model wrote.
1467
+ const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
1468
+ const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
1102
1469
  if (answer === "park")
1103
1470
  return { park: true };
1471
+ // A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
1472
+ // approved with it (host-calls.ts), as far as the card they approved named it: its ask as journaled, the card they
1473
+ // saw, never one built again now.
1474
+ if (answer.approved) {
1475
+ const seen = askedArgs.get(call.callId);
1476
+ approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
1477
+ }
1104
1478
  return answer.approved ? "allow" : { deny: deniedText(asked, answer.note) };
1105
1479
  };
1106
1480
  }
@@ -1110,10 +1484,13 @@ function adapterLoop(specOf, options, deps) {
1110
1484
  async function answerOf(call, price, asked = call.tool) {
1111
1485
  const conversation = await harness.root(context);
1112
1486
  const entries = await entriesOf(gate.journal, conversation.id, context);
1487
+ const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
1488
+ // The card the person answers is the ask as first journaled: kept for the caller, which scopes an approval to it.
1489
+ if (first)
1490
+ askedArgs.set(call.callId, first.args);
1113
1491
  const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
1114
1492
  if (known)
1115
1493
  return known;
1116
- const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
1117
1494
  // The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
1118
1495
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
1119
1496
  const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
@@ -1163,17 +1540,29 @@ function adapterLoop(specOf, options, deps) {
1163
1540
  await new Promise((resolve) => (wakeInbox = resolve));
1164
1541
  }
1165
1542
  }
1166
- /** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. */
1543
+ /** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. `later` when this
1544
+ * claim can no longer say: its Harness never opened, or its pass is parking, ending or stopping (the journal sealed,
1545
+ * closeSession closing the Harness behind the seal). The row is left untaken and the run's next claim checks it, as a
1546
+ * steer that comes as the run parks is (#2292: the read went through the closed Harness and threw). */
1167
1547
  async function waitsFor(approval) {
1168
1548
  if (approval === undefined)
1169
1549
  return false;
1170
1550
  await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
1171
- if (!gate || !harness)
1172
- return false;
1173
- const conversation = await harness.root(context);
1174
- const entries = await entriesOf(gate.journal, conversation.id, context);
1175
- const asked = findData(entries, KINDS.ask, (data) => data.callId === approval) !== undefined;
1176
- return asked && findData(entries, KINDS.answer, (data) => data.callId === approval) === undefined;
1551
+ const [theGate, theHarness] = [gate, harness];
1552
+ if (!theGate || !theHarness || theGate.sealed)
1553
+ return "later";
1554
+ try {
1555
+ const conversation = await theHarness.root(context);
1556
+ const entries = await entriesOf(theGate.journal, conversation.id, context);
1557
+ const asked = findData(entries, KINDS.ask, (data) => data.callId === approval) !== undefined;
1558
+ return asked && findData(entries, KINDS.answer, (data) => data.callId === approval) === undefined;
1559
+ }
1560
+ catch (error) {
1561
+ // Sealed while it read: closeSession seals, then closes the Harness the read went through.
1562
+ if (theGate.sealed)
1563
+ return "later";
1564
+ throw error;
1565
+ }
1177
1566
  }
1178
1567
  async function reportHeld(session, conversationId) {
1179
1568
  held?.detach();
@@ -1436,7 +1825,7 @@ function adapterLoop(specOf, options, deps) {
1436
1825
  // How this claim's turn ended; a turn answered before reads as its submission says.
1437
1826
  let turnStatus = "completed";
1438
1827
  if (!known) {
1439
- theRecord?.answering();
1828
+ await theRecord?.answering(requestId, prompt);
1440
1829
  await theSession.send(prompt, { id: requestId });
1441
1830
  const turn = theSession.turnEnd();
1442
1831
  const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
@@ -1555,7 +1944,12 @@ function adapterLoop(specOf, options, deps) {
1555
1944
  // A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
1556
1945
  // card reads answered (withdrawn), never waiting for good on a final run.
1557
1946
  const byPerson = data.state === "stopped" || stopReason?.kind === "command";
1558
- const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow()) : [];
1947
+ // A cancel's calls read cancelled with their run; a stop's, withdrawn.
1948
+ const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
1949
+ // A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
1950
+ // with the run's, in the same commit, saying it was not run (never interrupted: it never left).
1951
+ const recordEnds = cliRecord?.unsentParked() ?? [];
1952
+ const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
1559
1953
  const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
1560
1954
  // A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
1561
1955
  ended.catch(() => undefined);
@@ -1563,6 +1957,8 @@ function adapterLoop(specOf, options, deps) {
1563
1957
  await on.commit(async (tx) => {
1564
1958
  for (const answer of withdrawn)
1565
1959
  await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
1960
+ for (const callId of recordEnds)
1961
+ await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
1566
1962
  if (failedWith !== undefined)
1567
1963
  await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
1568
1964
  return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
@@ -1574,6 +1970,8 @@ function adapterLoop(specOf, options, deps) {
1574
1970
  throw error;
1575
1971
  }
1576
1972
  await ended;
1973
+ for (const callId of recordEnds)
1974
+ cliRecord?.noteEnd(callId, "refused", notRun);
1577
1975
  return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
1578
1976
  }
1579
1977
  return {
@@ -1592,7 +1990,10 @@ function adapterLoop(specOf, options, deps) {
1592
1990
  // An answer names its approval: the asked call's id. One that names no call waiting for its answer (an old
1593
1991
  // approval, another run's) is refused, never applied to the call that waits now.
1594
1992
  const approval = approvalOf(command);
1595
- if (!(await waitsFor(approval))) {
1993
+ const waits = await waitsFor(approval);
1994
+ if (waits === "later")
1995
+ return { later: "the run is parking or ending: the answer waits for its next claim" };
1996
+ if (!waits) {
1596
1997
  refusals += 1;
1597
1998
  wakeInbox();
1598
1999
  return { refused: `no call of this run waits for approval ${JSON.stringify(approval ?? "")}` };
@@ -1617,6 +2018,7 @@ function adapterLoop(specOf, options, deps) {
1617
2018
  if (reason.kind !== "command")
1618
2019
  gate?.seal(new Interrupted(reason.kind));
1619
2020
  stopped();
2021
+ stopAbort.abort(new Interrupted(reason.kind));
1620
2022
  wakeInbox();
1621
2023
  await finished?.catch(() => undefined);
1622
2024
  },