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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (399) hide show
  1. package/CHANGELOG.md +282 -0
  2. package/README.md +155 -92
  3. package/dist/agent-rows.d.ts +1 -1
  4. package/dist/agents-store.d.ts +35 -3
  5. package/dist/agents-store.js +39 -14
  6. package/dist/answer-json.d.ts +34 -1
  7. package/dist/answer-json.js +91 -9
  8. package/dist/api-only.d.ts +1 -1
  9. package/dist/api-only.js +2 -2
  10. package/dist/browser-cost.js +52 -93
  11. package/dist/cap.d.ts +0 -390
  12. package/dist/cap.js +4 -937
  13. package/dist/catalog.js +1 -1
  14. package/dist/composio-preset.d.ts +17 -0
  15. package/dist/composio-preset.js +43 -1
  16. package/dist/computer-calls.d.ts +36 -24
  17. package/dist/computer-calls.js +110 -27
  18. package/dist/computer-live.d.ts +5 -0
  19. package/dist/computer-live.js +12 -0
  20. package/dist/computer-setting.d.ts +15 -2
  21. package/dist/computer-setting.js +20 -4
  22. package/dist/computer-view.d.ts +3 -2
  23. package/dist/computer-view.js +5 -4
  24. package/dist/computer-viewer.js +26 -12
  25. package/dist/computers.d.ts +4 -1
  26. package/dist/computers.js +12 -6
  27. package/dist/console/assets/index-CjqQirbo.css +1 -0
  28. package/dist/console/assets/index-b6-XY5A9.js +576 -0
  29. package/dist/console/index.html +2 -2
  30. package/dist/console-links.d.ts +2 -0
  31. package/dist/console-links.js +3 -0
  32. package/dist/decisions.js +4 -0
  33. package/dist/faux-computers.js +4 -2
  34. package/dist/harness-opencode/adapter.js +7 -3
  35. package/dist/harness-opencode/facts.js +0 -2
  36. package/dist/harness-opencode/host/policy.d.ts +2 -5
  37. package/dist/harness-opencode/host/policy.js +8 -32
  38. package/dist/harness-table.d.ts +0 -2
  39. package/dist/harness-table.js +0 -2
  40. package/dist/host-tools.d.ts +1 -5
  41. package/dist/host-tools.js +7 -10
  42. package/dist/hosted-search.d.ts +0 -2
  43. package/dist/hosted-search.js +0 -21
  44. package/dist/key-words.d.ts +3 -2
  45. package/dist/key-words.js +4 -2
  46. package/dist/learn/check.d.ts +6 -1
  47. package/dist/learn/check.js +12 -4
  48. package/dist/learn/commit.d.ts +10 -0
  49. package/dist/learn/commit.js +18 -4
  50. package/dist/learn/compile.d.ts +243 -0
  51. package/dist/learn/compile.js +471 -0
  52. package/dist/learn/general.d.ts +3 -0
  53. package/dist/learn/general.js +4 -2
  54. package/dist/learn/grade.d.ts +1 -1
  55. package/dist/learn/grade.js +7 -6
  56. package/dist/learn/notes.d.ts +8 -0
  57. package/dist/learn/notes.js +18 -0
  58. package/dist/learn/promote.d.ts +253 -0
  59. package/dist/learn/promote.js +428 -0
  60. package/dist/learn/refit.d.ts +39 -0
  61. package/dist/learn/refit.js +236 -0
  62. package/dist/learn/reflect.d.ts +5 -25
  63. package/dist/learn/reflect.js +14 -131
  64. package/dist/learn/replay-calls.d.ts +63 -0
  65. package/dist/learn/replay-calls.js +158 -0
  66. package/dist/learn/skills.d.ts +17 -9
  67. package/dist/learn/skills.js +132 -42
  68. package/dist/learn/workflow-nodes.d.ts +15 -0
  69. package/dist/learn/workflow-nodes.js +44 -0
  70. package/dist/learned-nodes.d.ts +50 -2
  71. package/dist/learned-nodes.js +41 -2
  72. package/dist/learned-workflow.d.ts +19 -3
  73. package/dist/learned-workflow.js +105 -26
  74. package/dist/learning-batch.d.ts +2 -2
  75. package/dist/learning-batch.js +1 -1
  76. package/dist/learning-cost.d.ts +18 -6
  77. package/dist/learning-cost.js +15 -7
  78. package/dist/learning-routes.d.ts +14 -2
  79. package/dist/learning-routes.js +14 -3
  80. package/dist/learning-words.d.ts +7 -0
  81. package/dist/learning-words.js +7 -0
  82. package/dist/learning.d.ts +31 -6
  83. package/dist/learning.js +7 -4
  84. package/dist/llm.js +0 -3
  85. package/dist/mcp-gateway.d.ts +12 -20
  86. package/dist/mcp-gateway.js +16 -44
  87. package/dist/mcp-oauth.d.ts +5 -0
  88. package/dist/mcp-oauth.js +1 -1
  89. package/dist/mcp-pin-first.d.ts +37 -0
  90. package/dist/mcp-pin-first.js +107 -0
  91. package/dist/mcp-probe.d.ts +8 -9
  92. package/dist/mcp-probe.js +16 -33
  93. package/dist/mcp-servers-store.d.ts +89 -22
  94. package/dist/mcp-servers-store.js +131 -25
  95. package/dist/mcp-sources.d.ts +39 -0
  96. package/dist/mcp-sources.js +74 -0
  97. package/dist/mcp-store.d.ts +11 -0
  98. package/dist/mcp-store.js +16 -2
  99. package/dist/mcp-wire.d.ts +22 -0
  100. package/dist/mcp-wire.js +36 -0
  101. package/dist/mcp.js +3 -3
  102. package/dist/meta-tool-names.d.ts +1 -0
  103. package/dist/meta-tool-names.js +3 -0
  104. package/dist/model.d.ts +13 -0
  105. package/dist/model.js +46 -15
  106. package/dist/monid.d.ts +51 -25
  107. package/dist/monid.js +226 -140
  108. package/dist/openapi.js +336 -66
  109. package/dist/paid-calls.d.ts +26 -29
  110. package/dist/paid-calls.js +46 -102
  111. package/dist/propose.d.ts +7 -1
  112. package/dist/propose.js +18 -6
  113. package/dist/provider.js +9 -2
  114. package/dist/reflect-range.js +2 -1
  115. package/dist/rows.d.ts +5 -3
  116. package/dist/rows.js +15 -4
  117. package/dist/run-launch.d.ts +13 -0
  118. package/dist/run-launch.js +6 -0
  119. package/dist/run-learning-served.d.ts +13 -2
  120. package/dist/run-manifest.d.ts +5 -0
  121. package/dist/run-manifest.js +20 -0
  122. package/dist/run-secrets.js +2 -3
  123. package/dist/run-timeline-served.js +5 -2
  124. package/dist/run-view.d.ts +17 -6
  125. package/dist/run-view.js +51 -22
  126. package/dist/runnable.d.ts +0 -3
  127. package/dist/runnable.js +37 -29
  128. package/dist/runner/adapter-loop.d.ts +24 -10
  129. package/dist/runner/adapter-loop.js +852 -314
  130. package/dist/runner/adapter-run-spec.d.ts +12 -6
  131. package/dist/runner/adapter-run-spec.js +97 -46
  132. package/dist/runner/adapters/pi-computer.d.ts +3 -1
  133. package/dist/runner/adapters/pi-computer.js +13 -5
  134. package/dist/runner/adapters/pi.d.ts +16 -7
  135. package/dist/runner/adapters/pi.js +94 -33
  136. package/dist/runner/cli-run-spec.js +67 -27
  137. package/dist/runner/computer-channel.js +2 -1
  138. package/dist/runner/conformance/harness.d.ts +3 -0
  139. package/dist/runner/conformance/harness.js +145 -4
  140. package/dist/runner/conformance/subject.d.ts +11 -4
  141. package/dist/runner/end-of-run.d.ts +6 -5
  142. package/dist/runner/end-of-run.js +9 -6
  143. package/dist/runner/feedback-round.d.ts +52 -0
  144. package/dist/runner/feedback-round.js +79 -0
  145. package/dist/runner/journal-kinds.d.ts +24 -6
  146. package/dist/runner/journal-kinds.js +15 -0
  147. package/dist/runner/learning-end.d.ts +54 -19
  148. package/dist/runner/learning-end.js +272 -99
  149. package/dist/runner/learning-loop.d.ts +19 -1
  150. package/dist/runner/learning-loop.js +5 -2
  151. package/dist/runner/learning-seed.d.ts +4 -0
  152. package/dist/runner/learning-seed.js +14 -0
  153. package/dist/runner/loop-contract.d.ts +19 -3
  154. package/dist/runner/loop.d.ts +16 -1
  155. package/dist/runner/loop.js +21 -1
  156. package/dist/runner/mcp-claim.d.ts +5 -1
  157. package/dist/runner/mcp-claim.js +66 -50
  158. package/dist/runner/mcp-run.d.ts +16 -52
  159. package/dist/runner/mcp-run.js +12 -84
  160. package/dist/runner/meta-tools.d.ts +37 -0
  161. package/dist/runner/meta-tools.js +268 -0
  162. package/dist/runner/metrics.js +14 -3
  163. package/dist/runner/model-route.js +12 -3
  164. package/dist/runner/monid-run.d.ts +16 -0
  165. package/dist/runner/monid-run.js +96 -0
  166. package/dist/runner/promotion.d.ts +80 -0
  167. package/dist/runner/promotion.js +562 -0
  168. package/dist/runner/reflect-hook.d.ts +36 -21
  169. package/dist/runner/reflect-hook.js +138 -49
  170. package/dist/runner/runner.js +26 -4
  171. package/dist/runner/sessions.d.ts +8 -3
  172. package/dist/runner/sessions.js +5 -1
  173. package/dist/runner/step-guard.d.ts +62 -0
  174. package/dist/runner/step-guard.js +93 -0
  175. package/dist/runner/subagent.d.ts +0 -3
  176. package/dist/runner/subagent.js +7 -12
  177. package/dist/runner/workflow-first.d.ts +216 -0
  178. package/dist/runner/workflow-first.js +303 -0
  179. package/dist/runner/workflow-loop.js +17 -10
  180. package/dist/runner/workflow-spec.d.ts +1 -0
  181. package/dist/runner/workflow-spec.js +7 -3
  182. package/dist/runs-over-store.d.ts +11 -2
  183. package/dist/runs-over-store.js +21 -11
  184. package/dist/server.d.ts +88 -16
  185. package/dist/server.js +380 -87
  186. package/dist/settings-wake.d.ts +8 -6
  187. package/dist/settings-wake.js +13 -7
  188. package/dist/store/agent-body.d.ts +14 -3
  189. package/dist/store/agent-body.js +14 -10
  190. package/dist/store/command-wake.d.ts +3 -2
  191. package/dist/store/command-wake.js +4 -4
  192. package/dist/store/postgres/connection.js +3 -1
  193. package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
  194. package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
  195. package/dist/store/schema.d.ts +9 -0
  196. package/dist/store/schema.js +28 -8
  197. package/dist/store/sqlite/connection.d.ts +2 -2
  198. package/dist/store/sqlite/connection.js +2 -2
  199. package/dist/store/sqlite/run-patch.js +19 -7
  200. package/dist/store/sqlite/store.js +59 -18
  201. package/dist/store/store.d.ts +46 -14
  202. package/dist/store-reads/journal.d.ts +25 -1
  203. package/dist/store-reads/journal.js +63 -49
  204. package/dist/store-reads/learning.d.ts +101 -15
  205. package/dist/store-reads/learning.js +195 -61
  206. package/dist/store-reads/loop.d.ts +61 -0
  207. package/dist/store-reads/loop.js +111 -0
  208. package/dist/store-view.d.ts +3 -2
  209. package/dist/store-view.js +35 -17
  210. package/dist/template-eval.d.ts +18 -9
  211. package/dist/template-eval.js +91 -66
  212. package/dist/template-github-permissions.d.ts +2 -2
  213. package/dist/template-github-permissions.js +2 -1
  214. package/dist/template-import.d.ts +31 -0
  215. package/dist/template-import.js +121 -0
  216. package/dist/template-source.d.ts +51 -0
  217. package/dist/template-source.js +371 -0
  218. package/dist/templates.d.ts +218 -46
  219. package/dist/templates.js +493 -181
  220. package/dist/timeline/computer.d.ts +48 -0
  221. package/dist/timeline/computer.js +169 -0
  222. package/dist/timeline/index.d.ts +4 -3
  223. package/dist/timeline/index.js +4 -3
  224. package/dist/timeline/labels.d.ts +6 -2
  225. package/dist/timeline/labels.js +93 -2
  226. package/dist/timeline/origin.d.ts +19 -5
  227. package/dist/timeline/origin.js +11 -4
  228. package/dist/timeline/timeline.d.ts +11 -17
  229. package/dist/timeline/timeline.js +24 -9
  230. package/dist/tool-gate.d.ts +73 -46
  231. package/dist/tool-gate.js +133 -66
  232. package/dist/tool-keys.d.ts +4 -1
  233. package/dist/tool-keys.js +8 -3
  234. package/dist/tool-list.d.ts +26 -0
  235. package/dist/tool-list.js +43 -0
  236. package/dist/tool-names.d.ts +71 -0
  237. package/dist/tool-names.js +99 -0
  238. package/dist/tool-plane.d.ts +29 -27
  239. package/dist/tool-plane.js +65 -37
  240. package/dist/tools.d.ts +22 -6
  241. package/dist/tools.js +24 -20
  242. package/dist/validate.d.ts +15 -7
  243. package/dist/validate.js +91 -44
  244. package/dist/web-fetch.d.ts +1 -7
  245. package/dist/web-fetch.js +2 -22
  246. package/dist/workspace/computer-deps.d.ts +3 -0
  247. package/dist/workspace/computer-deps.js +5 -2
  248. package/dist/workspace/computer-for-claim.d.ts +6 -0
  249. package/dist/workspace/computer-for-claim.js +32 -14
  250. package/dist/workspace/computer-hold.js +7 -1
  251. package/dist/workspace/computer-script.d.ts +23 -7
  252. package/dist/workspace/computer-script.js +48 -14
  253. package/dist/workspace/index.d.ts +2 -2
  254. package/dist/workspace/index.js +1 -1
  255. package/dist/workspace/kind-skills/desktop/SKILL.md +13 -0
  256. package/dist/workspace/kind-skills/phone/SKILL.md +4 -0
  257. package/dist/workspace/local.js +2 -2
  258. package/dist/workspace/resolve-computer.d.ts +21 -1
  259. package/dist/workspace/resolve-computer.js +32 -14
  260. package/dist/workspace/run-tools.d.ts +28 -10
  261. package/dist/workspace/run-tools.js +39 -11
  262. package/dist/{tool-budget.d.ts → wrap-up.d.ts} +1 -18
  263. package/dist/wrap-up.js +21 -0
  264. package/launcher/agentrun-serve +4 -2
  265. package/package.json +9 -9
  266. package/templates/README.md +111 -45
  267. package/templates/code-review/agent.md +30 -14
  268. package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
  269. package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
  270. package/templates/code-review/evals/injection/case.yaml +2 -1
  271. package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
  272. package/templates/code-review/evals/mentions-defused/case.yaml +2 -2
  273. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
  274. package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
  275. package/templates/code-review/evals/never-flag/case.yaml +2 -1
  276. package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
  277. package/templates/code-review/evals/null-name/case.yaml +2 -1
  278. package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
  279. package/templates/code-review/evals/off-by-one/case.yaml +2 -1
  280. package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
  281. package/templates/code-review/evals/other-repo/case.yaml +16 -0
  282. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
  283. package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
  284. package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
  285. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
  286. package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
  287. package/templates/code-review/evals/other-repo/prompt.md +10 -0
  288. package/templates/code-review/evals/re-review/case.yaml +2 -1
  289. package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
  290. package/templates/code-review/evals/re-review-open/case.yaml +2 -1
  291. package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
  292. package/templates/code-review/evals/repo-rule/case.yaml +2 -1
  293. package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
  294. package/templates/code-review/evals/two-defects/case.yaml +2 -1
  295. package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
  296. package/templates/code-review/rules/CODEREVIEW.md +1 -1
  297. package/templates/code-review/skills/review/DEEP.md +3 -2
  298. package/templates/code-review/skills/review/REVIEWER.md +3 -2
  299. package/templates/code-review/skills/review/SKILL.md +4 -3
  300. package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
  301. package/templates/inbound-lead/agent.md +26 -16
  302. package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
  303. package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
  304. package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
  305. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
  306. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
  307. package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
  308. package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
  309. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
  310. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
  311. package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
  312. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
  313. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
  314. package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
  315. package/templates/kyb/agent.md +15 -5
  316. package/templates/kyb/evals/adverse-media/prompt.md +2 -7
  317. package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
  318. package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
  319. package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
  320. package/templates/kyb/evals/name-collision/prompt.md +2 -6
  321. package/templates/kyb/evals/no-invention/prompt.md +2 -6
  322. package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
  323. package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
  324. package/templates/kyb/kyb.schema.json +8 -7
  325. package/templates/kyb/skills/kyb/SKILL.md +9 -6
  326. package/templates/market-monitor/agent.md +19 -12
  327. package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
  328. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
  329. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
  330. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
  331. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  332. package/templates/release-notes/agent.md +32 -10
  333. package/templates/release-notes/evals/draft-not-publish/case.yaml +4 -3
  334. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
  335. package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
  336. package/templates/release-notes/evals/issue-write-refused/case.yaml +4 -3
  337. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
  338. package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
  339. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
  340. package/templates/release-notes/evals/learned-style/case.yaml +2 -1
  341. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
  342. package/templates/release-notes/evals/other-repo/case.yaml +24 -0
  343. package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
  344. package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
  345. package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
  346. package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
  347. package/templates/release-notes/evals/other-repo/prompt.md +32 -0
  348. package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
  349. package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
  350. package/templates/release-notes/notes.schema.json +1 -1
  351. package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
  352. package/dist/console/assets/index-Cn6JX1uH.js +0 -563
  353. package/dist/console/assets/index-DRN62V5v.css +0 -1
  354. package/dist/tool-blurbs.d.ts +0 -4
  355. package/dist/tool-blurbs.js +0 -28
  356. package/dist/tool-budget.js +0 -62
  357. package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
  358. package/templates/code-review/evals/injection/graders/schema.md +0 -5
  359. package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
  360. package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
  361. package/templates/code-review/evals/null-name/graders/schema.md +0 -5
  362. package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
  363. package/templates/code-review/evals/re-review/graders/schema.md +0 -5
  364. package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
  365. package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
  366. package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
  367. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
  368. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
  369. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
  370. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
  371. package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
  372. package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
  373. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
  374. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
  375. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
  376. package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
  377. package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
  378. package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
  379. package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
  380. package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
  381. package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
  382. package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
  383. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
  384. package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
  385. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
  386. package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
  387. package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
  388. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
  389. package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
  390. package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
  391. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
  392. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
  393. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
  394. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
  395. package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
  396. package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
  397. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
  398. package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
  399. package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
@@ -3,20 +3,35 @@ import { createModels } from "@earendil-works/pi-ai/models";
3
3
  import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
4
4
  import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
5
5
  import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
- import { CAP_WRAPUP, endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
6
+ import { turnEndedOnAsk } from "../store-reads/journal.js";
7
+ import { CAP_WRAPUP, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
7
8
  import { raiseFollowUpId } from "../run-view.js";
8
9
  import { durableWait } from "../workflow/pi-versions.js";
9
10
  /** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
10
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
11
12
  * on its end (a fresh reopen). */
12
13
  const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
14
+ /** A learned workflow's handback is the server's message to the agent, never the person's. */
15
+ const HANDED_BACK_ORIGIN = { kind: "server", reason: "handed_back" };
13
16
  /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
14
17
  const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
18
+ /** The output contract's one retry turn is the server's message too, under one request id per run: pi places it once from
19
+ * its submission, a CLI's record writes it once, and a claim that finds it on the record never asks again. */
20
+ const OUTPUT_RETRY_ORIGIN = { kind: "server", reason: "output_retry" };
21
+ const OUTPUT_RETRY_REQUEST = "agentrun:output-retry";
22
+ /** Whether the run had its one retry: the input entry the retry wrote (pi's submission, a CLI's record) with the model's
23
+ * answer after it. One written and never answered (a runner lost between a CLI's record and its send) is not had: the
24
+ * claim that opens the session again sends it, under the same request id, so it is written once. */
25
+ const outputRetried = (entries) => {
26
+ const at = entries.findLastIndex((entry) => entry.kind === KINDS.input && originOf(entry.data?.origin)?.reason === OUTPUT_RETRY_ORIGIN.reason);
27
+ return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
+ };
15
29
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
16
30
  import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
17
31
  import { ADAPTER_API } from "../turn-end.js";
18
32
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
19
- import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
33
+ import { approvalOf, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
34
+ import { outputMiss, outputRetryWords } from "../answer-json.js";
20
35
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
21
36
  import { isComputerCommand, journalHold } from "./computer-journal.js";
22
37
  import { isHeldCommand, journalHeld } from "./held-run.js";
@@ -26,15 +41,21 @@ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
26
41
  import { channelCallOf, runChannelCall } from "./computer-channel.js";
27
42
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
28
43
  import { journalSessions } from "./sessions.js";
29
- import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, previousAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
44
+ import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, recentAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
30
45
  import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
31
46
  import { bookedIn } from "../paid-calls.js";
32
47
  import { withHostCalls } from "../host-calls.js";
33
48
  import { sideEffect } from "./side-effects.js";
34
49
  import { McpClaimRefused } from "./mcp-claim.js";
50
+ import { CODEMODE, defersCatalog, isCatalogName, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
51
+ import { metaTools } from "./meta-tools.js";
52
+ import { builtinHarness } from "../harness-table.js";
35
53
  import { Fenced } from "../store/index.js";
36
- import { parkedFollowUp } from "./mcp-run.js";
37
- import { budgetOf, reserveFor, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
54
+ import { answerAsServed } from "../answer-json.js";
55
+ import { reserveFor, WRAP_UP_TEXT, wrappingUp } from "../wrap-up.js";
56
+ import { LEARNED_CLIP, LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
57
+ import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
58
+ import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
38
59
  /** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
39
60
  * and the harness's next call runs it. */
40
61
  export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
@@ -42,6 +63,34 @@ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool
42
63
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
43
64
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
44
65
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
66
+ /** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
67
+ const TURN_CUT_AT_QUESTION = "the turn ended at its question to the person";
68
+ function turnCut() {
69
+ let armedAt;
70
+ let ask;
71
+ let asked = new Promise((resolve) => (ask = resolve));
72
+ const held = [];
73
+ return {
74
+ arm: (callId) => void (armedAt = callId),
75
+ disarm: () => void (armedAt = undefined),
76
+ get armed() {
77
+ return armedAt !== undefined;
78
+ },
79
+ hold() {
80
+ ask();
81
+ return new Promise((_, reject) => held.push(reject));
82
+ },
83
+ get asked() {
84
+ return asked;
85
+ },
86
+ done() {
87
+ armedAt = undefined;
88
+ for (const reject of held.splice(0))
89
+ reject(new Error(TURN_CUT_AT_QUESTION));
90
+ asked = new Promise((resolve) => (ask = resolve));
91
+ },
92
+ };
93
+ }
45
94
  /** A HostLifecycle and the ToolHost members that fill it: what a spec's ToolHost takes, and hands the loop. */
46
95
  export function hostLifecycle() {
47
96
  const onConversation = [];
@@ -120,6 +169,21 @@ const cliErrorAnswer = (harness, error, at) => ({
120
169
  timestamp: at,
121
170
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
122
171
  });
172
+ /** The session's recent requests as its newest KINDS.capRecent record kept them: each that reads as one (a model, and each
173
+ * figure a finite number of 0 or more); none without a record. One that does not read is left out: a request is then
174
+ * priced from another or uncached, never under its worst. */
175
+ export function recentIn(records) {
176
+ const kept = records.findLast((record) => record.kind === KINDS.capRecent)?.data;
177
+ if (!Array.isArray(kept))
178
+ return [];
179
+ const figure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
180
+ return kept.flatMap((data) => {
181
+ const one = (data ?? {});
182
+ if (typeof one !== "object" || typeof one.model !== "string" || !figure(one.cachedTokens) || !figure(one.inputTokens) || !figure(one.boundTokens) || !figure(one.endedAt))
183
+ return [];
184
+ return [{ model: one.model, cachedTokens: one.cachedTokens, inputTokens: one.inputTokens, boundTokens: one.boundTokens, endedAt: one.endedAt, ...(typeof one.counted === "boolean" ? { counted: one.counted } : {}) }];
185
+ });
186
+ }
123
187
  /** The turns a session's records booked (its runner.turn records), in order. */
124
188
  export function turnsOf(records) {
125
189
  return records.filter((record) => record.kind === RUNNER_RECORDS.turn).map((record) => record.data.turn).filter((turn) => typeof turn === "number");
@@ -168,8 +232,9 @@ const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forG
168
232
  /** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
169
233
  * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
170
234
  * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
171
- * message's timestamp: the Timeline dates its rows by them. */
172
- async function openCliRecord(harness, journal, context, now, cwd) {
235
+ * message's timestamp: the Timeline dates its rows by them. `endsItsCalls`: a harness that says each call's end itself
236
+ * (pi, of the calls its tools nest: it reruns a replay-safe one a crash cut), so none is ended interrupted here. */
237
+ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls = false) {
173
238
  const root = await harness.root(context);
174
239
  const append = async (kind, data) => {
175
240
  await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
@@ -182,6 +247,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
182
247
  await tx.appendEntry(root.id, { kind: KINDS.turnStart, data: { at: now() } });
183
248
  }, context);
184
249
  turnsOpen += 1;
250
+ lastAsked = undefined;
185
251
  };
186
252
  // Each call started on the record: whether it has its end; and each end, by call id.
187
253
  const started = new Map();
@@ -190,6 +256,8 @@ async function openCliRecord(harness, journal, context, now, cwd) {
190
256
  // is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
191
257
  const parked = new Set();
192
258
  const sent = new Set();
259
+ // A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
260
+ const nesting = new Set();
193
261
  // The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
194
262
  const sending = new Set();
195
263
  let personWritten = false;
@@ -198,18 +266,29 @@ async function openCliRecord(harness, journal, context, now, cwd) {
198
266
  // The request ids of the follow-ups written (followUp): each is written once.
199
267
  const followUps = new Set();
200
268
  // Each end-of-run turn's prompt the record wrote as it asked the turn, by its request id: a turn asked again (a later
201
- // claim, after a crash in the turn) reuses it, never writes a second.
269
+ // claim, after a crash in the turn) reuses it, never writes a second. And what each kept as it was first asked.
202
270
  const askedAt = new Map();
271
+ const askedKept = new Map();
272
+ // The end-of-run turn asked last, while no turn of the job's (its input, a message, a follow-up) opened after it.
273
+ let lastAsked;
203
274
  for (const entry of await entriesOf(journal, root.id, context)) {
204
275
  const data = (entry.data ?? {});
205
276
  if (entry.kind === KINDS.messageSending && typeof data.commandId === "number")
206
277
  sending.add(data.commandId);
207
- if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string")
278
+ if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string") {
208
279
  askedAt.set(data.requestId, entry.id);
280
+ lastAsked = data.requestId;
281
+ if (data.kept && typeof data.kept === "object" && !Array.isArray(data.kept))
282
+ askedKept.set(data.requestId, data.kept);
283
+ }
284
+ if (entry.kind === KINDS.turnStart || (entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
285
+ lastAsked = undefined;
209
286
  if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
210
287
  ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
211
288
  if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.parked === true)
212
289
  parked.add(data.callId);
290
+ if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.nests === true)
291
+ nesting.add(data.callId);
213
292
  if (entry.kind === KINDS.callSent && typeof data.callId === "string")
214
293
  sent.add(data.callId);
215
294
  if (entry.kind === KINDS.callStart && typeof data.callId === "string")
@@ -226,7 +305,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
226
305
  followUps.add(data.requestId);
227
306
  }
228
307
  for (const [callId, ended] of started) {
229
- if (ended || (parked.has(callId) && !sent.has(callId)))
308
+ if (endsItsCalls || ended || (parked.has(callId) && !sent.has(callId)) || nesting.has(callId))
230
309
  continue;
231
310
  await append(KINDS.callEnd, { callId, status: "interrupted" });
232
311
  started.set(callId, true);
@@ -280,6 +359,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
280
359
  await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
281
360
  else
282
361
  await append(KINDS.message, { role: "person", text: input });
362
+ lastAsked = undefined;
283
363
  personWritten = true;
284
364
  }),
285
365
  input: (input, origin, opens = true) => inTurn(async () => {
@@ -290,6 +370,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
290
370
  await startsTurn({ entry });
291
371
  else
292
372
  await harness.commit((tx) => tx.appendEntry(root.id, entry), context);
373
+ lastAsked = undefined;
293
374
  personWritten = true;
294
375
  }),
295
376
  followUp: (input, requestId, origin) => inTurn(async () => {
@@ -327,7 +408,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
327
408
  });
328
409
  return again;
329
410
  },
330
- async start(callId, tool, input, replaySafe) {
411
+ async start(callId, tool, input, replaySafe, nests) {
331
412
  await flushText();
332
413
  await inTurn(async () => {
333
414
  if (started.has(callId)) {
@@ -338,16 +419,16 @@ async function openCliRecord(harness, journal, context, now, cwd) {
338
419
  }
339
420
  return;
340
421
  }
341
- await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
422
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...(cwd ? { cwd } : {}) });
342
423
  started.set(callId, false);
343
424
  });
344
425
  },
345
- async park(callId, tool, input, replaySafe, bridge) {
426
+ async park(callId, tool, input, replaySafe) {
346
427
  await flushText();
347
428
  await inTurn(async () => {
348
429
  if (started.has(callId))
349
430
  return;
350
- await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(bridge ? { bridge } : {}), ...(cwd ? { cwd } : {}) });
431
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(cwd ? { cwd } : {}) });
351
432
  started.set(callId, false);
352
433
  parked.add(callId);
353
434
  });
@@ -382,18 +463,29 @@ async function openCliRecord(harness, journal, context, now, cwd) {
382
463
  started.set(callId, true);
383
464
  ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
384
465
  }),
385
- answering: (requestId, prompt) => {
466
+ answering: async (requestId, prompt, keep) => {
386
467
  answer = "";
387
- return inTurn(async () => {
468
+ await inTurn(async () => {
388
469
  if (askedAt.has(requestId))
389
470
  return;
390
471
  await harness.commit(async (tx) => {
391
472
  if (await tx.submissionByRequest(root.id, requestId))
392
473
  return;
393
- const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
474
+ // What the step keeps as the turn is first asked, with its prompt: durable before the turn's first request leaves
475
+ // (that request's flush), so a later claim that asks the turn again reads the first ask's, never its own.
476
+ const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId, ...(keep ? { kept: keep } : {}) }, model: [{ role: "user", content: prompt, timestamp: now() }] });
394
477
  askedAt.set(requestId, asked.id);
478
+ lastAsked = requestId;
479
+ if (keep)
480
+ askedKept.set(requestId, keep);
395
481
  }, context);
396
482
  });
483
+ return askedKept.get(requestId);
484
+ },
485
+ keptOf: (requestId) => askedKept.get(requestId),
486
+ async lookingBack() {
487
+ const requestId = lastAsked;
488
+ return requestId !== undefined && !(await harness.commit((tx) => tx.submissionByRequest(root.id, requestId), context));
397
489
  },
398
490
  answered: (requestId, prompt, status) => inTurn(async () => {
399
491
  const said = answer ?? "";
@@ -511,6 +603,10 @@ function adapterLoop(specOf, options, deps) {
511
603
  * Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
512
604
  * the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
513
605
  let reopen;
606
+ /** A grade's feedback round this claim closes (runner/feedback-round.ts): the run opened again on a grade's words (its
607
+ * steer, taken with a FEEDBACK entry and never sent as a turn), or a claim that finds such an entry with no end after it.
608
+ * The agent is asked no turn of the job's: the run goes to its end-of-run turn, told the grade first (feedbackAsk). */
609
+ let feedbackNow;
514
610
  /** A reopen of a run whose session is still new (a person stopped it before its first input was sent): resolved once the
515
611
  * person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
516
612
  * late the runner hands the message over. */
@@ -525,6 +621,9 @@ function adapterLoop(specOf, options, deps) {
525
621
  let waitHolds = [];
526
622
  /** The wait's own `reopen`, while it is set. */
527
623
  let waitTurn;
624
+ /** The `reopen` of a CLI run parked on its question (its turn cut there: no steer reaches its idle session), while it is
625
+ * set: the person's answer is the claim's turn, and a trigger's message is no answer. */
626
+ let askReopen;
528
627
  /** A person's message placed as a steer while the session was idle and no wait took it (its turn tracked by no one): the
529
628
  * answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
530
629
  * answer (waitInClaim), once. */
@@ -542,6 +641,14 @@ function adapterLoop(specOf, options, deps) {
542
641
  /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
543
642
  * during the end-of-run turn does. */
544
643
  let turnsOver = false;
644
+ /** While the run's learned workflow runs first (AdapterRunSpec.workflowFirst): a message waits for it, then goes the way
645
+ * any message goes once the workflow answered (the run is ending) or handed the job back (the agent's turn runs). */
646
+ let servingFirst;
647
+ /** The messages waiting for the run's first input (steer: the session still new, or its learned workflow running first),
648
+ * placed one after another, in the order they came, once it is sent; `waitingFirst` counts those not placed yet, so a
649
+ * message after them waits its turn behind them. */
650
+ let afterFirst = Promise.resolve();
651
+ let waitingFirst = 0;
545
652
  /** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
546
653
  * only while it is that wait's (a wait that settles late never ends a later one). */
547
654
  const endWait = (of) => {
@@ -561,6 +668,10 @@ function adapterLoop(specOf, options, deps) {
561
668
  };
562
669
  /** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
563
670
  let cliRecord;
671
+ /** A CLI's turn cut at its question to the person (TurnCut): armed by the call's end, asked for by the next request. */
672
+ const askCut = turnCut();
673
+ /** Whether this loop sent the run its output retry (sendOutputRetry): never a second, even when its turn gave no answer. */
674
+ let outputRetrySent = false;
564
675
  /** The session's paid requests admitted and not yet booked (its model port's beforeRequest, then its afterRequest), and
565
676
  * who waits for none: the run's end waits for them, since a booking written after the end (the run's release) is
566
677
  * fenced and lost, and its request read back at its hold. */
@@ -817,13 +928,36 @@ function adapterLoop(specOf, options, deps) {
817
928
  if (data.capUsd > 0)
818
929
  raisedCapUsd = data.capUsd;
819
930
  }
931
+ const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
820
932
  const steer = async (command) => {
821
933
  // Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
822
934
  // Awaited even with a session there: until the claim is ready it has not said whether this message reopens the run.
823
- const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
824
935
  await Promise.race([ready, over()]);
825
936
  // The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
826
937
  // untaken for the next claim, which hands it on again; never refused for good.
938
+ if (!gate || !session || gate.sealed)
939
+ return { later: "the run is parking: the steer waits for its resume" };
940
+ // The session is still new and this is no reopen's message (the claim has yet to send the run's input), or the run's
941
+ // learned workflow runs first, or a message before it still waits for either: it waits for the input, off the runner's
942
+ // delivery, as a computer channel's call does (channelCommand). The runner hands the run's rows on one at a time, each
943
+ // once the one before it answered: held here for a workflow that runs long, this message would hold every row after it,
944
+ // and a person's stop or cancel (the stop that cuts the workflow's call, its spend and custody), a raise or a hand-back
945
+ // would never reach the run. `taken` here means its take rides on the commit that places it once the input is sent; a
946
+ // claim that ends first (a stop, a park, the workflow's answer) leaves the row untaken, for the run's end or its next
947
+ // claim to settle, as any message the run's end finds untaken.
948
+ if (waitingFirst > 0 || (!reopen && session.state === "new") || servingFirst) {
949
+ waitingFirst += 1;
950
+ const placing = afterFirst.then(() => placeSteer(command));
951
+ afterFirst = placing.then(() => void (waitingFirst -= 1), (error) => {
952
+ waitingFirst -= 1;
953
+ console.warn(`[runner] a message that waited for the run's first input was not placed: ${said(error)}`);
954
+ });
955
+ return { taken: true };
956
+ }
957
+ return placeSteer(command);
958
+ };
959
+ /** A person's message placed (steer): as the run's next turn, into the turn in flight, or after it. */
960
+ const placeSteer = async (command) => {
827
961
  if (!gate || !session || gate.sealed)
828
962
  return { later: "the run is parking: the steer waits for its resume" };
829
963
  // The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
@@ -834,6 +968,11 @@ function adapterLoop(specOf, options, deps) {
834
968
  if (!gate || !session || gate.sealed)
835
969
  return { later: "the run is parking: the steer waits for its resume" };
836
970
  }
971
+ // The run's learned workflow is running first: nothing is sent to the agent until it answered or handed the job back.
972
+ if (servingFirst)
973
+ await servingFirst;
974
+ if (!gate || !session || gate.sealed)
975
+ return { later: "the run is parking: the steer waits for its resume" };
837
976
  // The run's job has answered and it is looking back before its end: a person's message is not the end-of-run turn's
838
977
  // to answer. Left untaken, the run's end opens a completed run again with it as a new turn (store run-patch.ts
839
978
  // refuseLeftovers).
@@ -850,15 +989,40 @@ function adapterLoop(specOf, options, deps) {
850
989
  // first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
851
990
  // between that choice and the message's placing.
852
991
  const reopenedBefore = reopen;
853
- const endedOnAsk = session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
992
+ const endedOnAsk = session.state === "idle" && root !== undefined && turnEndedOnAsk((await entriesOf(gate.journal, root.id, context))) !== undefined;
854
993
  const askedLast = !reopenedBefore && endedOnAsk;
994
+ // A reopen of a run its learned workflow answered alone (its session new: the agent never took the job): what the
995
+ // workflow answered, said to the agent between the job and the message, which is a word on that answer.
996
+ const servedAnswer = reopen && !reopen.sent && session.state === "new" && root !== undefined ? servedAnswerOf(await entriesOf(gate.journal, root.id, context)) : undefined;
855
997
  if (!gate || !session || gate.sealed)
856
998
  return { later: "the run is parking: the steer waits for its resume" };
857
999
  // A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
858
- // between the question's turn end and that wait): never the wait's answer, never placed, refused in the words the
859
- // server refuses one with while the run waits (runs-over-store.ts WAITS_ON_A_PERSON).
860
- if (followUp && (askedLast || (reopen !== undefined && reopen === waitTurn)))
861
- return { refused: "The run is waiting on a person." };
1000
+ // between the question's turn end and that wait): never the wait's answer, never placed now. Its firing reads sent (the
1001
+ // door took the row), so it is never refused either: left untaken, it runs as a turn of its own after the person's
1002
+ // answer, as a parked run's does (the store's park takes no wake from it; the run's end opens the run again with it).
1003
+ if (followUp && (askedLast || (reopen !== undefined && (reopen === waitTurn || reopen === askReopen))))
1004
+ return { later: "the run is waiting on a person: the message runs as a turn of its own after the answer" };
1005
+ // A grade's feedback round (feedback-round.ts): the run opened again on the grade's words, which are never a turn of
1006
+ // the job's. Kept on the root as a FEEDBACK entry, whose commit takes the row; the claim goes to its end-of-run turn.
1007
+ const fed = reopen && !reopen.sent && (session.state === "idle" || session.state === "new") ? feedbackOf(command.body) : undefined;
1008
+ if (fed && reopen && harness && root) {
1009
+ const [on, theRoot, mine] = [harness, root, reopen];
1010
+ const taken = gate.expect(writesEntry(KINDS.feedback, (data) => data.requestId === requestId), { take: [command.id] });
1011
+ taken.catch(() => undefined);
1012
+ mine.feedback = fed;
1013
+ mine.sent = on.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.feedback, data: { ...fed, requestId, at: now() } }), context).then(() => undefined);
1014
+ mine.placed?.();
1015
+ try {
1016
+ await mine.sent;
1017
+ }
1018
+ catch (error) {
1019
+ if (gate.sealed)
1020
+ return { later: "the run is parking: the feedback waits for its resume" };
1021
+ return { refused: `the feedback was not kept: ${error.message}` };
1022
+ }
1023
+ await taken.catch(() => { });
1024
+ return { taken: true };
1025
+ }
862
1026
  // A reopened run's follow-up, its session idle: sent as a turn of its own, tracked to its end (as the input and a raise's
863
1027
  // follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
864
1028
  if (reopen && !reopen.sent && (session.state === "idle" || session.state === "new")) {
@@ -872,7 +1036,10 @@ function adapterLoop(specOf, options, deps) {
872
1036
  // never sent, or answered, as a turn of its own.
873
1037
  const first = theSession.state === "new" ? specNow : undefined;
874
1038
  const sendId = first ? INPUT_REQUEST : requestId;
875
- const content = first ? `${first.input}\n\n${text}` : text;
1039
+ // A run its learned workflow answered alone: the job, what the workflow answered (cut of the runner's secrets, as a
1040
+ // handback is), then the message.
1041
+ const answered = first && servedAnswer ? servedAnswerText(servedAnswer.workflow, deps.redact ? deps.redact(servedAnswer.answer) : servedAnswer.answer) : undefined;
1042
+ const content = first ? [first.input, ...(answered ? [answered] : []), text].join("\n\n") : text;
876
1043
  // The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
877
1044
  // writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
878
1045
  // row. A runner lost between the send and that entry leaves the row untaken, so the next claim sends it again: a
@@ -974,6 +1141,19 @@ function adapterLoop(specOf, options, deps) {
974
1141
  await cliRecord?.message(next.text, next.origin);
975
1142
  return session.turnEnd();
976
1143
  };
1144
+ /** The output contract's one retry (AdapterRunSpec.outputSchema): the server's message saying why the answer missed the
1145
+ * schema, sent as a turn of its own on the same session, its requests admitted and booked by the run's one cap as any
1146
+ * turn's. A CLI's record writes it first (once, under its request id); pi's submission carries its origin and is placed
1147
+ * once under that id. Sent at most once by this loop (outputRetrySent), and by a later claim only when the record has
1148
+ * it unanswered (outputRetried). Its turn's end is what this gives. */
1149
+ const sendOutputRetry = async (why) => {
1150
+ outputRetrySent = true;
1151
+ const text = outputRetryWords(deps.redact ? deps.redact(why) : why);
1152
+ await cliRecord?.followUp(text, OUTPUT_RETRY_REQUEST, OUTPUT_RETRY_ORIGIN);
1153
+ await session.send(text, { id: OUTPUT_RETRY_REQUEST, origin: OUTPUT_RETRY_ORIGIN });
1154
+ await specNow?.hooks?.afterMessageSent?.();
1155
+ return session.turnEnd();
1156
+ };
977
1157
  async function run(claim) {
978
1158
  context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
979
1159
  // Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
@@ -1031,25 +1211,33 @@ function adapterLoop(specOf, options, deps) {
1031
1211
  // What was spent beside them on the run's behalf (its spec's runCap.beside) is read with them at each admission
1032
1212
  // (runBooking), the spec's once it is known.
1033
1213
  const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
1034
- const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush() }), { beside: besideNow });
1214
+ const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush(), claim }), { beside: besideNow });
1035
1215
  let capBuilt;
1036
- /** The session's previous request, as the cap's `expected` pricing reads it (the kernel's Previous): the last of the
1037
- * harness's own requests on this claim that answered, its input as its usage reported it (read from or written to
1038
- * the cache, and the rest) and its input bound, and when it ended. None before one has: priced as a cache miss. */
1039
- let previous;
1216
+ /** The session's recent requests, as the cap's `expected` pricing reads them (the kernel's recentAfter and
1217
+ * warmFrom): the harness's own requests that answered under CACHE_WARM_MS ago, each one's input as its usage
1218
+ * reported it (read from or written to the cache, and the rest), its input bound and when it ended. Kept on the
1219
+ * session (KINDS.capRecent), so a new claim after an approval, a deny or a park starts from them (seeded below,
1220
+ * once the session's records are read), and its first request is warm or cold by when they ended, as within a
1221
+ * claim. None before one has: a cache miss. */
1222
+ let recent = [];
1223
+ /** What the run keeps back beside a request of its own session while it streams (RunCapOptions.keepBackUsd), set
1224
+ * once the wrap-up's reserve is known (below): a tool call it makes mid-stream finds room for the steps after it. */
1225
+ let keepBackOf;
1040
1226
  /** Each of this claim's requests as the cap was asked about it, by its turn, until it ends. */
1041
1227
  const askedFor = new Map();
1042
1228
  const theCap = () => {
1043
1229
  if (!specNow?.runCap)
1044
1230
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
1045
1231
  // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
1046
- // Its previous request is the session's own (requestEnded), unless the spec names one (a test's warm cache).
1232
+ // Its recent requests are the session's own (requestEnded), unless the spec names them (a test's warm cache).
1047
1233
  const { beside: _beside, ...config } = specNow.runCap;
1048
- return (capBuilt ??= runCap({ sessions, previousOf: (model) => (previous?.model === model ? previous : undefined), ...config, capUsd: capNow }));
1234
+ return (capBuilt ??= runCap({ sessions, recentOf: (model) => recent.filter((one) => one.model === model), keepBackUsd: (request, asked) => keepBackOf?.(request, asked), ...config, capUsd: capNow }));
1049
1235
  };
1050
1236
  /** A request of this claim ended (`request_end`): one of the harness's own (no host label, no side call) that
1051
- * answered with its input reported is the session's previous request from now. */
1052
- const requestEnded = (turn, usage, how) => {
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) => {
1053
1241
  const asked = askedFor.get(turn);
1054
1242
  askedFor.delete(turn);
1055
1243
  if (!asked?.own || asked.bound === undefined || usage.cut || (how !== undefined && how.end !== "answered"))
@@ -1057,9 +1245,11 @@ function adapterLoop(specOf, options, deps) {
1057
1245
  const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1058
1246
  if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
1059
1247
  return;
1060
- // A smaller request than the previous on the same model is a compaction or another conversation's (a child of the
1061
- // run, whose requests the proxy cannot tell from the root's): history resets (previousAfter), never sticks.
1062
- previous = previousAfter(previous, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
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);
1063
1253
  };
1064
1254
  const flushed = { flush: () => deps.flush() };
1065
1255
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -1246,11 +1436,13 @@ function adapterLoop(specOf, options, deps) {
1246
1436
  return { ...pending, refuse: text, figures };
1247
1437
  };
1248
1438
  const beforeRequest = async (request) => {
1249
- // Kept until it ends, so its answer can be the session's previous request (requestEnded).
1250
- askedFor.set(request.turn, { model: request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
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 });
1251
1442
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
1252
- // whatever else would pause it (a paid call's refusal, pendingPause).
1253
- const over = await overCap();
1443
+ // whatever else would pause it (a paid call's refusal, pendingPause). One a paid call stopped for good
1444
+ // (paid-calls.ts stopRun) ends in that call's words, which say why, past its cap too.
1445
+ const over = pendingPause?.forGood ? undefined : await overCap();
1254
1446
  if (!over && pendingPause) {
1255
1447
  pendingPause = await landing(pendingPause);
1256
1448
  // Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
@@ -1350,6 +1542,9 @@ function adapterLoop(specOf, options, deps) {
1350
1542
  // them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
1351
1543
  // (booked at its hold and bound, the worst case), one never sent, given back, owed or stopped.
1352
1544
  const claimRecords = await writer.read();
1545
+ // The recent requests an earlier claim or pass kept (KINDS.capRecent): this claim's first request is priced from
1546
+ // them, warm or cold by when they ended, never as if the session had no history.
1547
+ recent = recentIn(claimRecords);
1353
1548
  const claimHosts = sessionSpendOf(claimRecords).hosts;
1354
1549
  /** The turns of requests that are no main-model request of the harness's own: read from the records, then each
1355
1550
  * admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
@@ -1369,16 +1564,31 @@ function adapterLoop(specOf, options, deps) {
1369
1564
  }),
1370
1565
  restUsd: await restOf(),
1371
1566
  };
1567
+ /** A main-model request as the run's cap prices it at admission (RunCap.asked: its model and the session's previous
1568
+ * request, so its input reads the cache that request left warm), for the wrap-up's note and what the run keeps back
1569
+ * to answer. A request the note takes is measured as its client sent it (NoteRequest), by its bytes. */
1570
+ const pricedOf = (model, asked) => theCap().asked({ ...asked, model });
1372
1571
  /** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
1373
1572
  const figuresOf = (model, asked) => {
1374
1573
  const config = specNow?.runCap;
1375
- const capModel = config?.modelOf(model);
1376
- if (!config || !capModel)
1574
+ if (!config?.modelOf(model))
1377
1575
  return undefined;
1378
- return requestFigures({ kind: "model", id: "reserve", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, config.mode ?? "expected", Date.now());
1576
+ return requestFigures(pricedOf(model, asked), config.mode ?? "expected", (config.now ?? Date.now)());
1379
1577
  };
1380
- /** What the run keeps back to answer (tool-budget.ts reserveFor), its typical step the run's own priced answers'. */
1578
+ /** What the run keeps back to answer (wrap-up.ts reserveFor), its typical step the run's own priced answers'. */
1381
1579
  const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
1580
+ // A CLI harness's request of the session's own (no side call, no host's, no unanswered one, no paid step) keeps
1581
+ // back that same reserve, priced on itself as the wrap-up's gate prices it once it is admitted
1582
+ // (capNote.lastFigures): admitted at an output whose worst case leaves it free, a tool call it makes while it
1583
+ // streams is not refused for the reserve (the kernel rule's keepUsd says when it cannot be kept, and why the cap
1584
+ // holds either way). A CLI may start a call with its response still open (Codex) or book its cost after its calls
1585
+ // (Claude Code); pi starts a tool once its response is complete, so its requests keep none back.
1586
+ keepBackOf = (request, asked) => {
1587
+ const config = specNow?.runCap;
1588
+ if (!config || spec.record !== "loop" || request.key !== spec.session.key || request.host !== undefined || request.side || request.unanswered || request.paid)
1589
+ return undefined;
1590
+ return reserveOf(requestFigures(asked, config.mode ?? "expected", (config.now ?? Date.now)()));
1591
+ };
1382
1592
  let bookingNow;
1383
1593
  const wrapUpNote = (model, asked) => {
1384
1594
  const config = specNow?.runCap;
@@ -1403,9 +1613,9 @@ function adapterLoop(specOf, options, deps) {
1403
1613
  // The tools' gate counts a request in flight at its hold and its bound (sessionSpendOf: a cache miss adds the bound),
1404
1614
  // so the note counts it the same: it never comes later than the gate's first refusal.
1405
1615
  const heldUsd = inFlight + (bookingNow?.boundUsd() ?? 0) + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
1406
- const due = noteFor({ kind: "model", id: "wrap-up", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: Date.now() });
1616
+ const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: (config.now ?? Date.now)() });
1407
1617
  // The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
1408
- // answer (tool-budget.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
1618
+ // answer (wrap-up.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
1409
1619
  // its own has not made it due before: told on the request whose tool call would be refused now, no later than the
1410
1620
  // first refusal. The rule's figure here is the run's spend and holds as they stand at this take, and this request's
1411
1621
  // own reserve. (The gate's reader, wrapUp, reads the records at each call and is async; a reading kept from an
@@ -1437,7 +1647,7 @@ function adapterLoop(specOf, options, deps) {
1437
1647
  if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
1438
1648
  capNote.costs.push(event.usage.usd);
1439
1649
  if (event.type === "request_end")
1440
- requestEnded(event.turn, event.usage, event.ended);
1650
+ await requestEnded(event.turn, event.usage, event.ended, writer);
1441
1651
  if (event.type === "request_start") {
1442
1652
  // A new request means the model's last message is over: what it said so far is on the record before the request,
1443
1653
  // so an answer shows while the turn goes on (a CLI that answers, then makes another request).
@@ -1479,7 +1689,7 @@ function adapterLoop(specOf, options, deps) {
1479
1689
  const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
1480
1690
  if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
1481
1691
  await paidOf();
1482
- // The cap's wrap-up (tool-budget.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1692
+ // The cap's wrap-up (wrap-up.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1483
1693
  // spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
1484
1694
  // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1485
1695
  // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
@@ -1523,11 +1733,19 @@ function adapterLoop(specOf, options, deps) {
1523
1733
  // bridge asks first; one refused is on the record from the gate, bridgeGate), so its record's start is written
1524
1734
  // here, before the flush and the call, and its end after.
1525
1735
  call: async (args, toolContext) => {
1736
+ // A tool that only nests calls (tools_call, codemode) has its row on a CLI's record as pi's does, its start marked
1737
+ // `nests`; each call it makes is on the record after it as its own tool's (its id `<callId>/<key>`). It runs again
1738
+ // whole after a crash, its recorded calls answered from their records, so its own end never answers it.
1739
+ const record = cliRecord;
1526
1740
  // A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
1527
1741
  // from that end, never run again.
1528
- const ended = record?.endOf(toolContext.callId);
1742
+ const ended = tool.nests ? undefined : record?.endOf(toolContext.callId);
1529
1743
  if (ended)
1530
1744
  return endedAnswer(tool.name, ended);
1745
+ // A run a paid call stopped for good (paid-calls.ts stopRun) runs no tool after it, a script's own calls
1746
+ // included: each is refused in the stop's words, never run.
1747
+ if (pendingPause?.forGood)
1748
+ return { text: pendingPause.refuse, isError: true };
1531
1749
  // A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
1532
1750
  // attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
1533
1751
  // set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
@@ -1547,7 +1765,7 @@ function adapterLoop(specOf, options, deps) {
1547
1765
  const bySetting = now === "allow" && (await askStands(toolContext.callId));
1548
1766
  if (now === "ask" || bySetting) {
1549
1767
  const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
1550
- const price = mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null;
1768
+ const price = mcp?.priceOf(name) ?? null;
1551
1769
  const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
1552
1770
  if (answer === "park")
1553
1771
  return await heldUntilAborted(toolContext.signal);
@@ -1559,8 +1777,11 @@ function adapterLoop(specOf, options, deps) {
1559
1777
  if (stopAbort.signal.aborted || toolContext.signal?.aborted)
1560
1778
  return { text: STOPPED_WHILE_WAITING, isError: true };
1561
1779
  }
1780
+ // Another call after a turn-ending one: the turn goes on (TurnCut).
1781
+ if (record)
1782
+ askCut.disarm();
1562
1783
  if (record)
1563
- await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
1784
+ await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe", tool.nests);
1564
1785
  try {
1565
1786
  const answer = await sideEffect({
1566
1787
  replaySafe: tool.replay === "safe",
@@ -1571,7 +1792,7 @@ function adapterLoop(specOf, options, deps) {
1571
1792
  // loop wrapped it, and whether a person approved this call.
1572
1793
  // The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
1573
1794
  // row's computer_calls, before its result is written.
1574
- route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped)))),
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)))),
1575
1796
  beforeResult: async (answer) => {
1576
1797
  const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
1577
1798
  try {
@@ -1587,6 +1808,12 @@ function adapterLoop(specOf, options, deps) {
1587
1808
  // A call a stop cut answers whatever its tool said of the abort: it ends interrupted, never as its outcome.
1588
1809
  if (record)
1589
1810
  await record.end(toolContext.callId, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
1811
+ // A CLI's question to the person (a turn-ending tool's call, answered): its turn is cut at its next request,
1812
+ // as pi's ends here (TurnCut). Any other call's end after it lets the turn go on.
1813
+ if (record && endsTurn(tool.name) && !answer.isError && !stopAbort.signal.aborted)
1814
+ askCut.arm(toolContext.callId);
1815
+ else if (record)
1816
+ askCut.disarm();
1590
1817
  return answer;
1591
1818
  }
1592
1819
  catch (error) {
@@ -1598,7 +1825,40 @@ function adapterLoop(specOf, options, deps) {
1598
1825
  }
1599
1826
  },
1600
1827
  });
1601
- const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1828
+ const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
1829
+ // tools_search, tools_call and codemode over the session's tools (meta-tools.ts), on every harness (codemode on
1830
+ // each but one that runs scripts of its own): what they call is called nested, each call asked about and recorded
1831
+ // as its own tool's. A search finds a tool whose setting is not deny; an MCP tool's setting is its catalog name's.
1832
+ const settingOf = spec.gate?.permission;
1833
+ // The harness's own tools beside them (pi's subagent, its browser's): found and called by name as the host's are,
1834
+ // run by the harness as its own nested calls. Never called here: a nested call reaches them through the harness.
1835
+ const native = (spec.adapter.ownTools ?? []).filter((one) => !own.some((tool) => tool.name === one.name)).map((one) => ({
1836
+ name: one.name,
1837
+ description: one.description,
1838
+ inputSchema: one.inputSchema,
1839
+ replay: "never",
1840
+ call: async () => ({ text: `${one.name} is run by the harness itself, as a nested call of tools_call or a script.`, isError: true }),
1841
+ }));
1842
+ // One discovery system (tool-deferral.ts): a run whose catalog tools pass DEFER_CATALOG_OVER does not list them; the
1843
+ // model finds them with tools_search and runs them with tools_call (still the tool's own call at the gate). Claude
1844
+ // Code defers them itself (its ToolSearch, on under the same test), so it is offered neither. Under the threshold
1845
+ // every tool is listed and there is no search or call. codemode is offered as it always was.
1846
+ const facts = builtinHarness(spec.adapter.id)?.facts;
1847
+ // A meta tool whose setting is deny is not offered at all, rather than offered and refused.
1848
+ const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
1849
+ // Deferred only when the model can both find and run what it hid: with either helper denied every tool stays listed,
1850
+ // so denying a helper never takes an otherwise allowed tool out of reach.
1851
+ // The one verdict for every harness: one with a tool search of its own (Claude Code's) follows it too, handed it as
1852
+ // `deferCatalog` below, and so lists every tool when either helper is set to deny.
1853
+ const deferred = defersCatalog(own.map((one) => one.name)) && (await allowed(TOOLS_SEARCH)) && (await allowed(TOOLS_CALL));
1854
+ const offered = deferred && !facts?.ownToolSearch;
1855
+ const metas = metaTools({
1856
+ tools: () => [...own, ...native],
1857
+ granted: async (name) => !settingOf || (await settingOf(mcp?.catalogOf(name) ?? name).catch(() => "deny")) !== "deny",
1858
+ codemode: facts?.ownCodemode !== true && (await allowed(CODEMODE)),
1859
+ discovery: { search: offered, call: offered },
1860
+ }).filter((meta) => ![...own, ...native].some((one) => one.name === meta.name));
1861
+ const tools = [...own.map((one) => (offered && isCatalogName(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
1602
1862
  // An MCP tool of the run by its catalog name, as wrapped above: what a learned workflow's MCP node calls.
1603
1863
  mcpHosted = (catalog) => {
1604
1864
  const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
@@ -1611,6 +1871,10 @@ function adapterLoop(specOf, options, deps) {
1611
1871
  unbooked = 0;
1612
1872
  const counted = {
1613
1873
  beforeRequest: async (request) => {
1874
+ // The CLI's next request of its main model after its question to the person: never admitted, it asks for the
1875
+ // turn's cut (TurnCut). Its side calls and the host's own requests go on.
1876
+ if (askCut.armed && !request.side && request.host === undefined)
1877
+ return askCut.hold();
1614
1878
  // A command row since the MCP credentials were made fresh: made fresh again before this request.
1615
1879
  if (mcpStale && mcp) {
1616
1880
  mcpStale = false;
@@ -1684,20 +1948,56 @@ function adapterLoop(specOf, options, deps) {
1684
1948
  // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
1685
1949
  // start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
1686
1950
  // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it). A call it asks
1687
- // about goes on the record first, its start marked parked (once per call id), as an MCP call parked at its door does,
1688
- // and marked the bridge's: the bridge hands the CLI nothing while it waits, so no waiting result shows, as on pi. Its
1689
- // row shows while it waits, before its approval; the claim that runs it once allowed writes its sent mark on that
1690
- // one start (start()), and a stop withdraws it never sent (unsentParked). A start refused because another call of the
1691
- // round parked the run first (the journal sealed) leaves this call held as that one is.
1951
+ // about goes on the record first, its start marked parked (once per call id): the bridge hands the CLI nothing while it
1952
+ // waits, so no waiting result shows, as on pi. Its row shows while it waits, before its approval; the claim that runs
1953
+ // it once allowed writes its sent mark on that one start (start()), and a stop withdraws it never sent
1954
+ // (unsentParked). A start refused because another call of the round parked the run first (the journal sealed) leaves
1955
+ // this call held as that one is.
1692
1956
  const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
1957
+ // A call a tool of pi's nests (a script's, tools_call's) is pi's own tool task, of which pi's record keeps no row: it
1958
+ // goes on the loop's record as a CLI's call does, so the Timeline shows it as its own call, and an ask for it beside
1959
+ // it. Its start at its gate (marked parked while it waits for a person; refused, with its end, in the gate's words),
1960
+ // its end once pi has its outcome (nestedEnded). The record opens at the claim's first such call, and never ends a
1961
+ // call itself: pi says each one's end, a replay-safe one a crash cut run again first (endsItsCalls).
1962
+ const [nestedOn, nestedJournal] = [harness, gate.journal];
1963
+ let nestedOpen;
1964
+ const nestedRecord = () => (nestedOpen ??= openCliRecord(nestedOn, nestedJournal, context, now, undefined, true));
1965
+ const unlessSealed = (error) => {
1966
+ if (!gate?.sealed)
1967
+ throw error;
1968
+ };
1969
+ const nestedAsking = preIntentGate(spec, hooks, wrapUp, async (call) => (await nestedRecord()).park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed));
1970
+ const nestedGate = async (call, hookContext) => {
1971
+ if (call.nested !== true)
1972
+ return gateOf(call, hookContext);
1973
+ const answer = await nestedAsking(call, hookContext);
1974
+ const nests = await nestedRecord();
1975
+ if (answer === "allow")
1976
+ await nests.start(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed);
1977
+ else if ("deny" in answer)
1978
+ await nests.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny).catch(unlessSealed);
1979
+ return answer;
1980
+ };
1981
+ const nestedEnded = async (callId, status, output) => (await nestedRecord()).end(callId, status, output).catch(unlessSealed);
1693
1982
  const askingGate = record
1694
- ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), true).catch((error) => {
1983
+ ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
1695
1984
  if (!gate?.sealed)
1696
1985
  throw error;
1697
1986
  }))
1698
1987
  : gateOf;
1699
1988
  const bridgeGate = record
1700
1989
  ? async (call, hookContext) => {
1990
+ askCut.disarm();
1991
+ // An MCP call is on the record before its gate answers, its start marked parked (once per call id), so its
1992
+ // sent mark is committed before it is sent. A fault before the bridge writes its intent leaves no intent: the
1993
+ // CLI's re-issue asks again and sends it once. One after the intent is any bridged host tool's: told interrupted,
1994
+ // never run twice.
1995
+ if (mcp?.catalogOf(call.tool) !== undefined) {
1996
+ await record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
1997
+ if (!gate?.sealed)
1998
+ throw error;
1999
+ });
2000
+ }
1701
2001
  const answer = await askingGate(call, hookContext);
1702
2002
  if (answer !== "allow" && "deny" in answer)
1703
2003
  await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
@@ -1707,35 +2007,23 @@ function adapterLoop(specOf, options, deps) {
1707
2007
  await record.end(call.callId, "done", OWN_TOOL_RELEASED);
1708
2008
  return answer;
1709
2009
  }
1710
- : gateOf;
2010
+ : nestedGate;
1711
2011
  // A tool no call of which reaches the gate before it runs (Codex's live search, inside its model requests): its
1712
2012
  // setting now, read again at each request, so a deny or ask set mid-run reaches the next one.
1713
2013
  const permission = spec.gate?.permission;
1714
- const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost };
1715
- // The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
1716
- // MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
1717
- const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
1718
- const ownClient = mcp !== undefined && spec.adapter.capabilities().mcpClient !== undefined;
1719
- const sessionMcp = ownClient
1720
- ? mcp.session(new Map(tools.filter((tool) => mcpNames.has(tool.name)).map((tool) => [tool.name, tool])), async (call) => {
1721
- // A call through the door is on the run's record before its gate answers (once per call id; the gate's park
1722
- // seals the journal): its row, and an approval read beside it, show while it waits. A refused one ends there;
1723
- // a parked one runs, or is refused, on the claim that resumes it (parkedFollowUp); an allowed one runs now.
1724
- const wire = mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool);
1725
- if (record)
1726
- await record.park(call.callId, wire?.name ?? call.tool, call.args ?? {}, wire?.replay === "safe");
1727
- const answer = await gateOf(call, context);
1728
- if (answer === "allow")
1729
- return undefined;
1730
- if ("deny" in answer) {
1731
- if (record)
1732
- await record.end(call.callId, "refused", answer.deny);
1733
- return { refused: answer.deny };
1734
- }
1735
- return { parked: true };
1736
- })
1737
- : undefined;
1738
- session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
2014
+ // After a CLI's question to the person (TurnCut armed): what its model says is not on the record, as pi's turn says
2015
+ // nothing after the question; a call of another tool lets the turn go on.
2016
+ const onEvent = (theRecord) => (event) => {
2017
+ if (askCut.armed && event.type === "text")
2018
+ return;
2019
+ if (askCut.armed && event.type === "tool_start")
2020
+ askCut.disarm();
2021
+ theRecord.onEvent(event);
2022
+ };
2023
+ const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
2024
+ // The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
2025
+ // for host tools, each call through the gate before its intent.
2026
+ session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
1739
2027
  root = await harness.root(context);
1740
2028
  // The root as the claim found it, before this pass writes anything of its own there (the computer's show-up, a
1741
2029
  // takeover's note): what the reopen check below reads, so a fresh reopen is told by the run's own last entry.
@@ -1820,6 +2108,8 @@ function adapterLoop(specOf, options, deps) {
1820
2108
  // A session still new (a person stopped the run before its first input was sent): the follow-up is its first
1821
2109
  // input, and the input the person stopped is never sent.
1822
2110
  firstInputPlaced = undefined;
2111
+ // A feedback round an earlier claim took and never ended (its runner lost): this claim closes it, asking no turn.
2112
+ feedbackNow = endsRoot ? undefined : pendingFeedbackOf(foundEntries);
1823
2113
  if (endsRoot && !inFlight && session.state === "idle")
1824
2114
  reopen = {};
1825
2115
  else if (endsRoot && !inFlight && session.state === "new") {
@@ -1827,6 +2117,16 @@ function adapterLoop(specOf, options, deps) {
1827
2117
  firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
1828
2118
  reopen = mine;
1829
2119
  }
2120
+ // A CLI run parked on its question (its turn cut there, TurnCut): its session takes no steer, so the person's
2121
+ // answer is this claim's turn, sent as a reopened run's follow-up is (steer, through `reopen`), the row's waiting
2122
+ // summary going in its take. A turn the session still reads open is the one the cut stopped: settled first,
2123
+ // never recovered (recovered, the CLI would go on past its question).
2124
+ if (!endsRoot && !inFlight && spec.record === "loop" && !session.steer && turnEndedOnAsk(foundEntries) !== undefined) {
2125
+ if (session.state === "open_turn")
2126
+ await session.settleOpenTurn();
2127
+ if (session.state === "idle")
2128
+ reopen = askReopen = {};
2129
+ }
1830
2130
  }
1831
2131
  opened();
1832
2132
  // A channel call a fault's restart cut off from its pass: its record is written through this one.
@@ -1852,7 +2152,8 @@ function adapterLoop(specOf, options, deps) {
1852
2152
  return await writeEnd(harness, root, gate, { state: "stopped", outcome: "cancelled", summary: why }, []);
1853
2153
  }
1854
2154
  }
1855
- let followedUp = false;
2155
+ // A feedback round an earlier claim took (feedbackNow): its words are this claim's turn, never the job's input.
2156
+ let followedUp = feedbackNow !== undefined;
1856
2157
  if (raising.resuming) {
1857
2158
  // Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
1858
2159
  // together: one raise entry, and the run resumes once, at the latest cap, with one follow-up in the server's
@@ -1895,44 +2196,6 @@ function adapterLoop(specOf, options, deps) {
1895
2196
  followedUp = true;
1896
2197
  }
1897
2198
  }
1898
- if (!followedUp && ownClient) {
1899
- // MCP calls a harness with its own client parked through the door: each answered once (an allow runs it, a deny
1900
- // is told), then the session goes on with main's resume message for them, written on the record before it is
1901
- // sent (as the person's input is). A call still waiting parks the run again.
1902
- const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
1903
- const follow = await parkedFollowUp(mcp, {
1904
- entries: await entriesOf(gate.journal, root.id, context),
1905
- // As the gate before an intent does: a call still waiting on its person whose tool now reads allow is answered by
1906
- // the setting (allowedBySetting); any other waits for the person's answer.
1907
- answer: async (call, price) => {
1908
- const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
1909
- const bySetting = now === "allow" && (await askStands(call.callId));
1910
- return bySetting ? allowedBySetting(call, price, call.tool) : answerOf(call, price);
1911
- },
1912
- deniedNow: async (call) => {
1913
- // The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
1914
- const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
1915
- return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
1916
- },
1917
- run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
1918
- // A parked call refused ends on the run's record (its start was written at its park), in the refusal's words.
1919
- refused: async (call, text) => cliRecord?.end(call.callId, "refused", text),
1920
- });
1921
- if (follow === "park") {
1922
- // A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
1923
- // end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
1924
- if (stopReason?.kind === "command")
1925
- return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
1926
- gate.seal(new Parked());
1927
- return { state: "parked" };
1928
- }
1929
- if (follow) {
1930
- const theRoot = root;
1931
- await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" }, at: now() } }), context);
1932
- await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
1933
- followedUp = true;
1934
- }
1935
- }
1936
2199
  if (reopen) {
1937
2200
  // Every row the runner read for this claim has reached its command() (deps.delivered): the follow-up's steer, sent
1938
2201
  // by steer() as a turn, is the turn this claim runs. With none (a claim after that turn's answer), it ends again.
@@ -1947,10 +2210,13 @@ function adapterLoop(specOf, options, deps) {
1947
2210
  await Promise.race([firstInputPlaced, stopping, parking, harness.closed.then(() => undefined, () => undefined), lost]);
1948
2211
  }
1949
2212
  const sent = reopen.sent;
2213
+ const fed = reopen.feedback;
1950
2214
  reopen = undefined;
1951
2215
  if (sent) {
1952
2216
  await sent.catch(() => undefined);
1953
2217
  followedUp = true;
2218
+ if (fed)
2219
+ feedbackNow = fed;
1954
2220
  }
1955
2221
  }
1956
2222
  // A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
@@ -1958,9 +2224,161 @@ function adapterLoop(specOf, options, deps) {
1958
2224
  // A reopen of a session still new whose message was never placed (the run stopped, parked or was lost meanwhile):
1959
2225
  // nothing is sent, least of all the input the person stopped.
1960
2226
  const firstUnplaced = firstInputPlaced !== undefined && !followedUp;
1961
- const placed = followedUp || (session.state !== "idle" && !firstUnplaced);
1962
- if (followedUp || firstUnplaced) {
1963
- // The follow-up is the turn this claim runs, or there is none.
2227
+ // A CLI's end-of-run turn an earlier claim sent and never saw end (its prompt the last turn on the record, no
2228
+ // submission): the job's turn had ended before it, so the session's open turn is that look-back. One a person
2229
+ // stopped with a follow-up after it is not: the open turn is the follow-up's, recovered as the job's. It is settled, never recovered:
2230
+ // recovered, it ran as the job's turn, its answer lost, and the end-of-run step then asked the CLI again, a paid
2231
+ // look-back twice on one claim. The step asks it again once, under the run's cap (an earlier request of it booked
2232
+ // at its hold, bookCut), or skips it, reading what the first ask kept (EndOfRunTurn ask's `kept`). A feedback round
2233
+ // (feedbackNow) sends no turn of its own before its look-back, so its open look-back is settled the same way.
2234
+ if ((!followedUp || feedbackNow !== undefined) && !firstUnplaced && session.state === "open_turn" && (await record?.lookingBack()))
2235
+ await session.settleOpenTurn();
2236
+ /** The run's learned workflow, run first (AdapterRunSpec.workflowFirst), once for the run: the person's input on the
2237
+ * record, then the workflow's call through the session's own learned_workflow tool as the loop wrapped it (its gate
2238
+ * with its ask, its record, its flush and booking, the stop's abort), under one call id (replay never: a call a
2239
+ * crash cut is ended interrupted and handed back, never run again), then the WORKFLOW_FIRST entry saying how it
2240
+ * ended, with its answer as the model's message when it answered, in one commit. pi keeps no record of the loop's
2241
+ * (its own entries are its record): its call goes on a record of its own for this step, the same entries. A claim
2242
+ * that finds the entry or the call's end takes it as it is. Undefined: the run is its agent's (the tool is not the
2243
+ * run's, or the gate denies it before anything is written); "park": the call waits for a person's approval. */
2244
+ const serveFirst = async (first) => {
2245
+ const learned = tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
2246
+ if (!learned)
2247
+ return undefined;
2248
+ const [on, theRoot, theGate] = [harness, root, gate];
2249
+ const args = { name: first.name, input: first.input };
2250
+ const call = { callId: WORKFLOW_FIRST_CALL, tool: LEARNED_WORKFLOW_TOOL, args };
2251
+ const job = (text) => ({ outcome: "handed_back", text: handbackText(first.name, text, spec.input) });
2252
+ const kept = findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true);
2253
+ const rec = record ?? (await openCliRecord(on, theGate.journal, context, now, spec.cwd));
2254
+ const ended = rec.endOf(WORKFLOW_FIRST_CALL);
2255
+ /** The call's answer as the run takes it: one the agent could not stand behind goes back to it, either one the
2256
+ * tool cut (learnedText: no agent turn could recover its ending) or, for an agent with an output schema, one that
2257
+ * cannot be shaped to it (answerAsServed: the answer as the run serves it, the one replay and grading read; why
2258
+ * goes back with it). Pure in the call's end, so a claim that recovers a handback rebuilds the same words. */
2259
+ const taken = (got) => {
2260
+ if (got.isError)
2261
+ return got;
2262
+ if (got.text.length > LEARNED_CLIP)
2263
+ return { ...got, isError: true };
2264
+ const asServed = answerAsServed(got.text, first.outputSchema);
2265
+ return "why" in asServed ? { text: `${got.text}\n\n[${asServed.why}]`, isError: true } : { ...got, text: asServed.text };
2266
+ };
2267
+ const recorded = (end) => ({ text: end.output ?? (end.status === "interrupted" ? endedAnswer(LEARNED_WORKFLOW_TOOL, end).text : ""), isError: end.status !== "done" });
2268
+ if (kept?.outcome === "answered")
2269
+ return { outcome: "answered", text: ended?.output ?? "" };
2270
+ // Handed back on an earlier claim whose handback never reached the agent (the session is still new): sent now, in
2271
+ // the words that claim would have sent (its why included).
2272
+ if (kept)
2273
+ return job(ended ? taken(recorded(ended)).text : "");
2274
+ if (!ended) {
2275
+ // A deny before anything is written leaves the run its agent's, as if the workflow were not there.
2276
+ const before = await spec.gate?.({ callId: call.callId, tool: call.tool, args });
2277
+ if (before === "deny" || typeof before === "object")
2278
+ return undefined;
2279
+ if (spec.inputOrigin)
2280
+ await rec.input(spec.input, spec.inputOrigin);
2281
+ else
2282
+ await rec.person(spec.input);
2283
+ }
2284
+ let answer;
2285
+ if (ended)
2286
+ answer = recorded(ended);
2287
+ else {
2288
+ const verdict = await preIntentGate(spec, hooks, wrapUp, (asked) => rec.park(asked.callId, asked.tool, asked.args ?? {}, false))(call, context);
2289
+ if (verdict !== "allow" && "park" in verdict)
2290
+ return "park";
2291
+ if (verdict !== "allow") {
2292
+ // Refused at its gate once the job was on the record (its ask declined, the cap's wrap-up): handed back in
2293
+ // the gate's words, the call ended refused.
2294
+ if (rec.unsentParked().includes(WORKFLOW_FIRST_CALL))
2295
+ await rec.end(WORKFLOW_FIRST_CALL, "refused", verdict.deny);
2296
+ else
2297
+ await rec.refused(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false, verdict.deny);
2298
+ answer = { text: verdict.deny, isError: true };
2299
+ }
2300
+ else {
2301
+ // A CLI's record takes the call's start and end inside the wrapper; pi's step record here.
2302
+ if (!record)
2303
+ await rec.start(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false);
2304
+ const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal });
2305
+ answer = { text: got.text, isError: got.isError === true };
2306
+ if (!record)
2307
+ await rec.end(WORKFLOW_FIRST_CALL, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
2308
+ }
2309
+ }
2310
+ if (stopAbort.signal.aborted)
2311
+ return undefined;
2312
+ answer = taken(answer);
2313
+ const outcome = answer.isError ? "handed_back" : "answered";
2314
+ const data = { workflow: first.name, digest: first.digest, revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
2315
+ await on.commit(async (tx) => {
2316
+ if (outcome === "answered")
2317
+ await tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "model", text: answer.text, at: now() } });
2318
+ await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
2319
+ }, context);
2320
+ return outcome === "answered" ? { outcome, text: answer.text } : job(answer.text);
2321
+ };
2322
+ // The run's learned workflow first, before anything is sent to its agent (runner/workflow-first.ts): its answer is
2323
+ // the run's, or its handback is the agent's first input. Only while the session is new: a claim that finds a turn
2324
+ // under way (the handback sent) never runs it again.
2325
+ let served;
2326
+ // A workflow this run already served or handed back on an earlier claim (its end on the root): recovered whatever the
2327
+ // money rule says now, so a crash before the handback never makes the agent redo finished work.
2328
+ const keptFirst = spec.workflowFirst || !spec.workflowRevise || followedUp || firstUnplaced || session.state !== "new" ? undefined : findData(await entriesOf(gate.journal, root.id, context), WORKFLOW_FIRST, () => true);
2329
+ const recovered = keptFirst && keptFirst.outcome !== "needs_revision" ? { name: keptFirst.workflow, digest: keptFirst.digest, revision: keptFirst.revision, input: {}, ...(spec.workflowRevise?.outputSchema !== undefined ? { outputSchema: spec.workflowRevise.outputSchema } : {}) } : undefined;
2330
+ const firstToServe = spec.workflowFirst ?? recovered;
2331
+ // A fitting workflow the money rule stopped: why, on the root, once for the run, as the agent takes it.
2332
+ if (spec.workflowRevise && !followedUp && !firstUnplaced && session.state === "new") {
2333
+ const [on, theRoot, theGate] = [harness, root, gate];
2334
+ if (!findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true)) {
2335
+ const { workflow, digest, revision, served_usd, by_hand_usd, runs } = spec.workflowRevise;
2336
+ const data = { workflow, digest, revision, outcome: "needs_revision", served_usd, by_hand_usd, runs };
2337
+ await on.commit(async (tx) => {
2338
+ await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
2339
+ }, context);
2340
+ }
2341
+ }
2342
+ if (firstToServe && !followedUp && !firstUnplaced && session.state === "new") {
2343
+ let release;
2344
+ servingFirst = new Promise((resolve) => (release = resolve));
2345
+ try {
2346
+ const step = await serveFirst(firstToServe);
2347
+ // A stop while it ran, or while it was asked, ends the run stopped, its call ended interrupted (or its ask
2348
+ // withdrawn) on the record: given back parked with its stop untaken, the run would be claimed again only to end
2349
+ // then. A lost claim leaves it.
2350
+ const cutBy = stopReason;
2351
+ if (step === "park" && cutBy?.kind !== "command") {
2352
+ await releaseHost(harness);
2353
+ gate.seal(new Parked());
2354
+ return { state: "parked" };
2355
+ }
2356
+ if (cutBy?.kind === "command")
2357
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2358
+ if (cutBy || deps.signal.aborted || step === "park")
2359
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2360
+ served = step;
2361
+ // A replay run (runner/promotion.ts) ends on its workflow's step whichever way it ended: its hand-back is the
2362
+ // agent's recorded answer for that input, read from the graded run, never asked of the agent again.
2363
+ if (served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay))
2364
+ turnsOver = true;
2365
+ else if (served?.outcome === "handed_back") {
2366
+ // The agent's first input: the handback, the server's (its row "AgentRun: …"), the job whole after it. Cut of
2367
+ // every secret the runner holds: the workflow's words may quote what its steps read.
2368
+ const text = deps.redact ? deps.redact(served.text) : served.text;
2369
+ await record?.message(text, HANDED_BACK_ORIGIN);
2370
+ await session.send(text, { origin: HANDED_BACK_ORIGIN });
2371
+ }
2372
+ }
2373
+ finally {
2374
+ servingFirst = undefined;
2375
+ release();
2376
+ }
2377
+ }
2378
+ const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
2379
+ if (served || followedUp || firstUnplaced) {
2380
+ // The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
2381
+ // or there is none.
1964
2382
  }
1965
2383
  else if (session.state === "new") {
1966
2384
  // A trigger's first input is its origin's (the launch's), never written as the person's.
@@ -1975,8 +2393,11 @@ function adapterLoop(specOf, options, deps) {
1975
2393
  // A message handed over while the session was new is placed from here on, after what was just sent.
1976
2394
  inputSent();
1977
2395
  // The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
1978
- // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
1979
- let turn = placed ? session.turnEnd() : idleTurnOf(harness, root);
2396
+ // its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold. None
2397
+ // when the workflow answered: the run ends on its answer.
2398
+ // A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn.
2399
+ const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined;
2400
+ let turn = alone ? new Promise(() => { }) : placed ? session.turnEnd() : idleTurnOf(harness, root);
1980
2401
  // Set on every way out of the loop below but parkOn's, which returns before it is read.
1981
2402
  let data;
1982
2403
  let failedWith;
@@ -1984,173 +2405,189 @@ function adapterLoop(specOf, options, deps) {
1984
2405
  let parkOn;
1985
2406
  /** The ask_person call the run waits on in its claim, while it does. */
1986
2407
  let waitingOn;
1987
- for (;;) {
1988
- const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed")]);
1989
- if (end === "parked") {
1990
- // Let the tool host go first (a browser's release, booked under the live claim), then seal.
1991
- await releaseHost(harness);
1992
- gate.seal(new Parked());
1993
- return { state: "parked" };
1994
- }
1995
- if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
1996
- await closeSession();
1997
- continue passes;
1998
- }
1999
- if (end === "closed" || (stopReason && stopReason.kind !== "command"))
2000
- return await interrupted(stopReason?.kind ?? "the Session closed");
2001
- if (end === "stop" && stopReason?.kind === "command") {
2002
- // Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
2003
- // is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
2004
- const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
2005
- const settling = (async () => {
2006
- await session.interrupt().catch(() => { });
2007
- await harness.waitForIdle(context).catch(() => { });
2008
- return true;
2009
- })();
2010
- let timer;
2011
- const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
2012
- clearTimeout(timer);
2013
- // A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
2014
- const stopped = stopEnd(stopReason.cancel);
2015
- const cut = await cutRows(claim, spec, "stopped");
2016
- if (!settled)
2017
- return await writeEnd(harness, root, gate, { state: "failed", summary: `${stopped.summary}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
2018
- return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
2019
- }
2020
- // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
2021
- // it kept went): the run parks on its question, as it does with nothing open.
2022
- if (end === "lapsed") {
2023
- parkOn = waitingOn;
2024
- break;
2025
- }
2026
- const outcome = (await turn);
2027
- // What the model said last, on the record before the run's end.
2028
- await record?.flushText();
2029
- // The turn's end on the record, after its last text: a CLI run reads working until here.
2030
- await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
2031
- await harness.waitForIdle(context);
2032
- const settledEntries = await entriesOf(gate.journal, root.id, context);
2033
- const cutOff = restartLimited(settledEntries);
2034
- // A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
2035
- // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
2036
- await bookingsSettled();
2037
- const over = cutOff ? undefined : await overCap();
2038
- // A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
2039
- // poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
2040
- if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
2041
- let bound;
2042
- await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
2043
- clearTimeout(bound);
2044
- // A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
2045
- // narrowing TypeScript did before the delivery.
2046
- const cutBy = stopReason;
2047
- if (cutBy?.kind === "command")
2048
- return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2049
- if (cutBy || deps.signal.aborted)
2050
- return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2051
- }
2052
- if (cutOff)
2053
- data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
2054
- else if (over)
2055
- data = { state: "failed", summary: over };
2056
- else if (outcome.status !== "completed" && refused) {
2057
- // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
2058
- // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
2059
- // check's own words, never as a run with no answer.
2060
- const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
2061
- if (park?.outcome === "parked" && pausedAtRefusal) {
2062
- // Its pause and the run parked landed before pi heard of the refusal.
2063
- await releaseHost(harness);
2064
- gate.seal(new Parked());
2065
- return { state: "parked" };
2408
+ if (alone)
2409
+ data = { state: "ended" };
2410
+ else
2411
+ for (;;) {
2412
+ const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
2413
+ // Parked on a call held at the gate (a CLI's at its tool bridge): the answer that made the call may still be
2414
+ // streaming, and its booking lands before the claim goes (parkClaim).
2415
+ if (end === "parked")
2416
+ return await parkClaim(harness, gate);
2417
+ if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
2418
+ await closeSession();
2419
+ continue passes;
2066
2420
  }
2067
- if (park?.outcome === "parked")
2068
- return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
2069
- data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
2070
- }
2071
- else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
2072
- // A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
2073
- // queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
2074
- // answer (the same row the run's end would have written).
2075
- const said = outcome.error?.trim() ?? "";
2076
- const rootId = root.id;
2077
- await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
2078
- turn = sendAfterTurn(gate, afterTurn.shift());
2079
- continue;
2080
- }
2081
- else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
2082
- // A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
2083
- // turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
2084
- // with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
2085
- data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
2086
- }
2087
- else if (outcome.status !== "completed") {
2088
- // A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
2089
- // the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
2090
- // the loop's own words.
2091
- const said = outcome.error?.trim();
2092
- data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
2093
- // A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
2094
- // end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
2095
- if (said && spec.record === "loop")
2096
- failedWith = deps.redact ? deps.redact(said) : said;
2097
- }
2098
- else if (endedOnTurnEndingTool(settledEntries) !== undefined) {
2099
- // The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
2100
- // open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
2101
- // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
2102
- // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
2103
- const callId = endedOnTurnEndingTool(settledEntries);
2104
- // Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
2105
- // person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
2106
- if (pendingPause) {
2107
- pendingPause = undefined;
2108
- await keepPending(null);
2421
+ if (end === "closed" || (stopReason && stopReason.kind !== "command"))
2422
+ return await interrupted(stopReason?.kind ?? "the Session closed");
2423
+ if (end === "stop" && stopReason?.kind === "command") {
2424
+ // Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
2425
+ // is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
2426
+ const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
2427
+ const settling = (async () => {
2428
+ const interrupting = session.interrupt().catch(() => { });
2429
+ // A request held after a question to the person (TurnCut) is refused once the stop is under way.
2430
+ askCut.done();
2431
+ await interrupting;
2432
+ await harness.waitForIdle(context).catch(() => { });
2433
+ return true;
2434
+ })();
2435
+ let timer;
2436
+ const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
2437
+ clearTimeout(timer);
2438
+ // A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
2439
+ const stopped = stopEnd(stopReason.cancel);
2440
+ const cut = await cutRows(claim, spec, "stopped");
2441
+ if (!settled)
2442
+ return await writeEnd(harness, root, gate, { state: "failed", summary: `${stopped.summary}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
2443
+ return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
2109
2444
  }
2110
- const waited = await waitInClaim(harness, callId);
2111
- if (waited) {
2112
- turn = waited.next;
2113
- waitingOn = callId;
2114
- continue;
2445
+ // The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
2446
+ // it kept went): the run parks on its question, as it does with nothing open.
2447
+ if (end === "lapsed") {
2448
+ parkOn = waitingOn;
2449
+ break;
2115
2450
  }
2116
- parkOn = callId;
2117
- }
2118
- else {
2119
- // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
2120
- // the direct loop's rule: the words are loop-contract's cutAtLimit).
2121
- const cut = cutLast(settledEntries);
2122
- // The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
2123
- // message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
2124
- // command that waits on this loop cannot hold its end.
2125
- if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
2451
+ const outcome = end === "cut" ? await cutAtQuestion(session, turn, spec.stopSettleMs ?? STOP_SETTLE_MS) : (await turn);
2452
+ // A turn that ended with no cut (its CLI asked nothing more after its question): nothing armed past it.
2453
+ askCut.done();
2454
+ // What the model said last, on the record before the run's end.
2455
+ await record?.flushText();
2456
+ // The turn's end on the record, after its last text: a CLI run reads working until here.
2457
+ await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
2458
+ await harness.waitForIdle(context);
2459
+ const settledEntries = await entriesOf(gate.journal, root.id, context);
2460
+ const cutOff = restartLimited(settledEntries);
2461
+ // A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
2462
+ // answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
2463
+ await bookingsSettled();
2464
+ // A run a paid call stopped for good (paid-calls.ts stopRun) ends in that call's words, past its cap too.
2465
+ const stoppedBy = pendingPause?.forGood ? pendingPause : undefined;
2466
+ const over = cutOff || stoppedBy ? undefined : await overCap();
2467
+ // A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
2468
+ // poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
2469
+ if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
2126
2470
  let bound;
2127
2471
  await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
2128
2472
  clearTimeout(bound);
2129
- // A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
2130
- // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
2473
+ // A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
2474
+ // narrowing TypeScript did before the delivery.
2131
2475
  const cutBy = stopReason;
2132
2476
  if (cutBy?.kind === "command")
2133
2477
  return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2134
2478
  if (cutBy || deps.signal.aborted)
2135
2479
  return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2136
2480
  }
2137
- // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
2138
- const next = cut ? undefined : afterTurn.shift();
2139
- if (next) {
2140
- turn = sendAfterTurn(gate, next);
2141
- continue;
2481
+ if (cutOff)
2482
+ data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
2483
+ else if (over)
2484
+ data = { state: "failed", summary: over };
2485
+ else if (stoppedBy)
2486
+ data = { state: "failed", summary: stoppedBy.refuse };
2487
+ else if (outcome.status !== "completed" && refused) {
2488
+ // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
2489
+ // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
2490
+ // check's own words, never as a run with no answer.
2491
+ const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
2492
+ // Its pause and the run parked landed before pi heard of the refusal.
2493
+ if (park?.outcome === "parked" && pausedAtRefusal)
2494
+ return await parkClaim(harness, gate);
2495
+ if (park?.outcome === "parked")
2496
+ return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
2497
+ data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
2142
2498
  }
2143
- // A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
2144
- // the run's end. One already answered settles at once.
2145
- const steered = cut ? undefined : steeredIn.shift();
2146
- if (steered !== undefined) {
2147
- turn = turnOfRequest(harness, root, steered);
2499
+ else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
2500
+ // A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
2501
+ // queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
2502
+ // answer (the same row the run's end would have written).
2503
+ const said = outcome.error?.trim() ?? "";
2504
+ const rootId = root.id;
2505
+ await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
2506
+ turn = sendAfterTurn(gate, afterTurn.shift());
2148
2507
  continue;
2149
2508
  }
2150
- data = cut ? { state: "failed", summary: cut } : { state: "ended" };
2509
+ else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
2510
+ // A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
2511
+ // turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
2512
+ // with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
2513
+ data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
2514
+ }
2515
+ else if (outcome.status !== "completed") {
2516
+ // A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
2517
+ // the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
2518
+ // the loop's own words.
2519
+ const said = outcome.error?.trim();
2520
+ data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
2521
+ // A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
2522
+ // end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
2523
+ if (said && spec.record === "loop")
2524
+ failedWith = deps.redact ? deps.redact(said) : said;
2525
+ }
2526
+ else if (turnEndedOnAsk(settledEntries) !== undefined) {
2527
+ // The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
2528
+ // open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
2529
+ // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
2530
+ // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
2531
+ const callId = turnEndedOnAsk(settledEntries);
2532
+ // Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
2533
+ // person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
2534
+ if (pendingPause) {
2535
+ pendingPause = undefined;
2536
+ await keepPending(null);
2537
+ }
2538
+ const waited = await waitInClaim(harness, callId);
2539
+ if (waited) {
2540
+ turn = waited.next;
2541
+ waitingOn = callId;
2542
+ continue;
2543
+ }
2544
+ parkOn = callId;
2545
+ }
2546
+ else {
2547
+ // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
2548
+ // the direct loop's rule: the words are loop-contract's cutAtLimit).
2549
+ const cut = cutLast(settledEntries);
2550
+ // The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
2551
+ // message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
2552
+ // command that waits on this loop cannot hold its end.
2553
+ if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
2554
+ let bound;
2555
+ await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
2556
+ clearTimeout(bound);
2557
+ // A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
2558
+ // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
2559
+ const cutBy = stopReason;
2560
+ if (cutBy?.kind === "command")
2561
+ return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
2562
+ if (cutBy || deps.signal.aborted)
2563
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
2564
+ }
2565
+ // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
2566
+ const next = cut ? undefined : afterTurn.shift();
2567
+ if (next) {
2568
+ turn = sendAfterTurn(gate, next);
2569
+ continue;
2570
+ }
2571
+ // A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
2572
+ // the run's end. One already answered settles at once.
2573
+ const steered = cut ? undefined : steeredIn.shift();
2574
+ if (steered !== undefined) {
2575
+ turn = turnOfRequest(harness, root, steered);
2576
+ continue;
2577
+ }
2578
+ // The output contract: an answer whose last json block misses the agent's output schema is asked again, once,
2579
+ // in the same session, never a second time (outputRetried reads the record, so a later claim does not ask
2580
+ // either), and not once the run is wrapping up at its cap (the room left is its answer's, and a retry that
2581
+ // could not fit would park the run for the retry's sake). The run's result then says why (output_error).
2582
+ const miss = cut || spec.outputSchema === undefined || outputRetrySent || outputRetried(settledEntries) ? undefined : outputMiss(lastAnswerText(settledEntries), spec.outputSchema);
2583
+ if (miss !== undefined && !(await wrapUp())) {
2584
+ turn = sendOutputRetry(miss);
2585
+ continue;
2586
+ }
2587
+ data = cut ? { state: "failed", summary: cut } : { state: "ended" };
2588
+ }
2589
+ break;
2151
2590
  }
2152
- break;
2153
- }
2154
2591
  // No turn is sent after this one: a message from here on waits for the run's end (steer).
2155
2592
  turnsOver = true;
2156
2593
  if (parkOn !== undefined)
@@ -2251,12 +2688,6 @@ function adapterLoop(specOf, options, deps) {
2251
2688
  if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
2252
2689
  return { deny: REFLECT_NOTE_ONLY };
2253
2690
  await hooks.beforeIntent(kernelCall);
2254
- // The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
2255
- // asked about.
2256
- // A conversation's own budget (a subagent's max_tool_calls) narrows the run's, never widens it.
2257
- const budget = budgetOf(spec.gate?.toolCalls, call.ownBudget ? await call.ownBudget() : undefined);
2258
- if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
2259
- return { deny: TOOL_BUDGET_TEXT };
2260
2691
  // The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
2261
2692
  // in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
2262
2693
  if (call.nested !== true && (await wrapUp()))
@@ -2264,12 +2695,22 @@ function adapterLoop(specOf, options, deps) {
2264
2695
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
2265
2696
  const replayed = call.replayed === true;
2266
2697
  const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
2267
- if (typeof decision === "object")
2268
- return { deny: decision.deny };
2269
2698
  // Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
2270
2699
  // an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
2271
2700
  const asked = spec.gate?.askedAs?.(tool) ?? tool;
2272
- // Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
2701
+ // A call a person was asked about and has not answered, refused now because its tool is set to deny (a bare "deny",
2702
+ // or the gate's own words for it): the deny answers the ask first (deniedBySetting), a deny of theirs standing. The
2703
+ // model reads the gate's words (main's, from refusal-words.ts) either way.
2704
+ // The ask is read first: it is the claim's one journal read, the setting a store read.
2705
+ if (decision !== "allow" && decision !== "ask" && spec.gate && (await askStands(call.callId)) && (decision === "deny" || (await spec.gate.permission?.(tool)) === "deny")) {
2706
+ const answer = await deniedBySetting({ ...call, tool }, asked);
2707
+ if (answer === "park")
2708
+ return { park: true };
2709
+ if (answer.by !== "setting")
2710
+ return { deny: deniedText(asked, answer.note) };
2711
+ }
2712
+ if (typeof decision === "object")
2713
+ return { deny: decision.deny };
2273
2714
  if (decision === "deny")
2274
2715
  return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
2275
2716
  // A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
@@ -2285,8 +2726,13 @@ function adapterLoop(specOf, options, deps) {
2285
2726
  const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
2286
2727
  // The call on the record before its ask (beforeAsk), with the input its model gave it.
2287
2728
  await beforeAsk?.(call);
2288
- const price = mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null;
2289
- const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked);
2729
+ // Its price on the card: a catalog tool's (an MCP tool's, a monid endpoint's pinned price), else none.
2730
+ const price = mcp?.priceOf(tool) ?? null;
2731
+ // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the gate's `mcp_calls`, a
2732
+ // learned workflow's MCP calls set to ask): that allow takes the second confirm too.
2733
+ const covered = Array.isArray(shown?.mcp_calls) ? shown.mcp_calls.filter((name) => typeof name === "string") : [];
2734
+ const destructive = [asked, ...covered].some((name) => mcp?.effectOf(name) === "destructive");
2735
+ const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
2290
2736
  if (answer === "park")
2291
2737
  return { park: true };
2292
2738
  // A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
@@ -2304,7 +2750,7 @@ function adapterLoop(specOf, options, deps) {
2304
2750
  /** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
2305
2751
  * park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
2306
2752
  * was asked and its `price`; asked again on a resume, it is the same request. */
2307
- async function answerOf(call, price, asked = call.tool) {
2753
+ async function answerOf(call, price, asked = call.tool, destructive = mcp?.effectOf(asked) === "destructive") {
2308
2754
  const conversation = await harness.root(context);
2309
2755
  const entries = await entriesOf(gate.journal, conversation.id, context);
2310
2756
  const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
@@ -2316,7 +2762,9 @@ function adapterLoop(specOf, options, deps) {
2316
2762
  return known;
2317
2763
  // The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
2318
2764
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
2319
- const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
2765
+ // An MCP tool its run's pin marks destructive (ClaimMcp.effectOf), or a call whose allow covers one (`destructive`):
2766
+ // its card asks a second confirm of an allow.
2767
+ const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
2320
2768
  const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
2321
2769
  if (first === undefined) {
2322
2770
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
@@ -2387,6 +2835,25 @@ function adapterLoop(specOf, options, deps) {
2387
2835
  askedArgs.set(call.callId, first.args);
2388
2836
  return data;
2389
2837
  }
2838
+ /** The answer to an ask a person was shown and has not answered, once its tool's setting reads deny: the deny answers it
2839
+ * (by "setting"), so its rows say it was refused for that deny and the run's end never reads it withdrawn. A person's
2840
+ * allow already in the inbox for the call is taken with it and kept as the allow the deny overrode (`superseded`); a
2841
+ * deny of theirs stands, answered as any (answerOf). */
2842
+ async function deniedBySetting(call, asked) {
2843
+ // As allowedBySetting: decided only once the claim's stored commands are with the loop.
2844
+ await (deps.delivered ?? Promise.resolve());
2845
+ const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
2846
+ if (row?.kind === "deny")
2847
+ return answerOf(call, null, asked);
2848
+ const conversation = await harness.root(context);
2849
+ const answeredAt = isoNow();
2850
+ const data = { callId: call.callId, approved: false, decision: "deny", answeredAt, by: "setting", ...(row ? { superseded: { decision: "allow", answeredAt } } : {}) };
2851
+ if (row)
2852
+ inbox.splice(inbox.indexOf(row), 1);
2853
+ if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
2854
+ return "park";
2855
+ return data;
2856
+ }
2390
2857
  /** Whether a person was asked about this call and has not answered yet (an ask in the journal, no answer): its card is
2391
2858
  * theirs, so the call waits for that answer (answerOf) even when its tool's setting reads allow by now, and runs on
2392
2859
  * their allow, its rows reading so. Let through on the setting alone, it ran with its ask unanswered, which the run's
@@ -2489,9 +2956,29 @@ function adapterLoop(specOf, options, deps) {
2489
2956
  parkedAt.catch(() => undefined);
2490
2957
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
2491
2958
  await parkedAt;
2492
- await releaseHost(on);
2493
- theGate.seal(new Parked());
2494
- return { state: "parked" };
2959
+ return parkClaim(on, theGate);
2960
+ }
2961
+ /** A CLI's turn cut at its question to the person (TurnCut): its request after the question held, the turn is stopped
2962
+ * (interrupt), the held request refused once the stop is under way, and the turn the session still reads open settled,
2963
+ * as a host done with a stopped turn settles it. The turn reads completed, ended on the question, as pi's does. Bounded
2964
+ * as a stop is: a turn that does not settle in time fails the run in words. */
2965
+ async function cutAtQuestion(theSession, turn, settleMs) {
2966
+ const settling = (async () => {
2967
+ const stopped = theSession.interrupt().catch(() => { });
2968
+ askCut.done();
2969
+ await stopped;
2970
+ await turn.catch(() => undefined);
2971
+ if (theSession.state === "open_turn")
2972
+ await theSession.settleOpenTurn();
2973
+ return true;
2974
+ })().catch((error) => {
2975
+ console.warn(`[runner] the turn cut at its question did not settle: ${said(error)}`);
2976
+ return false;
2977
+ });
2978
+ let timer;
2979
+ const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
2980
+ clearTimeout(timer);
2981
+ return settled ? { status: "completed" } : { status: "failed", error: `the turn did not stop at its question to the person within ${settleMs / 1000} s` };
2495
2982
  }
2496
2983
  /** The row's waiting summary of a wait in the claim, gone: its answer came by a way whose commit did not clear it. */
2497
2984
  async function notWaiting(on, theGate, conversation, callId) {
@@ -2621,6 +3108,8 @@ function adapterLoop(specOf, options, deps) {
2621
3108
  async function closeSession() {
2622
3109
  gate?.seal(new Interrupted("the Session is closing"));
2623
3110
  endWait();
3111
+ // A request held at a cut turn goes with its session, refused, never left pending.
3112
+ askCut.done();
2624
3113
  const closing = Promise.all([session?.close().catch(() => { }), harness?.close(BACKGROUND_CONTEXT).catch(() => { })]);
2625
3114
  let timer;
2626
3115
  await Promise.race([closing, new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
@@ -2634,6 +3123,8 @@ function adapterLoop(specOf, options, deps) {
2634
3123
  releaseNow = undefined;
2635
3124
  await release?.().catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
2636
3125
  }
3126
+ /** What round `round`'s end-of-run turn kept as it was first asked (EndOfRunTurn's keptOf), on the CLI's record. */
3127
+ const keptOf = (claim) => (round) => cliRecord?.keptOf(reflectRequestId(claim.runId, false, round));
2637
3128
  /** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
2638
3129
  const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
2639
3130
  /** The end-of-run step (stepOf: the spec's, else LoopDeps.endOfRun), asked once: the rows to stage with the end; `stopped` when a person's stop
@@ -2653,7 +3144,7 @@ function adapterLoop(specOf, options, deps) {
2653
3144
  if (!spec.agentId)
2654
3145
  throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
2655
3146
  try {
2656
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1) });
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) });
2657
3148
  return cut() ?? { kind: "rows", also: rows?.also ?? [] };
2658
3149
  }
2659
3150
  catch (error) {
@@ -2671,7 +3162,7 @@ function adapterLoop(specOf, options, deps) {
2671
3162
  let timer;
2672
3163
  const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
2673
3164
  try {
2674
- const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse }), late]);
3165
+ const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: keptOf(claim) }), late]);
2675
3166
  if (rows === "late") {
2676
3167
  console.warn(`[runner] ${claim.runId}: its end-of-run step gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
2677
3168
  return [];
@@ -2686,18 +3177,41 @@ function adapterLoop(specOf, options, deps) {
2686
3177
  clearTimeout(timer);
2687
3178
  }
2688
3179
  }
3180
+ /** What end-of-run turn `requestId` kept as it was first asked, for a harness that keeps its own record (pi): the first
3181
+ * ask's `keep` on the run's root (KINDS.endOfRunKept), an earlier claim's when it asked first, else `keep`, written
3182
+ * there now, before the turn's first request leaves. A CLI's record keeps it with the turn's prompt (answering). */
3183
+ async function keptOnRoot(on, journal, conversation, requestId, keep) {
3184
+ const first = (await entriesOf(journal, conversation.id, context)).find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
3185
+ if (first) {
3186
+ const kept = first.data.kept;
3187
+ return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
3188
+ }
3189
+ if (!keep)
3190
+ return undefined;
3191
+ await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.endOfRunKept, data: { requestId, kept: keep } }), context);
3192
+ return keep;
3193
+ }
2689
3194
  /** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
2690
3195
  * answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
2691
3196
  * asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
2692
3197
  * per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. */
2693
- async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1) {
3198
+ async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1, keep, step) {
2694
3199
  if (!session || !harness || !gate || !root)
2695
3200
  throw new Error("the run's session is not open");
2696
3201
  const on = harness;
2697
3202
  const conversation = root;
2698
3203
  const theSession = session;
2699
- const requestId = reflectRequestId(claim.runId, again, round);
3204
+ const requestId = reflectRequestId(claim.runId, again, round, step);
2700
3205
  const theRecord = cliRecord;
3206
+ // A grade's feedback round (feedbackNow): its first ask is told the grade first (feedback-round.ts feedbackAsk), and,
3207
+ // when the agent never took the job (its learned workflow answered alone: its session is new), the job and the
3208
+ // workflow's answer before it, cut of every secret the runner holds, as a follow-up's are.
3209
+ if (feedbackNow && !again && step === undefined) {
3210
+ const cut = (text) => (deps.redact ? deps.redact(text) : text);
3211
+ const servedNow = theSession.state === "new" ? servedAnswerOf(await entriesOf(gate.journal, conversation.id, context)) : undefined;
3212
+ const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
3213
+ prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
3214
+ }
2701
3215
  reflecting = true;
2702
3216
  let timer;
2703
3217
  try {
@@ -2705,8 +3219,11 @@ function adapterLoop(specOf, options, deps) {
2705
3219
  const known = theRecord ? await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context) : undefined;
2706
3220
  // How this claim's turn ended; a turn answered before reads as its submission says.
2707
3221
  let turnStatus = "completed";
3222
+ // What the turn's first ask kept (`keep`), an earlier claim's when it asked first: every answer carries it.
3223
+ let kept = theRecord?.keptOf(requestId);
3224
+ const withKept = (answer) => (kept ? { ...answer, kept } : answer);
2708
3225
  if (!known) {
2709
- await theRecord?.answering(requestId, prompt);
3226
+ kept = theRecord ? await theRecord.answering(requestId, prompt, keep) : await keptOnRoot(on, gate.journal, conversation, requestId, keep);
2710
3227
  await theSession.send(prompt, { id: requestId });
2711
3228
  const turn = theSession.turnEnd();
2712
3229
  const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
@@ -2717,7 +3234,7 @@ function adapterLoop(specOf, options, deps) {
2717
3234
  await theSession.interrupt().catch(() => { });
2718
3235
  await on.waitForIdle(context).catch(() => { });
2719
3236
  await theRecord?.answered(requestId, prompt, "timed out");
2720
- return { timedOut: true };
3237
+ return withKept({ timedOut: true });
2721
3238
  }
2722
3239
  // The CLI's turn, as the submission pi's adapter writes: what the step reads next, one reader for both.
2723
3240
  turnStatus = end.status;
@@ -2725,32 +3242,34 @@ function adapterLoop(specOf, options, deps) {
2725
3242
  }
2726
3243
  const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
2727
3244
  if (turnStatus !== "completed" || record?.status !== "done")
2728
- return { failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } };
3245
+ return withKept({ failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } });
2729
3246
  const answer = (await entriesOf(gate.journal, conversation.id, context)).find((entry) => entry.id === record.answer);
2730
- return { ended: true, answer: answerText(answer) };
3247
+ return withKept({ ended: true, answer: answerText(answer) });
2731
3248
  }
2732
3249
  finally {
2733
3250
  clearTimeout(timer);
2734
3251
  reflecting = false;
2735
3252
  }
2736
3253
  }
2737
- /** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded like the cut step: late or failing, none. */
3254
+ /** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded (END_PATCH_MS): late or failing, the end says
3255
+ * its cost and metrics are unknown (END_PATCH_UNKNOWN). */
2738
3256
  async function endPatchOf(data) {
2739
3257
  if (!specNow?.endPatch)
2740
3258
  return {};
2741
3259
  let timer;
2742
- const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
3260
+ const boundMs = specNow.endPatchMs ?? END_PATCH_MS;
3261
+ const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), boundMs)));
2743
3262
  try {
2744
3263
  const patch = await Promise.race([specNow.endPatch(data), late]);
2745
3264
  if (patch === "late") {
2746
- console.warn(`[runner] its end's patch gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
2747
- return {};
3265
+ console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its cost and metrics unknown`);
3266
+ return END_PATCH_UNKNOWN;
2748
3267
  }
2749
3268
  return patch ?? {};
2750
3269
  }
2751
3270
  catch (error) {
2752
- console.warn(`[runner] its end's patch failed: ${said(error)}`);
2753
- return {};
3271
+ console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its cost and metrics unknown`);
3272
+ return END_PATCH_UNKNOWN;
2754
3273
  }
2755
3274
  finally {
2756
3275
  clearTimeout(timer);
@@ -2760,7 +3279,15 @@ function adapterLoop(specOf, options, deps) {
2760
3279
  * cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. */
2761
3280
  async function parkAtCap(on, conversation, theGate, data) {
2762
3281
  await pauseAtCap(on, conversation, theGate, data);
3282
+ return parkClaim(on, theGate);
3283
+ }
3284
+ /** A park's release of the claim, as the end's: the tool host let go first (a browser's release, booked under the live
3285
+ * claim), then every paid request the session admitted booked (bookingsSettled), then the journal sealed. A CLI turn
3286
+ * the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
3287
+ * would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
3288
+ async function parkClaim(on, theGate) {
2763
3289
  await releaseHost(on);
3290
+ await bookingsSettled();
2764
3291
  theGate.seal(new Parked());
2765
3292
  return { state: "parked" };
2766
3293
  }
@@ -2825,7 +3352,15 @@ function adapterLoop(specOf, options, deps) {
2825
3352
  await releaseHost(on);
2826
3353
  await bookingsSettled();
2827
3354
  const patch = await endPatchOf(base);
2828
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}) };
3355
+ // A person's stop that came while the end waited (its host's release, its bookings, its patch's reads, up to
3356
+ // END_PATCH_MS on a busy store) is this end's, as a stop during any earlier await of the end path is: the run ends
3357
+ // stopped and the end takes its row, never written completed with the stop left to be refused (refuseLeftovers).
3358
+ // Set by stop() during those awaits: read past the narrowing TypeScript did before them.
3359
+ const late = stopReason;
3360
+ const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
3361
+ if (lateStop)
3362
+ take = [...take, lateStop.commandId];
3363
+ const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
2829
3364
  const run = {
2830
3365
  state: data.state,
2831
3366
  // An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
@@ -2842,8 +3377,11 @@ function adapterLoop(specOf, options, deps) {
2842
3377
  // A cancel's calls read cancelled with their run; a stop's, withdrawn.
2843
3378
  const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
2844
3379
  // A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
2845
- // with the run's, in the same commit, saying it was not run (never interrupted: it never left).
2846
- const recordEnds = cliRecord?.unsentParked() ?? [];
3380
+ // with the run's, in the same commit, saying it was not run (never interrupted: it never left). pi's nested calls
3381
+ // (nestedGate) are on a record of their own, read here from the journal: a stop can end a parked run before this claim
3382
+ // opened a session.
3383
+ const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
3384
+ const recordEnds = ends.unsentParked();
2847
3385
  const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
2848
3386
  const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
2849
3387
  // A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
@@ -2869,7 +3407,7 @@ function adapterLoop(specOf, options, deps) {
2869
3407
  }
2870
3408
  await ended;
2871
3409
  for (const callId of recordEnds)
2872
- cliRecord?.noteEnd(callId, "refused", notRun);
3410
+ ends.noteEnd(callId, "refused", notRun);
2873
3411
  return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
2874
3412
  }
2875
3413
  return {