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

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 (423) hide show
  1. package/CHANGELOG.md +455 -0
  2. package/README.md +376 -125
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  37. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +83 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +15 -0
  46. package/dist/email/answer.js +217 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +373 -0
  53. package/dist/email/names.d.ts +50 -0
  54. package/dist/email/names.js +74 -0
  55. package/dist/email/routes.d.ts +10 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +27 -0
  58. package/dist/email/tools.js +562 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +12 -4
  93. package/dist/learn/compile.js +57 -20
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +130 -64
  97. package/dist/learn/promote.js +113 -202
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +35 -8
  109. package/dist/learning-cost.js +27 -9
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +39 -2
  118. package/dist/local-models.js +49 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +2 -1
  164. package/dist/openapi.js +404 -93
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +10 -2
  170. package/dist/port-models.js +6 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +14 -0
  180. package/dist/refusal-words.js +16 -2
  181. package/dist/run-launch.d.ts +12 -1
  182. package/dist/run-launch.js +13 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +44 -38
  191. package/dist/run-view.js +93 -56
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +48 -13
  195. package/dist/runner/adapter-loop.js +691 -254
  196. package/dist/runner/adapter-run-spec.d.ts +38 -12
  197. package/dist/runner/adapter-run-spec.js +175 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +95 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +59 -13
  217. package/dist/runner/journal-kinds.js +48 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +14 -3
  237. package/dist/runner/model-route.js +155 -19
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +76 -10
  243. package/dist/runner/promotion.js +476 -154
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +568 -137
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/dialect.d.ts +3 -0
  278. package/dist/store/dialect.js +1 -0
  279. package/dist/store/index.d.ts +1 -1
  280. package/dist/store/native-command-owner.d.ts +10 -0
  281. package/dist/store/native-command-owner.js +47 -0
  282. package/dist/store/postgres/connection.d.ts +11 -5
  283. package/dist/store/postgres/connection.js +44 -17
  284. package/dist/store/postgres/dialect.js +5 -0
  285. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  286. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  287. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  288. package/dist/store/postgres/store.d.ts +7 -3
  289. package/dist/store/postgres/store.js +4 -0
  290. package/dist/store/schema.d.ts +7 -0
  291. package/dist/store/schema.js +20 -1
  292. package/dist/store/sqlite/connection.js +72 -8
  293. package/dist/store/sqlite/run-launch.d.ts +11 -0
  294. package/dist/store/sqlite/run-launch.js +8 -0
  295. package/dist/store/sqlite/run-patch.d.ts +8 -1
  296. package/dist/store/sqlite/run-patch.js +14 -3
  297. package/dist/store/sqlite/store.js +170 -34
  298. package/dist/store/sqlite/worker.d.ts +2 -0
  299. package/dist/store/sqlite/worker.js +13 -10
  300. package/dist/store/store.d.ts +67 -7
  301. package/dist/store-reads/analytics.d.ts +7 -7
  302. package/dist/store-reads/analytics.js +23 -5
  303. package/dist/store-reads/cap.js +8 -6
  304. package/dist/store-reads/journal.d.ts +5 -0
  305. package/dist/store-reads/journal.js +85 -41
  306. package/dist/store-reads/learning.d.ts +115 -18
  307. package/dist/store-reads/learning.js +170 -68
  308. package/dist/store-reads/runs.d.ts +5 -0
  309. package/dist/store-reads/runs.js +3 -2
  310. package/dist/store-view.js +75 -21
  311. package/dist/template-eval.d.ts +73 -11
  312. package/dist/template-eval.js +535 -75
  313. package/dist/templates.d.ts +84 -21
  314. package/dist/templates.js +254 -47
  315. package/dist/text-urls.d.ts +38 -0
  316. package/dist/text-urls.js +170 -0
  317. package/dist/timeline/index.d.ts +3 -2
  318. package/dist/timeline/index.js +3 -2
  319. package/dist/timeline/labels.d.ts +5 -2
  320. package/dist/timeline/labels.js +29 -6
  321. package/dist/timeline/origin.d.ts +1 -1
  322. package/dist/timeline/origin.js +2 -2
  323. package/dist/timeline/render-text.js +1 -1
  324. package/dist/timeline/timeline.d.ts +66 -4
  325. package/dist/timeline/timeline.js +160 -30
  326. package/dist/timeline/util.d.ts +5 -0
  327. package/dist/timeline/util.js +44 -8
  328. package/dist/timeline/web-calls.d.ts +17 -0
  329. package/dist/timeline/web-calls.js +106 -0
  330. package/dist/tool-gate.d.ts +46 -44
  331. package/dist/tool-gate.js +101 -92
  332. package/dist/tool-list.d.ts +4 -1
  333. package/dist/tool-list.js +8 -1
  334. package/dist/tool-names.d.ts +18 -13
  335. package/dist/tool-names.js +19 -17
  336. package/dist/tool-plane.d.ts +17 -13
  337. package/dist/tool-plane.js +12 -5
  338. package/dist/tools.d.ts +57 -16
  339. package/dist/tools.js +33 -28
  340. package/dist/trigger-adapter.d.ts +56 -5
  341. package/dist/trigger-adapter.js +6 -0
  342. package/dist/trigger-adapters.js +3 -1
  343. package/dist/trigger-composio.d.ts +10 -0
  344. package/dist/trigger-composio.js +122 -0
  345. package/dist/trigger-email.d.ts +4 -0
  346. package/dist/trigger-email.js +181 -0
  347. package/dist/trigger-signatures.d.ts +6 -10
  348. package/dist/trigger-signatures.js +16 -16
  349. package/dist/trigger-targets.d.ts +1 -1
  350. package/dist/trigger-targets.js +4 -3
  351. package/dist/trigger-webhook.js +6 -4
  352. package/dist/triggers.d.ts +105 -8
  353. package/dist/triggers.js +286 -62
  354. package/dist/uploads.d.ts +9 -0
  355. package/dist/uploads.js +27 -0
  356. package/dist/validate.js +1 -7
  357. package/dist/web-fake.d.ts +56 -0
  358. package/dist/web-fake.js +102 -0
  359. package/dist/web-fetch-direct.d.ts +3 -0
  360. package/dist/web-fetch-direct.js +4 -1
  361. package/dist/web-fetch.d.ts +5 -1
  362. package/dist/web-fetch.js +8 -31
  363. package/dist/web-search.d.ts +51 -2
  364. package/dist/web-search.js +116 -18
  365. package/dist/webhooks.d.ts +2 -1
  366. package/dist/webhooks.js +5 -1
  367. package/dist/workflow/decision-recovery.js +5 -2
  368. package/dist/workflow/decisions.d.ts +7 -0
  369. package/dist/workflow/node-runner.js +10 -2
  370. package/dist/workspace/archil-claim.d.ts +3 -0
  371. package/dist/workspace/archil-claim.js +9 -2
  372. package/dist/workspace/computer-deps.d.ts +22 -9
  373. package/dist/workspace/computer-deps.js +78 -37
  374. package/dist/workspace/computer-for-claim.d.ts +54 -4
  375. package/dist/workspace/computer-for-claim.js +179 -39
  376. package/dist/workspace/computer-janitor.d.ts +10 -3
  377. package/dist/workspace/computer-janitor.js +96 -29
  378. package/dist/workspace/computer-kept.d.ts +82 -0
  379. package/dist/workspace/computer-kept.js +147 -0
  380. package/dist/workspace/computer-mcp.js +4 -3
  381. package/dist/workspace/computer-ports.d.ts +23 -3
  382. package/dist/workspace/computer-ports.js +115 -5
  383. package/dist/workspace/index.d.ts +1 -2
  384. package/dist/workspace/index.js +1 -2
  385. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  386. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  387. package/dist/workspace/resolve-computer.d.ts +15 -3
  388. package/dist/workspace/resolve-computer.js +10 -7
  389. package/dist/workspace/revision-skills.d.ts +6 -2
  390. package/dist/workspace/revision-skills.js +12 -5
  391. package/dist/workspace/run-end-computers.d.ts +30 -0
  392. package/dist/workspace/run-end-computers.js +137 -0
  393. package/dist/workspace/run-tools.d.ts +28 -29
  394. package/dist/workspace/run-tools.js +29 -30
  395. package/dist/wrap-up.d.ts +19 -5
  396. package/dist/wrap-up.js +31 -4
  397. package/package.json +13 -9
  398. package/skills/agentrun-serve/SKILL.md +248 -10
  399. package/templates/README.md +117 -23
  400. package/templates/TOOLS.md +168 -0
  401. package/templates/code-review/agent.md +18 -4
  402. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  404. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  405. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  406. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  407. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  408. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  409. package/templates/code-review/skills/review/DEEP.md +2 -2
  410. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  411. package/templates/code-review/skills/review/SKILL.md +7 -3
  412. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  413. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  414. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  415. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  416. package/dist/console/assets/index-CjqQirbo.css +0 -1
  417. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  418. package/dist/host-calls.d.ts +0 -20
  419. package/dist/host-calls.js +0 -12
  420. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  421. package/dist/runner/adapters/pi-computer.js +0 -51
  422. package/dist/workspace/computer-script.d.ts +0 -53
  423. package/dist/workspace/computer-script.js +0 -172
@@ -1,16 +1,16 @@
1
1
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
2
  import { createModels } from "@earendil-works/pi-ai/models";
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, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
3
+ import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID, ToolTask } from "@earendil-works/pi-durable";
4
+ import { modelPortFor, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
5
+ import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, toolCalls, withdrawnAnswers } from "./journal-kinds.js";
6
6
  import { turnEndedOnAsk } from "../store-reads/journal.js";
7
- import { CAP_WRAPUP, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
7
+ import { CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
8
8
  import { raiseFollowUpId } from "../run-view.js";
9
9
  import { durableWait } from "../workflow/pi-versions.js";
10
10
  /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
11
- * takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks whether the run's root ends
12
- * on its end (a fresh reopen). */
13
- const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
11
+ * takeover's note, its computer's hold, the learning seed it laid, the computer it made): read past when a claim asks
12
+ * whether the run's root ends on its end (a fresh reopen). */
13
+ const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, KINDS.computerMade, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
14
14
  /** A learned workflow's handback is the server's message to the agent, never the person's. */
15
15
  const HANDED_BACK_ORIGIN = { kind: "server", reason: "handed_back" };
16
16
  /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
@@ -27,10 +27,10 @@ const outputRetried = (entries) => {
27
27
  return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
28
  };
29
29
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
30
- import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
30
+ import { ASKED_BECAUSE, deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
31
31
  import { ADAPTER_API } from "../turn-end.js";
32
- import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
33
- import { approvalOf, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
32
+ import { answerText, REFLECT_NOTE_ONLY, REFLECT_PREFIX, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
33
+ import { agentEntriesOf, approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
34
34
  import { outputMiss, outputRetryWords } from "../answer-json.js";
35
35
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
36
36
  import { isComputerCommand, journalHold } from "./computer-journal.js";
@@ -41,19 +41,18 @@ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
41
41
  import { channelCallOf, runChannelCall } from "./computer-channel.js";
42
42
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
43
43
  import { journalSessions } from "./sessions.js";
44
- import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, recentAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
44
+ import { DECISION_SESSION, FIT_TOLERANCE, freeModel, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, noteFor, overCapOf, paidRefusal, requestFigures, runCap, SERVER_NOTE_LABEL, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
45
45
  import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
46
46
  import { bookedIn } from "../paid-calls.js";
47
- import { withHostCalls } from "../host-calls.js";
48
47
  import { sideEffect } from "./side-effects.js";
49
48
  import { McpClaimRefused } from "./mcp-claim.js";
50
- import { CODEMODE, defersCatalog, isCatalogName, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
49
+ import { CODEMODE, defersCatalog, isCatalogWire, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
51
50
  import { metaTools } from "./meta-tools.js";
52
51
  import { builtinHarness } from "../harness-table.js";
53
52
  import { Fenced } from "../store/index.js";
54
53
  import { answerAsServed } from "../answer-json.js";
55
- import { reserveFor, WRAP_UP_TEXT, wrappingUp } from "../wrap-up.js";
56
- import { LEARNED_CLIP, LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
54
+ import { reserveFor, stepAndAnswerFor, wrappingUp, wrapUpText } from "../wrap-up.js";
55
+ import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprovedTools } from "../learned-workflow.js";
57
56
  import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
58
57
  import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
59
58
  /** 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,
@@ -61,6 +60,15 @@ import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLO
61
60
  export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
62
61
  /** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
63
62
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
63
+ /** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
64
+ * still names them whatever the input's size, then the call's input, which the model wrote, without any field of
65
+ * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's, and so is the reason a
66
+ * call its setting allows asks anyway (ASKED_BECAUSE). */
67
+ function cardOf(tool, shown, args) {
68
+ if (!shown && tool !== LEARNED_WORKFLOW_TOOL && !(args && Object.hasOwn(args, ASKED_BECAUSE)))
69
+ return args;
70
+ return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && key !== ASKED_BECAUSE && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
71
+ }
64
72
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
65
73
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
66
74
  /** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
@@ -145,10 +153,17 @@ export function pendingPauseOf(entries) {
145
153
  }
146
154
  /** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
147
155
  const DELIVER_NOW_MS = 5_000;
148
- /** How long the cap's wrap-up note, once a request took it, waits for that request's admission before a later request
149
- * may take it. A request that leaves before its admission gives it back as it goes (ModelPort.noteReturned): this is
150
- * only the backstop for a path that never does. A proxy's token count and admission take well under it. */
156
+ /** How long a server note (the replaced computer's, a wrap-up), once a request took it, waits for that request's
157
+ * admission before a later request may take it. A request that leaves before its admission gives it back as it goes
158
+ * (ModelPort.noteReturned): this is only the backstop for a path that never does. A proxy's token count and admission
159
+ * take well under it. Once admitted, the request holds the note until it ends, however long it streams. */
151
160
  const WRAP_UP_OFFER_MS = 30_000;
161
+ /** A note the model was told (it begins with SERVER_NOTE_LABEL) as the server's row for it says it: the words after the
162
+ * label, their first letter a capital, since the row is the server's already ("AgentRun: …", timeline.ts CAP_WRAPUP). */
163
+ const rowWords = (told) => {
164
+ const words = told.startsWith(SERVER_NOTE_LABEL) ? told.slice(SERVER_NOTE_LABEL.length) : told;
165
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
166
+ };
152
167
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
153
168
  const cutWhole = (text, max) => {
154
169
  const cut = text.slice(0, max);
@@ -169,21 +184,6 @@ const cliErrorAnswer = (harness, error, at) => ({
169
184
  timestamp: at,
170
185
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
171
186
  });
172
- /** The session's recent requests as its newest KINDS.capRecent record kept them: each that reads as one (a model, and each
173
- * figure a finite number of 0 or more); none without a record. One that does not read is left out: a request is then
174
- * priced from another or uncached, never under its worst. */
175
- export function recentIn(records) {
176
- const kept = records.findLast((record) => record.kind === KINDS.capRecent)?.data;
177
- if (!Array.isArray(kept))
178
- return [];
179
- const figure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
180
- return kept.flatMap((data) => {
181
- const one = (data ?? {});
182
- if (typeof one !== "object" || typeof one.model !== "string" || !figure(one.cachedTokens) || !figure(one.inputTokens) || !figure(one.boundTokens) || !figure(one.endedAt))
183
- return [];
184
- return [{ model: one.model, cachedTokens: one.cachedTokens, inputTokens: one.inputTokens, boundTokens: one.boundTokens, endedAt: one.endedAt, ...(typeof one.counted === "boolean" ? { counted: one.counted } : {}) }];
185
- });
186
- }
187
187
  /** The turns a session's records booked (its runner.turn records), in order. */
188
188
  export function turnsOf(records) {
189
189
  return records.filter((record) => record.kind === RUNNER_RECORDS.turn).map((record) => record.data.turn).filter((turn) => typeof turn === "number");
@@ -221,12 +221,15 @@ export function bookingOfAnswer(records, given) {
221
221
  turns.push(turn.turn);
222
222
  if (side.has(turn.turn))
223
223
  continue;
224
- // An answer with no price of its own is unknown, never the hold it was booked at for the cap (answeredUnpriced).
225
- const figure = answeredUnpriced(turn) ? null : turn.bookedUsd !== undefined ? turn.bookedUsd : turn.usd;
224
+ // By the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it was booked at
225
+ // for the cap; one billed to a person's plan is $0 to the run.
226
+ const figure = turn.usd === undefined && turn.bookedUsd === undefined ? undefined : turnCostOf(turn).usd;
226
227
  usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
227
228
  }
228
229
  return { turns, usd };
229
230
  }
231
+ /** How often a park's wait for the calls beside it (siblingsSettled) reads whether they ended. */
232
+ const SIBLINGS_POLL_MS = 50;
230
233
  /** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
231
234
  const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
232
235
  /** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
@@ -258,6 +261,12 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
258
261
  const sent = new Set();
259
262
  // A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
260
263
  const nesting = new Set();
264
+ // The call of the harness's own each call runs inside (nestedIn), named on the call's start.
265
+ const parents = new Map();
266
+ const parentOf = (callId) => {
267
+ const parent = parents.get(callId);
268
+ return parent === undefined ? {} : { parent };
269
+ };
261
270
  // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
262
271
  const sending = new Set();
263
272
  let personWritten = false;
@@ -419,8 +428,10 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
419
428
  }
420
429
  return;
421
430
  }
422
- await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...(cwd ? { cwd } : {}) });
431
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...parentOf(callId), ...(cwd ? { cwd } : {}) });
423
432
  started.set(callId, false);
433
+ if (nests)
434
+ nesting.add(callId);
424
435
  });
425
436
  },
426
437
  async park(callId, tool, input, replaySafe) {
@@ -428,7 +439,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
428
439
  await inTurn(async () => {
429
440
  if (started.has(callId))
430
441
  return;
431
- await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(cwd ? { cwd } : {}) });
442
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...parentOf(callId), ...(cwd ? { cwd } : {}) });
432
443
  started.set(callId, false);
433
444
  parked.add(callId);
434
445
  });
@@ -439,7 +450,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
439
450
  if (started.get(callId) === true)
440
451
  return;
441
452
  const at = now();
442
- const start = { callId, tool, input, replaySafe, at };
453
+ const start = { callId, tool, input, replaySafe, ...parentOf(callId), at };
443
454
  const end = { callId, status: "refused", output: words, at };
444
455
  await harness.commit(async (tx) => {
445
456
  if (!started.has(callId))
@@ -450,7 +461,9 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
450
461
  ends.set(callId, { status: "refused", output: words });
451
462
  });
452
463
  },
464
+ nestedIn: (callId, parent) => void parents.set(callId, parent),
453
465
  unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
466
+ openNests: () => [...nesting].filter((callId) => started.get(callId) === false),
454
467
  noteEnd(callId, status, output) {
455
468
  started.set(callId, true);
456
469
  ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
@@ -545,6 +558,11 @@ function adapterLoop(specOf, options, deps) {
545
558
  void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
546
559
  let parked = () => { };
547
560
  const parking = new Promise((resolve) => (parked = resolve));
561
+ /** The claim is parking: it waits for the calls already running beside the parked one (siblingsSettled), and no call
562
+ * starts meanwhile, nor is an answer taken (it waits for the next claim, as once the journal is sealed). */
563
+ let parkPending = false;
564
+ /** The calls this claim parked the run on (their ask landed with the run parked): what siblingsSettled waits beside. */
565
+ const parkedCalls = new Set();
548
566
  let finished;
549
567
  let gate;
550
568
  let harness;
@@ -591,9 +609,18 @@ function adapterLoop(specOf, options, deps) {
591
609
  };
592
610
  /** The current pass's spec's release, until it is called (closeSession). */
593
611
  let releaseNow;
594
- /** While the end-of-run turn runs: a steer is left for the end, and its writes and edits under work/.learning/ are
595
- * refused (REFLECT_NOTE_ONLY). */
612
+ /** The current pass ended in a park that keeps its computer (keepAtPark), for this cause, until its release reads it. */
613
+ let parkedNow;
614
+ /** From the end-of-run step's start (or a claim that found its turn open: lookingBackOpen, from its session's open)
615
+ * until the claim ends: a steer is left for the end, writes and edits under work/.learning/ are refused
616
+ * (REFLECT_NOTE_ONLY), and every request is learning's, never the job's: the cap's wrap-up note is never told to it,
617
+ * and a refusal of one never parks the run (learningRefused). Held between the step's asks too: a turn a takeover
618
+ * resumed may send its next request while the step still reads an earlier answer. */
596
619
  let reflecting = false;
620
+ /** A cap refusal of a request of the end-of-run turn, until that turn's ask reads it: the run has answered, so it parks
621
+ * nothing; the ask fails in the refusal's words, and the learning is dropped as the cap's short room drops it
622
+ * (reflect-hook.ts CAP_REFUSAL: no_budget). An answered run never parks on learning spend. */
623
+ let learningRefused;
597
624
  /** 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
598
625
  * in the end-of-run turn, so no turn starts that the end, written after the hand-back, would cut. */
599
626
  let handingBack = false;
@@ -641,6 +668,16 @@ function adapterLoop(specOf, options, deps) {
641
668
  /** 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
642
669
  * during the end-of-run turn does. */
643
670
  let turnsOver = false;
671
+ /** Set, synchronously, once the claim has decided to park on its question (no wait in the claim holds, or the wait
672
+ * lapsed): from here to the park's seal (its host's release can take a while), a person's message is left untaken for
673
+ * the resume. Placed now, it would start a turn the seal then cuts, its row taken and the run parked with nothing to
674
+ * wake it, the message lost. */
675
+ let askParking = false;
676
+ /** The claim parks on its question: no message is placed from here (askParking). */
677
+ const parkingOnAsk = () => {
678
+ askParking = true;
679
+ return undefined;
680
+ };
644
681
  /** While the run's learned workflow runs first (AdapterRunSpec.workflowFirst): a message waits for it, then goes the way
645
682
  * any message goes once the workflow answered (the run is ending) or handed the job back (the agent's turn runs). */
646
683
  let servingFirst;
@@ -668,6 +705,15 @@ function adapterLoop(specOf, options, deps) {
668
705
  };
669
706
  /** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
670
707
  let cliRecord;
708
+ /** The writes of the harness's own calls (SessionIO.ownCalls) not yet settled: the run's end waits for them, so it never
709
+ * closes interrupted an exec whose own end is on its way. */
710
+ const ownWrites = new Set();
711
+ const ownWrite = (write) => {
712
+ ownWrites.add(write);
713
+ const settled = () => void ownWrites.delete(write);
714
+ write.then(settled, settled);
715
+ return write;
716
+ };
671
717
  /** A CLI's turn cut at its question to the person (TurnCut): armed by the call's end, asked for by the next request. */
672
718
  const askCut = turnCut();
673
719
  /** Whether this loop sent the run its output retry (sendOutputRetry): never a second, even when its turn gave no answer. */
@@ -677,6 +723,11 @@ function adapterLoop(specOf, options, deps) {
677
723
  * fenced and lost, and its request read back at its hold. */
678
724
  let unbooked = 0;
679
725
  let bookedAll = [];
726
+ /** Of those, the ones whose booking has begun (the request answered or ended, its runner.turn on its way to the
727
+ * store), and who waits for none: a booking under way is waited for past CLOSE_MS (bookingsSettled), so a busy store
728
+ * never lets the end, or an answer's cost, go ahead of it. */
729
+ let bookingsWriting = 0;
730
+ let writtenAll = [];
680
731
  /** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
681
732
  * to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
682
733
  const raising = { takes: [], resumes: false, resuming: false };
@@ -691,13 +742,9 @@ function adapterLoop(specOf, options, deps) {
691
742
  /** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
692
743
  * fresh (a parked token may have expired meanwhile). */
693
744
  let mcp;
694
- /** The calls of this run a person approved (an ask answered allow, on this claim or read from the journal on a resume),
695
- * each with the arguments its approval card showed (its journaled ask's): an approval covers what that card named. */
696
- const approvedCalls = new Map();
697
- /** Each answered call's ask as journaled (the card the person saw), set by answerOf as it reads or writes the answer. */
698
- const askedArgs = new Map();
699
- /** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
700
- let mcpHosted = () => undefined;
745
+ /** The calls of this run a person was asked about (their ask in the journal, on this claim or read on a resume), set as
746
+ * the ask is read: one of them the gate lets through was let through by a person's answer. */
747
+ const askedCalls = new Set();
701
748
  let mcpStale = false;
702
749
  /** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
703
750
  * input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
@@ -958,7 +1005,7 @@ function adapterLoop(specOf, options, deps) {
958
1005
  };
959
1006
  /** A person's message placed (steer): as the run's next turn, into the turn in flight, or after it. */
960
1007
  const placeSteer = async (command) => {
961
- if (!gate || !session || gate.sealed)
1008
+ if (!gate || !session || gate.sealed || askParking)
962
1009
  return { later: "the run is parking: the steer waits for its resume" };
963
1010
  // The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
964
1011
  // the message would be the session's first prompt and the input would follow it; it waits for the input instead, then
@@ -996,6 +1043,9 @@ function adapterLoop(specOf, options, deps) {
996
1043
  const servedAnswer = reopen && !reopen.sent && session.state === "new" && root !== undefined ? servedAnswerOf(await entriesOf(gate.journal, root.id, context)) : undefined;
997
1044
  if (!gate || !session || gate.sealed)
998
1045
  return { later: "the run is parking: the steer waits for its resume" };
1046
+ // The claim parks on its question (askParking), its seal still to come: the message is the resume's answer.
1047
+ if (askParking)
1048
+ return { later: "the run is parking on its question: the message answers it on the resume" };
999
1049
  // A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
1000
1050
  // between the question's turn end and that wait): never the wait's answer, never placed now. Its firing reads sent (the
1001
1051
  // door took the row), so it is never refused either: left untaken, it runs as a turn of its own after the person's
@@ -1213,43 +1263,30 @@ function adapterLoop(specOf, options, deps) {
1213
1263
  const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
1214
1264
  const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush(), claim }), { beside: besideNow });
1215
1265
  let capBuilt;
1216
- /** The session's recent requests, as the cap's `expected` pricing reads them (the kernel's recentAfter and
1217
- * warmFrom): the harness's own requests that answered under CACHE_WARM_MS ago, each one's input as its usage
1218
- * reported it (read from or written to the cache, and the rest), its input bound and when it ended. Kept on the
1219
- * session (KINDS.capRecent), so a new claim after an approval, a deny or a park starts from them (seeded below,
1220
- * once the session's records are read), and its first request is warm or cold by when they ended, as within a
1221
- * claim. None before one has: a cache miss. */
1222
- let recent = [];
1223
1266
  /** What the run keeps back beside a request of its own session while it streams (RunCapOptions.keepBackUsd), set
1224
1267
  * once the wrap-up's reserve is known (below): a tool call it makes mid-stream finds room for the steps after it. */
1225
1268
  let keepBackOf;
1226
- /** Each of this claim's requests as the cap was asked about it, by its turn, until it ends. */
1227
- const askedFor = new Map();
1269
+ /** The run's requests counted toward the free limit (free.ts freeRequestsIn) as of its last admission, in every
1270
+ * session: read from its records at the claim (below), then taken from each admission the cap judges, the count it
1271
+ * was judged with (runBooking's freeRequestsMade) and itself when it counts. Never a read of the run's records
1272
+ * between a request's admission and its leaving: that wait let a cancel close the session before the request was
1273
+ * booked, its cost left unknown. */
1274
+ let freeMade = 0;
1228
1275
  const theCap = () => {
1229
1276
  if (!specNow?.runCap)
1230
1277
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
1231
1278
  // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
1232
- // Its recent requests are the session's own (requestEnded), unless the spec names them (a test's warm cache).
1233
1279
  const { beside: _beside, ...config } = specNow.runCap;
1234
- return (capBuilt ??= runCap({ sessions, recentOf: (model) => recent.filter((one) => one.model === model), keepBackUsd: (request, asked) => keepBackOf?.(request, asked), ...config, capUsd: capNow }));
1235
- };
1236
- /** A request of this claim ended (`request_end`): one of the harness's own (no host label, no side call) that
1237
- * answered with its input reported is one of the session's recent requests from now, kept on the session
1238
- * (`keep`, the model session's writer) for a later claim. A write that fails leaves the later claim the older
1239
- * ones, or none: priced from them or uncached, never under the worst. */
1240
- const requestEnded = async (turn, usage, how, keep) => {
1241
- const asked = askedFor.get(turn);
1242
- askedFor.delete(turn);
1243
- if (!asked?.own || asked.bound === undefined || usage.cut || (how !== undefined && how.end !== "answered"))
1244
- return;
1245
- const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1246
- if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
1247
- return;
1248
- // A smaller request than the last (a CLI's own while a tool runs, a compaction's, a child's that the proxy cannot
1249
- // tell from the root's) is kept beside the others, never in their place: each request is priced from the one
1250
- // whose bound fits it best (warmFrom), so none resets the conversation's history.
1251
- recent = recentAfter(recent, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
1252
- await keep.append([{ kind: KINDS.capRecent, data: recent }]).catch(() => undefined);
1280
+ // runCap tells `judged` only the verdict a request goes by: a refusal that waits is asked again, told then, so a
1281
+ // request admitted after waiting sets freeMade from the count it was admitted at.
1282
+ const judged = (request, answer) => {
1283
+ config.judged?.(request, answer);
1284
+ if (request.freeRequestsMade !== undefined)
1285
+ freeMade = request.freeRequestsMade + (answer && !("refuse" in answer) && answer.freeRequest === true ? 1 : 0);
1286
+ };
1287
+ // A step waiting for room leaves once the run has a pause (pendingPause, below): nothing more is sent until a
1288
+ // raise, and it is refused in the pause's words (beforeRequest). It leaves at the run's stop too, unsent.
1289
+ return (capBuilt ??= runCap({ sessions, keepBackUsd: (request, asked) => keepBackOf?.(request, asked), parked: () => pendingPause !== undefined, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), ...config, judged, capUsd: capNow }));
1253
1290
  };
1254
1291
  const flushed = { flush: () => deps.flush() };
1255
1292
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -1377,6 +1414,10 @@ function adapterLoop(specOf, options, deps) {
1377
1414
  // outside any) and its decisions (ledger.decisions). Its last refusal is kept: a turn it ended ends the run in its
1378
1415
  // words.
1379
1416
  const paid = ledger.paid;
1417
+ // A host tool call's paid requests name the session the call runs in (RunTools.admit `under`): a request of it still
1418
+ // in flight may be the one that asked for the call (Claude Code books its cost after its calls; Codex starts a call
1419
+ // with its response open), so the call is judged beside it and never waits on it. pi's request has answered by then.
1420
+ const paidUnder = { admit: (request) => paid.admit({ ...request, under: spec.session.key }), settle: (id, usd, options) => paid.settle(id, usd, options) };
1380
1421
  let refused;
1381
1422
  /** The pause a refusal for room journaled before pi heard of it (pauseAtCap), the run parked with it. */
1382
1423
  let pausedAtRefusal = false;
@@ -1436,9 +1477,6 @@ function adapterLoop(specOf, options, deps) {
1436
1477
  return { ...pending, refuse: text, figures };
1437
1478
  };
1438
1479
  const beforeRequest = async (request) => {
1439
- // Kept until it ends, so its answer can be one of the session's recent requests (requestEnded): on its model as the cap
1440
- // prices it (RunCap.asked), which a CLI's request names as its provider does, so the next request finds it.
1441
- askedFor.set(request.turn, { model: specNow?.runCap ? theCap().asked(request).model.id : request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
1442
1480
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
1443
1481
  // whatever else would pause it (a paid call's refusal, pendingPause). One a paid call stopped for good
1444
1482
  // (paid-calls.ts stopRun) ends in that call's words, which say why, past its cap too.
@@ -1449,8 +1487,14 @@ function adapterLoop(specOf, options, deps) {
1449
1487
  if (pendingPause === undefined)
1450
1488
  await keepPending(null);
1451
1489
  }
1452
- const answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
1453
- if (answer && "refuse" in answer) {
1490
+ let answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
1491
+ // A request that waited for room while the run parked (the cap let it leave the line): refused in the pause's
1492
+ // words, as any request after the pause is.
1493
+ if (!over && answer && "refuse" in answer && pendingPause !== undefined)
1494
+ answer = pendingPause;
1495
+ if (answer && "refuse" in answer && reflecting)
1496
+ learningRefused ??= answer;
1497
+ else if (answer && "refuse" in answer) {
1454
1498
  refused = answer;
1455
1499
  await pauseAt(answer);
1456
1500
  }
@@ -1511,13 +1555,19 @@ function adapterLoop(specOf, options, deps) {
1511
1555
  // run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
1512
1556
  // (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
1513
1557
  // cap is told again when it too comes near; written as the server's row only once a request carrying the note is
1514
- // admitted with it.
1558
+ // answered.
1515
1559
  const wrapUpHarness = harness;
1516
1560
  const wrapUpRoot = root ?? (await harness.root(context));
1517
1561
  const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
1518
1562
  .filter((entry) => entry.kind === CAP_WRAPUP)
1519
1563
  .map((entry) => entry.data?.capUsd)
1520
1564
  .filter((capUsd) => typeof capUsd === "number");
1565
+ // The free limits it was told under (a CAP_WRAPUP row naming `freeLimit`), read at each claim, so a restart never tells
1566
+ // one twice.
1567
+ const toldFreeLimits = new Set((await entriesOf(gate.journal, wrapUpRoot.id, context))
1568
+ .filter((entry) => entry.kind === CAP_WRAPUP)
1569
+ .map((entry) => entry.data?.freeLimit)
1570
+ .filter((limit) => typeof limit === "number"));
1521
1571
  const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
1522
1572
  // What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
1523
1573
  // earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
@@ -1540,11 +1590,8 @@ function adapterLoop(specOf, options, deps) {
1540
1590
  };
1541
1591
  // The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
1542
1592
  // them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
1543
- // (booked at its hold and bound, the worst case), one never sent, given back, owed or stopped.
1593
+ // (booked at its hold, the worst case), one never sent, given back, owed or stopped.
1544
1594
  const claimRecords = await writer.read();
1545
- // The recent requests an earlier claim or pass kept (KINDS.capRecent): this claim's first request is priced from
1546
- // them, warm or cold by when they ended, never as if the session had no history.
1547
- recent = recentIn(claimRecords);
1548
1595
  const claimHosts = sessionSpendOf(claimRecords).hosts;
1549
1596
  /** The turns of requests that are no main-model request of the harness's own: read from the records, then each
1550
1597
  * admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
@@ -1554,6 +1601,11 @@ function adapterLoop(specOf, options, deps) {
1554
1601
  if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
1555
1602
  notOwn.add(data.turn);
1556
1603
  }
1604
+ // The free requests the run made before this claim, in every session (freeMade: each admission's from here on).
1605
+ let madeBefore = 0;
1606
+ for (const key of await sessions.keys())
1607
+ madeBefore += freeRequestsIn(await sessions.read(key));
1608
+ freeMade = madeBefore;
1557
1609
  const capNote = {
1558
1610
  costs: claimRecords.flatMap((record) => {
1559
1611
  if (record.kind !== RUNNER_RECORDS.turn)
@@ -1564,16 +1616,16 @@ function adapterLoop(specOf, options, deps) {
1564
1616
  }),
1565
1617
  restUsd: await restOf(),
1566
1618
  };
1567
- /** A main-model request as the run's cap prices it at admission (RunCap.asked: its model and the session's previous
1568
- * request, so its input reads the cache that request left warm), for the wrap-up's note and what the run keeps back
1569
- * to answer. A request the note takes is measured as its client sent it (NoteRequest), by its bytes. */
1619
+ /** A main-model request as the run's cap prices it at admission (RunCap.asked: its model, its whole input uncached),
1620
+ * for the wrap-up's note and what the run keeps back to answer. A request the note takes is measured as its client
1621
+ * sent it (NoteRequest), by the input count its admission reads (a provider's or a local count, else its bytes). */
1570
1622
  const pricedOf = (model, asked) => theCap().asked({ ...asked, model });
1571
1623
  /** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
1572
1624
  const figuresOf = (model, asked) => {
1573
1625
  const config = specNow?.runCap;
1574
1626
  if (!config?.modelOf(model))
1575
1627
  return undefined;
1576
- return requestFigures(pricedOf(model, asked), config.mode ?? "expected", (config.now ?? Date.now)());
1628
+ return requestFigures(pricedOf(model, asked));
1577
1629
  };
1578
1630
  /** What the run keeps back to answer (wrap-up.ts reserveFor), its typical step the run's own priced answers'. */
1579
1631
  const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
@@ -1587,10 +1639,71 @@ function adapterLoop(specOf, options, deps) {
1587
1639
  const config = specNow?.runCap;
1588
1640
  if (!config || spec.record !== "loop" || request.key !== spec.session.key || request.host !== undefined || request.side || request.unanswered || request.paid)
1589
1641
  return undefined;
1590
- return reserveOf(requestFigures(asked, config.mode ?? "expected", (config.now ?? Date.now)()));
1642
+ return reserveOf(requestFigures(asked));
1591
1643
  };
1592
1644
  let bookingNow;
1645
+ // The replaced computer's note (spec.computerNote), until a request carrying it is answered. It goes before the
1646
+ // wrap-up: one note per request, so the wrap-up waits a request.
1647
+ let computerWords = spec.computerNote;
1648
+ // The server's note a request carries (the replaced computer's, else the cap's wrap-up; `cap` says the wrap-up's
1649
+ // figures), one request at a time: from its take until that request's admission ends, then, admitted carrying it
1650
+ // (`turn`), until that request ends. Told once that request is answered (afterRequest); given back for the next
1651
+ // request by a refusal, a dropped note, or an end with no answer (an error status, a 429, a lost or cut stream).
1652
+ // A request that took it and left before its admission (a note its policy could not place, an error) gives it back
1653
+ // as it goes (noteReturned). WRAP_UP_OFFER_MS is only the backstop for a take that
1654
+ // never reaches its admission and is never given back: past it, a later request may take the note. An admitted
1655
+ // request always ends (the proxy books each one once), so no backstop is needed from there.
1656
+ let carried;
1657
+ const takeNote = (model, asked) => {
1658
+ if (carried && (carried.turn !== undefined || Date.now() - carried.at < WRAP_UP_OFFER_MS))
1659
+ return undefined;
1660
+ const note = computerWords !== undefined && !reflecting ? { words: computerWords } : wrapUpNote(model, asked);
1661
+ carried = note ? { ...note, at: Date.now() } : undefined;
1662
+ return note?.words;
1663
+ };
1664
+ /** Told: the note is the run's told at once (no request takes it again), and its row, once, the server's, is
1665
+ * what is returned to write: after the request is booked, so a finished request's hold never waits on the row. */
1666
+ const tell = (told) => {
1667
+ let kind = CAP_WRAPUP;
1668
+ let data;
1669
+ let what;
1670
+ if (told.freeLimit !== undefined) {
1671
+ if (toldFreeLimits.has(told.freeLimit))
1672
+ return undefined;
1673
+ toldFreeLimits.add(told.freeLimit);
1674
+ data = { words: rowWords(told.words), freeLimit: told.freeLimit };
1675
+ what = "the free-limit wrap-up's row";
1676
+ }
1677
+ else if (told.cap === undefined) {
1678
+ computerWords = undefined;
1679
+ kind = COMPUTER_NOTE;
1680
+ data = { words: rowWords(told.words) };
1681
+ what = "the replaced computer's note row";
1682
+ }
1683
+ else {
1684
+ const { leftUsd, capUsd } = told.cap;
1685
+ if (toldAt(capUsd))
1686
+ return undefined;
1687
+ toldCaps.push(capUsd);
1688
+ data = { words: rowWords(told.words), leftUsd, capUsd };
1689
+ what = "the wrap-up's row";
1690
+ }
1691
+ return async () => {
1692
+ try {
1693
+ await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind, data: data }), context);
1694
+ await deps.flush();
1695
+ }
1696
+ catch (error) {
1697
+ console.warn(`[runner] ${what} was not written (the note was answered): ${said(error)}`);
1698
+ }
1699
+ };
1700
+ };
1701
+ /** The wrap-up due for a request about to be sent: the cap's, with what is left and the cap it is told under, else
1702
+ * the free limit's. */
1593
1703
  const wrapUpNote = (model, asked) => {
1704
+ // The end-of-run turn comes after the run's answer: "finish now with your answer" is the job's note, never its.
1705
+ if (reflecting)
1706
+ return undefined;
1594
1707
  const config = specNow?.runCap;
1595
1708
  const capModel = config?.modelOf(model);
1596
1709
  const sessionSpent = bookingNow?.spentUsd();
@@ -1600,20 +1713,25 @@ function adapterLoop(specOf, options, deps) {
1600
1713
  // The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
1601
1714
  const inFlight = bookingNow?.heldUsd();
1602
1715
  const capUsd = capNow();
1603
- // One request at a time carries it: while one offered it waits for its admission, an overlapping request is not
1604
- // offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
1605
- // took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
1606
- // refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
1607
- // only the backstop for a path that never gives it back: past it, a later request is offered it.
1608
- if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
1609
- return undefined;
1610
- if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
1716
+ if (!config || !capModel)
1611
1717
  return undefined;
1718
+ // The free-model limit's wrap-up (free.ts): the same note and offer, one per run and limit, on a request of a free
1719
+ // model. The dollar cap's note, when it is due on this request, goes first: one note per request, and it is told
1720
+ // once, so the free one waits for the next request (or never comes, the run having answered).
1721
+ const freeNote = () => {
1722
+ const limit = config.freeRequests;
1723
+ if (limit === undefined || toldFreeLimits.has(limit) || !freeModel(capModel))
1724
+ return undefined;
1725
+ const due = freeWrapUpDue(limit, freeMade);
1726
+ return due ? { words: freeWrapUpWords(due.left), freeLimit: limit } : undefined;
1727
+ };
1728
+ if (capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
1729
+ return freeNote();
1612
1730
  const spentUsd = sessionSpent + decided + paidSpent + rest;
1613
- // The tools' gate counts a request in flight at its hold and its bound (sessionSpendOf: a cache miss adds the bound),
1614
- // so the note counts it the same: it never comes later than the gate's first refusal.
1615
- const heldUsd = inFlight + (bookingNow?.boundUsd() ?? 0) + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
1616
- const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: (config.now ?? Date.now)() });
1731
+ // The tools' gate counts a request in flight at its hold (sessionSpendOf), so the note counts it the same: it never
1732
+ // comes later than the gate's first refusal.
1733
+ const heldUsd = inFlight + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
1734
+ const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false });
1617
1735
  // The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
1618
1736
  // answer (wrap-up.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
1619
1737
  // its own has not made it due before: told on the request whose tool call would be refused now, no later than the
@@ -1623,8 +1741,7 @@ function adapterLoop(specOf, options, deps) {
1623
1741
  const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
1624
1742
  const leftUsd = capUsd - spentUsd - heldUsd;
1625
1743
  const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
1626
- capNote.offered = note ? { ...note, capUsd, at: Date.now() } : undefined;
1627
- return note?.words;
1744
+ return note ? { words: note.words, cap: { leftUsd: note.leftUsd, capUsd } } : freeNote();
1628
1745
  };
1629
1746
  // The rule before a side effect for every paid model request, on the path every adapter's requests take: the
1630
1747
  // booking writes the request's record, then awaits request_start before the request leaves, so the flush here
@@ -1633,11 +1750,11 @@ function adapterLoop(specOf, options, deps) {
1633
1750
  key: spec.session.key,
1634
1751
  label: spec.session.label,
1635
1752
  beforeRequest,
1636
- note: wrapUpNote,
1753
+ note: takeNote,
1637
1754
  // A request that took it and left before its admission gives it back: the next request may take it at once.
1638
1755
  noteReturned: (note) => {
1639
- if (capNote.offered?.words === note)
1640
- capNote.offered = undefined;
1756
+ if (carried?.turn === undefined && carried?.words === note)
1757
+ carried = undefined;
1641
1758
  },
1642
1759
  onEvent: async (event) => {
1643
1760
  // The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
@@ -1646,8 +1763,6 @@ function adapterLoop(specOf, options, deps) {
1646
1763
  // at their hold or cut, comes before `capNote.live` and is never one.)
1647
1764
  if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
1648
1765
  capNote.costs.push(event.usage.usd);
1649
- if (event.type === "request_end")
1650
- await requestEnded(event.turn, event.usage, event.ended, writer);
1651
1766
  if (event.type === "request_start") {
1652
1767
  // A new request means the model's last message is over: what it said so far is on the record before the request,
1653
1768
  // so an answer shows while the turn goes on (a CLI that answers, then makes another request).
@@ -1670,9 +1785,15 @@ function adapterLoop(specOf, options, deps) {
1670
1785
  const on = harness;
1671
1786
  const conversation = root ?? (await on.root(context));
1672
1787
  const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
1788
+ // One on a free model (`free`: booked a known $0) is no cost unknown: its mark says so, and the usage row counts
1789
+ // it at $0, never cut.
1790
+ // One cut with no answer and booked at its hold (bookCut's CUT_AT_HOLD) is that figure, the most it can have
1791
+ // cost: its mark says so, and the usage row counts it there, never as a cost no one knows.
1792
+ const atMost = typeof event.usage.atMostUsd === "number" && Number.isFinite(event.usage.atMostUsd) ? { atMostUsd: event.usage.atMostUsd } : {};
1793
+ const data = unsent ? { unsent: true } : event.usage.free ? { free: true } : atMost;
1673
1794
  // Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
1674
1795
  // mark cut all the same.
1675
- await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: (unsent ? { unsent: true } : {}) }), context).catch(() => undefined);
1796
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: data }), context).catch(() => undefined);
1676
1797
  }
1677
1798
  },
1678
1799
  });
@@ -1693,13 +1814,14 @@ function adapterLoop(specOf, options, deps) {
1693
1814
  // spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
1694
1815
  // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1695
1816
  // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
1817
+ // Its answer is the words a call reads once the run wraps up (wrap-up.ts wrapUpText), undefined while it does not.
1696
1818
  const wrapUp = async () => {
1697
1819
  // A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
1698
1820
  if (!spec.runCap)
1699
- return false;
1821
+ return undefined;
1700
1822
  const capUsd = capNow();
1701
1823
  if (capUsd === undefined)
1702
- return false;
1824
+ return undefined;
1703
1825
  // What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
1704
1826
  let taken = await besideNow();
1705
1827
  for (const key of await sessions.keys()) {
@@ -1709,7 +1831,10 @@ function adapterLoop(specOf, options, deps) {
1709
1831
  }
1710
1832
  // What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
1711
1833
  // is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
1712
- return wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures));
1834
+ if (!wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures)))
1835
+ return undefined;
1836
+ // A cap below what the model needs for one more step and an answer is named in the words, by the same rule.
1837
+ return wrapUpText(capUsd, capNote.lastModel, stepAndAnswerFor(capNote.lastFigures, (step0Usd) => typicalCost(capNote.costs, step0Usd)), capNote.lastEffort);
1713
1838
  };
1714
1839
  const gateOf = preIntentGate(spec, hooks, wrapUp);
1715
1840
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
@@ -1753,18 +1878,21 @@ function adapterLoop(specOf, options, deps) {
1753
1878
  // By the name the gate before the intent asks it by: an MCP tool by its catalog name.
1754
1879
  const name = mcp?.catalogOf(tool.name) ?? tool.name;
1755
1880
  const asked = spec.gate.askedAs?.(name) ?? name;
1756
- const now = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
1757
- if (now === "deny")
1881
+ const given = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
1882
+ if (given === "deny")
1758
1883
  return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
1759
- if (typeof now === "object")
1760
- return { text: now.deny, isError: true };
1884
+ if (typeof given === "object" && "deny" in given)
1885
+ return { text: given.deny, isError: true };
1886
+ // An ask with its card's own fields is an ask, its card as the gate shows it.
1887
+ const shown = typeof given === "object" ? given.ask : undefined;
1888
+ const now = shown ? "ask" : given;
1761
1889
  // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
1762
1890
  // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
1763
1891
  // the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
1764
1892
  // the setting at allow now: the setting answers the ask (allowedBySetting).
1765
1893
  const bySetting = now === "allow" && (await askStands(toolContext.callId));
1766
1894
  if (now === "ask" || bySetting) {
1767
- const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
1895
+ const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})) };
1768
1896
  const price = mcp?.priceOf(name) ?? null;
1769
1897
  const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
1770
1898
  if (answer === "park")
@@ -1788,11 +1916,9 @@ function adapterLoop(specOf, options, deps) {
1788
1916
  flush: () => deps.flush(),
1789
1917
  // Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
1790
1918
  // refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
1791
- // The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
1792
- // loop wrapped it, and whether a person approved this call.
1793
1919
  // The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
1794
1920
  // row's computer_calls, before its result is written.
1795
- route: () => bookedIn({ call: toolContext.callId, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped)))),
1921
+ route: () => bookedIn({ call: toolContext.callId, paid: paidUnder, pause: ledger.pause }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped))),
1796
1922
  beforeResult: async (answer) => {
1797
1923
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
1798
1924
  try {
@@ -1825,11 +1951,20 @@ function adapterLoop(specOf, options, deps) {
1825
1951
  }
1826
1952
  },
1827
1953
  });
1828
- const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1954
+ const facts = builtinHarness(spec.adapter.id)?.facts;
1829
1955
  // tools_search, tools_call and codemode over the session's tools (meta-tools.ts), on every harness (codemode on
1830
1956
  // each but one that runs scripts of its own): what they call is called nested, each call asked about and recorded
1831
1957
  // as its own tool's. A search finds a tool whose setting is not deny; an MCP tool's setting is its catalog name's.
1832
1958
  const settingOf = spec.gate?.permission;
1959
+ // A meta tool whose setting is deny is not offered at all, rather than offered and refused.
1960
+ const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
1961
+ const hostCodemode = facts?.ownCodemode !== true && (await allowed(CODEMODE));
1962
+ // A tool the spec binds for a script's nested calls alone (deferred: a desktop's computer_op, and its step tools
1963
+ // under its surface "code") is listed wherever the host offers no codemode to call it: on a harness that runs
1964
+ // scripts in its own code mode, which reaches only the tools it is handed (Codex's exec), and on a run whose
1965
+ // codemode is set to deny, so the computer is never out of the model's reach.
1966
+ const listedFor = ({ deferred: _, ...tool }) => tool;
1967
+ const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => (!hostCodemode && tool.deferred ? listedFor(tool) : tool)).map(hosted);
1833
1968
  // The harness's own tools beside them (pi's subagent, its browser's): found and called by name as the host's are,
1834
1969
  // run by the harness as its own nested calls. Never called here: a nested call reaches them through the harness.
1835
1970
  const native = (spec.adapter.ownTools ?? []).filter((one) => !own.some((tool) => tool.name === one.name)).map((one) => ({
@@ -1843,9 +1978,6 @@ function adapterLoop(specOf, options, deps) {
1843
1978
  // model finds them with tools_search and runs them with tools_call (still the tool's own call at the gate). Claude
1844
1979
  // Code defers them itself (its ToolSearch, on under the same test), so it is offered neither. Under the threshold
1845
1980
  // every tool is listed and there is no search or call. codemode is offered as it always was.
1846
- const facts = builtinHarness(spec.adapter.id)?.facts;
1847
- // A meta tool whose setting is deny is not offered at all, rather than offered and refused.
1848
- const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
1849
1981
  // Deferred only when the model can both find and run what it hid: with either helper denied every tool stays listed,
1850
1982
  // so denying a helper never takes an otherwise allowed tool out of reach.
1851
1983
  // The one verdict for every harness: one with a tool search of its own (Claude Code's) follows it too, handed it as
@@ -1855,20 +1987,17 @@ function adapterLoop(specOf, options, deps) {
1855
1987
  const metas = metaTools({
1856
1988
  tools: () => [...own, ...native],
1857
1989
  granted: async (name) => !settingOf || (await settingOf(mcp?.catalogOf(name) ?? name).catch(() => "deny")) !== "deny",
1858
- codemode: facts?.ownCodemode !== true && (await allowed(CODEMODE)),
1990
+ codemode: hostCodemode,
1859
1991
  discovery: { search: offered, call: offered },
1860
- }).filter((meta) => ![...own, ...native].some((one) => one.name === meta.name));
1861
- const tools = [...own.map((one) => (offered && isCatalogName(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
1862
- // An MCP tool of the run by its catalog name, as wrapped above: what a learned workflow's MCP node calls.
1863
- mcpHosted = (catalog) => {
1864
- const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
1865
- const host = wire && tools.find((one) => one.name === wire.name);
1866
- return host && ((args, ctx) => host.call(args, ctx));
1867
- };
1992
+ ...(facts?.hostName ? { hostName: facts.hostName } : {}),
1993
+ ...(spec.scriptComputer ? { computer: spec.scriptComputer } : {}),
1994
+ });
1995
+ const tools = [...own.map((one) => (offered && isCatalogWire(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
1868
1996
  // The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
1869
1997
  // session's proxy sees its upstream end, which can be after pi went idle).
1870
1998
  const port = booking.models;
1871
1999
  unbooked = 0;
2000
+ bookingsWriting = 0;
1872
2001
  const counted = {
1873
2002
  beforeRequest: async (request) => {
1874
2003
  // The CLI's next request of its main model after its question to the person: never admitted, it asks for the
@@ -1880,19 +2009,35 @@ function adapterLoop(specOf, options, deps) {
1880
2009
  mcpStale = false;
1881
2010
  await mcp.fresh();
1882
2011
  }
1883
- // The wrap-up this request carries, taken off the offer now: its admission tells it; a refusal (the throw below)
1884
- // or a dropped note leaves it untold, to be offered to a later request.
1885
- const offer = request.noted ? capNote.offered : undefined;
1886
- if (offer)
1887
- capNote.offered = undefined;
1888
- const ticket = await port.beforeRequest(request);
2012
+ // The note this request carries, the one it took (takeNote: one at a time). Admitted with it, the request holds it
2013
+ // until it ends (afterRequest tells it or gives it back); a refusal (the throw) or a dropped note gives it back
2014
+ // now, for a later request.
2015
+ const taken = request.noted === true && carried?.turn === undefined ? carried : undefined;
2016
+ let ticket;
2017
+ try {
2018
+ ticket = await port.beforeRequest(request);
2019
+ }
2020
+ catch (error) {
2021
+ if (taken && carried === taken)
2022
+ carried = undefined;
2023
+ throw error;
2024
+ }
2025
+ if (taken && carried === taken) {
2026
+ if (ticket && !ticket.noteDropped)
2027
+ taken.turn = ticket.turn;
2028
+ else
2029
+ carried = undefined;
2030
+ }
1889
2031
  unbooked += 1;
1890
2032
  // The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
1891
2033
  if (ticket && request.side)
1892
2034
  notOwn.add(ticket.turn);
1893
2035
  // The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
1894
- if (!request.side && request.host === undefined)
1895
- capNote.lastFigures = figuresOf(request.model, request) ?? capNote.lastFigures;
2036
+ if (!request.side && request.host === undefined) {
2037
+ const figures = figuresOf(request.model, request);
2038
+ if (figures)
2039
+ Object.assign(capNote, { lastFigures: figures, lastModel: request.model, lastEffort: request.effort });
2040
+ }
1896
2041
  // What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
1897
2042
  // the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
1898
2043
  try {
@@ -1902,28 +2047,31 @@ function adapterLoop(specOf, options, deps) {
1902
2047
  capNote.restUsd = null;
1903
2048
  console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
1904
2049
  }
1905
- // Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
1906
- // row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
1907
- if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
1908
- const { words, leftUsd, capUsd } = offer;
1909
- toldCaps.push(capUsd);
1910
- try {
1911
- await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
1912
- await deps.flush();
1913
- }
1914
- catch (error) {
1915
- console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
1916
- }
1917
- }
1918
2050
  return ticket;
1919
2051
  },
1920
- afterRequest: async (...args) => {
2052
+ afterRequest: async (usage, ticket, ended) => {
2053
+ // The note this request carried: told once the model answered it, else given back. Settled before anything here
2054
+ // waits: the proxy calls this as its client has the end, so a client's retry finds the note told or on offer.
2055
+ const held = carried?.turn !== undefined && carried.turn === ticket?.turn ? carried : undefined;
2056
+ if (held)
2057
+ carried = undefined;
2058
+ // An answer the model gave, not the provider's error inside one (a stream ended in an error event, a translated
2059
+ // route's failure in words included: the client drops it and asks again).
2060
+ const row = held && ended?.end === "answered" && ended.label !== "error" ? tell(held) : undefined;
2061
+ // Its booking has begun: waited for past CLOSE_MS, as long as its write takes (bookingsSettled).
2062
+ bookingsWriting += 1;
1921
2063
  try {
1922
2064
  await hooks.beforeBooking?.();
1923
- await port.afterRequest(...args);
2065
+ await port.afterRequest(usage, ticket, ended);
1924
2066
  }
1925
2067
  finally {
2068
+ bookingsWriting = Math.max(0, bookingsWriting - 1);
2069
+ if (row)
2070
+ await row();
1926
2071
  unbooked = Math.max(0, unbooked - 1);
2072
+ if (bookingsWriting === 0)
2073
+ for (const wake of writtenAll.splice(0))
2074
+ wake();
1927
2075
  if (unbooked === 0)
1928
2076
  for (const wake of bookedAll.splice(0))
1929
2077
  wake();
@@ -2003,7 +2151,7 @@ function adapterLoop(specOf, options, deps) {
2003
2151
  await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
2004
2152
  // A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
2005
2153
  // run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
2006
- else if (answer === "allow" && approvedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
2154
+ else if (answer === "allow" && askedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
2007
2155
  await record.end(call.callId, "done", OWN_TOOL_RELEASED);
2008
2156
  return answer;
2009
2157
  }
@@ -2020,7 +2168,27 @@ function adapterLoop(specOf, options, deps) {
2020
2168
  askCut.disarm();
2021
2169
  theRecord.onEvent(event);
2022
2170
  };
2023
- const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
2171
+ // A call of the CLI's own that its host tool calls run inside (Codex's code-mode `exec`): on its record as a call, and
2172
+ // each call it makes named under it, so its rows read as a codemode script's do on every other harness. Its start is
2173
+ // marked `nests`, so a crash leaves it open: its harness ends it (ownCalls.ended) from its CLI's own answer to it after
2174
+ // the resume, which comes after the rows of the calls it made, never as an interrupted end ahead of them. One no answer
2175
+ // of its CLI ends (a stop while it waits, a crash no resume follows) the run's end closes, interrupted (openNests).
2176
+ const ownCalls = record
2177
+ ? {
2178
+ opened: (callId, name, input) => ownWrite(record.start(callId, name, input, false, true).catch(unlessSealed)),
2179
+ nestedIn: (callId, parent) => record.nestedIn(callId, parent),
2180
+ ended: (callId, output, failed) => ownWrite(record.end(callId, failed ? "failed" : "done", output).catch(unlessSealed)),
2181
+ }
2182
+ : undefined;
2183
+ const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, ...(ownCalls ? { ownCalls } : {}), bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
2184
+ // The end-of-run turn an earlier claim asked and never saw end (its runner lost mid look-back or mid compile): the
2185
+ // root's newest input still in flight is that turn's (end-of-run.ts REFLECT_PREFIX), which pi picks up again as its
2186
+ // session opens. The job's turn ended before it, answered: this pass runs no job turn (no recovery as the job's, no
2187
+ // wrap-up note, no park on its spend), and the end-of-run step's ask, under the same request id, waits on it (a
2188
+ // CLI's look-back has no submission until it ends: its record's lookingBack, below). Read before the session
2189
+ // opens, so its first request is already learning's.
2190
+ const lookingBackOpen = (await harness.inspect(context)).submissions.filter((one) => one.type === "input" && Number(one.conversationId) === Number(ROOT_CONVERSATION_ID)).at(-1)?.requestId?.startsWith(REFLECT_PREFIX) === true;
2191
+ reflecting = lookingBackOpen;
2024
2192
  // The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
2025
2193
  // for host tools, each call through the gate before its intent.
2026
2194
  session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
@@ -2040,6 +2208,13 @@ function adapterLoop(specOf, options, deps) {
2040
2208
  await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
2041
2209
  }, context) };
2042
2210
  }
2211
+ // The run's own computer, made by this claim: its kind recorded once per claim, before any request of the claim
2212
+ // (each request's flush makes it durable first), so a later claim knows the run had one (computer-journal.ts
2213
+ // hadComputer) however this one ends.
2214
+ if (restarts === 0 && spec.computer?.own) {
2215
+ const [rootOf, kind] = [root, spec.computer.kind];
2216
+ await harness.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.computerMade, data: { computer: kind } }), context);
2217
+ }
2043
2218
  if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
2044
2219
  const [journalOf, rootOf] = [harness, root];
2045
2220
  computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
@@ -2173,7 +2348,7 @@ function adapterLoop(specOf, options, deps) {
2173
2348
  await takeRaises();
2174
2349
  if (paused) {
2175
2350
  if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
2176
- return await parkAtCap(harness, root, gate, paused);
2351
+ return await parkAtCap(harness, root, gate, paused, "cap");
2177
2352
  // The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
2178
2353
  const followUp = spec.cap.followUpOf(raising.capUsd).text;
2179
2354
  const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
@@ -2241,10 +2416,40 @@ function adapterLoop(specOf, options, deps) {
2241
2416
  * (its own entries are its record): its call goes on a record of its own for this step, the same entries. A claim
2242
2417
  * that finds the entry or the call's end takes it as it is. Undefined: the run is its agent's (the tool is not the
2243
2418
  * run's, or the gate denies it before anything is written); "park": the call waits for a person's approval. */
2419
+ /** The session's tools as calls nested in the workflow served first (`outer`), with no harness to nest them: each
2420
+ * asked at the gate as its own tool under `<outer>/<key>` (a deny, its argument pins; an ask passes when the card
2421
+ * a person approved for `outer` named the tool, and any other is refused, since a workflow served first never parks
2422
+ * part way), then run as this loop wraps the tool (its record, its flush and booking, the stop's abort). The call
2423
+ * is never run again, so a value is its first run's as it is. */
2424
+ const servedNested = (outer) => ({
2425
+ async call(name, args, key, own) {
2426
+ const tool = tools.find((one) => one.name === name);
2427
+ if (!tool)
2428
+ return { text: `${name} is no tool of this run.`, isError: true, refused: true, fresh: true };
2429
+ const callId = `${outer}/${key}`;
2430
+ const catalog = mcp?.catalogOf(name) ?? name;
2431
+ const asked = spec.gate?.askedAs?.(catalog) ?? catalog;
2432
+ const given = (await spec.gate?.({ callId, tool: catalog, args })) ?? "allow";
2433
+ if (given === "deny")
2434
+ return { text: setToDenyText(asked, undefined, "server", "no"), isError: true, refused: true, fresh: true };
2435
+ if (typeof given === "object" && "deny" in given)
2436
+ return { text: given.deny, isError: true, refused: true, fresh: true };
2437
+ if (given !== "allow" && !learnedApprovedTools(await approvedCardOver(callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(catalog)) {
2438
+ return { text: `This ${asked} call needs a person's approval, which a learned workflow run first cannot wait for; it was not run.`, isError: true, refused: true, fresh: true };
2439
+ }
2440
+ const got = await tool.call(args, { callId, signal: own ? AbortSignal.any([stopAbort.signal, own]) : stopAbort.signal });
2441
+ return { text: got.text, ...(got.isError ? { isError: true } : {}), ...(got.images?.length ? { images: got.images } : {}), ...(got.structured !== undefined ? { structured: got.structured } : {}), fresh: true };
2442
+ },
2443
+ memo: async (_key, value) => (typeof value === "function" ? value() : value),
2444
+ });
2244
2445
  const serveFirst = async (first) => {
2245
- const learned = tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
2246
- if (!learned)
2446
+ // The session's learned_workflow as this loop wraps a tool, but nesting nothing of the harness's: a call a crash
2447
+ // cut is ended interrupted and handed back, never run again (its record's start is not marked `nests`).
2448
+ const bare = spec.session.tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
2449
+ if (!bare || !tools.some((tool) => tool.name === LEARNED_WORKFLOW_TOOL))
2247
2450
  return undefined;
2451
+ const { nests: _nests, ...plain } = bare;
2452
+ const learned = hosted(plain);
2248
2453
  const [on, theRoot, theGate] = [harness, root, gate];
2249
2454
  const args = { name: first.name, input: first.input };
2250
2455
  const call = { callId: WORKFLOW_FIRST_CALL, tool: LEARNED_WORKFLOW_TOOL, args };
@@ -2274,7 +2479,7 @@ function adapterLoop(specOf, options, deps) {
2274
2479
  if (!ended) {
2275
2480
  // A deny before anything is written leaves the run its agent's, as if the workflow were not there.
2276
2481
  const before = await spec.gate?.({ callId: call.callId, tool: call.tool, args });
2277
- if (before === "deny" || typeof before === "object")
2482
+ if (before === "deny" || (typeof before === "object" && "deny" in before))
2278
2483
  return undefined;
2279
2484
  if (spec.inputOrigin)
2280
2485
  await rec.input(spec.input, spec.inputOrigin);
@@ -2301,7 +2506,7 @@ function adapterLoop(specOf, options, deps) {
2301
2506
  // A CLI's record takes the call's start and end inside the wrapper; pi's step record here.
2302
2507
  if (!record)
2303
2508
  await rec.start(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false);
2304
- const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal });
2509
+ const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal, nested: servedNested(WORKFLOW_FIRST_CALL) });
2305
2510
  answer = { text: got.text, isError: got.isError === true };
2306
2511
  if (!record)
2307
2512
  await rec.end(WORKFLOW_FIRST_CALL, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
@@ -2311,7 +2516,7 @@ function adapterLoop(specOf, options, deps) {
2311
2516
  return undefined;
2312
2517
  answer = taken(answer);
2313
2518
  const outcome = answer.isError ? "handed_back" : "answered";
2314
- const data = { workflow: first.name, digest: first.digest, revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
2519
+ const data = { workflow: first.name, digest: first.digest, ...(first.promotion !== undefined ? { promotion: first.promotion } : {}), revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
2315
2520
  await on.commit(async (tx) => {
2316
2521
  if (outcome === "answered")
2317
2522
  await tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "model", text: answer.text, at: now() } });
@@ -2350,6 +2555,7 @@ function adapterLoop(specOf, options, deps) {
2350
2555
  const cutBy = stopReason;
2351
2556
  if (step === "park" && cutBy?.kind !== "command") {
2352
2557
  await releaseHost(harness);
2558
+ await keepAtPark(harness, "workflow");
2353
2559
  gate.seal(new Parked());
2354
2560
  return { state: "parked" };
2355
2561
  }
@@ -2376,7 +2582,10 @@ function adapterLoop(specOf, options, deps) {
2376
2582
  }
2377
2583
  }
2378
2584
  const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
2379
- if (served || followedUp || firstUnplaced) {
2585
+ // The end-of-run turn found open (lookingBackOpen), with no turn of this claim's sent before it: never recovered as
2586
+ // the job's; the run goes to its end-of-run step, on the job's end the claim that asked it kept (jobEndKept).
2587
+ const lookingBack = lookingBackOpen && !followedUp && served === undefined;
2588
+ if (served || followedUp || firstUnplaced || lookingBack) {
2380
2589
  // The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
2381
2590
  // or there is none.
2382
2591
  }
@@ -2395,8 +2604,9 @@ function adapterLoop(specOf, options, deps) {
2395
2604
  // The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
2396
2605
  // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold. None
2397
2606
  // when the workflow answered: the run ends on its answer.
2398
- // A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn.
2399
- const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined;
2607
+ // A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn. Nor does a claim that found
2608
+ // that turn open (lookingBack).
2609
+ const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined || lookingBack;
2400
2610
  let turn = alone ? new Promise(() => { }) : placed ? session.turnEnd() : idleTurnOf(harness, root);
2401
2611
  // Set on every way out of the loop below but parkOn's, which returns before it is read.
2402
2612
  let data;
@@ -2405,15 +2615,26 @@ function adapterLoop(specOf, options, deps) {
2405
2615
  let parkOn;
2406
2616
  /** The ask_person call the run waits on in its claim, while it does. */
2407
2617
  let waitingOn;
2408
- if (alone)
2618
+ if (alone && lookingBack)
2619
+ ({ end: data, failedWith } = await jobEndKept(root));
2620
+ else if (alone)
2409
2621
  data = { state: "ended" };
2410
2622
  else
2411
2623
  for (;;) {
2412
- const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
2624
+ let end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
2413
2625
  // Parked on a call held at the gate (a CLI's at its tool bridge): the answer that made the call may still be
2414
- // streaming, and its booking lands before the claim goes (parkClaim).
2415
- if (end === "parked")
2416
- return await parkClaim(harness, gate);
2626
+ // streaming, and its booking lands before the claim goes (parkClaim). pi's calls already running beside it end
2627
+ // first (siblingsSettled), so their results are on the journal for the resume. A person's stop or cancel while
2628
+ // they do ends the run in its words, as it would have before the park.
2629
+ if (end === "parked" && spec.record === "loop")
2630
+ return await parkClaim(harness, gate, "approval");
2631
+ if (end === "parked") {
2632
+ parkPending = true;
2633
+ await siblingsSettled(harness, spec);
2634
+ if (stopReason?.kind !== "command")
2635
+ return await parkClaim(harness, gate, "approval");
2636
+ end = "stop";
2637
+ }
2417
2638
  if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
2418
2639
  await closeSession();
2419
2640
  continue passes;
@@ -2491,9 +2712,9 @@ function adapterLoop(specOf, options, deps) {
2491
2712
  const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
2492
2713
  // Its pause and the run parked landed before pi heard of the refusal.
2493
2714
  if (park?.outcome === "parked" && pausedAtRefusal)
2494
- return await parkClaim(harness, gate);
2715
+ return await parkClaim(harness, gate, "refusal");
2495
2716
  if (park?.outcome === "parked")
2496
- return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
2717
+ return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words }, "refusal");
2497
2718
  data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
2498
2719
  }
2499
2720
  else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
@@ -2627,20 +2848,16 @@ function adapterLoop(specOf, options, deps) {
2627
2848
  return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
2628
2849
  // The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
2629
2850
  // writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
2630
- const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
2851
+ // The run's status is how its job's own turn ended (`data`), whatever the step spends after it: learning spend that
2852
+ // takes the run past its cap is the learning's (askEndOfRun reads overCap after each of its turns), never the run's.
2853
+ // That end is kept before the step's first ask, so a claim that finds its turn open ends the run on it (jobEndKept).
2854
+ if (!lookingBack)
2855
+ await keepJobEnd(harness, root, spec, data, failedWith);
2856
+ const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap);
2631
2857
  if (step.kind === "stopped")
2632
2858
  return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
2633
2859
  if (step.kind === "interrupted")
2634
2860
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
2635
- // The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
2636
- // read again once its booking settled), as a job's answer that passed it does, never completed. An end already
2637
- // failed keeps its own words.
2638
- if (data.state !== "failed") {
2639
- await bookingsSettled();
2640
- const overAtEnd = await overCap();
2641
- if (overAtEnd)
2642
- data = { state: "failed", summary: overAtEnd };
2643
- }
2644
2861
  return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
2645
2862
  }
2646
2863
  }
@@ -2668,6 +2885,8 @@ function adapterLoop(specOf, options, deps) {
2668
2885
  heldNow = undefined;
2669
2886
  channelNow = undefined;
2670
2887
  handingBack = false;
2888
+ reflecting = false;
2889
+ learningRefused = undefined;
2671
2890
  deps.live?.(() => undefined);
2672
2891
  // A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
2673
2892
  // A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
@@ -2676,7 +2895,7 @@ function adapterLoop(specOf, options, deps) {
2676
2895
  }
2677
2896
  }
2678
2897
  /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
2679
- * `wrapUp`: whether the run has taken its share of the cap, so every call the model makes is refused in its fixed words.
2898
+ * `wrapUp`: once the run has taken its share of the cap, the words every call the model makes is refused in (wrapUpText).
2680
2899
  * `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
2681
2900
  * through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
2682
2901
  function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
@@ -2690,14 +2909,24 @@ function adapterLoop(specOf, options, deps) {
2690
2909
  await hooks.beforeIntent(kernelCall);
2691
2910
  // 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
2692
2911
  // in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
2693
- if (call.nested !== true && (await wrapUp()))
2694
- return { deny: WRAP_UP_TEXT };
2912
+ const wrapUpDeny = call.nested !== true ? await wrapUp() : undefined;
2913
+ if (wrapUpDeny !== undefined)
2914
+ return { deny: wrapUpDeny };
2695
2915
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
2696
2916
  const replayed = call.replayed === true;
2697
- const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
2917
+ const given = (await spec.gate?.(kernelCall, { ...(replayed ? { replayed } : {}), ran: ranOf })) ?? "allow";
2918
+ // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
2919
+ const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
2920
+ let decision = shown ? "ask" : given;
2921
+ // A call nested in a learned_workflow call a person approved, of an MCP tool that call's card named: its ask is
2922
+ // answered by that approval, as the card they saw named it (never one built again now). Any other asks for itself.
2923
+ if (call.nested === true && decision === "ask" && learnedApprovedTools(await approvedCardOver(call.callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(tool))
2924
+ decision = "allow";
2698
2925
  // Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
2699
2926
  // an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
2700
- const asked = spec.gate?.askedAs?.(tool) ?? tool;
2927
+ // A script's computer op is asked about by the tool it is held to (RunGate.askedAs with its arguments: bash for its
2928
+ // shell, write or read for its files).
2929
+ const asked = spec.gate?.askedAs?.(tool, call.args) ?? tool;
2701
2930
  // A call a person was asked about and has not answered, refused now because its tool is set to deny (a bare "deny",
2702
2931
  // or the gate's own words for it): the deny answers the ask first (deniedBySetting), a deny of theirs standing. The
2703
2932
  // model reads the gate's words (main's, from refusal-words.ts) either way.
@@ -2716,37 +2945,46 @@ function adapterLoop(specOf, options, deps) {
2716
2945
  // A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
2717
2946
  // (allowedBySetting), and the call runs without asking the person again.
2718
2947
  const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
2948
+ // While pi's park waits for the calls already running beside it (siblingsSettled), no new one starts: it is held as the
2949
+ // parked call is, its intent never stored, and asked again on the resume. A call a running tool makes is that tool's,
2950
+ // let through.
2951
+ if (decision === "allow" && !bySetting && parkPending && call.nested !== true)
2952
+ return { park: true };
2719
2953
  if (decision === "allow" && !bySetting)
2720
2954
  return "allow";
2721
2955
  // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
2722
- // (a learned workflow's MCP calls set to ask: askedFor).
2723
- const shown = await spec.gate?.askedFor?.(tool, call.args);
2724
- // Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
2725
- // The gate's own fields win over any of the same name in the call's input, which the model wrote.
2726
- const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
2956
+ // (a learned workflow's MCP actions set to ask: the gate's `ask`).
2957
+ const args = cardOf(tool, shown, call.args);
2727
2958
  // The call on the record before its ask (beforeAsk), with the input its model gave it.
2728
2959
  await beforeAsk?.(call);
2729
2960
  // Its price on the card: a catalog tool's (an MCP tool's, a monid endpoint's pinned price), else none.
2730
2961
  const price = mcp?.priceOf(tool) ?? null;
2731
- // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the gate's `mcp_calls`, a
2732
- // learned workflow's MCP calls set to ask): that allow takes the second confirm too.
2733
- const covered = Array.isArray(shown?.mcp_calls) ? shown.mcp_calls.filter((name) => typeof name === "string") : [];
2734
- const destructive = [asked, ...covered].some((name) => mcp?.effectOf(name) === "destructive");
2962
+ // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the card's `mcp_calls`, a
2963
+ // learned workflow's MCP actions set to ask): that allow takes the second confirm too.
2964
+ const destructive = [asked, ...learnedApprovedTools(shown)].some((name) => mcp?.effectOf(name) === "destructive");
2735
2965
  const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
2736
2966
  if (answer === "park")
2737
2967
  return { park: true };
2738
- // A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
2739
- // approved with it (host-calls.ts), as far as the card they approved named it: its ask as journaled, the card they
2740
- // saw, never one built again now.
2741
- if (answer.approved) {
2742
- const seen = askedArgs.get(call.callId);
2743
- approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
2744
- }
2745
2968
  if (answer.approved)
2746
2969
  return "allow";
2747
2970
  return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
2748
2971
  };
2749
2972
  }
2973
+ /** The card a person approved for the learned_workflow call that `callId` (`<outer>/<key>`, its key never holding a
2974
+ * "/") is nested in: the ask journaled under that call's own id, answered with an allow. Keyed to that one call, so a
2975
+ * card approved for any other call (an earlier call of the same workflow among them) never passes it. None when its
2976
+ * outer call was not asked as learned_workflow, or its ask was denied or not answered. */
2977
+ async function approvedCardOver(callId, learnedAs) {
2978
+ const at = callId.lastIndexOf("/");
2979
+ if (at <= 0)
2980
+ return undefined;
2981
+ const outer = callId.slice(0, at);
2982
+ const conversation = await harness.root(context);
2983
+ const entries = await entriesOf(gate.journal, conversation.id, context);
2984
+ const ask = findData(entries, KINDS.ask, (data) => data.callId === outer);
2985
+ const answer = ask && findData(entries, KINDS.answer, (data) => data.callId === outer);
2986
+ return ask?.tool === learnedAs && answer?.approved === true ? ask.args : undefined;
2987
+ }
2750
2988
  /** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
2751
2989
  * park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
2752
2990
  * was asked and its `price`; asked again on a resume, it is the same request. */
@@ -2754,9 +2992,8 @@ function adapterLoop(specOf, options, deps) {
2754
2992
  const conversation = await harness.root(context);
2755
2993
  const entries = await entriesOf(gate.journal, conversation.id, context);
2756
2994
  const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
2757
- // The card the person answers is the ask as first journaled: kept for the caller, which scopes an approval to it.
2758
2995
  if (first)
2759
- askedArgs.set(call.callId, first.args);
2996
+ askedCalls.add(call.callId);
2760
2997
  const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
2761
2998
  if (known)
2762
2999
  return known;
@@ -2768,8 +3005,10 @@ function adapterLoop(specOf, options, deps) {
2768
3005
  const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
2769
3006
  if (first === undefined) {
2770
3007
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
2771
- if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
3008
+ if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
3009
+ parkedCalls.add(call.callId);
2772
3010
  parked();
3011
+ }
2773
3012
  return "park";
2774
3013
  }
2775
3014
  for (;;) {
@@ -2788,8 +3027,10 @@ function adapterLoop(specOf, options, deps) {
2788
3027
  // no waiting call and was refused): the call is asked again and the run parks on it, so it never waits here
2789
3028
  // holding the claim while it reads running.
2790
3029
  if (delivered || refusals > 0) {
2791
- if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
3030
+ if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
3031
+ parkedCalls.add(call.callId);
2792
3032
  parked();
3033
+ }
2793
3034
  return "park";
2794
3035
  }
2795
3036
  await new Promise((resolve) => (wakeInbox = resolve));
@@ -2829,10 +3070,8 @@ function adapterLoop(specOf, options, deps) {
2829
3070
  inbox.splice(inbox.indexOf(row), 1);
2830
3071
  if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
2831
3072
  return "park";
2832
- // The call's ask, as journaled: kept for the caller, which scopes an approval to it.
2833
- const first = findData(await entriesOf(gate.journal, conversation.id, context), KINDS.ask, (ask) => ask.callId === call.callId);
2834
- if (first)
2835
- askedArgs.set(call.callId, first.args);
3073
+ // A call whose ask stands (askStands): a person was asked about it.
3074
+ askedCalls.add(call.callId);
2836
3075
  return data;
2837
3076
  }
2838
3077
  /** The answer to an ask a person was shown and has not answered, once its tool's setting reads deny: the deny answers it
@@ -2860,6 +3099,12 @@ function adapterLoop(specOf, options, deps) {
2860
3099
  * end reads withdrawn: its rows said "Not run: the run ended while it waited" of a call that ran. A deny set since still
2861
3100
  * refuses it first. Read from the journal once a claim: an ask written later in the claim parks it, and an answer
2862
3101
  * written later is read by answerOf itself. */
3102
+ /** The calls of `tool` the run's journal shows now (toolCalls): run to a good end, and every one with a result. Read
3103
+ * over every agent conversation of the run (agentEntriesOf): the root's and each subagent's, so a child's calls count
3104
+ * on the claim after a pause as on the one they ran in. */
3105
+ async function ranOf(tool) {
3106
+ return toolCalls(await agentEntriesOf(gate.journal, context), tool);
3107
+ }
2863
3108
  async function askStands(callId) {
2864
3109
  standing ??= (async () => {
2865
3110
  const conversation = await harness.root(context);
@@ -2893,7 +3138,7 @@ function adapterLoop(specOf, options, deps) {
2893
3138
  return false;
2894
3139
  await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
2895
3140
  const [theGate, theHarness] = [gate, harness];
2896
- if (!theGate || !theHarness || theGate.sealed)
3141
+ if (!theGate || !theHarness || theGate.sealed || parkPending)
2897
3142
  return "later";
2898
3143
  try {
2899
3144
  const conversation = await theHarness.root(context);
@@ -2952,11 +3197,12 @@ function adapterLoop(specOf, options, deps) {
2952
3197
  * the run's next user message and resumes it on the next claim, as on main: the ask_person tool result stays what pi
2953
3198
  * wrote, so nothing is re-asked or re-billed. The summary is plain words, never the question. */
2954
3199
  async function parkOnAsk(on, conversation, theGate, callId) {
3200
+ parkingOnAsk();
2955
3201
  const parkedAt = theGate.expect(writesEntry(KINDS.personAsked, (entry) => entry.callId === callId), { run: { state: "parked", summary: ASK_PERSON_WAITING } });
2956
3202
  parkedAt.catch(() => undefined);
2957
3203
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
2958
3204
  await parkedAt;
2959
- return parkClaim(on, theGate);
3205
+ return parkClaim(on, theGate, "answer");
2960
3206
  }
2961
3207
  /** A CLI's turn cut at its question to the person (TurnCut): its request after the question held, the turn is stopped
2962
3208
  * (interrupt), the held request refused once the stop is under way, and the turn the session still reads open settled,
@@ -2998,6 +3244,24 @@ function adapterLoop(specOf, options, deps) {
2998
3244
  return { status: "completed" };
2999
3245
  return turnOfRequest(on, conversation, last.requestId);
3000
3246
  }
3247
+ /** How the job's own turn ended (`data`, and a CLI's error answer `failedWith`), as this claim decided it, kept on the
3248
+ * root before the end-of-run step asks its first turn (KINDS.jobEnd), for a run with a step to ask (stepOf). Its
3249
+ * summary is cut of every secret the runner holds, as every summary is when served. */
3250
+ async function keepJobEnd(on, conversation, spec, data, failedWith) {
3251
+ if (!stepOf(spec))
3252
+ return;
3253
+ const end = data.summary !== undefined && deps.redact ? { ...data, summary: deps.redact(data.summary) } : data;
3254
+ const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}) };
3255
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.jobEnd, data: kept }), context);
3256
+ }
3257
+ /** The job's end for a claim that found the end-of-run turn open (lookingBackOpen): the newest keepJobEnd kept (a
3258
+ * follow-up's round keeps its own), never worked out again. */
3259
+ async function jobEndKept(conversation) {
3260
+ const kept = (await entriesOf(gate.journal, conversation.id, context)).filter((entry) => entry.kind === KINDS.jobEnd).at(-1);
3261
+ if (!kept)
3262
+ throw new Error("the end-of-run turn is open, but the job's end was never kept before it");
3263
+ return kept.data;
3264
+ }
3001
3265
  /** How the turn of the root's submission `requestId` ended (a steer of the idle session, which no session tracks). */
3002
3266
  async function turnOfRequest(on, conversation, requestId) {
3003
3267
  const found = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
@@ -3020,9 +3284,18 @@ function adapterLoop(specOf, options, deps) {
3020
3284
  * or the session went), and the run parks on its question. Undefined when no host holds anything: the run parks. */
3021
3285
  async function waitInClaim(on, callId) {
3022
3286
  const holders = specNow?.lifecycle?.personWait ?? [];
3023
- if (!holders.length || !session || !gate || gate.sealed || !root)
3024
- return undefined;
3025
3287
  await options.beforePersonWait?.();
3288
+ if (!session || !gate || gate.sealed || !root)
3289
+ return parkingOnAsk();
3290
+ if (!holders.length) {
3291
+ // Nothing to hold open: the run parks, unless the answer already came, between the question's turn end and here,
3292
+ // placed as a steer of the idle session (steer): then its turn is the next, at once, never cut by the park's seal.
3293
+ const early = idleSteer;
3294
+ idleSteer = undefined;
3295
+ if (early && (await early.placed))
3296
+ return { next: turnOfRequest(on, root, early.requestId) };
3297
+ return parkingOnAsk();
3298
+ }
3026
3299
  // Set before anything else: an answer sent from here is the claim's next turn, never a steer into no turn.
3027
3300
  const [theSession, theGate, conversation] = [session, gate, root];
3028
3301
  const mine = {};
@@ -3056,7 +3329,7 @@ function adapterLoop(specOf, options, deps) {
3056
3329
  // Nothing held, and no answer placed meanwhile: the run parks.
3057
3330
  if (!waitHolds.length && !mine.sent) {
3058
3331
  endWait(mine);
3059
- return undefined;
3332
+ return parkingOnAsk();
3060
3333
  }
3061
3334
  // The wait's start, once, in the journal, with the row's waiting summary (the server tells run.needs_input by it).
3062
3335
  if (!marked && !mine.sent) {
@@ -3072,9 +3345,12 @@ function adapterLoop(specOf, options, deps) {
3072
3345
  if (done)
3073
3346
  return;
3074
3347
  done = true;
3075
- if (value === "lapsed")
3348
+ if (value === "lapsed") {
3076
3349
  for (const hold of waitHolds)
3077
3350
  hold.confirmed?.();
3351
+ // The run parks on its question (the turn loop's "lapsed"): the person's next message is the resume's.
3352
+ parkingOnAsk();
3353
+ }
3078
3354
  endWait(mine);
3079
3355
  resolve(value);
3080
3356
  };
@@ -3119,18 +3395,34 @@ function adapterLoop(specOf, options, deps) {
3119
3395
  mcp?.release();
3120
3396
  mcp = undefined;
3121
3397
  // The pass's resources go once nothing more is written through them (AdapterRunSpec.release), once each.
3398
+ // A park's keeps the run's computer (keepAtPark).
3122
3399
  const release = releaseNow;
3400
+ const parked = parkedNow;
3123
3401
  releaseNow = undefined;
3124
- await release?.().catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
3402
+ parkedNow = undefined;
3403
+ await release?.(parked ? { parked } : {}).catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
3404
+ }
3405
+ /** What a round's first ask kept, read before the hook can skip or close its resumed turn: the CLI's record, or pi's
3406
+ * durable root entry. A different round's snapshot never prices this one. */
3407
+ async function keptOf(claim) {
3408
+ const record = cliRecord;
3409
+ const entries = !record && gate && root ? await entriesOf(gate.journal, root.id, context) : [];
3410
+ return (round) => {
3411
+ const requestId = reflectRequestId(claim.runId, false, round);
3412
+ if (record)
3413
+ return record.keptOf(requestId);
3414
+ const first = entries.find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
3415
+ const kept = first?.data?.kept;
3416
+ return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
3417
+ };
3125
3418
  }
3126
- /** What round `round`'s end-of-run turn kept as it was first asked (EndOfRunTurn's keptOf), on the CLI's record. */
3127
- const keptOf = (claim) => (round) => cliRecord?.keptOf(reflectRequestId(claim.runId, false, round));
3128
3419
  /** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
3129
3420
  const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
3130
3421
  /** The end-of-run step (stepOf: the spec's, else LoopDeps.endOfRun), asked once: the rows to stage with the end; `stopped` when a person's stop
3131
3422
  * came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
3132
- * asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. */
3133
- async function endOfRunStep(claim, spec, outcome) {
3423
+ * asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. `over`:
3424
+ * the claim's overCap, read after each turn the step asks (askEndOfRun). */
3425
+ async function endOfRunStep(claim, spec, outcome, over) {
3134
3426
  const cut = () => {
3135
3427
  if (stopReason?.kind === "command")
3136
3428
  return { kind: "stopped", commandId: stopReason.commandId };
@@ -3143,8 +3435,10 @@ function adapterLoop(specOf, options, deps) {
3143
3435
  return { kind: "rows", also: [] };
3144
3436
  if (!spec.agentId)
3145
3437
  throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
3438
+ // Every request from here is learning's, between the step's asks too, until the claim ends (reflecting).
3439
+ reflecting = true;
3146
3440
  try {
3147
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: keptOf(claim) });
3441
+ const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3148
3442
  return cut() ?? { kind: "rows", also: rows?.also ?? [] };
3149
3443
  }
3150
3444
  catch (error) {
@@ -3162,7 +3456,8 @@ function adapterLoop(specOf, options, deps) {
3162
3456
  let timer;
3163
3457
  const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
3164
3458
  try {
3165
- const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: keptOf(claim) }), late]);
3459
+ const pending = async () => step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: await keptOf(claim) });
3460
+ const rows = await Promise.race([pending(), late]);
3166
3461
  if (rows === "late") {
3167
3462
  console.warn(`[runner] ${claim.runId}: its end-of-run step gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
3168
3463
  return [];
@@ -3194,8 +3489,9 @@ function adapterLoop(specOf, options, deps) {
3194
3489
  /** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
3195
3490
  * answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
3196
3491
  * asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
3197
- * per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. */
3198
- async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1, keep, step) {
3492
+ * per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. `over`:
3493
+ * the claim's overCap, read once the turn's booking settled. */
3494
+ async function askEndOfRun(claim, over, prompt, deadlineMs, again = false, round = 1, keep, step) {
3199
3495
  if (!session || !harness || !gate || !root)
3200
3496
  throw new Error("the run's session is not open");
3201
3497
  const on = harness;
@@ -3212,11 +3508,12 @@ function adapterLoop(specOf, options, deps) {
3212
3508
  const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
3213
3509
  prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
3214
3510
  }
3215
- reflecting = true;
3216
3511
  let timer;
3217
3512
  try {
3218
- // A CLI's record answers a turn it already wrote from its submission, as pi does: its CLI is never asked twice.
3219
- const known = theRecord ? await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context) : undefined;
3513
+ // A turn already answered (an earlier claim's) is read from its submission; a CLI's record answers one it already
3514
+ // wrote from it too, as pi does: its CLI is never asked twice.
3515
+ const prior = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
3516
+ const known = theRecord ? prior : undefined;
3220
3517
  // How this claim's turn ended; a turn answered before reads as its submission says.
3221
3518
  let turnStatus = "completed";
3222
3519
  // What the turn's first ask kept (`keep`), an earlier claim's when it asked first: every answer carries it.
@@ -3240,6 +3537,20 @@ function adapterLoop(specOf, options, deps) {
3240
3537
  turnStatus = end.status;
3241
3538
  await theRecord?.answered(requestId, prompt, end.status);
3242
3539
  }
3540
+ // A turn the cap refused a request of (this claim's, or the one a takeover found open: lookingBackOpen) fails in the
3541
+ // refusal's words: the learning is dropped for the cap's room (reflect-hook.ts CAP_REFUSAL), the run never parked.
3542
+ const capped = prior?.status === "done" ? undefined : learningRefused;
3543
+ if (capped) {
3544
+ learningRefused = undefined;
3545
+ return withKept({ failed: { code: "refused", message: capped.refuse } });
3546
+ }
3547
+ // The run's booked spend once this turn's settled (its cut requests at their worst case, an earlier claim's too): past
3548
+ // the cap, the turn fails in the cap's words (overCap), and the learning is dropped as a refusal drops it
3549
+ // (reflect-hook.ts CAP_REFUSAL: no_budget), its spend still booked. The run keeps the end its job's turn gave it.
3550
+ await bookingsSettled();
3551
+ const passed = await over();
3552
+ if (passed)
3553
+ return withKept({ failed: { code: "refused", message: passed } });
3243
3554
  const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
3244
3555
  if (turnStatus !== "completed" || record?.status !== "done")
3245
3556
  return withKept({ failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } });
@@ -3248,49 +3559,152 @@ function adapterLoop(specOf, options, deps) {
3248
3559
  }
3249
3560
  finally {
3250
3561
  clearTimeout(timer);
3251
- reflecting = false;
3252
3562
  }
3253
3563
  }
3254
3564
  /** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded (END_PATCH_MS): late or failing, the end says
3255
3565
  * its cost and metrics are unknown (END_PATCH_UNKNOWN). */
3256
3566
  async function endPatchOf(data) {
3257
- if (!specNow?.endPatch)
3567
+ const spec = specNow;
3568
+ if (!spec?.endPatch && !spec?.endCost)
3258
3569
  return {};
3259
3570
  let timer;
3260
- const boundMs = specNow.endPatchMs ?? END_PATCH_MS;
3571
+ const boundMs = spec.endPatchMs ?? END_PATCH_MS;
3261
3572
  const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), boundMs)));
3262
- try {
3263
- const patch = await Promise.race([specNow.endPatch(data), late]);
3264
- if (patch === "late") {
3265
- console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its cost and metrics unknown`);
3573
+ // The cost, read apart (AdapterRunSpec.endCost): a patch whose metrics run late or fail never takes it with them. A
3574
+ // read that fails is read again within the same bound (END_COST_TRIES): the stored cost is every reader's answer
3575
+ // (the list, the view, usage), so a null there is kept only when the booking could not be read at all.
3576
+ const endCost = spec.endCost;
3577
+ const cost = endCost
3578
+ ? readAgain(endCost, late, (error, tries, last) => console.warn(last ? `[runner] its end's cost failed ${tries} times, last: ${said(error)}; the end is written with its cost unknown` : `[runner] its end's cost failed: ${said(error)}; read again`)).then((answer) => {
3579
+ if (answer === "late")
3580
+ console.warn(`[runner] its end's cost gave no answer within ${boundMs / 1000} s; the end is written with its cost unknown`);
3581
+ return answer === "late" || answer === "failed" ? { costUsd: null, costUpperBound: false } : answer;
3582
+ })
3583
+ : undefined;
3584
+ const patched = async () => {
3585
+ if (!spec.endPatch)
3586
+ return {};
3587
+ try {
3588
+ const patch = await Promise.race([spec.endPatch(data), late]);
3589
+ if (patch === "late") {
3590
+ console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
3591
+ return END_PATCH_UNKNOWN;
3592
+ }
3593
+ return patch ?? {};
3594
+ }
3595
+ catch (error) {
3596
+ console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
3266
3597
  return END_PATCH_UNKNOWN;
3267
3598
  }
3268
- return patch ?? {};
3269
- }
3270
- catch (error) {
3271
- console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its cost and metrics unknown`);
3272
- return END_PATCH_UNKNOWN;
3599
+ };
3600
+ try {
3601
+ const [patch, read] = await Promise.all([patched(), cost]);
3602
+ return read ? { ...patch, ...read } : patch;
3273
3603
  }
3274
3604
  finally {
3275
3605
  clearTimeout(timer);
3276
3606
  }
3277
3607
  }
3278
3608
  /** The run parked at its cap: its pending budget as an agentrun.budget entry, in one commit with the run parked in the
3279
- * cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. */
3280
- async function parkAtCap(on, conversation, theGate, data) {
3609
+ * cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. `cause`: parked again
3610
+ * at the cap on a resume, or at a refusal the turn ended on. */
3611
+ async function parkAtCap(on, conversation, theGate, data, cause) {
3281
3612
  await pauseAtCap(on, conversation, theGate, data);
3282
- return parkClaim(on, theGate);
3613
+ return parkClaim(on, theGate, cause);
3614
+ }
3615
+ /** Waits, at most the spec's parkSiblingsMs (PARK_SIBLINGS_MS), until no call pi started beside a parked one is still
3616
+ * running: a model call of the same answer (its assistant entry) past its stored intent. Each one's result is then on the
3617
+ * journal before the park seals it, and the resume hands it to the model with the parked call's answer, never as a call
3618
+ * cut short. Not waited on: a call held before its intent (the parked one, any held with it), the parked call itself
3619
+ * when it was asked after its intent (a replay-safe rerun), and every call it is nested in (a script or a workflow node
3620
+ * waiting on it), nor any call of another answer. A stop, a lost claim or a closed Harness ends the wait at once. Past
3621
+ * the bound the seal cuts what still runs, as before, and the model reads it interrupted. pi's alone: a CLI's park
3622
+ * (spec.record "loop") lets its claim go at once, and its resume settles a call that ended (resumeUnstartedCalls). */
3623
+ async function siblingsSettled(on, spec) {
3624
+ const until = Date.now() + (spec.parkSiblingsMs ?? PARK_SIBLINGS_MS);
3625
+ let over = false;
3626
+ let end = () => { };
3627
+ const ended = new Promise((resolve) => (end = resolve)).then(() => {
3628
+ over = true;
3629
+ });
3630
+ // Its own listener on the claim's signal, taken off on every way out (settled, past the bound, sealed): a loop leaves
3631
+ // nothing on the signal it was lent. The stop and the Harness's close are promises, which hold nothing on it.
3632
+ const onAbort = () => end();
3633
+ if (deps.signal.aborted)
3634
+ end();
3635
+ else
3636
+ deps.signal.addEventListener("abort", onAbort, { once: true });
3637
+ void stopping.then(() => end());
3638
+ void on.closed.then(() => end(), () => end());
3639
+ try {
3640
+ while (!over && !gate?.sealed && Date.now() < until) {
3641
+ let tasks;
3642
+ try {
3643
+ ({ tasks } = await on.inspect(context));
3644
+ }
3645
+ catch {
3646
+ return;
3647
+ }
3648
+ if (siblingsRunning(tasks).length === 0)
3649
+ return;
3650
+ let timer;
3651
+ await Promise.race([ended, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, Math.min(SIBLINGS_POLL_MS, until - Date.now())))))]);
3652
+ clearTimeout(timer);
3653
+ }
3654
+ }
3655
+ finally {
3656
+ deps.signal.removeEventListener("abort", onAbort);
3657
+ }
3658
+ }
3659
+ /** siblingsSettled's read of the Harness's live tasks: the model calls past their intent that share an answer with a
3660
+ * call this claim parked on, less that call and every call it is nested in. */
3661
+ function siblingsRunning(tasks) {
3662
+ const calls = tasks.map((task) => task.record).filter((record) => record.kind === ToolTask.definition.name);
3663
+ const byId = new Map(calls.map((record) => [String(record.id), record]));
3664
+ const inputOf = (record) => (record.input ?? {});
3665
+ const answers = new Set();
3666
+ const holding = new Set();
3667
+ for (const record of calls) {
3668
+ const input = inputOf(record);
3669
+ if (!parkedCalls.has((input.kind === "nested" ? input.call?.id : input.callId) ?? ""))
3670
+ continue;
3671
+ // The parked call and each call it is nested in, up to the model's call that holds it, whose answer it shares.
3672
+ for (let at = record; at; at = byId.get(String(inputOf(at).parent ?? at.owner ?? ""))) {
3673
+ holding.add(String(at.id));
3674
+ const own = inputOf(at);
3675
+ if (own.kind !== "nested" && own.assistant !== undefined)
3676
+ answers.add(own.assistant);
3677
+ }
3678
+ }
3679
+ return calls
3680
+ .filter((record) => {
3681
+ const input = inputOf(record);
3682
+ const phase = record.state.checkpoint?.phase;
3683
+ return input.kind !== "nested" && input.assistant !== undefined && answers.has(input.assistant) && !holding.has(String(record.id)) && phase === "execute";
3684
+ })
3685
+ .map((record) => String(record.id));
3283
3686
  }
3284
3687
  /** A park's release of the claim, as the end's: the tool host let go first (a browser's release, booked under the live
3285
3688
  * claim), then every paid request the session admitted booked (bookingsSettled), then the journal sealed. A CLI turn
3286
3689
  * the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
3287
3690
  * would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
3288
- async function parkClaim(on, theGate) {
3691
+ async function parkClaim(on, theGate, cause) {
3289
3692
  await releaseHost(on);
3290
3693
  await bookingsSettled();
3694
+ await keepAtPark(on, cause);
3291
3695
  theGate.seal(new Parked());
3292
3696
  return { state: "parked" };
3293
3697
  }
3698
+ /** At a park for `cause`, before its seal: a pass whose spec keeps its computer (AdapterRunSpec.keptWords) has it kept
3699
+ * for the resume at its release (closeSession), once the run's timeline says so, for the person deciding; its owner's
3700
+ * live view is closed saying the cause. A write that fails (the fence's refusal: a lost claim, whose run a later claim
3701
+ * may hold already) keeps nothing: the computer goes as at the run's end. */
3702
+ async function keepAtPark(on, cause) {
3703
+ const summary = specNow?.keptWords;
3704
+ if (!summary)
3705
+ return;
3706
+ parkedNow = await on.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data: { summary, at: Date.now() } }), context).then(() => cause, () => undefined);
3707
+ }
3294
3708
  /** The run's pause at its cap: its agentrun.budget entry, in one commit with the run parked in the cap's words. */
3295
3709
  async function pauseAtCap(on, conversation, theGate, data) {
3296
3710
  const parkedAt = theGate.expect(writesEntry(KINDS.budget), { run: { state: "parked", summary: data.words } });
@@ -3306,8 +3720,9 @@ function adapterLoop(specOf, options, deps) {
3306
3720
  await parkedAt;
3307
3721
  }
3308
3722
  /** Waits, at most CLOSE_MS, until every paid request the session admitted is booked: a person's stop is booked at what
3309
- * streamed once the session's proxy sees its upstream end. Past the bound the end is written anyway, and a request left
3310
- * unbooked reads at its hold and bound, the worst it can have cost. */
3723
+ * streamed once the session's proxy sees its upstream end. Then, for a booking whose write has begun, as long as that
3724
+ * write takes (bookingWriteMs). Past the bounds the end is written anyway, and a request left unbooked reads at its
3725
+ * hold and bound, the worst it can have cost, and the run's cost unknown: never a known figure that leaves it out. */
3311
3726
  async function bookingsSettled() {
3312
3727
  if (unbooked === 0)
3313
3728
  return;
@@ -3315,6 +3730,15 @@ function adapterLoop(specOf, options, deps) {
3315
3730
  let timer;
3316
3731
  await Promise.race([new Promise((resolve) => bookedAll.push(resolve)), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
3317
3732
  clearTimeout(timer);
3733
+ // A booking whose write has begun (its request answered) is waited for as long as its write takes, bounded
3734
+ // (BOOKING_WRITE_MS): written after the end, it would be fenced and lost, and the run's cost read unknown for good.
3735
+ if (bookingsWriting === 0)
3736
+ return;
3737
+ const boundMs = specNow?.bookingWriteMs ?? BOOKING_WRITE_MS;
3738
+ const written = await Promise.race([new Promise((resolve) => writtenAll.push(() => resolve(true))), new Promise((resolve) => (timer = setTimeout(() => resolve(false), boundMs)))]);
3739
+ clearTimeout(timer);
3740
+ if (!written)
3741
+ console.warn(`[runner] ${bookingsWriting} paid request booking(s) still being written after ${boundMs / 1000} s; going on without them: each reads at its hold, and the run's cost unknown`);
3318
3742
  }
3319
3743
  /** The run's timeline says it went on after its runner was lost (RUN_RESUMED, `after: runner_lost`): one root entry,
3320
3744
  * no run patch. A journal sealed meanwhile (the claim lost again, a shutdown) refuses it, and the loop goes on as it
@@ -3351,6 +3775,8 @@ function adapterLoop(specOf, options, deps) {
3351
3775
  // their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
3352
3776
  await releaseHost(on);
3353
3777
  await bookingsSettled();
3778
+ // The pull request's checkout goes before the end is committed: a run that reads final never still holds its code.
3779
+ await specNow?.endCheckout?.();
3354
3780
  const patch = await endPatchOf(base);
3355
3781
  // A person's stop that came while the end waited (its host's release, its bookings, its patch's reads, up to
3356
3782
  // END_PATCH_MS on a busy store) is this end's, as a stop during any earlier await of the end path is: the run ends
@@ -3360,7 +3786,7 @@ function adapterLoop(specOf, options, deps) {
3360
3786
  const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
3361
3787
  if (lateStop)
3362
3788
  take = [...take, lateStop.commandId];
3363
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
3789
+ const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
3364
3790
  const run = {
3365
3791
  state: data.state,
3366
3792
  // An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
@@ -3368,7 +3794,7 @@ function adapterLoop(specOf, options, deps) {
3368
3794
  ...(data.summary ? { summary: data.summary } : {}),
3369
3795
  ...(!data.summary ? { summary: null } : {}),
3370
3796
  ...(data.outcome !== undefined ? { outcome: data.outcome } : {}),
3371
- ...(data.costUsd !== undefined ? { costUsd: data.costUsd } : {}),
3797
+ ...(data.costUsd !== undefined ? { costUsd: data.costUsd, costUpperBound: data.costUpperBound === true } : {}),
3372
3798
  ...(data.metrics !== undefined ? { metrics: data.metrics } : {}),
3373
3799
  };
3374
3800
  // A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
@@ -3383,6 +3809,13 @@ function adapterLoop(specOf, options, deps) {
3383
3809
  const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
3384
3810
  const recordEnds = ends.unsentParked();
3385
3811
  const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
3812
+ // A call that only nests calls (a harness's own: Codex's `exec`) still open when the run ends: nothing will end it now
3813
+ // (a stop while its call waited, a crash whose next drive never resumed its CLI's thread), so it ends with the run,
3814
+ // interrupted, after the rows of its calls (their withdrawals above it in this commit). Its own end on its way is
3815
+ // written first. Marked `withRun`: a park or a stop failed nothing, so its row reads interrupted, never failed.
3816
+ while (ownWrites.size > 0)
3817
+ await Promise.allSettled([...ownWrites]);
3818
+ const cutOpen = ends.openNests();
3386
3819
  const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
3387
3820
  // A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
3388
3821
  ended.catch(() => undefined);
@@ -3392,6 +3825,8 @@ function adapterLoop(specOf, options, deps) {
3392
3825
  await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
3393
3826
  for (const callId of recordEnds)
3394
3827
  await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
3828
+ for (const callId of cutOpen)
3829
+ await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "interrupted", withRun: true, at: now() } });
3395
3830
  // A turn the run ends while it is open (a stop or cancel cut it, or the run failed in it) ends with the run.
3396
3831
  if (cliRecord?.openTurn())
3397
3832
  await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
@@ -3408,6 +3843,8 @@ function adapterLoop(specOf, options, deps) {
3408
3843
  await ended;
3409
3844
  for (const callId of recordEnds)
3410
3845
  ends.noteEnd(callId, "refused", notRun);
3846
+ for (const callId of cutOpen)
3847
+ ends.noteEnd(callId, "interrupted");
3411
3848
  return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
3412
3849
  }
3413
3850
  return {