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

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 (810) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/NOTICE +18 -0
  3. package/README.md +887 -241
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -140
  7. package/dist/adapters.js +153 -377
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +5 -3
  11. package/dist/agents.js +37 -17
  12. package/dist/app.d.ts +2 -4
  13. package/dist/app.js +207 -92
  14. package/dist/approvals.d.ts +4 -0
  15. package/dist/approvals.js +7 -0
  16. package/dist/archil-routes.d.ts +45 -0
  17. package/dist/archil-routes.js +150 -0
  18. package/dist/archil-settings.d.ts +30 -0
  19. package/dist/archil-settings.js +34 -0
  20. package/dist/background.js +28 -9
  21. package/dist/bounds.d.ts +26 -0
  22. package/dist/bounds.js +137 -0
  23. package/dist/box-egress-vm.d.ts +2 -1
  24. package/dist/box-egress-vm.js +20 -6
  25. package/dist/box-egress.d.ts +16 -6
  26. package/dist/box-egress.js +27 -15
  27. package/dist/box-paths.d.ts +59 -0
  28. package/dist/box-paths.js +92 -0
  29. package/dist/box-relay-vm.js +28 -1
  30. package/dist/box-relay.d.ts +2 -0
  31. package/dist/box-relay.js +2 -2
  32. package/dist/boxes.d.ts +13 -1
  33. package/dist/boxes.js +37 -3
  34. package/dist/browser-commands.d.ts +43 -0
  35. package/dist/browser-commands.js +154 -0
  36. package/dist/browser-cost.d.ts +30 -3
  37. package/dist/browser-cost.js +276 -21
  38. package/dist/browser-live.d.ts +124 -0
  39. package/dist/browser-live.js +324 -0
  40. package/dist/browser-person.d.ts +168 -0
  41. package/dist/browser-person.js +769 -0
  42. package/dist/budget.d.ts +80 -0
  43. package/dist/budget.js +211 -0
  44. package/dist/cap.d.ts +272 -62
  45. package/dist/cap.js +599 -189
  46. package/dist/cli.js +201 -17
  47. package/dist/coding-tools.d.ts +13 -1
  48. package/dist/coding-tools.js +107 -5
  49. package/dist/computer-adb.d.ts +12 -0
  50. package/dist/computer-adb.js +14 -0
  51. package/dist/computer-commands.d.ts +103 -0
  52. package/dist/computer-commands.js +256 -0
  53. package/dist/computer-keys.d.ts +68 -0
  54. package/dist/computer-keys.js +148 -0
  55. package/dist/computer-routes.d.ts +38 -0
  56. package/dist/computer-routes.js +56 -0
  57. package/dist/computer-setting.d.ts +37 -0
  58. package/dist/computer-setting.js +47 -0
  59. package/dist/computer-view.d.ts +38 -0
  60. package/dist/computer-view.js +14 -0
  61. package/dist/computers.d.ts +137 -0
  62. package/dist/computers.js +197 -0
  63. package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
  64. package/dist/console/assets/index-35-7aeIZ.js +519 -0
  65. package/dist/console/assets/index-Cejbov-Y.css +1 -0
  66. package/dist/console/index.html +2 -2
  67. package/dist/console-links.d.ts +2 -0
  68. package/dist/console-links.js +6 -0
  69. package/dist/decision-cap.d.ts +63 -0
  70. package/dist/decision-cap.js +163 -0
  71. package/dist/decision-rows.d.ts +5 -2
  72. package/dist/decision-rows.js +8 -6
  73. package/dist/decisions.d.ts +28 -1
  74. package/dist/decisions.js +63 -6
  75. package/dist/disk.d.ts +33 -0
  76. package/dist/disk.js +85 -0
  77. package/dist/door-line.d.ts +23 -0
  78. package/dist/door-line.js +83 -0
  79. package/dist/egress-proxy.d.ts +45 -0
  80. package/dist/egress-proxy.js +416 -0
  81. package/dist/egress-table.d.ts +24 -0
  82. package/dist/egress-table.js +165 -0
  83. package/dist/errors.d.ts +15 -0
  84. package/dist/errors.js +22 -2
  85. package/dist/exa-keyless.js +1 -1
  86. package/dist/explain.d.ts +22 -0
  87. package/dist/explain.js +207 -0
  88. package/dist/faux-computers.d.ts +35 -0
  89. package/dist/faux-computers.js +126 -0
  90. package/dist/file-types.d.ts +4 -0
  91. package/dist/file-types.js +11 -0
  92. package/dist/files.d.ts +3 -35
  93. package/dist/files.js +9 -120
  94. package/dist/github-connection.d.ts +207 -0
  95. package/dist/github-connection.js +595 -0
  96. package/dist/github.d.ts +64 -0
  97. package/dist/github.js +119 -0
  98. package/dist/grade.d.ts +9 -42
  99. package/dist/grade.js +42 -228
  100. package/dist/graph-served.d.ts +23 -2
  101. package/dist/graph-served.js +44 -3
  102. package/dist/graph-view.d.ts +7 -3
  103. package/dist/graph-view.js +26 -15
  104. package/dist/handed-values.d.ts +23 -0
  105. package/dist/handed-values.js +36 -0
  106. package/dist/harness-app.d.ts +33 -4
  107. package/dist/harness-app.js +530 -85
  108. package/dist/harness-install.d.ts +120 -0
  109. package/dist/harness-install.js +359 -0
  110. package/dist/harness-opencode/adapter.js +42 -8
  111. package/dist/harness-opencode/facts.d.ts +2 -0
  112. package/dist/harness-opencode/facts.js +28 -0
  113. package/dist/harness-opencode/harness.d.ts +4 -0
  114. package/dist/harness-opencode/harness.js +38 -5
  115. package/dist/harness-opencode/host/policy.js +11 -3
  116. package/dist/harness-opencode/transcript.d.ts +25 -0
  117. package/dist/harness-opencode/transcript.js +81 -0
  118. package/dist/harness-table.d.ts +75 -0
  119. package/dist/harness-table.js +145 -0
  120. package/dist/harness.d.ts +7 -28
  121. package/dist/harness.js +15 -41
  122. package/dist/heard.d.ts +12 -0
  123. package/dist/heard.js +45 -0
  124. package/dist/helper-env.d.ts +4 -0
  125. package/dist/helper-env.js +14 -0
  126. package/dist/home-path.d.ts +0 -4
  127. package/dist/home-path.js +3 -17
  128. package/dist/host-check.d.ts +4 -3
  129. package/dist/host-check.js +5 -4
  130. package/dist/host-tools.d.ts +51 -8
  131. package/dist/host-tools.js +108 -117
  132. package/dist/host.d.ts +12 -6
  133. package/dist/host.js +30 -24
  134. package/dist/hosted-search.d.ts +3 -0
  135. package/dist/hosted-search.js +5 -3
  136. package/dist/import-proxy.d.ts +42 -0
  137. package/dist/import-proxy.js +105 -0
  138. package/dist/import-summary.js +4 -8
  139. package/dist/import-worker.d.ts +2 -3
  140. package/dist/import-worker.js +18 -16
  141. package/dist/import.d.ts +37 -17
  142. package/dist/import.js +208 -222
  143. package/dist/key-meta.d.ts +26 -0
  144. package/dist/key-meta.js +30 -0
  145. package/dist/key-refusal.d.ts +4 -1
  146. package/dist/key-refusal.js +20 -7
  147. package/dist/learn/check.d.ts +3 -1
  148. package/dist/learn/check.js +2 -2
  149. package/dist/learn/commit.d.ts +86 -0
  150. package/dist/learn/commit.js +182 -0
  151. package/dist/learn/folder.d.ts +296 -0
  152. package/dist/learn/folder.js +796 -0
  153. package/dist/learn/grade.d.ts +22 -9
  154. package/dist/learn/grade.js +95 -49
  155. package/dist/learn/index.d.ts +2 -2
  156. package/dist/learn/index.js +2 -2
  157. package/dist/learn/learning.sh +366 -0
  158. package/dist/learn/reflect.d.ts +12 -5
  159. package/dist/learn/reflect.js +70 -41
  160. package/dist/learn/secrets.d.ts +15 -7
  161. package/dist/learn/secrets.js +66 -16
  162. package/dist/learn/seed-check.d.ts +74 -0
  163. package/dist/learn/seed-check.js +103 -0
  164. package/dist/learn/skills.d.ts +5 -1
  165. package/dist/learn/skills.js +5 -4
  166. package/dist/learned-workflow.d.ts +12 -2
  167. package/dist/learned-workflow.js +9 -5
  168. package/dist/learning-routes.d.ts +88 -41
  169. package/dist/learning-routes.js +340 -539
  170. package/dist/learning-run.d.ts +60 -53
  171. package/dist/learning-run.js +181 -224
  172. package/dist/learning-words.d.ts +3 -5
  173. package/dist/learning-words.js +3 -5
  174. package/dist/learning.d.ts +177 -112
  175. package/dist/learning.js +289 -380
  176. package/dist/live/stream.d.ts +30 -0
  177. package/dist/live/stream.js +175 -0
  178. package/dist/live/translate.d.ts +52 -0
  179. package/dist/live/translate.js +276 -0
  180. package/dist/llm.js +3 -0
  181. package/dist/llms.txt +1 -0
  182. package/dist/local-models.d.ts +23 -0
  183. package/dist/local-models.js +35 -0
  184. package/dist/mcp-gateway.d.ts +46 -13
  185. package/dist/mcp-gateway.js +145 -45
  186. package/dist/mcp-meta.d.ts +3 -0
  187. package/dist/mcp-meta.js +14 -2
  188. package/dist/mcp-oauth.d.ts +172 -0
  189. package/dist/mcp-oauth.js +403 -0
  190. package/dist/mcp-private-hosts.d.ts +48 -0
  191. package/dist/mcp-private-hosts.js +141 -0
  192. package/dist/mcp-probe.d.ts +101 -0
  193. package/dist/mcp-probe.js +359 -0
  194. package/dist/mcp-secret-writes.d.ts +23 -0
  195. package/dist/mcp-secret-writes.js +60 -0
  196. package/dist/mcp-servers-store.d.ts +251 -0
  197. package/dist/mcp-servers-store.js +447 -0
  198. package/dist/mcp-servers.d.ts +180 -50
  199. package/dist/mcp-servers.js +284 -321
  200. package/dist/mcp-store.d.ts +103 -0
  201. package/dist/mcp-store.js +123 -0
  202. package/dist/mcp.js +22 -21
  203. package/dist/model.d.ts +77 -59
  204. package/dist/model.js +237 -98
  205. package/dist/monid.d.ts +8 -6
  206. package/dist/monid.js +39 -25
  207. package/dist/openapi.d.ts +22 -1
  208. package/dist/openapi.js +919 -108
  209. package/dist/owner.d.ts +46 -10
  210. package/dist/owner.js +123 -43
  211. package/dist/page.d.ts +10 -0
  212. package/dist/page.js +27 -4
  213. package/dist/paid-calls.d.ts +71 -2
  214. package/dist/paid-calls.js +125 -5
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -13
  218. package/dist/place.js +25 -15
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/propose.d.ts +9 -8
  222. package/dist/propose.js +82 -49
  223. package/dist/provider.d.ts +85 -0
  224. package/dist/provider.js +178 -0
  225. package/dist/push-handler.d.ts +52 -0
  226. package/dist/push-handler.js +165 -0
  227. package/dist/refusal-words.d.ts +23 -0
  228. package/dist/refusal-words.js +25 -0
  229. package/dist/request-start.d.ts +6 -1
  230. package/dist/request-start.js +41 -10
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-box.d.ts +22 -3
  234. package/dist/run-box.js +78 -17
  235. package/dist/run-computer.d.ts +24 -0
  236. package/dist/run-computer.js +15 -0
  237. package/dist/run-cut.d.ts +33 -0
  238. package/dist/run-cut.js +42 -0
  239. package/dist/run-db.d.ts +64 -0
  240. package/dist/run-db.js +155 -0
  241. package/dist/run-files.d.ts +31 -0
  242. package/dist/run-files.js +125 -0
  243. package/dist/run-holder.d.ts +52 -0
  244. package/dist/run-holder.js +139 -0
  245. package/dist/run-launch.d.ts +72 -0
  246. package/dist/run-launch.js +108 -0
  247. package/dist/run-learning-served.d.ts +43 -0
  248. package/dist/run-learning-served.js +16 -0
  249. package/dist/run-manifest.d.ts +7 -6
  250. package/dist/run-manifest.js +20 -10
  251. package/dist/run-reads-over-store.d.ts +102 -0
  252. package/dist/run-reads-over-store.js +151 -0
  253. package/dist/run-timeline-served.d.ts +13 -0
  254. package/dist/run-timeline-served.js +69 -0
  255. package/dist/run-view.d.ts +436 -0
  256. package/dist/run-view.js +620 -0
  257. package/dist/runnable.d.ts +30 -5
  258. package/dist/runnable.js +149 -72
  259. package/dist/runner/adapter-loop.d.ts +237 -0
  260. package/dist/runner/adapter-loop.js +1625 -0
  261. package/dist/runner/adapter-run-spec.d.ts +216 -0
  262. package/dist/runner/adapter-run-spec.js +537 -0
  263. package/dist/runner/adapters/index.d.ts +37 -0
  264. package/dist/runner/adapters/index.js +66 -0
  265. package/dist/runner/adapters/pi.d.ts +99 -0
  266. package/dist/runner/adapters/pi.js +260 -0
  267. package/dist/runner/beside.d.ts +12 -0
  268. package/dist/runner/beside.js +30 -0
  269. package/dist/runner/claim-secrets.d.ts +30 -0
  270. package/dist/runner/claim-secrets.js +90 -0
  271. package/dist/runner/cli-run-spec.d.ts +17 -0
  272. package/dist/runner/cli-run-spec.js +371 -0
  273. package/dist/runner/commands.d.ts +23 -0
  274. package/dist/runner/commands.js +67 -0
  275. package/dist/runner/computer-journal.d.ts +38 -0
  276. package/dist/runner/computer-journal.js +120 -0
  277. package/dist/runner/conformance/child.d.ts +1 -0
  278. package/dist/runner/conformance/child.js +78 -0
  279. package/dist/runner/conformance/harness.d.ts +89 -0
  280. package/dist/runner/conformance/harness.js +928 -0
  281. package/dist/runner/conformance/subject.d.ts +83 -0
  282. package/dist/runner/conformance/subject.js +1 -0
  283. package/dist/runner/dispatch.d.ts +30 -0
  284. package/dist/runner/dispatch.js +99 -0
  285. package/dist/runner/end-of-run.d.ts +32 -0
  286. package/dist/runner/end-of-run.js +56 -0
  287. package/dist/runner/github-app.d.ts +16 -0
  288. package/dist/runner/github-app.js +37 -0
  289. package/dist/runner/hand-back.d.ts +43 -0
  290. package/dist/runner/hand-back.js +69 -0
  291. package/dist/runner/harness-loops.d.ts +10 -0
  292. package/dist/runner/harness-loops.js +70 -0
  293. package/dist/runner/journal-kinds.d.ts +211 -0
  294. package/dist/runner/journal-kinds.js +116 -0
  295. package/dist/runner/journal-reader.d.ts +44 -0
  296. package/dist/runner/journal-reader.js +127 -0
  297. package/dist/runner/learning-ask.d.ts +37 -0
  298. package/dist/runner/learning-ask.js +99 -0
  299. package/dist/runner/learning-dispatch.d.ts +38 -0
  300. package/dist/runner/learning-dispatch.js +75 -0
  301. package/dist/runner/learning-end.d.ts +31 -0
  302. package/dist/runner/learning-end.js +136 -0
  303. package/dist/runner/learning-factory.d.ts +13 -0
  304. package/dist/runner/learning-factory.js +37 -0
  305. package/dist/runner/learning-loop.d.ts +150 -0
  306. package/dist/runner/learning-loop.js +246 -0
  307. package/dist/runner/learning-seed.d.ts +30 -0
  308. package/dist/runner/learning-seed.js +41 -0
  309. package/dist/runner/live-ticker.d.ts +18 -0
  310. package/dist/runner/live-ticker.js +88 -0
  311. package/dist/runner/loop-contract.d.ts +153 -0
  312. package/dist/runner/loop-contract.js +26 -0
  313. package/dist/runner/loop.d.ts +79 -0
  314. package/dist/runner/loop.js +185 -0
  315. package/dist/runner/main.d.ts +89 -0
  316. package/dist/runner/main.js +282 -0
  317. package/dist/runner/mcp-claim.d.ts +67 -0
  318. package/dist/runner/mcp-claim.js +403 -0
  319. package/dist/runner/mcp-github.d.ts +53 -0
  320. package/dist/runner/mcp-github.js +91 -0
  321. package/dist/runner/mcp-run.d.ts +116 -0
  322. package/dist/runner/mcp-run.js +152 -0
  323. package/dist/runner/metrics.d.ts +18 -0
  324. package/dist/runner/metrics.js +24 -0
  325. package/dist/runner/model-route.d.ts +111 -0
  326. package/dist/runner/model-route.js +183 -0
  327. package/dist/runner/pi-stop.d.ts +6 -0
  328. package/dist/runner/pi-stop.js +8 -0
  329. package/dist/runner/redact.d.ts +26 -0
  330. package/dist/runner/redact.js +51 -0
  331. package/dist/runner/reflect-hook.d.ts +81 -0
  332. package/dist/runner/reflect-hook.js +111 -0
  333. package/dist/runner/runner.d.ts +114 -0
  334. package/dist/runner/runner.js +672 -0
  335. package/dist/runner/sessions.d.ts +9 -0
  336. package/dist/runner/sessions.js +145 -0
  337. package/dist/runner/side-effects.d.ts +19 -0
  338. package/dist/runner/side-effects.js +20 -0
  339. package/dist/runner/spec-holds.d.ts +41 -0
  340. package/dist/runner/spec-holds.js +58 -0
  341. package/dist/runner/store-port.d.ts +9 -0
  342. package/dist/runner/store-port.js +7 -0
  343. package/dist/runner/store-secrets.d.ts +11 -0
  344. package/dist/runner/store-secrets.js +105 -0
  345. package/dist/runner/workflow-adapters.d.ts +1 -0
  346. package/dist/runner/workflow-adapters.js +4 -0
  347. package/dist/runner/workflow-host.d.ts +88 -0
  348. package/dist/runner/workflow-host.js +66 -0
  349. package/dist/runner/workflow-loop.d.ts +126 -0
  350. package/dist/runner/workflow-loop.js +372 -0
  351. package/dist/runner/workflow-spec.d.ts +157 -0
  352. package/dist/runner/workflow-spec.js +801 -0
  353. package/dist/runs-over-store.d.ts +203 -0
  354. package/dist/runs-over-store.js +396 -0
  355. package/dist/runs.d.ts +351 -220
  356. package/dist/runs.js +1570 -540
  357. package/dist/seal-key.d.ts +30 -0
  358. package/dist/seal-key.js +141 -0
  359. package/dist/sealed-settings-store.d.ts +71 -0
  360. package/dist/sealed-settings-store.js +205 -0
  361. package/dist/sealed-settings.d.ts +60 -0
  362. package/dist/sealed-settings.js +178 -0
  363. package/dist/secret-writes.d.ts +147 -0
  364. package/dist/secret-writes.js +144 -0
  365. package/dist/secrets.d.ts +7 -0
  366. package/dist/secrets.js +17 -2
  367. package/dist/served-only.d.ts +5 -0
  368. package/dist/served-only.js +12 -0
  369. package/dist/server-approvers.d.ts +8 -0
  370. package/dist/server-approvers.js +12 -0
  371. package/dist/server-fs.d.ts +40 -0
  372. package/dist/server-fs.js +138 -0
  373. package/dist/server-keys.d.ts +18 -0
  374. package/dist/server-keys.js +31 -0
  375. package/dist/server-lock.js +1 -1
  376. package/dist/server-secrets-store.d.ts +18 -0
  377. package/dist/server-secrets-store.js +54 -0
  378. package/dist/server-secrets.d.ts +23 -0
  379. package/dist/server-secrets.js +73 -0
  380. package/dist/server.d.ts +142 -73
  381. package/dist/server.js +1683 -596
  382. package/dist/sessions.d.ts +3 -1
  383. package/dist/sessions.js +8 -4
  384. package/dist/sign-ins-secrets.d.ts +35 -0
  385. package/dist/sign-ins-secrets.js +109 -0
  386. package/dist/sign-ins-store.d.ts +200 -0
  387. package/dist/sign-ins-store.js +373 -0
  388. package/dist/sign-ins.d.ts +43 -7
  389. package/dist/sign-ins.js +94 -18
  390. package/dist/skills.d.ts +6 -5
  391. package/dist/skills.js +18 -14
  392. package/dist/standard-webhooks.d.ts +30 -0
  393. package/dist/standard-webhooks.js +72 -0
  394. package/dist/stats.d.ts +5 -7
  395. package/dist/stats.js +8 -24
  396. package/dist/stop-signals.d.ts +22 -0
  397. package/dist/stop-signals.js +38 -0
  398. package/dist/store/agent-body.d.ts +103 -0
  399. package/dist/store/agent-body.js +126 -0
  400. package/dist/store/dialect.d.ts +59 -0
  401. package/dist/store/dialect.js +32 -0
  402. package/dist/store/fence.d.ts +22 -0
  403. package/dist/store/fence.js +15 -0
  404. package/dist/store/index.d.ts +17 -0
  405. package/dist/store/index.js +17 -0
  406. package/dist/store/journal/storage.d.ts +137 -0
  407. package/dist/store/journal/storage.js +1021 -0
  408. package/dist/store/open.d.ts +34 -0
  409. package/dist/store/open.js +30 -0
  410. package/dist/store/postgres/connection.d.ts +74 -0
  411. package/dist/store/postgres/connection.js +532 -0
  412. package/dist/store/postgres/dialect.d.ts +9 -0
  413. package/dist/store/postgres/dialect.js +39 -0
  414. package/dist/store/postgres/migrate.d.ts +21 -0
  415. package/dist/store/postgres/migrate.js +106 -0
  416. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  417. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  418. package/dist/store/postgres/store.d.ts +37 -0
  419. package/dist/store/postgres/store.js +48 -0
  420. package/dist/store/prompts.d.ts +11 -0
  421. package/dist/store/prompts.js +112 -0
  422. package/dist/store/schema.d.ts +26 -0
  423. package/dist/store/schema.js +522 -0
  424. package/dist/store/seal.d.ts +48 -0
  425. package/dist/store/seal.js +69 -0
  426. package/dist/store/sqlite/connection.d.ts +105 -0
  427. package/dist/store/sqlite/connection.js +309 -0
  428. package/dist/store/sqlite/memory.d.ts +2 -0
  429. package/dist/store/sqlite/memory.js +4 -0
  430. package/dist/store/sqlite/run-launch.d.ts +8 -0
  431. package/dist/store/sqlite/run-launch.js +20 -0
  432. package/dist/store/sqlite/run-patch.d.ts +54 -0
  433. package/dist/store/sqlite/run-patch.js +114 -0
  434. package/dist/store/sqlite/store.d.ts +33 -0
  435. package/dist/store/sqlite/store.js +1337 -0
  436. package/dist/store/sqlite/worker.d.ts +78 -0
  437. package/dist/store/sqlite/worker.js +242 -0
  438. package/dist/store/store.d.ts +1253 -0
  439. package/dist/store/store.js +190 -0
  440. package/dist/store-reads/analytics.d.ts +55 -0
  441. package/dist/store-reads/analytics.js +135 -0
  442. package/dist/store-reads/cap.d.ts +17 -0
  443. package/dist/store-reads/cap.js +17 -0
  444. package/dist/store-reads/decisions.d.ts +5 -0
  445. package/dist/store-reads/decisions.js +31 -0
  446. package/dist/store-reads/import-summary.d.ts +6 -0
  447. package/dist/store-reads/import-summary.js +14 -0
  448. package/dist/store-reads/journal.d.ts +30 -0
  449. package/dist/store-reads/journal.js +120 -0
  450. package/dist/store-reads/learning.d.ts +93 -0
  451. package/dist/store-reads/learning.js +202 -0
  452. package/dist/store-reads/runs.d.ts +42 -0
  453. package/dist/store-reads/runs.js +84 -0
  454. package/dist/store-reads/stats.d.ts +30 -0
  455. package/dist/store-reads/stats.js +59 -0
  456. package/dist/store-reads/workflow.d.ts +7 -0
  457. package/dist/store-reads/workflow.js +14 -0
  458. package/dist/store-view.d.ts +37 -0
  459. package/dist/store-view.js +305 -0
  460. package/dist/template-eval.d.ts +239 -0
  461. package/dist/template-eval.js +1020 -0
  462. package/dist/template-github-permissions.d.ts +18 -0
  463. package/dist/template-github-permissions.js +32 -0
  464. package/dist/templates.d.ts +199 -0
  465. package/dist/templates.js +637 -0
  466. package/dist/tool-blurbs.d.ts +4 -0
  467. package/dist/tool-blurbs.js +27 -0
  468. package/dist/tool-gate.d.ts +166 -35
  469. package/dist/tool-gate.js +411 -91
  470. package/dist/tool-keys-store.d.ts +110 -0
  471. package/dist/tool-keys-store.js +291 -0
  472. package/dist/tool-keys.d.ts +25 -12
  473. package/dist/tool-keys.js +20 -2
  474. package/dist/tool-plane.d.ts +113 -27
  475. package/dist/tool-plane.js +229 -76
  476. package/dist/tool-settings-store.d.ts +30 -0
  477. package/dist/tool-settings-store.js +53 -0
  478. package/dist/tools.d.ts +95 -24
  479. package/dist/tools.js +337 -61
  480. package/dist/trigger-accept.d.ts +36 -0
  481. package/dist/trigger-accept.js +152 -0
  482. package/dist/trigger-adapter.d.ts +143 -0
  483. package/dist/trigger-adapter.js +31 -0
  484. package/dist/trigger-adapters.d.ts +2 -0
  485. package/dist/trigger-adapters.js +4 -0
  486. package/dist/trigger-github.d.ts +2 -0
  487. package/dist/trigger-github.js +85 -0
  488. package/dist/trigger-schedule.d.ts +6 -0
  489. package/dist/trigger-schedule.js +115 -0
  490. package/dist/trigger-secrets-shown.d.ts +66 -0
  491. package/dist/trigger-secrets-shown.js +77 -0
  492. package/dist/trigger-signatures.d.ts +58 -0
  493. package/dist/trigger-signatures.js +79 -0
  494. package/dist/trigger-targets.d.ts +46 -0
  495. package/dist/trigger-targets.js +95 -0
  496. package/dist/trigger-webhook.d.ts +2 -0
  497. package/dist/trigger-webhook.js +92 -0
  498. package/dist/triggers.d.ts +282 -237
  499. package/dist/triggers.js +720 -608
  500. package/dist/turn-end.d.ts +3 -0
  501. package/dist/turn-end.js +3 -0
  502. package/dist/uploads.d.ts +10 -8
  503. package/dist/uploads.js +45 -45
  504. package/dist/usage.d.ts +33 -3
  505. package/dist/usage.js +38 -4
  506. package/dist/validate.d.ts +6 -0
  507. package/dist/validate.js +42 -12
  508. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  509. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  510. package/dist/web-fetch.d.ts +17 -9
  511. package/dist/web-fetch.js +53 -18
  512. package/dist/web-search.d.ts +1 -1
  513. package/dist/web-search.js +1 -1
  514. package/dist/webhooks.d.ts +33 -23
  515. package/dist/webhooks.js +69 -56
  516. package/dist/wires.d.ts +11 -0
  517. package/dist/wires.js +7 -0
  518. package/dist/workspace/archil-claim.d.ts +57 -0
  519. package/dist/workspace/archil-claim.js +154 -0
  520. package/dist/workspace/archil-disk.d.ts +104 -0
  521. package/dist/workspace/archil-disk.js +254 -0
  522. package/dist/workspace/archil-exec.d.ts +59 -0
  523. package/dist/workspace/archil-exec.js +218 -0
  524. package/dist/workspace/archil-key.d.ts +17 -0
  525. package/dist/workspace/archil-key.js +30 -0
  526. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  527. package/dist/workspace/archil-mount-credential.js +165 -0
  528. package/dist/workspace/archil.d.ts +59 -0
  529. package/dist/workspace/archil.js +676 -0
  530. package/dist/workspace/attach.d.ts +48 -0
  531. package/dist/workspace/attach.js +439 -0
  532. package/dist/workspace/computer-deps.d.ts +58 -0
  533. package/dist/workspace/computer-deps.js +113 -0
  534. package/dist/workspace/computer-for-claim.d.ts +115 -0
  535. package/dist/workspace/computer-for-claim.js +198 -0
  536. package/dist/workspace/computer-hold.d.ts +145 -0
  537. package/dist/workspace/computer-hold.js +258 -0
  538. package/dist/workspace/computer-ledger.d.ts +22 -0
  539. package/dist/workspace/computer-ledger.js +19 -0
  540. package/dist/workspace/computer-ports.d.ts +13 -0
  541. package/dist/workspace/computer-ports.js +108 -0
  542. package/dist/workspace/computer-providers.d.ts +12 -0
  543. package/dist/workspace/computer-providers.js +17 -0
  544. package/dist/workspace/computer-serves.d.ts +12 -0
  545. package/dist/workspace/computer-serves.js +15 -0
  546. package/dist/workspace/executors.d.ts +38 -0
  547. package/dist/workspace/executors.js +150 -0
  548. package/dist/workspace/glob.d.ts +2 -0
  549. package/dist/workspace/glob.js +25 -0
  550. package/dist/workspace/grep-worker.d.ts +11 -0
  551. package/dist/workspace/grep-worker.js +91 -0
  552. package/dist/workspace/hands.d.ts +25 -0
  553. package/dist/workspace/hands.js +121 -0
  554. package/dist/workspace/index.d.ts +23 -0
  555. package/dist/workspace/index.js +25 -0
  556. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  557. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  558. package/dist/workspace/kind-skills.d.ts +11 -0
  559. package/dist/workspace/kind-skills.js +16 -0
  560. package/dist/workspace/learning-workspace.d.ts +24 -0
  561. package/dist/workspace/learning-workspace.js +107 -0
  562. package/dist/workspace/local.d.ts +6 -0
  563. package/dist/workspace/local.js +632 -0
  564. package/dist/workspace/paths.d.ts +48 -0
  565. package/dist/workspace/paths.js +134 -0
  566. package/dist/workspace/pi-env.d.ts +39 -0
  567. package/dist/workspace/pi-env.js +397 -0
  568. package/dist/workspace/place.d.ts +7 -0
  569. package/dist/workspace/place.js +3 -0
  570. package/dist/workspace/resolve-computer.d.ts +106 -0
  571. package/dist/workspace/resolve-computer.js +188 -0
  572. package/dist/workspace/revision-skills.d.ts +15 -0
  573. package/dist/workspace/revision-skills.js +42 -0
  574. package/dist/workspace/run-tools.d.ts +173 -0
  575. package/dist/workspace/run-tools.js +172 -0
  576. package/dist/workspace/run-workspace.d.ts +25 -0
  577. package/dist/workspace/run-workspace.js +56 -0
  578. package/dist/workspace/server-run-workspace.d.ts +24 -0
  579. package/dist/workspace/server-run-workspace.js +84 -0
  580. package/dist/workspace/workspace.d.ts +169 -0
  581. package/dist/workspace/workspace.js +54 -0
  582. package/dist/workspace-paths.d.ts +1 -10
  583. package/dist/workspace-paths.js +3 -37
  584. package/dist/workspace.d.ts +3 -17
  585. package/dist/workspace.js +6 -74
  586. package/harnesses/claude-agent/package-lock.json +1533 -0
  587. package/harnesses/claude-agent/package.json +7 -0
  588. package/harnesses/codex/package-lock.json +135 -0
  589. package/harnesses/codex/package.json +7 -0
  590. package/launcher/agentrun-serve +13 -3
  591. package/package.json +36 -21
  592. package/skills/agentrun-serve/SKILL.md +2 -0
  593. package/templates/README.md +211 -0
  594. package/templates/code-review/agent.md +50 -0
  595. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  596. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  597. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  598. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  599. package/templates/code-review/evals/injection/case.yaml +3 -0
  600. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  601. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  602. package/templates/code-review/evals/injection/prompt.md +23 -0
  603. package/templates/code-review/evals/null-name/case.yaml +3 -0
  604. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  605. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  606. package/templates/code-review/evals/null-name/prompt.md +17 -0
  607. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  608. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  609. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  610. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  611. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  612. package/templates/code-review/evals/re-review/case.yaml +3 -0
  613. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  614. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  615. package/templates/code-review/evals/re-review/prompt.md +23 -0
  616. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  617. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  618. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  619. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  620. package/templates/code-review/findings.schema.json +125 -0
  621. package/templates/code-review/rules/REVIEW.md +41 -0
  622. package/templates/code-review/skills/review/SKILL.md +162 -0
  623. package/templates/inbound-lead/agent.md +76 -0
  624. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  626. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  627. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  629. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  630. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  631. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  632. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  633. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  634. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  635. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  636. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  637. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  638. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  639. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  640. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  641. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  644. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  645. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  646. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  647. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  648. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  649. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  650. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  652. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  654. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  656. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  657. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  658. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  659. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  660. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  661. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  662. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  663. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  664. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  665. package/templates/inbound-lead/lead.schema.json +587 -0
  666. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  667. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  668. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  669. package/templates/kyb/agent.md +44 -0
  670. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  671. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  672. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  673. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  674. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  675. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  676. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  677. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  678. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  679. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  680. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  681. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  682. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  683. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  684. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  685. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  686. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  687. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  688. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  689. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  690. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  691. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  692. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  693. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  694. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  695. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  696. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  697. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  698. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  699. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  700. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  701. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  702. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  703. package/templates/kyb/kyb.schema.json +274 -0
  704. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  705. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  706. package/templates/kyb/rules/SANCTIONS.md +140 -0
  707. package/templates/kyb/rules/SOURCES.md +92 -0
  708. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  709. package/templates/market-monitor/agent.md +58 -0
  710. package/templates/market-monitor/digest.schema.json +194 -0
  711. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  712. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  713. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  714. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  715. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  716. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  717. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  719. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  720. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  721. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  722. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  723. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  724. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  725. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  726. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  727. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  728. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  729. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  730. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  731. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  733. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  734. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  735. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  736. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  737. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  739. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  741. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  742. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  743. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  744. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  745. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  746. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  747. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  748. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  749. package/templates/market-monitor/rules/MONITOR.md +33 -0
  750. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  751. package/templates/release-notes/agent.md +47 -0
  752. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  753. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  754. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  755. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  756. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  757. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  758. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  759. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  760. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  761. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  762. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  763. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  764. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  765. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  766. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  767. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  768. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  769. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  770. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  771. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  772. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  773. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  774. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  775. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  776. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  777. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  778. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  779. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  780. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  781. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  782. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  783. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  784. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  785. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  786. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  787. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  788. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  789. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  790. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  791. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  792. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  793. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  794. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  795. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  796. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  797. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  798. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  799. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  800. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  801. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  802. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  803. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  804. package/templates/release-notes/notes.schema.json +145 -0
  805. package/templates/release-notes/rules/STYLE.md +47 -0
  806. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  807. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  808. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  809. package/dist/trigger-secrets.d.ts +0 -32
  810. package/dist/trigger-secrets.js +0 -143
package/dist/runs.js CHANGED
@@ -5,24 +5,32 @@
5
5
  // again on its directory, and resumes from its store.
6
6
  import { spawn } from "node:child_process";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
- import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
- import { open as openFile, rm, stat } from "node:fs/promises";
8
+ import { once } from "node:events";
9
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
10
+ import { open as openFile, readFile, rm, stat } from "node:fs/promises";
10
11
  import { join } from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
13
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
13
14
  import { processAlive } from "@parcha/agentrun-kernel/host";
14
- import { doorTook } from "@parcha/pi-durable-disk";
15
- import { AgentHomeError } from "@parcha/pi-durable-agent";
16
- import { chargedTool, isMessageRow, registerLabel, registerTurnEnding, REQUEST_STARTED, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
15
+ import { doorKey, doorTook } from "@parcha/pi-durable-disk";
16
+ import { RUN_STATUS_TABLE } from "@parcha/pi-durable-disk/internals";
17
+ import { AgentHomeError, runDirIn } from "@parcha/pi-durable-agent";
18
+ import { endedUsage, isMessageRow, MESSAGE_ORIGIN, NOTE_SUFFIX, originOf, REQUEST_STARTED, runMetricsWithDecisions, scrubUrls, timelineOf, timelineReducer, TRIGGER_LABELS } from "@parcha/pi-durable-agent/timeline";
17
19
  import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
18
- import { DEFAULT_HARNESS, harnessOfBody, steersMidTurn } from "./harness.js";
20
+ import { runLink } from "./console-links.js";
21
+ import { harnessOfBody } from "./harness.js";
22
+ import { builtinHarness, harnessOf } from "./harness-table.js";
19
23
  import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
20
24
  import { storeBusy, storeError, whenFree } from "./agents.js";
21
- import { FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, readJson, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, SETUP_LOST, writeDurableSync, writeWhole } from "./files.js";
22
- import { MCP_PIN, mcpCredentialsOf, mcpPinOf } from "./mcp-gateway.js";
25
+ import { dropHandover } from "./browser-live.js";
26
+ import { asked, askShown, dropAsks, HANDOFF_TOOL } from "./browser-person.js";
27
+ import { DATA_ENV, dataOfRun, FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, SETUP_LOST, writeDurableSync, writeWhole } from "./files.js";
28
+ import { MCP_PIN, mcpCredentialsOf, mcpNameOf, mcpPinOf } from "./mcp-gateway.js";
23
29
  import { META_REASON, metaToolOf } from "./mcp-meta.js";
24
30
  import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
31
+ import { servedOnly, servedOnlyIds } from "./served-only.js";
25
32
  import { LEARNING_LABEL, shortOf } from "./learning.js";
33
+ import { Hearing } from "./heard.js";
26
34
  import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
27
35
  import { settleBox, sweepBoxes } from "./box/sweep.js";
28
36
  import { rowPaths } from "./workspace-paths.js";
@@ -31,45 +39,99 @@ import { withDecisions } from "./decision-rows.js";
31
39
  import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
32
40
  import { ApiError, invalid, unsupported } from "./errors.js";
33
41
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
34
- import { CAP_ENV, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
42
+ import { CAP_ENV, CAP_MODE_ENV, CAP_MODES, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
35
43
  import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
36
44
  import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
45
+ import { BUDGET_PAUSE, budgetPausedIn, capStoppedIn, clearBudgetPause, raiseFinishes, writeRaisedCap } from "./budget.js";
37
46
  import { durationMs } from "./print.js";
38
47
  import { handsParallel, keptFromBefore, keptVendor, planeFor, recheckPlane, relaunchPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
39
- import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV, previewOf, RESUME_PREFIX, TURN_ORIGIN_FILE } from "./tool-gate.js";
48
+ import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV, RESUME_PREFIX, resumeHead, TURN_ORIGIN_FILE } from "./tool-gate.js";
49
+ import { approvalsOf } from "./approvals.js";
40
50
  import { ChangeClock, RowLog } from "./rows.js";
41
51
  import { TOOL_KEYS } from "./tool-keys.js";
42
52
  import { isObject } from "./validate.js";
53
+ import { RequestBounds } from "./bounds.js";
43
54
  import { firstMessage } from "./run-manifest.js";
44
55
  import { REFLECT_REQUEST, Turns } from "./turns.js";
45
- import { DECISION_KEYS, handover, handoverSignIn, hostSecrets, mcpHandover, mcpSecretValues, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
56
+ import { DECISION_KEYS, handover, handoverSignIn, mcpHandover, mcpSecretValues, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
57
+ import { pointerHash } from "./sign-ins.js";
46
58
  import { MIN_SECRET } from "./learn/secrets.js";
47
- import { keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf, withoutLoopback } from "./key-refusal.js";
48
- import { GRAPH_CACHE_BYTES, PartCache, servedPart } from "./graph-served.js";
59
+ import { cutStrings, keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf } from "./key-refusal.js";
49
60
  import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
50
61
  import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
51
62
  import { remotePlace, storedPlace } from "./place.js";
52
- import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, RUN_LABEL, sweepRunBoxes } from "./run-box.js";
53
- import { BACKGROUND_DIR, endBackground } from "./background.js";
63
+ import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
54
64
  import { removeEgressDir, RUN_BOX_ALLOW_ENV } from "./box-egress.js";
65
+ import { BehindReadError, checkpointRunDb, MonotonicReads, readRunDb } from "./run-db.js";
66
+ import { holderLives, holderOfClaim, holderOfProcess, holderState, killHolder, LAUNCH_HOLDER, RUN_EPOCH_ENV, RUN_LAUNCH_ENV, signal } from "./run-holder.js";
67
+ import { firstDoorLine, untilOpened, verifyDoor } from "./door-line.js";
68
+ import { BUDGET_PAUSED, actingOn, approvalOf, browserPending, budgetPending, cents, centsUp, continuationOf, costOf, costView, handedMark, handedPointers as handedPointersOf, knownToolCostOf, MALFORMED, meaningful, micro, microUp, overByMiss, pauseOf, pausedAt, pendingOf, raisedToGo, redactorOf, refusedValuesOf, rowShown as rowShownOf, servedReviewWith, servedRunErrorWith, shownOf, HELD, outcomeSays, outcomeShows, soFarOf, statusOf as statusOfView, stopped, stoppedAt, SUGGESTED_RAISE_FACTOR, suggestedCap, shownArgs, toolCostOf, usersOf, waitingApproval, WITHHELD_SIGN_IN, withAsks, withdrawn, withOverCap, withPaused } from "./run-view.js";
69
+ // The cost reads, the served row transforms, the status and pending views and the redaction choke point kept their import
70
+ // path here for the server routes and tests that read them from this module.
71
+ export { costOf, costView, knownToolCostOf, soFarOf, toolCostOf, withOverCap, withPaused, stoppedAt, suggestedCap, SUGGESTED_RAISE_FACTOR, WITHHELD_SIGN_IN };
72
+ /** `holder` with this launch's door nonce, which the row keeps so a next server can prove the door too. */
73
+ const withNonce = (holder, nonce) => holder && { ...holder, nonce };
74
+ import { localDisk } from "./disk.js";
55
75
  import { RUN_BOX_VOLUME_ENV } from "./box-egress-vm.js";
76
+ import { egressParentOf, RUN_BOX_PATHS_ENV } from "./box-paths.js";
56
77
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
78
+ // Status and State move to run-view.ts (the run's served view), re-exported above.
57
79
  export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
58
80
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
59
81
  const RELEASED = new Set(["sleeping", "paused", "done", "failed"]);
60
- const LEASE_MS = 90_000;
61
82
  /** How long an agentic run's process may finish its turn after SIGTERM, unless the server says otherwise. */
62
83
  const DRAIN = "30s";
63
- /** The run process's stderr, beside run.json: a file, so the process outlives a server that stops without stopping it. */
84
+ /** The run process's stderr, in its folder: a file, so the process outlives a server that stops without stopping it. */
64
85
  const PROCESS_LOG = "process.log";
65
86
  /** How long a request waits for a run's door: its process coming up, or a settle in progress. */
66
87
  const READY_TIMEOUT_MS = 45_000;
88
+ /** How long a launched process whose door failed its proof has to exit on its own before it is stopped. */
89
+ const DOOR_EXIT_WAIT_MS = 2_000;
90
+ /** How often a raised workflow run waiting for a place to open again in tries again (finishRaise, waitForPlace). */
91
+ const PLACE_RETRY_MS = 1_000;
92
+ /** How many launches in a row a raised run waiting for a place may fail before it leaves the queue (finishRaise). */
93
+ const RAISE_TRIES = 3;
67
94
  /** The reducer's live "Run started" and "Run finished" rows: a turn's edges, which no store entry makes on any harness,
68
95
  * so a run's settled timeline never has them. Never served, live or settled, so no row a reader saw goes at the end. */
69
96
  const QUIET = /:run:(start|end)$/;
70
97
  const RETRY_CODES = ["OPENING", "PARKING", "RELEASED"];
71
98
  /** How often one server opens a run again whose process went before the run ended, before it fails the run. */
72
99
  const MAX_RELAUNCHES = 3;
100
+ // MALFORMED, the Handed type and handedMark move to run-view.ts (the run's served view), imported above.
101
+ /** A run's serve.json at `path`, the one read every reader of it shares (load, forget's handedTo, a list row): `stored`,
102
+ * what it holds when it is whole JSON of an object, else null; `damaged`, whether it is there but can't be read or
103
+ * parsed (a damaged disk, a hand's edit), as told apart from not there (a run never set up, never launched). */
104
+ async function readMeta(path) {
105
+ const text = await readFile(path, "utf8").catch((error) => (error.code === "ENOENT" ? undefined : null));
106
+ if (text === undefined)
107
+ return { stored: null, damaged: false };
108
+ let stored = null;
109
+ try {
110
+ stored = text === null ? null : JSON.parse(text);
111
+ }
112
+ catch {
113
+ stored = null;
114
+ }
115
+ return isObject(stored) ? { stored: stored, damaged: false } : { stored: null, damaged: true };
116
+ }
117
+ /** What a run's serve.json at `path` says it was handed of its agent's sign-in, read from disk for a run this server does
118
+ * not hold: as load reads it, and MALFORMED for a serve.json that is damaged, as a held run's `damaged` reads. */
119
+ async function handedOnDisk(path) {
120
+ const { stored, damaged } = await readMeta(path);
121
+ return damaged ? MALFORMED : handedMark(stored?.sign_in_handed);
122
+ }
123
+ /** Why a run going when its server started was stopped: the browser sign-in it was handed can't be read here (the seal
124
+ * key changed or is missing, or the sign-ins file is damaged or can't be read). */
125
+ export const UNREADABLE_SIGN_IN = "This server can't read the run's browser sign-in (its seal key changed or is missing, or the sign-in is damaged): the run was stopped, so nothing it says can show it.";
126
+ /** Why a run going when its server started was stopped: its serve.json is there but can't be read or parsed, and with it
127
+ * went which browser it ran on and whether it was handed its agent's sign-in, so its text can't be cut of the pointer. */
128
+ export const UNREADABLE_RUN_META = "This server can't read the run's record (its serve.json is damaged or can't be read), so it can't tell whether the run was handed its agent's browser sign-in: the run was stopped, so nothing it says can show it.";
129
+ // WITHHELD_SIGN_IN moves to run-view.ts (the run's served view), re-exported above.
130
+ /** How soon a launch whose claim was refused tries again, at its first tries: a store another writer holds is let go of
131
+ * within moments, and a run waits on its launch. Past these, every settle retry. */
132
+ const CLAIM_RETRY_MS = [50, 100, 200, 400, 800, 1_600];
133
+ /** The epoch of the claim a run's process holds, which the server gave it at its launch (run-holder.ts). */
134
+ export { RUN_EPOCH_ENV };
73
135
  /** How often a run's end that the agent store refused is written again. */
74
136
  const SETTLE_RETRY_MS = 30_000;
75
137
  /** How a run ended in the store, as its status: the store's `stopped` is v2's `cancelled`, and an escalated workflow
@@ -83,8 +145,6 @@ const CARRY_BACK_RETRIES_MS = [500, 1_000, 2_000, 4_000, 8_000];
83
145
  /** How long a run's process may live on after it released the run before its store is read anyway: the process holds the
84
146
  * store's exclusive lock until it exits. */
85
147
  const EXIT_AFTER_RELEASE_MS = 30_000;
86
- /** How many 500 ms ticks in a row a live run's record is unreadable before the server says so. */
87
- const UNREADABLE_TICKS = 10;
88
148
  const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
89
149
  /** How long serve's calls on a run's box (its destroy, the start's sweep) may take. */
90
150
  const BOX_CALL_MS = 60_000;
@@ -96,6 +156,10 @@ const PULL_WAIT_MS = 120_000;
96
156
  /** A run's end that waits for its remote box's last pull: its settle is tried again until the pull lands. */
97
157
  class PullPending extends Error {
98
158
  }
159
+ /** A settle that cannot tell who holds the run (its row, or the process listing, cannot be read): tried again, never taken
160
+ * for a holder that is gone. */
161
+ class HolderUnknown extends Error {
162
+ }
99
163
  /** Run directory `dir`'s own door token, made now (mode 0600, never through a link) when it has none. */
100
164
  function ensureRunDoorToken(dir) {
101
165
  const held = runDoorToken(dir);
@@ -118,7 +182,6 @@ function ensureRunDoorToken(dir) {
118
182
  }
119
183
  const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
120
184
  const isLoopback = (host) => host === "localhost" || host === "[::1]" || host === "::1" || /^127\./.test(host);
121
- const holderPid = (record) => (isObject(record?.holder) && Number.isSafeInteger(record.holder.pid) ? record.holder.pid : undefined);
122
185
  /** How a workflow run's workflow ended, as its app wrote it in the run's final status: absent until it ended. */
123
186
  function workflowEnding(record) {
124
187
  const detail = isObject(record?.detail) ? record.detail : undefined;
@@ -126,8 +189,6 @@ function workflowEnding(record) {
126
189
  return undefined;
127
190
  return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
128
191
  }
129
- /** A call withdrawn with its run (a cancel, or a stop while it waited): never run, and an answer after is 409. */
130
- const withdrawn = (answer) => answer?.decision === "canceled" || answer?.decision === "withdrawn";
131
192
  /** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
132
193
  const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
133
194
  /** A failed run's error from its row and serve.json: its own, else the row's summary. */
@@ -135,40 +196,18 @@ const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", me
135
196
  /** An ended run's review from its row and serve.json: an escalated one's as its end saved it, else (an end saved before
136
197
  * reviews were kept) the row's summary; null for every other run. */
137
198
  const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
199
+ /** GET /runs/{id}/graph's view (graph-view.ts, loaded when a graph is first read). */
138
200
  /** A value's sha256, of its JSON. */
139
201
  const digestOf = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
140
- const ASKED = "Asked you: ";
141
- registerLabel(ASK_TOOL, (args) => `${ASKED}${typeof args.question === "string" ? args.question : ""}`, undefined, { name: "Ask you a question" });
142
- // ask_person ends its turn (tools.ts): the person's reply is their next message, never a steer.
143
- registerTurnEnding(ASK_TOOL);
144
- /** The waiting row after each answered `ask_person` call, which the timeline module does not know. The question comes
145
- * from the call's row, whose label this module registers. */
146
- export function withAsks(rows) {
147
- const out = [];
148
- const questions = new Map();
149
- for (const row of rows) {
150
- out.push(row);
151
- if (row.kind === "tool_use" && row.tool_name === ASK_TOOL && row.tool_use_id && row.summary?.startsWith(ASKED))
152
- questions.set(row.tool_use_id, row.summary.slice(ASKED.length));
153
- if (row.kind === "tool_result" && row.tool_name === ASK_TOOL && row.tool_status === "success") {
154
- const question = questions.get(row.tool_use_id ?? "") || "the agent asked you a question";
155
- out.push({ ...row, id: `${row.id}:waiting`, kind: "waiting", summary: `Waiting for you: ${clip(question, 480)}`, text: clip(question, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null });
156
- }
157
- }
158
- return out;
159
- }
160
- /** The row that says a run's booked spend passed its cap, and by how much, after its usage row: a request's cost is
161
- * booked once it answers, and one carrying a native web search is held at an allowance, not a bound (cap.ts), so a run
162
- * can pass its cap by its last request. The next request is then refused, and the run ends spend_cap_reached. */
163
- export function withOverCap(rows, cap) {
164
- const at = rows.findLastIndex((row) => row.kind === "usage");
165
- const usd = rows[at]?.usage?.usd;
166
- if (cap === undefined || typeof usd !== "number" || usd <= cap + FIT_TOLERANCE)
167
- return rows;
168
- const { usage: _, ...usage } = rows[at];
169
- const over = { ...usage, id: `${usage.id}:over_cap`, kind: "phase", summary: `Spent $${usd.toFixed(4)}, $${(usd - cap).toFixed(4)} over the run's cap of $${cap}`, text: null };
170
- return [...rows.slice(0, at + 1), over, ...rows.slice(at + 1)];
171
- }
202
+ // ask_person's label, its turn-ending rule and withAsks moved to run-view.ts (the store-backed view uses them too); this
203
+ // module imports withAsks from there, and run-view's load registers the label.
204
+ /** The over-cap row and the cent-rounding its words use move to run-view.ts (over the run's rows), unchanged. */
205
+ /** A user message's text parts, joined as the timeline joins them. */
206
+ const userText = (message) => {
207
+ const content = isObject(message) ? message.content : undefined;
208
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.filter(isObject) : [];
209
+ return blocks.filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("\n").trim();
210
+ };
172
211
  /** Notes the messages the run's turns took and how each turn ended, from `entries` (its root's), `submissions` (pi's
173
212
  * input submissions) and a reconnect's `snapshot` of them (the door's `inputs`, the run's whole state of them), and the
174
213
  * newest entry (learning-run.ts reads it). The end-of-run learning turn's entries are no turn of the run's: none of
@@ -183,7 +222,12 @@ function noteTurns(run, entries, submissions = [], snapshot) {
183
222
  if (data)
184
223
  run.capMark = value.id;
185
224
  if (data)
186
- run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd } : undefined;
225
+ run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" && typeof data.leastCapUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd, leastCapUsd: data.leastCapUsd, ...(typeof data.boundUsd === "number" && data.boundUsd > 0 ? { boundUsd: data.boundUsd } : {}) } : undefined;
226
+ // What was said to the run, whole, by entry (heard.ts): kept only while its learning has yet to keep it (seeded or
227
+ // reflecting), so a run that does not learn holds none, and learning-run.ts beforeSettle lets it go once kept.
228
+ const learning = run.meta.learning?.state;
229
+ if (learning === "seeded" || learning === "reflecting")
230
+ (run.hearing ??= new Hearing()).note(value);
187
231
  // The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
188
232
  // (learning-run.ts). The ledger skips them; this is their only reader here.
189
233
  if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
@@ -193,16 +237,26 @@ function noteTurns(run, entries, submissions = [], snapshot) {
193
237
  }
194
238
  const reflect = (id) => reflects(run.meta.reflect, id);
195
239
  run.turns.note(entries, submissions, reflect);
240
+ (run.bounds ??= new RequestBounds()).note(entries, run.meta.max_cost_usd);
196
241
  if (snapshot)
197
242
  run.turns.snapshot(snapshot, reflect);
198
243
  }
199
- /** Read only on a run's `rows`, which hold no QUIET row (take). */
200
- const shows = (r) => r.kind !== "usage" && r.kind !== "phase";
201
- const meaningful = (rows) => rows.findLast((r) => shows(r) && r.agent_label !== LEARNING_LABEL);
202
- const pendingOf = (rows) => {
203
- const last = meaningful(rows);
204
- return last?.kind === "waiting" ? { kind: "question", question: last.text ?? last.summary ?? "", asked_at: last.timestamp } : null;
244
+ // shows, meaningful, the Pending type and pendingOf move to run-view.ts (the run's served view), imported above.
245
+ /** The ask its agent made for the person in its browser (browser-person.ts) that the run waits on, once its waiting row
246
+ * is in the run's rows. */
247
+ const browserAsk = (run) => (run.dir ? askShown(run.dir, run.rows) : undefined);
248
+ /** Whether the run's agent waits on an ask a process must still take up: unanswered, expired or not; or answered, while
249
+ * the agent's hand-off call has no saved result yet (the owner answered after its process went: the answer is on disk,
250
+ * but only a process that takes the ask up hands it to the agent). */
251
+ const askWaits = (run) => run.dir !== undefined && (askShown(run.dir, run.rows, "waiting") !== undefined || (handoffOpen(run.rows) && asked(run.dir)));
252
+ /** Whether a hand-off call of the agent's (HANDOFF_TOOL) has no saved result: the call is still under way, or was cut off
253
+ * with its process. A cut-off call shows an "interrupted" result row, which is no result (no output: tool_result_size_bytes
254
+ * null, as the timeline marks it); the next process resumes the call and saves its real one. */
255
+ const handoffOpen = (rows) => {
256
+ const done = new Set(rows.filter((row) => row.kind === "tool_result" && row.tool_name === HANDOFF_TOOL && row.tool_result_size_bytes !== null).map((row) => row.tool_use_id));
257
+ return rows.some((row) => row.kind === "tool_use" && row.tool_name === HANDOFF_TOOL && !done.has(row.tool_use_id));
205
258
  };
259
+ // browserPending moves to run-view.ts (the run's served view), taking the ask as input; imported above.
206
260
  /** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
207
261
  * acted on. */
208
262
  function noteApprovals(run, entries) {
@@ -218,15 +272,15 @@ function noteApprovals(run, entries) {
218
272
  known.resolved = true;
219
273
  }
220
274
  }
221
- /** The tool call that waits for a person's answer: requested in the run's store, not resolved there, not answered. */
222
- const waitingApproval = (run) => [...(run.approvals?.values() ?? [])].find((a) => !a.resolved && !run.meta.approvals?.[a.id]);
223
- /** What is shown of a call's arguments: the whole of them redacted with the run's redactor, then cut (previewOf), so
224
- * no cut leaves the head of a held key. */
225
- const shownArgs = (approval, redact) => previewOf(redact(approval.args_json));
275
+ // waitingApproval and shownArgs move to run-view.ts (the run's served view), imported above.
226
276
  /** `entries` with the gate's resume messages (RESUME_PREFIX) redacted whole with `redact`, before the timeline cuts
227
- * them: the message carries a call's arguments and its result, which may hold a held key. */
277
+ * them: the message carries a call's arguments and its result, which may hold a held key. The marker that names a
278
+ * resume the server's (its origin, on pi) is redacted alike, so its text is still the message's, which it matches. */
228
279
  function redactGateMessages(entries, redact) {
229
280
  return entries.map((entry) => {
281
+ const data = isObject(entry) && entry.kind === MESSAGE_ORIGIN && isObject(entry.data) ? entry.data : undefined;
282
+ if (data && typeof data.text === "string" && data.text.startsWith(RESUME_PREFIX))
283
+ return { ...entry, data: { ...data, text: redact(data.text) } };
230
284
  const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
231
285
  if (!isObject(first) || first.role !== "user")
232
286
  return entry;
@@ -238,22 +292,59 @@ function redactGateMessages(entries, redact) {
238
292
  return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
239
293
  });
240
294
  }
241
- /** The run's pending approval (`pending`, kind approval): the call that waits; else undefined. */
242
- const approvalOf = (run, redact) => {
243
- const waiting = waitingApproval(run);
244
- return waiting ? { kind: "approval", id: waiting.id, tool: waiting.tool, call_id: waiting.call_id, args_preview: shownArgs(waiting, redact), requested_at: waiting.requested_at, ...(waiting.price !== undefined ? { price: waiting.price } : {}) } : undefined;
245
- };
246
- /** One answered (allow or deny) whose answer the run's process has not acted on yet. */
247
- const actingOn = (run) => [...(run.approvals?.values() ?? [])].some((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
295
+ // approvalOf and actingOn move to run-view.ts (the run's served view), imported above.
248
296
  /** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
249
297
  * (`redact`, the Timeline's own: no held key), before any cut. */
250
- function withApprovals(rows, run, redact) {
298
+ function withApprovals(given, run, redact) {
251
299
  if (!run.approvals?.size)
252
- return [...rows];
300
+ return [...given];
301
+ // The approval rows are this function's own, made again below from each call's result row: rows it gave before (an
302
+ // answer's restate) come in without them, so it gives the same rows run on its own output.
303
+ const rows = given.filter((row) => row.kind !== APPROVAL_ROW);
253
304
  const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
254
305
  const waiting = waitingApproval(run);
306
+ // The result rows of the calls that waited for approval: the park answered each with the gate's waiting text.
307
+ const parkedResults = new Set(rows.filter((row) => row.kind === "tool_result" && row.tool_use_id && byCall.has(row.tool_use_id)).map((row) => row.id));
308
+ // A resume row's approval: from the gate's head the first time the row comes in (noted by its id), and by that id after,
309
+ // once the row's text is the rewritten one (`fresh` false: it is given as it is, never rewritten twice).
310
+ const links = (run.resumeRows ??= new Map());
311
+ const resumeOf = (row) => {
312
+ if (row.kind !== "phase")
313
+ return undefined;
314
+ if (row.text?.startsWith(RESUME_PREFIX)) {
315
+ const approval = resumedBy(row.text, byCall);
316
+ if (approval)
317
+ links.set(row.id, approval.id);
318
+ return approval ? { approval, fresh: true } : undefined;
319
+ }
320
+ const linked = links.get(row.id);
321
+ const approval = linked === undefined ? undefined : run.approvals.get(linked);
322
+ return approval ? { approval, fresh: false } : undefined;
323
+ };
324
+ // The approvals whose resume row is on the timeline: that row, after the approval's, says what came of the call.
325
+ const resumedIds = new Set(rows.flatMap((row) => { const found = resumeOf(row); return found ? [found.approval.id] : []; }));
255
326
  return rows.flatMap((row) => {
256
- const approval = row.kind === "tool_result" && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
327
+ // A Saved row (pi-durable-agent's, read from a write's arguments) of a call that waited: the park wrote nothing, a
328
+ // deny or a withdrawal never will, and what an allowed call wrote is its resume's, so the row would say a file was
329
+ // written that its call never wrote.
330
+ const savedBy = row.kind === "phase" ? /^(.*):saved:\d+$/.exec(row.id)?.[1] : undefined;
331
+ if (savedBy !== undefined && parkedResults.has(savedBy))
332
+ return [];
333
+ // The gate's resume, the server's row: it says what came of the answer, never the head the model reads.
334
+ const found = resumeOf(row);
335
+ if (found && !found.fresh)
336
+ return [row];
337
+ const resumed = found?.approval;
338
+ if (resumed)
339
+ return [{ ...row, summary: resumeSays(resumed, run.meta.approvals?.[resumed.id], row.text, redact), text: resumeShows(resumed, run.meta.approvals?.[resumed.id], row.text, redact) }];
340
+ const own = (row.kind === "tool_use" || row.kind === "tool_result") && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
341
+ // The call's own rows: what it answered at the park is not what it did. A client folds them into the call's step, at
342
+ // the call's place above the approval row, so once the resume row (below the approval's) says what came of it they
343
+ // say only that it was held; before that, they say what came of the approval.
344
+ const called = own ? { ...row, summary: resumedIds.has(own.id) && own !== waiting ? HELD : parkedCallSays(own, run, waiting), tool_status: null } : row;
345
+ if (row.kind === "tool_use")
346
+ return [called];
347
+ const approval = own;
257
348
  if (!approval)
258
349
  return [row];
259
350
  const args = shownArgs(approval, redact);
@@ -265,99 +356,86 @@ function withApprovals(rows, run, redact) {
265
356
  // the row says so (the record keeps them whole).
266
357
  const dropped = run.meta.approvals?.[approval.id]?.superseded;
267
358
  const text = dropped?.by === "message" && dropped.note !== undefined ? `${args}\n\nNot sent: the run was ${said === "canceled" ? "cancelled" : "stopped"}. Your message: ${redact(dropped.note)}` : args;
268
- return [row, { ...row, id: `${row.id}:approval`, kind: APPROVAL_ROW, summary, text, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null }];
359
+ return [called, { ...row, id: `${row.id}:approval`, kind: APPROVAL_ROW, summary, text, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null }];
269
360
  });
270
361
  }
271
- /** A dollar figure to a millionth, as the timeline's cost.usd is. */
272
- const micro = (usd) => Math.round(usd * 1e6) / 1e6;
362
+ /** What a call that waited for approval came to, as its own rows (its call's and its result's) say it: the park answered
363
+ * it with the gate's waiting text, so they never say it ran while it had not (no tool verb, no outcome, no status). */
364
+ function parkedCallSays(approval, run, waiting) {
365
+ const given = run.meta.approvals?.[approval.id];
366
+ if (approval === waiting || !given)
367
+ return approval.resolved ? "Not run" : "Not run yet: it waits for your approval";
368
+ const ended = given.decision === "canceled" ? "cancelled" : "stopped";
369
+ if (given.decision === "withdrawn" || given.decision === "canceled")
370
+ return given.superseded?.decision === "allow" ? `Allowed, then the run was ${ended}: no result of it reached the model` : `Not run: the run was ${ended} while it waited`;
371
+ if (given.decision === "deny")
372
+ return given.by === "message" ? "Not run: your message declined it" : "Not run: you declined it";
373
+ return approval.resolved ? "Ran once you allowed it; its result went to the agent" : "Allowed: it runs now";
374
+ }
375
+ /** The call a resume (resumeText, its text as the row has it) answers: its head names the call's tool and id. */
376
+ const resumedBy = (text, byCall) => [...byCall.values()].find((approval) => text.startsWith(`${RESUME_PREFIX}This answers your ${approval.tool} call ${approval.call_id} `));
377
+ /** A resume's row as the approval's outcome (run-view.ts outcomeSays, the store path's words too): what ran, or "You
378
+ * declined <tool>[: <note>]". */
379
+ function resumeSays(approval, given, text, redact) {
380
+ return outcomeSays(approval.tool, given ?? { decision: "allow" }, text.includes(" They allowed it, and it ran and failed."), redact);
381
+ }
382
+ /** What a person reads when they open a resume's row: the outcome, then the call's result or the refusal's words, from the
383
+ * model's message (already redacted whole, as the row's text is), with its head left out. The head is rebuilt exactly as
384
+ * the gate wrote it (tool-gate.ts resumeHead, from the stored answer's arguments), never searched for, so arguments that
385
+ * quote the gate's words can't move it; a row whose text doesn't start with it shows the outcome alone. The model's own
386
+ * message is unchanged. */
387
+ function resumeShows(approval, given, text, redact) {
388
+ const answer = given ?? { decision: "allow" };
389
+ const failed = text.includes(" They allowed it, and it ran and failed.");
390
+ // The row's text is the message as the Timeline shows it: redacted whole (the run's redactor) and its links scrubbed
391
+ // (scrubUrls), so the gate's head is compared after the same two steps.
392
+ const written = resumeHead(approval, given?.args_shown ?? "(not shown)");
393
+ const head = [scrubUrls(redact(written)), redact(written), scrubUrls(written), written].find((h) => text.startsWith(h));
394
+ if (head === undefined)
395
+ return answer.decision === "deny" ? outcomeShows(approval.tool, answer, "", false) : `${approval.tool} ran once you allowed it${failed ? ", and failed" : ""}.`;
396
+ const rest = text.slice(head.length).replace(/^ They allowed it, and it ran(?: and failed)?\. Its result:\n?/, "");
397
+ return outcomeShows(approval.tool, answer, rest, failed);
398
+ }
399
+ // micro and microUp move to run-view.ts (the run's served view), imported above.
273
400
  /** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
274
401
  const CONTINUE_TRIES = 3;
275
402
  const CONTINUE_RETRY_MS = [1_000, 3_000];
276
- /** How many of the refused request's least a run paused at its cap is offered on top of what was taken (suggestedCap). */
277
- export const SUGGESTED_RAISE_FACTOR = 10;
278
- /** The raise a run paused at its cap is offered: what the cap counted as taken plus SUGGESTED_RAISE_FACTOR times the
279
- * refused request's least, rounded up to a whole dollar, and always above the cap (the next dollar above it, if not),
280
- * so a PATCH with it is a raise. */
281
- export const suggestedCap = (cap, spentUsd, needsUsd) => {
282
- // A hair under, so a sum a float puts just past a whole dollar (3.0000000000000004) stays that dollar.
283
- const up = Math.ceil(spentUsd + SUGGESTED_RAISE_FACTOR * needsUsd - 1e-9);
284
- // Above the cap as a raise must be (by more than CAP_TOLERANCE, takeRaise), so a PATCH with it is always taken.
285
- return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
286
- };
287
- /** A run paused at its cap waits on a raise: its cap, what the cap counted as taken and the least the refused request
288
- * needs (its refusal's mark; none from a store written before it kept them), the raise it is offered (suggestedCap),
289
- * the refusal's words, and when it came (its error row's time). The figures are as the cap counts them, never rounded.
290
- * What was taken is the store's spend once its process is gone (`spentNow`), when that is lower: the refusal counted
291
- * requests still answering at what it held for them, and they have settled. */
292
- const budgetPending = (run, spentNow) => {
293
- const said = pausedAt(run);
294
- const cap = run.meta.max_cost_usd;
295
- if (said === undefined || cap === undefined)
403
+ // SUGGESTED_RAISE_FACTOR and suggestedCap move to run-view.ts (the run's served view), re-exported above.
404
+ // budgetPending moves to run-view.ts (the run's served view), imported above.
405
+ /** A workflow run paused at its cap (budget.ts): its step waits for a raise in its process, or with none (let go). */
406
+ const budgetWaiting = (run) => run.kind === "workflow" && !!run.dir && existsSync(join(run.dir, BUDGET_PAUSE));
407
+ /** A workflow run's pause at its cap, as its process wrote it: the refusal's words and figures, as an agentic run's
408
+ * budgetPending serves them, and the node whose step waits. */
409
+ const workflowBudgetPending = (run) => {
410
+ const mark = run.kind === "workflow" && run.dir ? budgetPausedIn(run.dir) : undefined;
411
+ if (!mark)
296
412
  return undefined;
297
- const r = run.capRefusal;
298
- const spent = r && spentNow !== undefined ? Math.min(r.spentUsd, spentNow) : r?.spentUsd;
299
- // Shown as cost.usd is (to a millionth of a dollar), the suggestion from the figures as the cap counts them.
300
- const figures = r && spent !== undefined ? { spent_usd: micro(spent), needs_usd: micro(r.needsUsd), suggested_cap_usd: suggestedCap(cap, spent, r.needsUsd) } : {};
301
- return { kind: "budget", cap_usd: cap, ...figures, said, at: meaningful(run.rows)?.timestamp ?? run.updatedAt };
413
+ const cap = run.meta.max_cost_usd ?? mark.cap_usd;
414
+ const figures = mark.spent_usd !== undefined && mark.needs_usd !== undefined
415
+ ? { spent_usd: micro(mark.spent_usd), needs_usd: micro(mark.needs_usd), ...(mark.least_cap_usd !== undefined ? { least_cap_usd: mark.least_cap_usd } : {}), suggested_cap_usd: suggestedCap(cap, mark.spent_usd, mark.needs_usd), overshoot_bound_usd: microUp(mark.bound_usd ?? 0) }
416
+ : {};
417
+ return { kind: "budget", cap_usd: cap, ...figures, said: mark.words, at: mark.at, node: mark.node };
302
418
  };
303
- /** The waiting row of a run paused at its cap, after the refusal's error row: "Paused at the run's $1 cap: Not sent: …". */
304
- function withPaused(rows, said, cap) {
305
- const at = rows.findLastIndex((row) => row.kind === "error");
306
- if (at < 0)
307
- return [...rows];
308
- const error = rows[at];
309
- const paused = { ...error, id: `${error.id}:paused`, kind: "waiting", summary: `Paused at the run's ${money(cap)} cap: ${clip(said, 400)}`, text: clip(said, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null };
310
- return [...rows.slice(0, at + 1), paused, ...rows.slice(at + 1)];
311
- }
419
+ /** The row a run shows while its harness installs for it (harness-install.ts), since `at`. */
420
+ /** The row a raised workflow run shows once its launch failed RAISE_TRIES times (finishRaise), since `at`. */
421
+ export const raiseFailedRow = ({ at, words }) => servedOnly({ id: "server:raise-failed", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
422
+ /** The row a raised workflow run shows while it waits for a place to open again in (finishRaise), since `at`. */
423
+ export const placeRow = ({ at, words }) => servedOnly({ id: "server:waiting-place", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
424
+ export const installRow = ({ at, words }) => servedOnly({ id: "harness:installing", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
425
+ /** The paused run's waiting row and the BUDGET_PAUSED/BUDGET_WAITING words move to run-view.ts (over the run's rows). */
426
+ /** Whether an error row of `run`'s is a refusal for room it paused at: one in an agentic run's own turn (decide never
427
+ * fails that run on it; it waits for a raise, pausedAt), now or before a raise. Read from the row and the run's kind
428
+ * alone, never from its status, so a row reads the same live, on a full re-read and from a server started again. A
429
+ * workflow's refusal and the end-of-run turn's (learning: the run has ended) pause nothing; a refusal no cap fixes is
430
+ * no refusal for room. */
431
+ const pausedOn = (run, row) => run.kind === "agentic" && row.agent_label !== LEARNING_LABEL && roomRefusal(row.text ?? undefined) !== undefined;
312
432
  /** An import's answer, the one row reading of an answer left: its records hold no turn's end (it ran elsewhere), so its
313
433
  * last meaningful row is its answer when that row is one, a final answer's or a text row's. */
314
434
  const importAnswerOf = (rows) => {
315
435
  const last = meaningful(rows);
316
436
  return last?.kind === "final_answer" || last?.kind === "text_block" ? last : undefined;
317
437
  };
318
- const usageOf = (rows) => rows.findLast((r) => r.kind === "usage");
319
- /** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
320
- export const costOf = (rows) => {
321
- const usage = usageOf(rows);
322
- return usage ? (usage.usage?.usd ?? null) : 0;
323
- };
324
- /** Whether `row` carries a paid tool's charge counted here: `tool`'s alone when given, every other tool's with `others`
325
- * (chargedTool: a charge's own `phase` row, or a browser call's row its charges fold into). */
326
- const chargeOf = (row, tool, others) => {
327
- const charged = chargedTool(row);
328
- return charged !== undefined && (tool === undefined || (others ? charged !== tool : charged === tool));
329
- };
330
- /** What a run's paid tools charged (`tool`'s alone, when given; every other tool's with `others`), from the same rows its
331
- * cost is read from: each charge's line carries it (`usage` on a `phase` row), and a browser call's row what its charges
332
- * came to; null when one is unknown. A call still marked, in flight or cut, is no charge here. */
333
- export const toolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (!chargeOf(row, tool, others) ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
334
- /** What a run's paid tools are known to have charged (`tool`'s alone, when given; every other tool's with `others`): each
335
- * charge's line that names its cost, a charge of unknown cost adding nothing (a browser call's row, what is known of it). */
336
- export const knownToolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (!chargeOf(row, tool, others) ? sum : sum + (row.usage.usd ?? row.usage.so_far_usd ?? 0)), 0);
337
- /** A run's cost for its views: its usage row's, else what the store kept when it carried the run back (0 before any
338
- * request). A usage row that says unknown, or says nothing, stays unknown: what the store kept dates from before a
339
- * follow-up. */
340
- export function costView(rows, stored, decisions) {
341
- const usage = usageOf(rows);
342
- // A workflow run's decisions, once its end is read: their cost joins its model nodes', and one unknown makes it unknown.
343
- if (decisions !== undefined) {
344
- const models = usage ? (usage.usage?.usd ?? null) : 0;
345
- return models === null || decisions === null ? null : models + decisions;
346
- }
347
- if (!usage)
348
- return stored === undefined ? 0 : stored;
349
- return usage.usage?.usd ?? null;
350
- }
351
- export function soFarOf(rows, decisions) {
352
- if (decisions === null)
353
- return undefined;
354
- const usage = usageOf(rows)?.usage;
355
- const models = !usage ? { known: 0, unpriced: 0 } : usage.usd !== null ? { known: usage.usd, unpriced: 0 } : usage.so_far_usd !== undefined && usage.unpriced !== undefined ? { known: usage.so_far_usd, unpriced: usage.unpriced } : undefined;
356
- if (!models)
357
- return undefined;
358
- const unpriced = models.unpriced + (decisions?.unpriced ?? 0);
359
- return unpriced > 0 ? { so_far_usd: Math.round((models.known + (decisions?.known ?? 0)) * 1e6) / 1e6, unpriced } : undefined;
360
- }
438
+ /** The cost reads a run's views show move to run-view.ts (over the run's rows), unchanged. */
361
439
  /** What a run's meta kept of its cost so far at its end, when it is well formed. */
362
440
  const soFarOfMeta = (meta) => {
363
441
  const kept = meta?.cost_so_far;
@@ -381,56 +459,10 @@ function answerOfRun(run) {
381
459
  const imported = run.imported ? importAnswerOf(run.rows) : undefined;
382
460
  return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
383
461
  }
384
- // A run's messages are its message rows (isMessageRow): a person's, and those the server wrote, the message its turn took.
385
- const usersOf = (rows) => rows.filter(isMessageRow).length;
462
+ // usersOf moves to run-view.ts (the run's served view), imported above.
386
463
  const lastUserMessage = (rows) => rows.findLast(isMessageRow)?.id;
387
- // A row's place in the store: its entry's id. The store mints conversation and entry ids from one counter, so entry ids
388
- // order rows across conversations and the conversation is no part of the order.
389
- const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
390
- /** Whether the turn a stop ended is still where the run stands: no message shown is newer than the stop's. By order,
391
- * never by a count or by the stopped message itself, which a compaction can take off the rows. */
392
- export const stoppedAt = (meta, rows) => {
393
- if (meta.stopped_at === undefined)
394
- return meta.stopped_after !== undefined && meta.stopped_after === usersOf(rows);
395
- const at = placeOf(meta.stopped_at);
396
- return !rows.some((r) => isMessageRow(r) && placeOf(r.id) > at);
397
- };
398
- const stopped = (run) => stoppedAt(run.meta, run.rows);
399
- /** The words of the cap's refusal for room an agentic run stands paused at: its newest message's turn ended on it (cap.ts
400
- * roomRefusal: what is left of its cap cannot buy the next request's least, which a higher cap would send), and nothing
401
- * came since. The run then waits for its cap to be raised (input_required, `pending.kind` budget), never failed; a
402
- * refusal no cap fixes (an unknown spend, no price) still fails it (decide). Undefined for any other run. */
403
- const refusedAt = (run) => {
404
- if (run.kind !== "agentic" || run.cancel || run.submitted > 0 || run.turns.open > 0 || stopped(run))
405
- return undefined;
406
- const end = run.turns.end();
407
- return end?.status === "failed" ? roomRefusal(end.error) : undefined;
408
- };
409
- /** The pause a run stands at, by its refusal's own start mark (its entry), so no row shown after it moves it; a store
410
- * with no such mark keys it to the refusal's row. Undefined when it stands at no refusal for room. */
411
- const pauseOf = (run) => {
412
- if (refusedAt(run) === undefined)
413
- return undefined;
414
- if (run.capMark !== undefined)
415
- return `mark:${run.capMark}`;
416
- const row = meaningful(run.rows)?.id;
417
- return row === undefined ? undefined : `row:${row}`;
418
- };
419
- /** Its cap was raised since the refusal it stands at (a raise names that pause): it waits for its follow-up then, not
420
- * for a raise (input_required, idle). */
421
- const raisedSince = (run) => {
422
- const pause = pauseOf(run);
423
- return pause !== undefined && run.meta.cap_raised?.some((raise) => raise.pause === pause) === true;
424
- };
425
- /** The follow-up a raise of the pause it stands at asked for and that has not gone yet: one per pause. */
426
- const continuationOf = (run) => {
427
- // A run that has ended, or is ending (its follow-up's tries spent: failRaised, a cancel), sends none any more.
428
- if (run.outcome || run.finishing || run.cancel)
429
- return undefined;
430
- const pause = pauseOf(run);
431
- const next = run.meta.cap_continue;
432
- return pause !== undefined && next?.pause === pause && !next.sent ? next : undefined;
433
- };
464
+ // placeOf, stoppedAt, stopped, refusedAt, pauseOf, raisedSince and continuationOf move to run-view.ts (the run's served
465
+ // view), imported above (stoppedAt re-exported).
434
466
  /** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
435
467
  function processIdentity(pid) {
436
468
  if (pid === undefined)
@@ -443,65 +475,70 @@ function processIdentity(pid) {
443
475
  return String(pid);
444
476
  }
445
477
  }
446
- const pausedAt = (run) => (raisedSince(run) ? undefined : refusedAt(run));
478
+ // pausedAt moves to run-view.ts (the run's served view), imported above.
479
+ /** Whether the run waits on its person: a tool call parked for its owner's approval, a pause at its cap, or a question
480
+ * (ask_person) its turn ended on. Read from the run itself, so a message in flight (which reads working) hides none. */
481
+ const waitsOnPerson = (run) => {
482
+ if (run.kind !== "agentic")
483
+ return false;
484
+ if (waitingApproval(run) !== undefined || pausedAt(run, { inFlight: false }) !== undefined)
485
+ return true;
486
+ const { status, state } = statusOf(run);
487
+ return status === "input_required" && state === "waiting";
488
+ };
489
+ /** The refusal of a message that may not answer a person, as the door's WAITING is read: a trigger's firing is skipped. */
490
+ const waitingRefusal = () => new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
491
+ // raisedToGo moves to run-view.ts (the run's served view), imported above.
447
492
  /** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
448
493
  export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
449
494
  /** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
450
495
  * showed live is not one (`live` holds them for the run), so a live row that ended while the door was away goes. */
451
- export function keepCommitted(live, rows, isLive) {
496
+ /** The live path's keep: a row a committed entry made stays served though a later snapshot no longer holds it (the
497
+ * timeline only grows); a row the reducer showed live does not, nor one only the served view makes (`madeHere`, the ids
498
+ * show() tagged servedOnly, read as it grows), which goes once show() stops making it. */
499
+ export function keepCommitted(live, rows, isLive, madeHere = new Set()) {
452
500
  for (const row of rows)
453
501
  if (isLive(row.id))
454
502
  live.add(row.id);
455
- return (id) => !live.has(id) && !isLive(id);
503
+ return (id) => !madeHere.has(id) && !live.has(id) && !isLive(id);
456
504
  }
457
505
  /** A wait's mark: the stop it stands at, while that stop holds, else its newest row (the question it waits on). */
458
506
  const waitMark = (run) => (stopped(run) && run.meta.stopped_at) || meaningful(run.rows)?.id || "";
507
+ /** What a wait's run.needs_input notice is keyed on: a workflow paused at its cap, by its pause's own mark (budget.ts:
508
+ * where it waits and since when), which needs no row, so a pause at its first decision, before any model row, is told
509
+ * too, and a pause written again at a higher cap is told again; any other wait, by waitMark. */
510
+ const noticeMark = (run) => {
511
+ const mark = run.kind === "workflow" && run.dir && budgetWaiting(run) ? budgetPausedIn(run.dir) : undefined;
512
+ return mark ? `budget:${mark.path ?? mark.node ?? ""}:${mark.at}` : waitMark(run);
513
+ };
459
514
  /** Waits for `work`, or until `deadline` (ms since the epoch), whichever comes first. */
460
515
  async function untilDeadline(work, deadline) {
461
516
  let timer;
462
517
  await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))))]);
463
518
  clearTimeout(timer);
464
519
  }
465
- /** A run's status and state, by the contract's table. */
520
+ /** A run's status and state, by the contract's table (run-view.ts statusOf). The table is read over the run's rows, its
521
+ * turns and its store entries; the file-backed facts (a workflow paused at its cap or in its process, the browser ask)
522
+ * this server reads from the run's directory and passes in. The store-backed view builds the same facts from the run's
523
+ * row and journal, so the status a person or a model sees is the same. The facts are thunks, read only where the table
524
+ * reaches them, so the hot path (an ended or stopped run) touches no file, as it did when the reads lived here. */
466
525
  export function statusOf(run) {
467
- if (run.outcome)
468
- return { status: run.outcome, state: "idle" };
469
- if (run.finishing)
470
- return { status: run.finishing, state: "idle" };
471
- // A paused workflow run finishes what it has in flight and starts nothing new until it is resumed (pause.ts). A held run
472
- // read without its directory (a view built for a count) has no mark to read.
473
- if (run.kind === "workflow")
474
- return run.dir && pausedIn(run.dir) ? { status: "paused", state: "idle" } : { status: run.working ? "working" : "queued", state: "working" };
475
- const users = usersOf(run.rows);
476
- if (run.submitted > 0)
477
- return { status: users ? "working" : "queued", state: "working" };
478
- // No rows is a run not shown yet (adopted, before its first snapshot), whatever an old stop says. Rows with no
479
- // message of the person's are a compaction's (it shows its summary), which can summarize every message of a stop.
480
- if (!run.rows.length)
481
- return { status: "queued", state: "working" };
482
- if (stopped(run))
483
- return { status: "input_required", state: "idle" };
484
- if (!users)
485
- return { status: "queued", state: "working" };
486
- // A tool call parked for approval (tool-gate.ts) waits for the person; once answered, its process acts on it.
487
- if (run.kind === "agentic" && run.submitted === 0 && !run.working) {
488
- if (waitingApproval(run))
489
- return { status: "input_required", state: "waiting" };
490
- if (actingOn(run))
491
- return { status: "working", state: "working" };
492
- }
493
- // Every message's turn is over and the newest one's ended interrupted, with no stop of the person's saying so (the
494
- // harness ended it on its own): the run waits for the person, as after a stop, never working for good.
495
- if (run.kind === "agentic" && run.submitted === 0 && run.turns.end()?.status === "interrupted")
496
- return { status: "input_required", state: "idle" };
497
- // Paused at its cap: it waits for the cap to be raised; raised, for a message, if the raise's own follow-up did not go.
498
- if (refusedAt(run) !== undefined)
499
- return pausedAt(run) !== undefined ? { status: "input_required", state: "waiting" } : { status: "input_required", state: "idle" };
500
- if (run.working)
501
- return { status: "working", state: "working" };
502
- if (meaningful(run.rows)?.kind === "waiting")
503
- return { status: "input_required", state: "waiting" };
504
- return { status: "working", state: "idle" };
526
+ return statusOfView(run, { budgetWaiting: () => budgetWaiting(run), paused: () => !!run.dir && pausedIn(run.dir), browserAsk: () => browserAsk(run) });
527
+ }
528
+ /** A run's first message's origin as its serve.json keeps it. A run with a trigger (`trigger`, read from the same file)
529
+ * always has a trigger's: the kept one when it names that trigger and has the owner its source makes it (true for a
530
+ * schedule alone), else that trigger's with owner false, so a forged or lost origin never reads as the person's or the
531
+ * owner's. A run with none keeps none. */
532
+ function inputOriginOf(stored, trigger) {
533
+ if (trigger === null)
534
+ return undefined;
535
+ const origin = originOf(stored);
536
+ if (origin?.kind === "trigger" && origin.trigger_id === trigger.id && origin.owner === (origin.source === "schedule"))
537
+ return origin;
538
+ // owner false is the point; the source is a best-effort label: the stored one when it is a known source other than a
539
+ // schedule's, else "webhook".
540
+ const source = origin?.kind === "trigger" && origin.source !== "schedule" ? origin.source : "webhook";
541
+ return { kind: "trigger", trigger_id: trigger.id, source, owner: false };
505
542
  }
506
543
  /** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
507
544
  function triggerOf(meta) {
@@ -511,8 +548,9 @@ function triggerOf(meta) {
511
548
  /** Why a message that may not answer a person's question is not sent. */
512
549
  export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
513
550
  /** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
514
- * the tool keys are kept under (tool-keys.ts), and the boxes' keys (boxes.ts), which only the server's box providers use. */
515
- const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", ...BOX_KEYS]);
551
+ * the tool keys are kept under (tool-keys.ts), the store's URL (it may hold the database's password), and the boxes'
552
+ * keys (boxes.ts), which only the server's box providers use. */
553
+ const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS]);
516
554
  /** The secrets a run's process is handed over its pipe (secrets.ts): every one but the server's own and the decision
517
555
  * keys, which go on their own descriptor. */
518
556
  export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
@@ -531,7 +569,7 @@ export async function needsOf(revision) {
531
569
  const nodes = workflow ? workflowNodes(workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(workflow)) : undefined;
532
570
  const bound = nodes && workflowTools(nodes);
533
571
  return {
534
- harness: revision.body.harness ?? DEFAULT_HARNESS,
572
+ harness: harnessOfBody(revision.body),
535
573
  ...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}),
536
574
  tools: bound ? [...bound.nodes, ...bound.calls] : [...(revision.body.tools ?? [])],
537
575
  ...(nodes ? { tiers: llmTiers(nodes, nodeTiers(nodes)) } : {}),
@@ -541,14 +579,15 @@ export async function needsOf(revision) {
541
579
  /** The secrets a run of `needs` is handed over its pipe, by the keys `env` holds now: RUN_SECRETS but each field of a
542
580
  * `tool` row of `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does
543
581
  * not need, from the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the
544
- * gateway's (model.ts' modelKeys: its own model, or the host's of each tier it runs); codex's and claude-agent's, the
545
- * one key their route sends for the revision's model (adapters.ts' harnessModelKeys). Read at each launch, so a key
582
+ * gateway's (model.ts' modelKeys: its own model, or the host's of each tier it runs); a run on an adapter's, the
583
+ * one key its wire's route sends for the revision's model (adapters.ts' harnessModelKeys). Read at each launch, so a key
546
584
  * saved with no restart counts at the next. */
547
585
  export function keysFor(needs, env, rows = TOOL_KEYS) {
548
586
  const named = new Set(needs.tools);
549
587
  const unlocked = new Set(rows.filter((row) => row.unlocks.some((name) => named.has(name))).flatMap((row) => row.fields));
550
588
  const scoped = scopedOf(rows);
551
- const model = new Set(needs.harness !== DEFAULT_HARNESS ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
589
+ const entry = harnessOf(env, needs.harness);
590
+ const model = new Set(!entry || entry.facts ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
552
591
  return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
553
592
  }
554
593
  /** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
@@ -633,26 +672,41 @@ export async function lastLogLine(run) {
633
672
  await file.close();
634
673
  }
635
674
  }
636
- /** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went. */
675
+ /** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went;
676
+ * `beforeRestartCheck` holds a settle that found the run's process gone just before it decides whether to open it again. */
637
677
  export const runsTestHooks = {};
638
678
  export class Runs {
639
679
  options;
640
680
  runs = new Map();
641
- /** Each workflow revision's workflow, by revision id, as a graph read it: a revision never changes. */
642
- workflows = new Map();
681
+ /** The current name of each trigger a held run names, by its id (servedTriggerRow): pushed in at a firing's start (the
682
+ * run's trigger), on a rename or delete (server.ts triggerChanged), and resolved once when a run is loaded, so a
683
+ * served row names its trigger with no store read. `undefined` for a trigger that is gone. */
684
+ triggerNames = new Map();
685
+ /** The last entry each run's database reads have seen (run-db.ts): a read behind it is never shown. */
686
+ reads = new MonotonicReads();
687
+ /** The disk the runs' folders are on (disk.ts): on this machine, the data directory's own. */
688
+ get disk() {
689
+ return (this.#disk ??= localDisk(this.options.agents.dir, this.store));
690
+ }
691
+ #disk;
643
692
  /** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
644
693
  * run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
645
694
  needs = new Map();
646
- /** Every run's graph as served, part by part (servedGraph), and each workflow run's last graph read whole, which a
647
- * poll that met a busy store answers, marked stale: one LRU by bytes across runs (graph-served.ts PartCache). */
648
- graphCache = new PartCache(GRAPH_CACHE_BYTES);
649
695
  adopting = new Map();
696
+ /** The runs this process is starting, from the store's row until the run is held (start): its serve.json and its seed
697
+ * copy are written in between. A read of one waits for its start and never loads it from disk, where it would look
698
+ * like a run a stopped server left mid-copy. Null once a start failed. */
699
+ startingRuns = new Map();
650
700
  /** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
651
701
  remoteAllow;
652
702
  clock = new ChangeClock();
653
703
  cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
654
704
  app = fileURLToPath(new URL("./app.js", import.meta.url));
655
705
  closing = false;
706
+ /** Raised workflow runs waiting for a place to open again in (finishRaise), tried again every PLACE_RETRY_MS. */
707
+ placeWaiters = new Set();
708
+ placeRetry;
709
+ placeRetrying = false;
656
710
  /** Set once `close` is done: the store is closed, so nothing settles after it. */
657
711
  closed = false;
658
712
  /** Runs past the cap's check whose process is not started yet. */
@@ -660,6 +714,7 @@ export class Runs {
660
714
  /** The memory the starts counted in `starting` reserve, in MiB. */
661
715
  startingMib = 0;
662
716
  /** This host's memory, out of which each live run reserves what its harness takes (host.ts), beside `maxRuns`. */
717
+ /** This host's memory for runs (host.ts); a test's seam sets it (startServe's `hostMemory`). */
663
718
  memory = hostMemory();
664
719
  /** The start sweep of the boxes runs left: once, before any run opens a box (sweepOnce). */
665
720
  swept;
@@ -691,6 +746,11 @@ export class Runs {
691
746
  /** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
692
747
  * launch, so a test can hold a reopen there. */
693
748
  beforeReopenLaunch;
749
+ /** A test's seam (startServe's `beforeRaiseLaunch`): awaited where a raise that opens a let-go workflow pins what its
750
+ * launch needs (finishRaise), after its place is taken; one that throws stands for a pin that fails there. */
751
+ beforeRaiseLaunch;
752
+ /** A test's seam (startServe's `onPauseCheck`): told each stat and each read of a workflow run's pause by its watch. */
753
+ onPauseCheck;
694
754
  /** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
695
755
  onRunLoad;
696
756
  /** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
@@ -713,6 +773,10 @@ export class Runs {
713
773
  const known = this.runs.get(id);
714
774
  if (known)
715
775
  return known;
776
+ // One this process is starting is its start's Run once held; a start that failed leaves its row, read as any.
777
+ const starting = await this.startingRuns.get(id);
778
+ if (starting)
779
+ return starting;
716
780
  const row = await this.options.agents.request(() => this.store.readRun(id));
717
781
  return row ? this.adopt(row) : null;
718
782
  }
@@ -721,6 +785,10 @@ export class Runs {
721
785
  const known = this.runs.get(row.id);
722
786
  if (known)
723
787
  return Promise.resolve(known);
788
+ // One this process is starting is never read from disk (startingRuns): its start holds it.
789
+ const starting = this.startingRuns.get(row.id);
790
+ if (starting)
791
+ return starting.then((run) => run ?? this.adopt(row));
724
792
  let pending = this.adopting.get(row.id);
725
793
  if (!pending) {
726
794
  pending = this.load(row).finally(() => this.adopting.delete(row.id));
@@ -730,8 +798,11 @@ export class Runs {
730
798
  }
731
799
  async load(row) {
732
800
  this.onRunLoad?.(row.id);
733
- const dir = join(this.options.agents.dir, "runs", row.id);
734
- const stored = (await readJson(join(dir, RUN_META)));
801
+ const dir = runDirIn(this.options.agents.dir, row.agent, row.id);
802
+ // There, but not whole JSON of an object (a damaged disk, a hand's edit): what it kept is lost. Missing is no damage:
803
+ // a run whose server went down before it set the run up has none (notSetUp). Kept on the run (run.damaged), so
804
+ // forget reads of a held run what it reads from disk of one not held (handedTo).
805
+ const { stored, damaged } = await readMeta(join(dir, RUN_META));
735
806
  const trigger = triggerOf(stored);
736
807
  const meta = {
737
808
  title: typeof stored?.title === "string" ? stored.title : "",
@@ -739,6 +810,7 @@ export class Runs {
739
810
  ...(isObject(stored?.input) ? { input: stored.input } : {}),
740
811
  ...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
741
812
  ...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
813
+ ...(CAP_MODES.includes(stored?.cap_mode) ? { cap_mode: stored.cap_mode } : {}),
742
814
  // Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
743
815
  ...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
744
816
  ...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
@@ -749,31 +821,86 @@ export class Runs {
749
821
  ...(typeof stored?.stopped_after === "number" ? { stopped_after: stored.stopped_after } : {}),
750
822
  ...(isObject(stored?.launch_thinking) ? { launch_thinking: stored.launch_thinking } : {}),
751
823
  ...(isObject(stored?.tool_plane) ? { tool_plane: stored.tool_plane } : {}),
824
+ ...(stored?.unshown === true ? { unshown: true } : {}),
825
+ ...(handedMark(stored?.sign_in_handed) ? { sign_in_handed: handedMark(stored?.sign_in_handed) } : {}),
752
826
  ...(stored?.place ? { place: storedPlace(stored.place) } : {}),
753
827
  ...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
754
828
  ...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
755
829
  ...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
756
830
  ...(trigger ? { trigger } : {}),
831
+ // Its first message's origin, for a relaunch that sends it again: its own trigger's, never the person's or the
832
+ // owner's unless it holds up (inputOriginOf).
833
+ ...(inputOriginOf(stored?.input_origin, trigger) ? { input_origin: inputOriginOf(stored?.input_origin, trigger) } : {}),
757
834
  };
758
835
  // A turn's origin a server before this one set is not known to be the turn running now: it goes.
759
836
  await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
760
837
  // A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
761
- // follow-up (learning-run.ts onLoad).
838
+ // follow-up (learning-run.ts onLoad). A run this process is starting is never read here (startingRuns), and every
839
+ // start that ended saved its learning, so a copy with none saved is a stopped server's.
762
840
  if (stored)
763
841
  await this.learning.onLoad(row, dir, meta, () => writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`));
764
842
  const known = await this.options.agents.revision(row.agent, row.revision);
765
843
  const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
844
+ if (damaged)
845
+ run.damaged = true;
846
+ // Its browser's sign-in pointer, read back before anything of the run is read or held here: its rows, answers and
847
+ // errors are cut of it from the first, though no launch of this server handed it one.
848
+ const signIn = await this.peekSignIn(run);
766
849
  this.runs.set(row.id, run);
767
850
  run.launching = existsSync(join(dir, RUN_LAUNCHING));
768
851
  run.notSetUp = row.state === "running" && !isObject(stored?.input);
769
- const record = await this.record(run);
852
+ // The process its row names, when it lives on: an earlier server's, serving the run or still opening it.
853
+ const adopted = this.holder(run);
854
+ const lives = adopted !== undefined && adopted.pid !== process.pid && holderLives(adopted);
770
855
  // An ended run is ended before its rows are read, so they never make it a wait: a last row that asks is no notice.
771
856
  if (row.state !== "running")
772
857
  run.outcome = STATUS_OF[row.state];
773
- // Only a store no live instance holds is opened: released, or left by an instance whose lease lapsed.
774
- if (row.state !== "running" || !this.doorOf(record))
858
+ // A run still going whose serve.json is damaged: the plane it ran on (kept there alone) and whether it was handed its
859
+ // agent's sign-in (sign_in_handed) went with it, so the pointer is not read back and its text could hold it uncut.
860
+ // Hidden as one whose sign-in does not open is, below, when its revision grants the browser or can't be read; one whose
861
+ // revision has none never had a browser, so was never handed a sign-in. Nothing is written over the damaged file here:
862
+ // its end writes serve.json anew, hidden, and until then each server finds it damaged and hides it again.
863
+ if (row.state === "running" && damaged && !row.importedFrom && !run.meta.unshown && (!run.tooling || run.tooling.tools.includes("browser"))) {
864
+ run.error = { code: "run_failed", message: UNREADABLE_RUN_META, retryable: false };
865
+ run.meta.unshown = true;
866
+ }
867
+ // An ended run whose serve.json was damaged since: withheld as an ended run whose sign-in does not open is (below:
868
+ // no store read, no answer, output or error words), on the same terms. It ended as it ended: nothing is stopped or
869
+ // failed, and nothing is saved, so its words are shown again only once serve.json reads (each server decides anew).
870
+ if (row.state !== "running" && damaged && !row.importedFrom && !run.meta.unshown && (!run.tooling || run.tooling.tools.includes("browser")))
871
+ run.meta.unshown = true;
872
+ // A run still going whose agent's browser sign-in does not open under this server's seal key: whatever it said, or
873
+ // says, could repeat the pointer, which nothing here can cut. Its rows are never read, and it ends failed, saying
874
+ // why: a live process is stopped (below), one already gone is never opened again.
875
+ // Only a run that was handed it: one launched signed out since the key changed is taken up as any other.
876
+ if (row.state === "running" && signIn === "unreadable" && run.meta.sign_in_handed && !run.meta.unshown) {
877
+ run.error = { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
878
+ run.meta.unshown = true;
879
+ // Unsaved (a full disk), it is still hidden here, stopped and ended; the next server reads the same unreadable
880
+ // sign-in and hides it again. A load that threw here would leave this run cached half taken up, never watched.
881
+ await this.saveMeta(run).catch((error) => warn(run.id, `that it is hidden is not saved: ${error.message}`));
882
+ }
883
+ // An ended run handed a sign-in that does not open under this server's seal key: what it said could repeat the pointer,
884
+ // which nothing here can cut, so none of it is served: its store is not read, and its answer, output and error words
885
+ // are withheld. It ended as it ended: nothing is stopped or failed. Here only, never saved for it: each server decides
886
+ // from its own key, so the sign-in opening again shows it again, cut. Only a run that was handed it: one launched
887
+ // signed out is shown as any other.
888
+ if (row.state !== "running" && signIn === "unreadable" && run.meta.sign_in_handed && !run.meta.unshown)
889
+ run.meta.unshown = true;
890
+ // Hidden under a key that did not open its sign-in, and that very sign-in opens again now (not one made since in its
891
+ // place, which would not cut the pointer its rows hold): its rows are read, cut of it.
892
+ // That very pointer, live or forgotten since, is read back (peekSignIn, by its hash).
893
+ if (run.meta.unshown && signIn === "read" && Array.isArray(run.meta.sign_in_handed)) {
894
+ delete run.meta.unshown;
895
+ // Unsaved, the next server finds it hidden and this same sign-in open, and shows it again as this one does.
896
+ await this.saveMeta(run).catch((error) => warn(run.id, `that it is shown again is not saved: ${error.message}`));
897
+ }
898
+ // Only a store no live process holds is opened: released, or left by a process that is gone. Never a hidden run's.
899
+ if ((row.state !== "running" || !lives) && !run.meta.unshown)
775
900
  await this.storeWhenFree(run);
776
901
  if (row.state !== "running") {
902
+ // An ended run's one read is done: no guard is kept for it.
903
+ this.reads.forget(row.id);
777
904
  run.endedAt = row.endedAt;
778
905
  // An ended run the store kept no cost for has an unknown cost, never $0.
779
906
  run.costUsd = row.costUsd ?? null;
@@ -782,8 +909,9 @@ export class Runs {
782
909
  await this.readDecisionCost(run).catch(() => void (run.decisionCost = null));
783
910
  if (row.importedFrom)
784
911
  run.imported = row.importedFrom;
912
+ // Its error words are the run's too (the row's summary may be its last line): withheld with the rest.
785
913
  if (run.outcome === "failed")
786
- run.error = errorOfRow(row, meta);
914
+ run.error = run.meta.unshown ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : errorOfRow(row, meta);
787
915
  run.settled = true;
788
916
  }
789
917
  else {
@@ -793,8 +921,37 @@ export class Runs {
793
921
  run.cancel = true;
794
922
  run.finishing = "cancelled";
795
923
  }
796
- const adopted = record && this.doorOf(record) ? record : null;
797
- if (adopted) {
924
+ // A process an earlier server started that is gone took its browser's view with it. Its agent's ask, if one waits,
925
+ // stays for the run's next process to take up (browser-person.ts).
926
+ if (!lives)
927
+ void dropHandover(dir).catch(() => undefined);
928
+ if (run.meta.unshown && !lives && !run.outcome) {
929
+ // Its process gone: never opened again. The start's recovery settles it, failed (settleOnce reads `finishing`).
930
+ run.error ??= { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
931
+ run.finishing = "failed";
932
+ run.endedAt = new Date().toISOString();
933
+ }
934
+ else if (lives && run.meta.unshown) {
935
+ // Its process may repeat a pointer this server cannot read, so cannot cut: it is never followed; it is stopped
936
+ // (SIGTERM, as a cancel's), and the run ends failed, saying why, once it has gone.
937
+ run.error ??= { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
938
+ this.adoptProcess(run, adopted, false);
939
+ // Its turn aborted first, so the drain SIGTERM starts does not wait for it; one that outlives its drain is killed,
940
+ // only while it is still the holder adopted here, confirmed by its identity (killHolder: its pid, of the same
941
+ // start, on this boot), never a process that took its pid since.
942
+ this.finish(run, "failed", true);
943
+ setTimeout(() => {
944
+ if (run.orphanHolder !== adopted)
945
+ return;
946
+ try {
947
+ killHolder(adopted);
948
+ }
949
+ catch (error) {
950
+ warn(run.id, `its process is not killed: ${error.message}`);
951
+ }
952
+ }, this.killAfterMs() + 5_000).unref();
953
+ }
954
+ else if (lives) {
798
955
  // A server that died between saving a stop and its abort reaching the run leaves the turn working.
799
956
  run.finishStop = run.meta.stopped_at !== undefined || run.meta.stopped_after !== undefined;
800
957
  this.adoptProcess(run, adopted);
@@ -804,8 +961,12 @@ export class Runs {
804
961
  }
805
962
  // One a server left in its end-of-run turn finishes with its job's outcome, and its turn, when its process lives,
806
963
  // is asked again (learning-run.ts).
807
- this.learning.onAdopt(run, adopted !== null);
964
+ this.learning.onAdopt(run, lives);
808
965
  }
966
+ // A run restored after a restart has no pushed name yet: its trigger's name is resolved once from the store here (the
967
+ // load path is already async), so its served rows name it, never left blank; a later rename pushes the new one.
968
+ if (trigger && !this.triggerNames.has(trigger.id))
969
+ this.triggerNames.set(trigger.id, await this.options.triggerName?.(trigger.id));
809
970
  this.refresh(run);
810
971
  return run;
811
972
  }
@@ -831,22 +992,50 @@ export class Runs {
831
992
  });
832
993
  return run.saving;
833
994
  }
834
- record(run) {
835
- return readJson(join(run.dir, "run.json"));
995
+ /** The process that holds the run, as its row's claim names it (run-holder.ts); undefined for none, or the server. */
996
+ holder(run) {
997
+ return this.holderView(run).holder;
836
998
  }
837
- /** The door a live run serves, from its run.json: running, a fresh heartbeat, and a loopback address. */
838
- doorOf(record) {
839
- if (record?.status !== "running" || !isObject(record.holder) || typeof record.holder.serve !== "string")
840
- return undefined;
841
- // A run's process is a process on this machine: one that is gone serves no door, however fresh its heartbeat.
842
- const pid = holderPid(record);
843
- if (pid !== undefined && !alive(pid))
844
- return undefined;
845
- if (typeof record.heartbeatAt !== "string" || Date.now() - Date.parse(record.heartbeatAt) >= LEASE_MS)
846
- return undefined;
847
- const url = URL.parse(record.holder.serve);
999
+ /** Who holds the run, as its row says and the processes show: `unknown` when the row or the process listing cannot be
1000
+ * read, which a caller never takes for a holder that is gone. */
1001
+ holderView(run) {
1002
+ try {
1003
+ const holder = holderOfClaim(run.id, this.store.runClaim(run.id));
1004
+ return holder === undefined ? { unknown: false } : holderState(holder) === "unknown" ? { holder, unknown: true } : { holder, unknown: false };
1005
+ }
1006
+ catch {
1007
+ return { unknown: true };
1008
+ }
1009
+ }
1010
+ /** The door a live run serves, from its row's holder: a process that lives (its pid, of the same start, on this boot)
1011
+ * and a loopback address it named. */
1012
+ doorOf(run) {
1013
+ let door = run.child && run.door !== undefined ? run.door : undefined;
1014
+ if (door === undefined) {
1015
+ const holder = this.holder(run);
1016
+ if (holder?.door === undefined || !holderLives(holder))
1017
+ return undefined;
1018
+ door = holder.door;
1019
+ }
1020
+ const url = URL.parse(door);
848
1021
  return url?.protocol === "http:" && isLoopback(url.hostname) ? url.origin : undefined;
849
1022
  }
1023
+ /** The record the run's process keeps in its own store (pi-durable-disk RUN_STATUS_TABLE: its status, `detail` and
1024
+ * `wakeAt`), read lock-free; null when it has none or it cannot be read. */
1025
+ async runRecord(run) {
1026
+ const file = this.storeFile(run);
1027
+ if (!existsSync(file))
1028
+ return null;
1029
+ try {
1030
+ return await readRunDb(file, this.live(run), (db) => {
1031
+ const row = db.prepare(`SELECT record FROM ${RUN_STATUS_TABLE} WHERE id = 1`).get();
1032
+ return row ? JSON.parse(row.record) : null;
1033
+ });
1034
+ }
1035
+ catch {
1036
+ return null;
1037
+ }
1038
+ }
850
1039
  storeFile(run) {
851
1040
  return join(run.dir, "store", "run.sqlite");
852
1041
  }
@@ -857,11 +1046,13 @@ export class Runs {
857
1046
  const file = this.storeFile(run);
858
1047
  if (!(await stat(file).catch(() => null)))
859
1048
  return;
860
- const { DatabaseSync } = await import("node:sqlite");
861
1049
  const read = [];
862
1050
  const submissions = [];
863
- const db = new DatabaseSync(file, { readOnly: true });
864
- try {
1051
+ // A fresh read-only, lock-free read (run-db.ts), after any take-back's checkpoint of this run: one at a time.
1052
+ const last = await this.runDb(run, () => readRunDb(file, this.live(run), (db) => {
1053
+ // A read made again (its file changed during it, run-db.ts) starts from none.
1054
+ read.length = 0;
1055
+ submissions.length = 0;
865
1056
  const rows = run.kind === "workflow" || atEnd
866
1057
  ? db.prepare("SELECT conversation_id, record FROM entries ORDER BY id").iterate()
867
1058
  : db.prepare("SELECT conversation_id, record FROM entries WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").iterate();
@@ -873,9 +1064,16 @@ export class Runs {
873
1064
  for (const row of inputs)
874
1065
  submissions.push(JSON.parse(String(row.record)));
875
1066
  }
1067
+ return Number(db.prepare("SELECT max(id) AS last FROM entries").get().last ?? 0);
1068
+ }));
1069
+ // An older view of the file than one read before is never shown: what was read before stays.
1070
+ try {
1071
+ this.reads.accept(run.id, last);
876
1072
  }
877
- finally {
878
- db.close();
1073
+ catch (error) {
1074
+ if (error instanceof BehindReadError)
1075
+ return warn(run.id, `a read of its store was behind one before (${error.message}); the earlier read stands`);
1076
+ throw error;
879
1077
  }
880
1078
  const root = read.reduce((min, r) => Math.min(min, r.conversation), Infinity);
881
1079
  const entries = read.flatMap((r) => (run.kind === "workflow" || r.conversation === root ? [r.entry] : []));
@@ -884,7 +1082,7 @@ export class Runs {
884
1082
  // Decisions it cannot read add no rows, and leave the served usage row's total unknown, as the run's cost read
885
1083
  // does (readDecisionCost): never its model nodes' total alone.
886
1084
  try {
887
- run.decisions = durableDecisions(file);
1085
+ run.decisions = durableDecisions(file, { unlocked: true });
888
1086
  }
889
1087
  catch {
890
1088
  run.decisions = null;
@@ -899,10 +1097,33 @@ export class Runs {
899
1097
  noteApprovals(run, entries);
900
1098
  this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
901
1099
  }
1100
+ /** `act` on run `run`'s database, after every earlier one on it: its reads and its take-back's checkpoint never meet. */
1101
+ runDb(run, act) {
1102
+ const next = (run.dbQueue ?? Promise.resolve()).then(act);
1103
+ run.dbQueue = next.then(() => undefined, () => undefined);
1104
+ return next;
1105
+ }
1106
+ /** The server takes run `run` back once no process holds it: its claim's epoch is bumped, with the server as its
1107
+ * holder (the disk's revoke, disk.ts), and only then its database checkpointed (run-db.ts), its WAL emptied into the
1108
+ * database file. A run whose process still lives is not taken. A take-back that fails (the agent store held by another
1109
+ * writer, or not writable) only warns: the run settles all the same, its database read with its WAL, and the next
1110
+ * settle or start takes it back. */
1111
+ async takeBack(run) {
1112
+ if (this.live(run))
1113
+ return;
1114
+ await this.runDb(run, async () => {
1115
+ // Tried once: a store another writer holds is not waited on, since what follows (a relaunch, a message) must not wait
1116
+ // on it; the next take-back tries again. No checkpoint before the claim is the server's.
1117
+ await this.disk.revoke(run.id);
1118
+ const file = this.storeFile(run);
1119
+ if (await stat(file).catch(() => null))
1120
+ await checkpointRunDb(file, this.live(run));
1121
+ }).catch((error) => warn(run.id, `it was not taken back (${error.message}); its database keeps its WAL until the next take-back`));
1122
+ }
902
1123
  /** New rows in: into the log, then the run's status, then whatever the status asks for. */
903
1124
  /** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
904
1125
  take(run, rows, keep) {
905
- run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd);
1126
+ run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd, run.bounds?.ended());
906
1127
  // Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
907
1128
  // messages waiting, so a count of rows would leave the run working forever.
908
1129
  const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
@@ -918,7 +1139,8 @@ export class Runs {
918
1139
  restate(run) {
919
1140
  if (!run.approvals?.size)
920
1141
  return;
921
- run.rows = withApprovals(run.rows.filter((row) => row.kind !== APPROVAL_ROW), run, this.redactor(run));
1142
+ // The rows as served, run through again: withApprovals gives the same rows run on its own output.
1143
+ run.rows = withApprovals(run.rows, run, this.redactor(run));
922
1144
  this.show(run);
923
1145
  }
924
1146
  /** The run's rows into its log, as served: a workflow run's decisions and the run's learning row are the served view's
@@ -926,19 +1148,68 @@ export class Runs {
926
1148
  show(run) {
927
1149
  // The decisions' rows are the served view's only: the run's own rows, which its cost is read from, stay its model nodes'.
928
1150
  // Their summary and text are redacted whole, then cut (decision-rows.ts): a provider's error can quote a held key.
929
- const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions, this.decisionShown(run));
1151
+ // An ended run's usage row says its cost, never "so far": its rows may have been read while it ran.
1152
+ const ended = TERMINAL.has(statusOf(run).status);
1153
+ const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions, this.decisionShown(run), { ended });
930
1154
  // An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
931
- const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
1155
+ const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : ended ? endedUsage(row) : row));
932
1156
  // A run paused at its cap says so after the refusal, as the row its status reads.
933
1157
  const said = pausedAt(run);
934
- const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served, said, run.meta.max_cost_usd);
935
- if (run.log.sync(withLearning(rows, run.meta.learning, this.learning.shown()), run.keep))
1158
+ const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served);
1159
+ // While its harness installs, the run says so (a phase row of the server's, gone once it is installed).
1160
+ const installing = run.installRow ? [...rows, installRow(run.installRow)] : rows;
1161
+ // While a raised run waits for a place to open again in, it says so (gone once it opens).
1162
+ const waitingPlace = run.placeWait ? [...installing, placeRow(run.placeWait)] : installing;
1163
+ // A raise taken whose launch kept failing: the run says why it is paused again.
1164
+ const placing = run.raiseFailedRow ? [...waitingPlace, raiseFailedRow(run.raiseFailedRow)] : waitingPlace;
1165
+ // A trigger's row names the trigger as it is now (its name, else its id), here alone: every page, the stream and the
1166
+ // final rows are read from this view.
1167
+ const view = withLearning(placing, run.meta.learning, this.learning.shown()).map((row) => (row.trigger ? this.servedTriggerRow(run, row) : row));
1168
+ // Every row only this view makes, remembered by id, so the live path's keep never holds one once it is no longer made.
1169
+ servedOnlyIds(view, (run.madeHere ??= new Set()));
1170
+ if (run.log.sync(view, run.keep))
936
1171
  run.updatedAt = new Date().toISOString();
937
1172
  }
1173
+ /** A trigger's row as served: "<label> <its name>: <its first line>" for a trigger that has a name now; as the timeline
1174
+ * wrote it, "<label> <its id>: …", for one that is gone. The name is put in after the run's rows were redacted, so it
1175
+ * is redacted here with the run's redactor: a key pasted into a trigger's name never shows on its runs' rows. */
1176
+ servedTriggerRow(run, row) {
1177
+ const { id, source } = row.trigger;
1178
+ const given = this.triggerNames.get(id);
1179
+ const name = given === undefined ? undefined : this.redactor(run)(given).replace(/\s+/g, " ").trim();
1180
+ const label = TRIGGER_LABELS[source];
1181
+ const written = `${label} ${id}: `;
1182
+ // The name on the row's trigger too, as the summary shows it: a client drops exactly "<label> <name>: ", whatever
1183
+ // colons the name and the message hold.
1184
+ return name && row.summary?.startsWith(written) ? { ...row, summary: `${label} ${name}: ${row.summary.slice(written.length)}`, trigger: { ...row.trigger, name } } : row;
1185
+ }
1186
+ /** Trigger `id` renamed or deleted, with its name now (`name`, undefined when it is gone): the name is pushed to the
1187
+ * one the runs read (triggerNames), and each held run whose Timeline names it is shown again, its row naming the
1188
+ * trigger as it is now. With no `id` (the triggers just read at a start): every run so named is shown again. */
1189
+ triggerChanged(id, name) {
1190
+ if (id !== undefined)
1191
+ this.triggerNames.set(id, name);
1192
+ for (const run of this.runs.values())
1193
+ if (run.rows.some((row) => row.trigger && (id === undefined || row.trigger.id === id)))
1194
+ this.show(run);
1195
+ }
938
1196
  /** A live process: the child this server started, or one an earlier server started that still serves the run. */
939
1197
  live(run) {
940
1198
  return Boolean(run.child || run.orphan);
941
1199
  }
1200
+ /** Run `id`'s status read again now: the owner answered its browser ask (browser-person.ts), so it is working again
1201
+ * before its process has read the answer. */
1202
+ remark(id) {
1203
+ const run = this.runs.get(id);
1204
+ if (run)
1205
+ this.mark(run);
1206
+ }
1207
+ /** Whether run `id` has a process serving it now: the child this server started, or an adopted one that is alive. A
1208
+ * run's live browser view is that process's alone (browser-live.ts). */
1209
+ hasProcess(id) {
1210
+ const run = this.runs.get(id);
1211
+ return Boolean(run && ((run.child && run.child.exitCode === null && run.child.signalCode === null) || (run.orphan && alive(run.orphan))));
1212
+ }
942
1213
  /** How an agentic run ends: over its cap, or as the turn of the person's newest message ended (turns.ts), once every
943
1214
  * message the run took has had its turn. Undefined while one is open, or when the run stopped, waits, or its turn
944
1215
  * ended interrupted (the run then waits for the person), or while its records name no message (a live process of an
@@ -953,8 +1224,10 @@ export class Runs {
953
1224
  return undefined;
954
1225
  const cap = run.meta.max_cost_usd;
955
1226
  const cost = costOf(run.rows);
956
- if (cap !== undefined && cost !== null && cost > cap + FIT_TOLERANCE)
957
- return { outcome: "failed", abort: true, error: { code: SPEND_CAP_REACHED, message: `The run cost $${cost.toFixed(4)}, $${(cost - cap).toFixed(4)} over its cap of $${cap}.`, retryable: false } };
1227
+ // Past it by a cache miss, within the bound its cap admitted it at (overByMiss), the run goes on: its next request is
1228
+ // refused, and it pauses at its cap for a raise, as when the cap has no room; the over-cap row says what happened.
1229
+ if (cap !== undefined && cost !== null && cost > cap + FIT_TOLERANCE && !overByMiss(cost, cap, run.bounds?.ended() ?? 0))
1230
+ return { outcome: "failed", abort: true, error: { code: SPEND_CAP_REACHED, message: `The run cost ${cents(cost)}, ${centsUp(cost - cap)} over its cap of ${cents(cap)}.`, retryable: false } };
958
1231
  if (run.submitted > 0)
959
1232
  return undefined;
960
1233
  if (run.turns.open > 0 || stopped(run))
@@ -987,9 +1260,15 @@ export class Runs {
987
1260
  errorWords(run, text) {
988
1261
  return text ? this.shown(run, this.plainKey(run, text) ?? text) : text;
989
1262
  }
990
- /** An error row as served: its summary and text in errorWords' terms. The run's own rows, which its status reads, keep
991
- * what the harness said. */
1263
+ /** An error row as served: its summary and text in errorWords' terms, or the pause's phase row of a refusal for room the
1264
+ * run paused at. The run's own rows, which its status reads, keep what the harness said. */
992
1265
  servedError(run, row) {
1266
+ // A refusal for room the run paused at (pausedOn) is a pause, never a failure: the request was not sent, and a raise
1267
+ // goes on. Its row is a phase row in short words, marked `paused`; the refusal's sentence is the banner's
1268
+ // (pending.said), never said again here. It is the server's row (origin server), and no message: its id ends in
1269
+ // NOTE_SUFFIX, which isMessageRow passes over, as the wrap-up's does. It stays so after a raise, as the run's history.
1270
+ if (pausedOn(run, row))
1271
+ return { ...row, id: `${row.id}${NOTE_SUFFIX}`, kind: "phase", origin: "server", summary: BUDGET_PAUSED, text: BUDGET_PAUSED, paused: true };
993
1272
  const plain = this.plainKey(run, row.text ?? undefined);
994
1273
  if (plain) {
995
1274
  const words = this.shown(run, plain);
@@ -997,10 +1276,38 @@ export class Runs {
997
1276
  }
998
1277
  return { ...row, ...(row.summary ? { summary: this.shown(run, row.summary) } : {}), ...(row.text ? { text: this.shown(run, row.text) } : {}) };
999
1278
  }
1000
- /** What serve shows of a run's error text, for every run kind: no held secret (redacted, key-refusal.ts' one rule) and
1001
- * no loopback address. */
1279
+ /** What serve shows of a run's error text, for every run kind (run-view.ts shownOf): no held secret and no loopback. */
1002
1280
  shown(run, text) {
1003
- return withoutLoopback(redacted(text, this.refusedValues(run)));
1281
+ return shownOf(this.refusedValues(run))(text);
1282
+ }
1283
+ /** A run's error as its view and the run lists serve it (run-view.ts servedRunErrorWith): its message in shown()'s terms. */
1284
+ servedRunError(run, error) {
1285
+ return servedRunErrorWith((text) => this.shown(run, text), error);
1286
+ }
1287
+ /** A run's review as its view serves it (run-view.ts servedReviewWith): its reason in shown()'s terms, or withheld while
1288
+ * the run is hidden (meta.unshown). */
1289
+ servedReview(run, review) {
1290
+ return servedReviewWith((text) => this.shown(run, text), run.meta.unshown, review);
1291
+ }
1292
+ /** The pointers a run was handed, read back to cut them (sign-ins.ts peek and forgotten), by its serve.json's
1293
+ * `sign_in_handed`: none for a run with no mark (it was never handed one); else, for each hash it names, the live or
1294
+ * forgotten pointer whose SHA-256 it is. `unreadable` when what it was handed can't be read back here: a MALFORMED
1295
+ * mark, no vendor browser kept beside the mark, the sign-ins file can't be read, or any of its hashes matches no
1296
+ * pointer that opens (one under another seal key or none, one forgotten and dropped past MAX_FORGOTTEN, the sign-ins
1297
+ * file gone). Fails closed: a marked run is cut of every pointer it was handed, or withheld, never served uncut. Read
1298
+ * anew at each load: nothing caches this verdict, so a run withheld while its key was missing is shown once it opens. */
1299
+ handedPointers(agentId, browser, handed) {
1300
+ return handedPointersOf(this.options.signIns, agentId, browser, handed);
1301
+ }
1302
+ /** shown() for a run this server holds no Run for (an ended one a list reads from its row and serve.json alone, the
1303
+ * summary choke point: run-view.ts rowShown): cut of every secret this server never shows (serverSecrets) and of what
1304
+ * the run was handed of its agent's sign-in (handedPointers); `withheld` when that can't be read back here, as a load
1305
+ * would hide the run. */
1306
+ rowShown(agentId, meta, damaged = false) {
1307
+ // Its serve.json there but unreadable: what it was handed went with it (load hides such a run, its revision granting
1308
+ // the browser; a list row, which reads no revision, withholds it whatever its revision).
1309
+ const browser = isObject(meta?.tool_plane) ? keptVendor(meta.tool_plane).browser : undefined;
1310
+ return rowShownOf({ serverSecrets: this.options.serverSecrets, signIns: this.options.signIns }, agentId, browser, handedMark(meta?.sign_in_handed), damaged);
1004
1311
  }
1005
1312
  /** A run's answer as serve serves it: no held secret, never cut (redactedAnswer). Loopback addresses stay: an answer is
1006
1313
  * the model's own words, and a local address there can be what the person asked about. */
@@ -1024,26 +1331,6 @@ export class Runs {
1024
1331
  run.served = { ...run.served, [slot]: { keys, input, out } };
1025
1332
  return out;
1026
1333
  }
1027
- /** A workflow run's graph as serve serves it: its nodes, each decision and each call (its input, output and error) with
1028
- * no held secret, by its answer's rule (redactedOutput), and only then cut: a map item's label at 200 characters, a
1029
- * call's error at 2000, and a text stored cut (a decision's state past 64 KB, an error logged cut) less its last 6
1030
- * times the longest held value plus 16 characters, where a value the stored cut split would sit. The view a busy
1031
- * store's read keeps is the one graph-view.ts made, whole, so a key saved after it is still found. Each part is
1032
- * served once per content and held value set: a console polls the graph while the run goes. */
1033
- servedGraph(run, view) {
1034
- const values = this.refusedValues(run);
1035
- const keys = digestOf([...values].sort());
1036
- const once = (kind, value) => {
1037
- const at = `part:${keys}:${kind}:${digestOf(value)}`;
1038
- const kept = this.graphCache.get(at);
1039
- if (kept !== undefined)
1040
- return kept;
1041
- const out = servedPart(kind, value, values);
1042
- this.graphCache.set(at, out, Buffer.byteLength(JSON.stringify(out) ?? ""));
1043
- return out;
1044
- };
1045
- return { ...view, nodes: once("nodes", view.nodes), decisions: view.decisions.map((value) => once("decision", value)), effects: view.effects.map((value) => once("effect", value)) };
1046
- }
1047
1334
  /** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
1048
1335
  * before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
1049
1336
  * redacted()'s SHOWN, so its window holds. */
@@ -1054,18 +1341,17 @@ export class Runs {
1054
1341
  return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
1055
1342
  }
1056
1343
  redactor(run) {
1057
- return (text) => redacted(text, this.refusedValues(run));
1344
+ return redactorOf(this.refusedValues(run));
1058
1345
  }
1059
1346
  /** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
1060
1347
  * show cut out: its process may have written a secret or its sign-in's pointer there. */
1061
1348
  async lastLine(run) {
1062
1349
  return this.redactor(run)(await lastLogLine(run));
1063
1350
  }
1064
- /** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): this
1065
- * server's secrets wherever its launcher put them and the keys saved on it, what each launch handed the run, and the
1066
- * server's own tokens. */
1351
+ /** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): every one
1352
+ * this server never shows (serverSecrets, read now, so one rotated is cut at once) and what each launch handed the run. */
1067
1353
  refusedValues(run) {
1068
- return [...hostSecrets(process.env, this.options.storedKeys), ...(run.handed ?? []), this.options.token, this.options.doorToken];
1354
+ return refusedValuesOf(this.options.serverSecrets, run.handed);
1069
1355
  }
1070
1356
  /** A run's model error in a person's words when its provider refused the run's key (key-refusal.ts): the key its
1071
1357
  * harness's route sends, by this server's settings and keys, and no secret's value. */
@@ -1144,44 +1430,111 @@ export class Runs {
1144
1430
  /** SIGTERM to the run's process: it drains, releases the run and exits. */
1145
1431
  terminate(run) {
1146
1432
  if (run.child)
1147
- run.child.kill("SIGTERM");
1148
- else if (run.orphan && alive(run.orphan))
1149
- process.kill(run.orphan, "SIGTERM");
1150
- }
1151
- /** Supervise a run process an earlier server started: follow its door, and settle the run once its run.json says it
1152
- * let go (released, or its lease lapsed) or the process is gone. */
1153
- adoptProcess(run, record) {
1154
- const pid = holderPid(record);
1155
- if (!pid)
1433
+ return void run.child.kill("SIGTERM");
1434
+ // An adopted process only once its identity is confirmed (its pid, of the same start, on this boot): a pid another
1435
+ // process took over gets no signal, and one that cannot be checked keeps its stop pending, tried again every second
1436
+ // until it can be (said once for each reason), never sent unidentified. The timer keeps no server up, and close()
1437
+ // clears it.
1438
+ const holder = run.orphanHolder;
1439
+ if (holder === undefined)
1440
+ return;
1441
+ const state = holderState(holder);
1442
+ if (state === "alive") {
1443
+ run.stopWaits = undefined;
1444
+ // Already exited (ESRCH) or another user's pid now (EPERM): nothing to stop.
1445
+ return void signal(holder.pid, "SIGTERM");
1446
+ }
1447
+ if (state === "gone" || this.closed)
1156
1448
  return;
1449
+ if (!run.stopWaits)
1450
+ warn(run.id, `its stop waits: its process ${holder.pid} cannot be identified (the process listing cannot be read); it is sent once it can be`);
1451
+ run.stopWaits = true;
1452
+ clearTimeout(run.stopPending);
1453
+ run.stopPending = setTimeout(() => {
1454
+ run.stopPending = undefined;
1455
+ try {
1456
+ if (run.orphanHolder === holder && !this.closed)
1457
+ this.terminate(run);
1458
+ }
1459
+ catch (error) {
1460
+ warn(run.id, `its stop is not sent: ${error.message}`);
1461
+ }
1462
+ }, 1_000).unref();
1463
+ }
1464
+ /** Supervise a run process an earlier server started, its row's holder: follow its door, and settle the run once the
1465
+ * process is gone, or once the record it keeps in its store has said for EXIT_AFTER_RELEASE_MS that it let go while
1466
+ * the process lives on. `follow`: its rows are followed live from its door (never for a run whose rows are not
1467
+ * shown, meta.unshown). */
1468
+ adoptProcess(run, holder, follow = true) {
1469
+ const pid = holder.pid;
1157
1470
  run.orphan = pid;
1471
+ run.orphanHolder = holder;
1158
1472
  this.reportedBack(run);
1159
- this.connect(run);
1473
+ if (follow)
1474
+ this.connect(run);
1160
1475
  let releasedAt;
1161
- let unreadable = 0;
1476
+ let reading = false;
1477
+ let failedWith;
1478
+ // A holder that never says where it serves within the ready time is fenced: killed, then taken over.
1479
+ const doorBy = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS);
1480
+ const done = (released) => {
1481
+ if (run.orphan !== pid)
1482
+ return;
1483
+ clearInterval(timer);
1484
+ run.orphan = undefined;
1485
+ run.orphanHolder = undefined;
1486
+ // Its live browser view went with the process (browser-live.ts).
1487
+ void dropHandover(run.dir).catch(() => undefined);
1488
+ void this.settle(run, null, !holderLives(holder) && !released);
1489
+ };
1162
1490
  const timer = setInterval(() => {
1163
- void this.record(run).then((now) => {
1164
- if (now !== null)
1165
- unreadable = 0;
1166
- if (run.orphan !== pid || (this.doorOf(now) && alive(pid)))
1167
- return;
1168
- // A record that cannot be read while the process lives is read again at every tick: settling on no record could
1169
- // leave the run unsettled and unwatched. The server says so once the record has been unreadable for a while.
1170
- if (now === null && alive(pid)) {
1171
- if (++unreadable === UNREADABLE_TICKS)
1172
- warn(run.id, `its run.json has been unreadable for ${UNREADABLE_TICKS / 2} s; still watching its process ${pid}`);
1173
- return;
1174
- }
1175
- if (RELEASED.has(String(now?.status)) && alive(pid)) {
1176
- releasedAt ??= Date.now();
1177
- if (Date.now() - releasedAt < EXIT_AFTER_RELEASE_MS)
1491
+ if (run.orphan !== pid)
1492
+ return clearInterval(timer);
1493
+ if (reading)
1494
+ return;
1495
+ reading = true;
1496
+ const lives = holderLives(holder);
1497
+ void this.runRecord(run)
1498
+ .then(async (now) => {
1499
+ const released = RELEASED.has(String(now?.status));
1500
+ if (!lives)
1501
+ return done(released);
1502
+ // Its door, when the server that launched it went before it read the line: the one this process keeps in its
1503
+ // own store (the record names its pid), under the epoch its row holds.
1504
+ if (this.doorOf(run) === undefined) {
1505
+ const claim = this.store.runClaim(run.id);
1506
+ const own = isObject(now?.holder) && now.holder.pid === holder.pid ? now.holder : undefined;
1507
+ const serve = own?.serve;
1508
+ // Proven with the nonce the launching server kept on the row, as that server would have.
1509
+ const proven = now?.generation === claim.epoch && typeof serve === "string" && holder.nonce !== undefined && (await verifyDoor(serve, holder.nonce, this.headers(run)));
1510
+ if (proven) {
1511
+ this.nameHolder(run, claim.epoch, { ...holder, door: serve });
1512
+ if (follow)
1513
+ this.connect(run);
1514
+ }
1515
+ else if (Date.now() > doorBy) {
1516
+ warn(run.id, `its process ${pid} named no door within ${(this.options.readyTimeoutMs ?? READY_TIMEOUT_MS) / 1000} s; it is killed and the run taken over`);
1517
+ killHolder(holder);
1178
1518
  return;
1179
- warn(run.id, `its process ${pid} released the run ${EXIT_AFTER_RELEASE_MS / 1000} s ago and has not exited; reading its store anyway`);
1519
+ }
1180
1520
  }
1181
- clearInterval(timer);
1182
- run.orphan = undefined;
1183
- void this.settle(run, null, !alive(pid) && !RELEASED.has(String(now?.status)));
1184
- });
1521
+ if (!released)
1522
+ return;
1523
+ releasedAt ??= Date.now();
1524
+ if (Date.now() - releasedAt < EXIT_AFTER_RELEASE_MS)
1525
+ return;
1526
+ warn(run.id, `its process ${pid} released the run ${EXIT_AFTER_RELEASE_MS / 1000} s ago and has not exited; reading its store anyway`);
1527
+ done(true);
1528
+ })
1529
+ // A poll that fails (the agent store held by another writer, a listing that cannot be read) changes nothing: the
1530
+ // run stays watched, and the next tick looks again.
1531
+ .catch((error) => {
1532
+ // Said once for each reason, not at every tick.
1533
+ if (error.message !== failedWith)
1534
+ warn(run.id, `its watch of process ${pid} looks again: ${error.message}`);
1535
+ failedWith = error.message;
1536
+ })
1537
+ .finally(() => void (reading = false));
1185
1538
  }, 500);
1186
1539
  timer.unref();
1187
1540
  }
@@ -1203,7 +1556,8 @@ export class Runs {
1203
1556
  }
1204
1557
  // A remote box of an ended run is pulled first, so what it changed after its run's last pull is kept, and goes only
1205
1558
  // once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
1206
- const dirOf = (id) => join(this.options.agents.dir, "runs", id);
1559
+ const agentOf = new Map(rows.map((row) => [row.id, row.agent]));
1560
+ const dirOf = (id) => runDirIn(this.options.agents.dir, agentOf.get(id) ?? "", id);
1207
1561
  const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
1208
1562
  warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
1209
1563
  await this.keepBox(id, boxId, daytona);
@@ -1221,7 +1575,7 @@ export class Runs {
1221
1575
  }
1222
1576
  if (!box)
1223
1577
  return;
1224
- const settled = await sweepBoxes(box.host, box.quarantine, rows.map((row) => ({ id: row.id, dir: join(this.options.agents.dir, "runs", row.id) })));
1578
+ const settled = await sweepBoxes(box.host, box.quarantine, rows.map((row) => ({ id: row.id, dir: runDirIn(this.options.agents.dir, row.agent, row.id) })));
1225
1579
  for (const [id, how] of Object.entries(settled))
1226
1580
  if (how === "quarantined")
1227
1581
  warn(id, "its box could not be emptied; it is quarantined, and tried again at each start");
@@ -1250,19 +1604,8 @@ export class Runs {
1250
1604
  const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
1251
1605
  if (!boxes)
1252
1606
  return;
1253
- // Its background processes first (background.ts), so each one's exit code and whole log are in work/ before the
1254
- // pull and the destroy. A bound box with no work/background/ started none, and costs no command here. A failure only
1255
- // warns: the destroy ends them all the same.
1256
- if (remote || existsSync(join(run.dir, "work", BACKGROUND_DIR))) {
1257
- try {
1258
- const ended = await endBackground(boxes, { [RUN_LABEL]: run.id }, boxContext());
1259
- if (ended)
1260
- this.options.log?.("background_ended", { run: run.id, ended });
1261
- }
1262
- catch (error) {
1263
- warn(run.id, `its background processes were not ended before its box goes (${error.message}); destroying the box ends them`);
1264
- }
1265
- }
1607
+ // A box's background processes are ended by the run's own end on the runner (its tools' close), before this runs: the
1608
+ // destroy ends any that outlive it the same way.
1266
1609
  if (remote) {
1267
1610
  try {
1268
1611
  await this.pullBox(run, true);
@@ -1281,7 +1624,7 @@ export class Runs {
1281
1624
  try {
1282
1625
  await destroyRunBoxes(boxes, run.id, boxContext());
1283
1626
  // The box's egress proxy directory (box-egress.ts), its socket the run's process left: nothing binds it now.
1284
- await removeEgressDir(run.id).catch(() => undefined);
1627
+ await removeEgressDir(run.id, this.options.dockerPaths ? egressParentOf(this.options.agents.dir) : undefined).catch(() => undefined);
1285
1628
  }
1286
1629
  catch (error) {
1287
1630
  warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
@@ -1432,7 +1775,7 @@ export class Runs {
1432
1775
  run.updatedAt = new Date().toISOString();
1433
1776
  // What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
1434
1777
  if (status === "input_required")
1435
- this.notice(run, "run.needs_input", waitMark(run), { kind: state !== "waiting" ? "stopped" : waitingApproval(run) ? "approval" : pausedAt(run) !== undefined ? "budget" : "question" });
1778
+ this.notice(run, "run.needs_input", noticeMark(run), { kind: state !== "waiting" ? "stopped" : waitingApproval(run) ? "approval" : pausedAt(run) !== undefined || budgetWaiting(run) ? "budget" : browserAsk(run) ? "browser" : "question" });
1436
1779
  }
1437
1780
  /** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
1438
1781
  * has (settle, persistLater, reopen). What it already queued it queues no more. */
@@ -1470,7 +1813,7 @@ export class Runs {
1470
1813
  run.feed = abort;
1471
1814
  void (async () => {
1472
1815
  while (!abort.signal.aborted) {
1473
- const door = this.doorOf(await this.record(run));
1816
+ const door = this.doorOf(run);
1474
1817
  if (door)
1475
1818
  this.reportedBack(run);
1476
1819
  if (door && run.kind === "workflow") {
@@ -1478,17 +1821,53 @@ export class Runs {
1478
1821
  run.working = true;
1479
1822
  this.refresh(run);
1480
1823
  }
1824
+ // Its pause at its cap is written by its process (budget.json): a new one, or one written again at a higher cap
1825
+ // (a raise that did not cover the step), is read here, so its status and its webhook notice follow it. Each
1826
+ // round costs one stat; the file is read only when its time or size moved since the last read (fs.watch is not
1827
+ // to be trusted on the run's mount).
1828
+ this.watchPause(run);
1481
1829
  }
1482
1830
  else if (door)
1483
1831
  await this.follow(run, door, abort.signal).catch(() => undefined);
1484
- if (abort.signal.aborted || (!this.live(run) && !this.doorOf(await this.record(run))))
1832
+ if (abort.signal.aborted || (!this.live(run) && !this.doorOf(run)))
1485
1833
  break;
1486
- await sleep(run.kind === "workflow" ? 500 : 200);
1834
+ // Unref'd, and cut short by the watch's end (the process's settle, the server's close): nothing waits on it. Its
1835
+ // listener goes when its timer fires, so a long watch holds one at most, never one a round.
1836
+ await new Promise((resolve) => {
1837
+ const cut = () => (clearTimeout(timer), resolve());
1838
+ const timer = setTimeout(() => (abort.signal.removeEventListener("abort", cut), resolve()), run.kind === "workflow" ? 500 : 200);
1839
+ timer.unref();
1840
+ abort.signal.addEventListener("abort", cut, { once: true });
1841
+ });
1487
1842
  }
1488
1843
  if (run.feed === abort)
1489
1844
  run.feed = undefined;
1490
1845
  })();
1491
1846
  }
1847
+ /** One round of a live workflow run's watch of its pause at its cap: a stat of budget.json, and a read only when it
1848
+ * changed (its time or size); a new pause, or one written again, refreshes the run (its status, its notice). */
1849
+ watchPause(run) {
1850
+ let stamp;
1851
+ try {
1852
+ const stat = statSync(join(run.dir, BUDGET_PAUSE));
1853
+ stamp = `${stat.mtimeMs}:${stat.size}`;
1854
+ }
1855
+ catch {
1856
+ stamp = undefined;
1857
+ }
1858
+ this.onPauseCheck?.(run.id, "stat");
1859
+ if (stamp === run.pauseStamp)
1860
+ return;
1861
+ run.pauseStamp = stamp;
1862
+ if (stamp !== undefined)
1863
+ this.onPauseCheck?.(run.id, "read");
1864
+ const pause = stamp === undefined ? undefined : noticeMark(run);
1865
+ if (pause === run.pauseSeen)
1866
+ return;
1867
+ run.pauseSeen = pause;
1868
+ if (pause !== undefined)
1869
+ this.refresh(run);
1870
+ }
1492
1871
  async follow(run, door, signal) {
1493
1872
  // A file a call names by its absolute path in the run's workspace (a harness's CLI sends one) reads by its name there.
1494
1873
  const reducer = timelineReducer({ path: rowPaths(run.dir), redact: this.redactor(run), redactLive: (text) => redactedLive(text, this.refusedValues(run)) });
@@ -1535,14 +1914,19 @@ export class Runs {
1535
1914
  noteApprovals(run, entries);
1536
1915
  const redact = this.redactor(run);
1537
1916
  reducer.apply(events.map((e) => (Array.isArray(e.entries) ? { ...e, entries: redactGateMessages(e.entries, redact) } : e.entry !== undefined ? { ...e, entry: redactGateMessages([e.entry], redact)[0] } : e)));
1917
+ // The rows this connection makes, for a stop to read as over at once (stopTurn): only once its snapshot is in.
1918
+ // Until then the last connection's reducer stands, whose rows the run shows; a new one has none yet.
1919
+ if (event === "snapshot")
1920
+ run.timeline = reducer;
1538
1921
  // A stopped turn is over while the run's process lives on: a request it cut is a charge with no price (costsofar/1),
1539
- // as the settled read counts it, never one in flight.
1540
- if (!run.working && stopped(run))
1922
+ // as the settled read counts it, never one in flight. Read so from the stop on (stopTurn), not from the turn's
1923
+ // end reaching here: the run reads stopped from then. A message sent since (`submitted`) starts a turn of its own.
1924
+ if (run.submitted === 0 && stopped(run))
1541
1925
  reducer.idle();
1542
1926
  // A snapshot rebuilds from the conversation's current view: after a compaction it holds fewer of the rows
1543
1927
  // already shown, which stay; only live rows go when they end.
1544
1928
  const rows = reducer.rows();
1545
- this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive));
1929
+ this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive, (run.madeHere ??= new Set())));
1546
1930
  if (event === "snapshot" && run.finishStop) {
1547
1931
  run.finishStop = false;
1548
1932
  if (run.working && stopped(run) && run.submitted === 0) {
@@ -1555,9 +1939,51 @@ export class Runs {
1555
1939
  }
1556
1940
  }
1557
1941
  }
1942
+ /** The install `run`'s harness waits for before it launches (claude-agent's Claude Code, codex's Codex: harness-install.ts), or undefined
1943
+ * when it waits for none. One per run at a time, every run's on the server's one install: while that runs the run
1944
+ * shows it (installRow). A failed install ends the run failed, with the install's words, which name the command that
1945
+ * installs it by hand. */
1946
+ harnessReady(run) {
1947
+ const install = this.options.installs?.[run.harness];
1948
+ if (!install || install.installed)
1949
+ return undefined;
1950
+ if (run.installing)
1951
+ return run.installing;
1952
+ // Counted as holding its place until its launch (takePlace); a run whose process lives holds one already.
1953
+ if (!this.live(run))
1954
+ run.waitsInstall = true;
1955
+ const installing = (async () => {
1956
+ if (!(await install.needed()))
1957
+ return true;
1958
+ run.installRow = { at: new Date().toISOString(), words: install.installingWords };
1959
+ this.show(run);
1960
+ try {
1961
+ await install.ensure();
1962
+ return true;
1963
+ }
1964
+ catch (error) {
1965
+ // A server that stops mid-install leaves the run as it is, for the next server to install and launch.
1966
+ if (this.closing)
1967
+ return false;
1968
+ run.submitted = 0;
1969
+ if (!(run.outcome || run.finishing || run.cancel)) {
1970
+ run.error = { code: "run_failed", message: error.message, retryable: false };
1971
+ run.finishing = "failed";
1972
+ void this.settle(run, 1, true);
1973
+ }
1974
+ return false;
1975
+ }
1976
+ finally {
1977
+ run.installRow = undefined;
1978
+ this.show(run);
1979
+ }
1980
+ })().finally(() => void (run.installing = undefined));
1981
+ run.installing = installing;
1982
+ return installing;
1983
+ }
1558
1984
  /** The door of a run that is not finished, starting or waking its process when it is not live. */
1559
- async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS) {
1560
- const deadline = Date.now() + timeoutMs;
1985
+ async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS, refresh = false) {
1986
+ let deadline = Date.now() + timeoutMs;
1561
1987
  // A run brought up by a request (a message before the start's recovery reached it) waits for the sweep as well.
1562
1988
  await this.sweepOnce();
1563
1989
  await this.pinNeeds(run);
@@ -1568,12 +1994,18 @@ export class Runs {
1568
1994
  if (run.preparing === copying)
1569
1995
  throw new ApiError("unavailable", "the run's files are still being copied into its workspace", { retry_after_ms: 1000 }, { "retry-after": "1" });
1570
1996
  }
1571
- for (let launched = false;; await sleep(100)) {
1572
- const record = await this.record(run);
1573
- // Checked after the read: a settle may end the run while it is read, and nothing starts a run that ended.
1997
+ // And for its harness, installed on first use (harness-install.ts): its own time, bounded by the install's, before the
1998
+ // ready time starts. A failed install ended the run, which the loop says.
1999
+ const installing = this.harnessReady(run);
2000
+ if (installing) {
2001
+ await installing;
2002
+ deadline = Date.now() + timeoutMs;
2003
+ }
2004
+ for (let launched = false, refreshed = !refresh;; await sleep(100)) {
2005
+ // Checked first: a settle may have ended the run, and nothing starts a run that ended.
1574
2006
  if (run.outcome || run.finishing || run.cancel)
1575
2007
  throw this.finished(run);
1576
- const door = this.doorOf(record);
2008
+ const door = this.doorOf(run);
1577
2009
  if (door)
1578
2010
  return door;
1579
2011
  if (!this.live(run)) {
@@ -1582,31 +2014,64 @@ export class Runs {
1582
2014
  // Within the time left: a settle waiting on a busy store must not hold this caller past its deadline.
1583
2015
  await untilDeadline(run.settling, deadline);
1584
2016
  if (Date.now() > deadline)
1585
- throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
2017
+ throw this.notUp(run);
2018
+ continue;
2019
+ }
2020
+ // A launch waiting on its claim has no process yet, and tries again on its own (launch): waited for, within the time
2021
+ // left, never launched a second time nor read as a process that exited.
2022
+ if (run.claimWait) {
2023
+ if (Date.now() > deadline)
2024
+ throw this.notUp(run);
1586
2025
  continue;
1587
2026
  }
1588
2027
  if (launched)
1589
2028
  throw new ApiError("internal", `the run's process exited before it served: ${await this.lastLine(run)}`);
1590
- const pid = holderPid(record);
1591
- const fresh = record?.status === "running" && typeof record.heartbeatAt === "string" && Date.now() - Date.parse(record.heartbeatAt) < LEASE_MS && (pid === undefined || alive(pid));
2029
+ // A holder another server started that lives on (its door still to come): waited for, never launched over.
2030
+ const holder = this.holder(run);
2031
+ const fresh = holder !== undefined && holder.pid !== process.pid && holderLives(holder);
1592
2032
  // A run already going is never refused a place, but one whose harness this host's memory never holds (after a
1593
2033
  // restart on a smaller one) is not started: said, never tried.
1594
2034
  const never = fresh ? undefined : neverFits(run.harness, this.memory);
1595
2035
  if (never)
1596
2036
  throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
1597
- // Its sign-in pinned only for a launch: a run whose process still serves keeps the one it was handed.
2037
+ // Only for a launch: its MCP OAuth tokens near expiry refreshed (when this path may: a message's, an approval's
2038
+ // answer, never a stop's) and its sign-in pinned; a run whose process still serves keeps what it was handed. Looked at again
2039
+ // after the waits: they may have let another path launch it.
1598
2040
  if (!fresh) {
2041
+ if (!refreshed) {
2042
+ refreshed = true;
2043
+ const refreshing = this.mcpFresh(run);
2044
+ // A wait here lets the rest of the server go on: a recovery may start settling the run (recover's settle of
2045
+ // a process an earlier server left), or another path launch it. Every check above is read again first.
2046
+ if (refreshing) {
2047
+ await refreshing;
2048
+ continue;
2049
+ }
2050
+ }
1599
2051
  await this.pinSignIn(run);
1600
- if (run.outcome || run.finishing || run.cancel || this.live(run))
2052
+ // A settle that began during a wait owns the run until it ends: launching under it would start a process the
2053
+ // settle then ends, so it is waited for (the top of the loop), as one under way before the waits is.
2054
+ if (run.outcome || run.finishing || run.cancel || this.live(run) || run.settles > 0)
1601
2055
  continue;
1602
2056
  this.launch(run);
1603
2057
  launched = true;
1604
2058
  }
1605
2059
  }
1606
2060
  if (Date.now() > deadline)
1607
- throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
2061
+ throw this.notUp(run);
1608
2062
  }
1609
2063
  }
2064
+ /** A request's 503 for a run that did not come up in time, naming why, as far as this server can tell: the process
2065
+ * listing cannot be read (who holds it is unknown), the agent store is busy (its claim waits on it), or the run never
2066
+ * opened (its process is up, its door not serving). */
2067
+ notUp(run) {
2068
+ const why = run.claimWait
2069
+ ? (run.claimWaitWhy ?? "its claim could not be written yet")
2070
+ : this.holderView(run).unknown
2071
+ ? "the process listing cannot be read, so who holds it is not known"
2072
+ : "its process has not opened it yet (its door does not serve)";
2073
+ return new ApiError("unavailable", `the run did not come up in time: ${why}`, { retry_after_ms: 1000 }, { "retry-after": "1" });
2074
+ }
1610
2075
  /** The refusal of a message to an imported run: it was run elsewhere, and is kept as history. */
1611
2076
  importedRefusal(run) {
1612
2077
  const source = run.imported?.source;
@@ -1627,7 +2092,7 @@ export class Runs {
1627
2092
  async abortTurn(run) {
1628
2093
  if (run.kind === "workflow")
1629
2094
  return;
1630
- const door = this.doorOf(await this.record(run));
2095
+ const door = this.doorOf(run);
1631
2096
  if (door)
1632
2097
  await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
1633
2098
  }
@@ -1641,7 +2106,7 @@ export class Runs {
1641
2106
  for (const deadline = Date.now() + 30_000;; await sleep(200)) {
1642
2107
  if (!this.live(run) || run.cancel)
1643
2108
  throw new Error("the run's process is gone");
1644
- const door = this.doorOf(await this.record(run));
2109
+ const door = this.doorOf(run);
1645
2110
  const res = door ? await fetch(new URL(path, door), { method: body ? "POST" : "GET", headers: this.headers(run, body !== undefined), body: body && JSON.stringify(body), signal: AbortSignal.timeout(15_000) }).catch(() => null) : null;
1646
2111
  const data = res ? (await res.json().catch(() => null)) : null;
1647
2112
  if (res && res.status < 400)
@@ -1652,10 +2117,10 @@ export class Runs {
1652
2117
  throw new Error("the run's door did not answer");
1653
2118
  }
1654
2119
  }
1655
- async toDoor(run, path, body, readyMs) {
2120
+ async toDoor(run, path, body, readyMs, refresh = false) {
1656
2121
  const deadline = Date.now() + 30_000;
1657
2122
  for (;;) {
1658
- const door = await this.ensureLive(run, readyMs);
2123
+ const door = await this.ensureLive(run, readyMs, refresh);
1659
2124
  const res = await fetch(new URL(path, door), {
1660
2125
  method: body === undefined ? "GET" : "POST",
1661
2126
  headers: this.headers(run, body !== undefined),
@@ -1678,6 +2143,29 @@ export class Runs {
1678
2143
  const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
1679
2144
  this.needs.set(run.revision, await needsOf(revision));
1680
2145
  }
2146
+ /** Just before a launch that spawns the run's process (after pinNeeds): its MCP servers' OAuth tokens near expiry are
2147
+ * refreshed in serve (mcp-servers.ts headersForRun), so the synchronous launch hands it a fresh access token, never a
2148
+ * refresh token. Never on a path that only reaches a live process, nor on a stop's: an authorization server that is
2149
+ * slow to answer never holds an abort. */
2150
+ mcpFresh(run) {
2151
+ const source = this.options.mcpServers;
2152
+ if (!source?.refresh)
2153
+ return undefined;
2154
+ // The servers its pin names, or, before its first launch makes the pin (which may refuse the launch in words, there
2155
+ // alone), the ones its granted tools name: read only, never pinned here.
2156
+ const file = join(run.dir, MCP_PIN);
2157
+ let names = [];
2158
+ try {
2159
+ names = existsSync(file) ? Object.keys(JSON.parse(readFileSync(file, "utf8"))) : [...new Set((this.needs.get(run.revision)?.tools ?? []).flatMap((tool) => mcpNameOf(tool)?.server ?? []))];
2160
+ }
2161
+ catch {
2162
+ return undefined;
2163
+ }
2164
+ // Nothing to refresh, nothing awaited: a launch path with no OAuth server takes not one tick more than it did.
2165
+ if (!names.length)
2166
+ return undefined;
2167
+ return Promise.all(names.map((name) => source.refresh(name))).then(() => undefined);
2168
+ }
1681
2169
  /** `run`'s pinned MCP tools: read from its directory, or at its first launch made from the granted `tools` and the
1682
2170
  * servers saved now, and written before its process starts. Undefined when it grants none. */
1683
2171
  mcpPin(run, tools) {
@@ -1708,10 +2196,68 @@ export class Runs {
1708
2196
  // Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
1709
2197
  const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
1710
2198
  const signIns = this.options.signIns;
1711
- run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
2199
+ run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser, (handed) => this.keepHanded(run, handed)).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
2200
+ }
2201
+ /** That `run` is handed `signIn`, kept before it is (forRun's keep, under its agent's sign-ins lock, so no forget comes
2202
+ * between): false when that can't be saved, and the run is handed none. */
2203
+ async keepHanded(run, signIn) {
1712
2204
  // Never shown in its errors, from now on: a server started since its launch has handed it nothing yet.
1713
- if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
1714
- (run.handed ??= new Set()).add(run.signIn.ref);
2205
+ if (signIn.ref.length >= MIN_SECRET)
2206
+ (run.handed ??= new Set()).add(signIn.ref);
2207
+ // Kept, as its hash alone beside those of any it was handed before: a later server that cannot read the sign-in knows
2208
+ // this run's text could hold it, and which; and forget waits for the run (handedTo). Not kept, the run is handed none
2209
+ // (it starts signed out): a run whose text could hold the pointer is always one a server knows.
2210
+ const before = run.meta.sign_in_handed;
2211
+ const hash = pointerHash(signIn.ref);
2212
+ const now = before === undefined ? [hash] : before === MALFORMED || before.includes(hash) ? before : [...before, hash];
2213
+ if (now === before)
2214
+ return true;
2215
+ run.meta.sign_in_handed = now;
2216
+ return this.saveMeta(run).then(() => true, (error) => {
2217
+ if (before === undefined)
2218
+ delete run.meta.sign_in_handed;
2219
+ else
2220
+ run.meta.sign_in_handed = before;
2221
+ warn(run.id, `its browser starts signed out: that it was handed a sign-in could not be saved (${error.message})`);
2222
+ return false;
2223
+ });
2224
+ }
2225
+ /** The run of `agentId` still going (its row running) that was handed the sign-in whose pointer hashes to `hash`, or
2226
+ * any sign-in when `hash` is undefined (a pointer that does not open here): forget waits for it (sign-ins.ts). From the
2227
+ * run this server holds, else its serve.json: a run still going need not be held yet (a recovery under way, or one it
2228
+ * could not recover). One whose mark is MALFORMED, or whose serve.json is damaged (run.damaged for a held run, the same
2229
+ * answer the disk read gives), counts: what it was handed is not known. */
2230
+ async handedTo(agentId, hash) {
2231
+ for (const row of await this.options.agents.request(() => this.store.listRuns({ agent: agentId }))) {
2232
+ if (row.state !== "running")
2233
+ continue;
2234
+ const held = this.runs.get(row.id);
2235
+ const handed = held ? (held.damaged ? MALFORMED : held.meta.sign_in_handed) : await handedOnDisk(join(runDirIn(this.options.agents.dir, row.agent, row.id), RUN_META));
2236
+ if (handed !== undefined && (handed === MALFORMED || hash === undefined || handed.includes(hash)))
2237
+ return row.id;
2238
+ }
2239
+ return undefined;
2240
+ }
2241
+ /** The pointer of the sign-in a run this server loads was handed, among the values its rows, errors and answers never
2242
+ * show: read only, with no lease taken (pinSignIn takes one at its next launch). `unreadable` when its agent keeps
2243
+ * one that does not open under this server's seal key. */
2244
+ async peekSignIn(run) {
2245
+ // Its plane's vendor as a launch reads it (keptVendor: a missing-key refusal an earlier server saved is that vendor).
2246
+ const browser = run.meta.tool_plane && keptVendor(run.meta.tool_plane).browser;
2247
+ const peeked = browser ? await this.options.signIns?.peek(run.agentId, browser).catch(() => "unreadable") : undefined;
2248
+ // The agent's live pointer, which a launch of it may hand it next.
2249
+ if (typeof peeked === "object" && peeked.ref.length >= MIN_SECRET)
2250
+ (run.handed ??= new Set()).add(peeked.ref);
2251
+ // What it was handed, forgotten since or not (sign-ins.ts Forgotten): a sign-in forgotten after the run ended, or
2252
+ // replaced since, is still cut from what it said. A run with no mark was never handed one. `unreadable` when what it
2253
+ // was handed can't be read back here (handedPointers), and the run is hidden (load).
2254
+ const pointers = await this.handedPointers(run.agentId, browser, run.meta.sign_in_handed);
2255
+ if (pointers === "unreadable")
2256
+ return pointers;
2257
+ for (const ref of pointers.refs)
2258
+ if (ref.length >= MIN_SECRET)
2259
+ (run.handed ??= new Set()).add(ref);
2260
+ return "read";
1715
2261
  }
1716
2262
  /** Lets go of the save lease the run holds on its agent's sign-in, if any: at once when its process let its sessions go
1717
2263
  * (`clean`), else by the gone rule (sign-ins.ts). */
@@ -1720,8 +2266,29 @@ export class Runs {
1720
2266
  await this.options.signIns?.release(run.agentId, run.id, run.dir, clean).catch((error) => warn(run.id, `its sign-in's save lease is not let go: ${error.message}`));
1721
2267
  }
1722
2268
  launch(run, followUp = run.followUpOpen === true) {
1723
- if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing)
2269
+ // A launch that waited on its claim lets go of the place it kept (takePlace) as it tries again: from here it is a live
2270
+ // run again, or not one at all.
2271
+ run.claimWait = undefined;
2272
+ run.claimWaitWhy = undefined;
2273
+ run.notOpened = undefined;
2274
+ if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing || run.installing)
1724
2275
  return;
2276
+ // Every launch of a run whose harness installs on first use (its start, a recovery after a restart, a relaunch, a
2277
+ // wake) waits for that install to be whole first (harnessReady), holding its place meanwhile (waitsInstall), and
2278
+ // launches once it is: never a process that would load a missing CLI.
2279
+ const installing = this.harnessReady(run);
2280
+ // After the install, its MCP OAuth tokens are refreshed again: the wait (up to the install's bound) may have outlived
2281
+ // what the refresh before it gave (mcpFresh); launch() reads every check again.
2282
+ if (installing)
2283
+ return void installing.then(async (installed) => {
2284
+ if (!installed)
2285
+ return;
2286
+ const refreshing = this.mcpFresh(run);
2287
+ if (refreshing)
2288
+ await refreshing;
2289
+ this.launch(run, followUp);
2290
+ });
2291
+ run.waitsInstall = undefined;
1725
2292
  // Taken by this launch only: a later launch (a relaunch after its process went) opens the run as any other.
1726
2293
  run.followUpOpen = undefined;
1727
2294
  // Its secrets go over fd 3, written whole and closed as it starts; it reads them first (secrets.ts). Each launch path
@@ -1766,11 +2333,17 @@ export class Runs {
1766
2333
  ...childEnv(process.env, this.options.token),
1767
2334
  // The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
1768
2335
  [RUN_BOX_ALLOW_ENV]: this.options.dockerAllow === undefined || this.options.dockerAllow === "none" ? "none" : this.options.dockerAllow.join(","),
2336
+ // And, for a server in a container, where its Docker has the data directory: set always, empty on a host, so a stale
2337
+ // value in the server's own environment never reaches a run.
2338
+ [RUN_BOX_PATHS_ENV]: this.options.dockerPaths ? JSON.stringify(this.options.dockerPaths) : "",
1769
2339
  // And, on a Mac, its proxy's volume: set always, empty for none, so a stale value in the server's own environment
1770
2340
  // never reaches a run.
1771
2341
  [RUN_BOX_VOLUME_ENV]: this.options.dockerVolume ?? "",
1772
2342
  [SECRETS_FD_ENV]: "3",
1773
2343
  [SECRETS_LEN_ENV]: String(secrets.length),
2344
+ // The server's data (dataOfRun: a run's directory is on its agent's disk under it): claude-agent loads Claude Code
2345
+ // from its harnesses.
2346
+ [DATA_ENV]: dataOfRun(run.dir),
1774
2347
  ...this.fauxEnv(),
1775
2348
  ...(run.meta.effort ? { [EFFORT_ENV]: run.meta.effort } : {}),
1776
2349
  ...(this.options.documents ? { [DOCUMENTS_ENV]: this.options.documents } : {}),
@@ -1779,17 +2352,21 @@ export class Runs {
1779
2352
  run.meta.launch_thinking = { ...(env[EFFORT_ENV] ? { effort: env[EFFORT_ENV] } : {}), ...(env.AGENT_THINKING ? { host: env.AGENT_THINKING } : {}) };
1780
2353
  void this.saveMeta(run).catch((error) => warn(run.id, `what its process thinks at is not saved: ${error.message}`));
1781
2354
  delete env[CAP_ENV];
2355
+ delete env[CAP_MODE_ENV];
1782
2356
  if (run.meta.max_cost_usd !== undefined)
1783
2357
  env[CAP_ENV] = String(run.meta.max_cost_usd);
2358
+ if (run.meta.max_cost_usd !== undefined && run.meta.cap_mode !== undefined)
2359
+ env[CAP_MODE_ENV] = run.meta.cap_mode;
1784
2360
  // A run on the host's default (its revision names no model) gets the model the server picks for its harness, never
1785
2361
  // the key that gave it: behind a gateway its process holds the gateway's key alone (keysFor) and could not tell. It is
1786
2362
  // the run's last choice (model.ts hostModel: the tier's variable, then AGENT_MODEL where the harness runs it, then a
1787
2363
  // key the run holds, then this), so a host's setting the harness can run still wins; and one it cannot (AGENT_MODEL
1788
2364
  // on Anthropic's model, for codex) no longer leaves the run with none. pi and codex choose through the gateway
1789
- // (chooseModel); claude-agent never does, and holds the key its route sends, which gives its default.
2365
+ // (chooseModel); a harness whose model is its own (its facts' ownModel: claude-agent) never does, and holds the key
2366
+ // its route sends, which gives its default.
1790
2367
  delete env[DEFAULT_MODEL_ENV];
1791
- const harness = run.tooling?.harness ?? DEFAULT_HARNESS;
1792
- const defaultModel = run.tooling && !run.tooling.model && harness !== "claude-agent" ? hostModel(served, "default", harness) : undefined;
2368
+ const harness = run.harness;
2369
+ const defaultModel = run.tooling && !run.tooling.model && !builtinHarness(harness)?.facts?.ownModel ? hostModel(served, "default", harness) : undefined;
1793
2370
  if (defaultModel)
1794
2371
  env[DEFAULT_MODEL_ENV] = defaultModel;
1795
2372
  // Opened for a person's follow-up to a run whose turn had ended: nothing it resumes was cut (app.ts markResumed).
@@ -1834,15 +2411,70 @@ export class Runs {
1834
2411
  const providers = needs?.decisionProviders;
1835
2412
  const decisionKeys = providers ? decisionKeysFor(served, { providers, parallelWeb: handsParallel(plane) }) : {};
1836
2413
  const handsKey = Object.keys(decisionKeys).length > 0;
2414
+ // The run's claim, for its process: from the epoch its row holds, bumped with the holder named, in one statement (a
2415
+ // claim that moved meanwhile is stale, and this launch writes nothing). A holder the row names that still lives (a
2416
+ // process an earlier server left that serves no door) is killed first, and the claim waits until it is gone: no
2417
+ // process of a lower epoch runs, or commits to the run's store, once the epoch is bumped. A claim that cannot be
2418
+ // written (the agent store held, or not writable) launches nothing now, and is tried again, the launch whole, soon at
2419
+ // first (CLAIM_RETRY_MS) and then every settle retry, until it is written: a run never stays without a process for
2420
+ // want of one.
2421
+ let epoch;
2422
+ const nonce = randomBytes(32).toString("hex");
2423
+ try {
2424
+ const claim = this.store.runClaim(run.id);
2425
+ const held = holderOfClaim(run.id, claim);
2426
+ if (held && killHolder(held))
2427
+ throw new Error(`its holder ${held.pid} still lived; it is killed first`);
2428
+ epoch = this.store.claimRun(run.id, LAUNCH_HOLDER, claim.epoch);
2429
+ env[RUN_EPOCH_ENV] = String(epoch);
2430
+ // Its mark: should the row still name the launch when this server goes, the next one finds the process by it.
2431
+ env[RUN_LAUNCH_ENV] = `${run.id}:${epoch}`;
2432
+ run.claimTries = undefined;
2433
+ }
2434
+ catch (error) {
2435
+ // Soon at first (a store another writer holds for a moment), then every settle retry.
2436
+ const tries = run.claimTries ?? 0;
2437
+ run.claimTries = tries + 1;
2438
+ const every = CLAIM_RETRY_MS[tries] ?? this.options.settleRetryMs ?? SETTLE_RETRY_MS;
2439
+ // What this launch took goes back, so the next one launches as this one would have.
2440
+ if (followUp)
2441
+ run.followUpOpen = true;
2442
+ if (first)
2443
+ run.firstLaunch = true;
2444
+ run.claimWait = true;
2445
+ run.claimWaitWhy = storeBusy(error) ? "the agent store is busy (another writer holds it)" : /cannot be (checked|looked for)/.test(error.message) ? "the process listing cannot be read, so its holder cannot be checked" : error.message;
2446
+ warn(run.id, `its process is not started: its claim was not written (${error.message}); trying again in ${every / 1000} s`);
2447
+ setTimeout(async () => {
2448
+ if (this.closing)
2449
+ return;
2450
+ // Refreshed again before the retry, as after any wait (mcpFresh); launch() reads every check again.
2451
+ const refreshing = this.mcpFresh(run);
2452
+ if (refreshing)
2453
+ await refreshing.catch(() => undefined);
2454
+ if (this.closing)
2455
+ return;
2456
+ try {
2457
+ this.launch(run);
2458
+ }
2459
+ catch (error) {
2460
+ warn(run.id, `its process is not started: ${error.message}`);
2461
+ }
2462
+ }, every).unref();
2463
+ return;
2464
+ }
1837
2465
  this.markLaunching(run);
1838
2466
  const log = openSync(join(run.dir, PROCESS_LOG), "a", 0o600);
1839
- const stdio = ["ignore", "ignore", log, "pipe"];
2467
+ const stdio = ["ignore", "pipe", log, "pipe"];
1840
2468
  // The first descriptor after the others: macOS aborts the parent of a spawn with a pipe at 16 or above.
1841
2469
  const keyFd = stdio.length;
1842
2470
  if (handsKey) {
1843
2471
  stdio.push("pipe");
1844
2472
  env[DECISION_KEY_FD_ENV] = String(keyFd);
1845
2473
  }
2474
+ // This launch's door nonce, on a pipe of its own, never in an environment (which stays readable by the user's other
2475
+ // processes): the process reads it first and closes it, and its door proves it (door-line.ts).
2476
+ const nonceFd = stdio.length;
2477
+ stdio.push("pipe");
1846
2478
  // A workflow run resumes from its journal when it opens again, so SIGTERM lets it go at once, undrained.
1847
2479
  const drain = run.kind === "workflow" ? "0s" : (this.options.drainTimeout ?? DRAIN);
1848
2480
  // Its own door token, which its door takes and its calls to the box relay carry: no other run's process holds it.
@@ -1852,7 +2484,12 @@ export class Runs {
1852
2484
  // secrets.ts first, as a preload: the pipe is read and closed before pi-durable-disk's CLI loads or starts anything.
1853
2485
  "--no-warnings=ExperimentalWarning", "--import", SECRETS_MODULE, this.cli, "run", "--dir", run.dir, "--app", this.app,
1854
2486
  "--serve", "0", "--serve-host", "127.0.0.1", "--serve-token-file", doorTokenFile, "--drain-timeout", drain, // key-gate: loopback-rule the door of a run listens on loopback only, for this server
2487
+ "--epoch", String(epoch), "--door-nonce-fd", String(nonceFd),
1855
2488
  ], { stdio, env });
2489
+ const noncePipe = child.stdio[nonceFd];
2490
+ // A process that dies before it reads the nonce closes the pipe: that is its exit to settle, not an error here.
2491
+ noncePipe?.on("error", () => undefined);
2492
+ noncePipe?.end(this.options.fauxHandedNonce ?? nonce);
1856
2493
  closeSync(log);
1857
2494
  const pipe = child.stdio[3];
1858
2495
  pipe?.on("error", () => { });
@@ -1864,9 +2501,17 @@ export class Runs {
1864
2501
  keyPipe?.end(JSON.stringify(decisionKeys));
1865
2502
  }
1866
2503
  run.child = child;
2504
+ run.door = undefined;
1867
2505
  child.once("exit", (code) => {
1868
- if (run.child === child)
2506
+ if (run.child === child) {
1869
2507
  run.child = undefined;
2508
+ run.door = undefined;
2509
+ }
2510
+ // Its live browser view went with it, however it ended (browser-live.ts): a process killed before it let its
2511
+ // sessions go leaves its hand-over behind, naming a port another listener may take.
2512
+ void dropHandover(run.dir).catch(() => undefined);
2513
+ // Its agent's ask, if one waits, stays: the run's next process takes it up (browser-person.ts), and the run ends
2514
+ // with it gone (carryBack).
1870
2515
  this.reportedBack(run);
1871
2516
  void this.settle(run, code, true);
1872
2517
  });
@@ -1875,8 +2520,99 @@ export class Runs {
1875
2520
  run.child = undefined;
1876
2521
  this.reportedBack(run);
1877
2522
  });
2523
+ // Only once the child is wired (its exit and error handled above): the row names the process (its pid, its start and
2524
+ // this boot) under the epoch it was given, and its door once it says, on stdout, where it serves: its one line there
2525
+ // (pi-durable-disk's run under its host's epoch). A process listing that cannot be read names nothing.
2526
+ this.nameHolder(run, epoch, child.pid === undefined ? undefined : withNonce(holderOfProcess(child.pid), nonce));
2527
+ // Its door: the first line it prints, before any harness or agent code of it runs, proven with this launch's nonce
2528
+ // before it is recorded; no later line is read (door-line.ts).
2529
+ if (child.stdout && child.pid !== undefined) {
2530
+ const pid = child.pid;
2531
+ void firstDoorLine(child.stdout, epoch).then(async (door) => {
2532
+ if (door === undefined || !isLoopback(new URL(door).hostname))
2533
+ return warn(run.id, `its process ${pid} named no loopback door first on stdout; none is recorded`);
2534
+ // A door that does not answer this launch's nonce (wrongly, or not within the proof's time) is not this launch's
2535
+ // to record, and its process is not taken for up: as one that misses its open time, it is said once and stopped,
2536
+ // by this server's own handle on its child, and its exit opens the run again (up to MAX_RELAUNCHES), the last
2537
+ // one's failure naming this cause. One that has exited already is its exit's to settle, and so is one that exits
2538
+ // on its own within DOOR_EXIT_WAIT_MS: an app that fails at its start closes its door, failing the proof, before its
2539
+ // exit is seen here, and that exit fails the run with its own error, never as a process that did not open it.
2540
+ if (!(await verifyDoor(door, nonce, this.headers(run)))) {
2541
+ if (run.child === child && child.exitCode === null && child.signalCode === null)
2542
+ await once(child, "exit", { signal: AbortSignal.timeout(DOOR_EXIT_WAIT_MS) }).catch(() => undefined);
2543
+ if (run.child !== child || child.exitCode !== null || child.signalCode !== null)
2544
+ return;
2545
+ run.notOpened = "its process's door did not answer this launch's nonce";
2546
+ warn(run.id, `its process ${pid}'s door did not answer this launch's nonce; it is stopped`);
2547
+ this.reportedBack(run);
2548
+ child.kill("SIGKILL");
2549
+ return;
2550
+ }
2551
+ // Recorded once its run serves: a door listens before its run opens, and the run is up only then. One that never
2552
+ // serves within the ready time is said once, by its cause, and stopped: its exit settles the run, which opens it
2553
+ // again (up to MAX_RELAUNCHES) as for any process that went before the run ended.
2554
+ const readyMs = this.options.openTimeoutMs ?? READY_TIMEOUT_MS;
2555
+ const opened = await untilOpened(door, this.headers(run), () => run.child !== child, Date.now() + readyMs);
2556
+ if (!opened.opened) {
2557
+ if (opened.why === "deadline" && run.child === child) {
2558
+ run.notOpened = `its process did not open the run within ${readyMs / 1000} s (its door last answered ${opened.last})`;
2559
+ warn(run.id, `its process ${pid} did not open the run within ${readyMs / 1000} s (its door last answered ${opened.last}); it is stopped`);
2560
+ // Its launch came through (the server is up): its stop is no launch that took the server down.
2561
+ this.reportedBack(run);
2562
+ child.kill("SIGKILL");
2563
+ }
2564
+ return;
2565
+ }
2566
+ if (run.child === child)
2567
+ run.door = door;
2568
+ const holder = holderOfProcess(pid);
2569
+ if (holder)
2570
+ this.nameHolder(run, epoch, { ...holder, nonce, door });
2571
+ }).catch((error) => warn(run.id, `its door is not recorded: ${error.message}`));
2572
+ }
1878
2573
  this.connect(run);
1879
2574
  }
2575
+ /** Names `holder` on the run's row under `epoch`, the claim its launch made: a claim that moved on since (a take-back,
2576
+ * a later launch) is left as it is, and a store that is busy is tried again shortly, a few times. */
2577
+ nameHolder(run, epoch, holder) {
2578
+ if (holder === undefined)
2579
+ return;
2580
+ const pending = run.naming;
2581
+ run.naming = { epoch, holder, tries: 0 };
2582
+ // One write at a time per run, of the newest holder: a retry under way takes this one.
2583
+ if (pending === undefined)
2584
+ this.writeHolder(run);
2585
+ }
2586
+ /** Writes the run's newest holder to name (`naming`); a store another writer holds is tried again, soon at first, then
2587
+ * every settle retry, while the process lives and the server runs. */
2588
+ writeHolder(run) {
2589
+ const naming = run.naming;
2590
+ if (naming === undefined)
2591
+ return;
2592
+ if (this.closed || !holderLives(naming.holder))
2593
+ return void (run.naming = undefined);
2594
+ try {
2595
+ this.store.setRunHolder(run.id, naming.epoch, JSON.stringify(naming.holder));
2596
+ }
2597
+ catch (error) {
2598
+ if (storeBusy(error)) {
2599
+ const every = CLAIM_RETRY_MS[naming.tries] ?? this.options.settleRetryMs ?? SETTLE_RETRY_MS;
2600
+ naming.tries++;
2601
+ setTimeout(() => {
2602
+ try {
2603
+ this.writeHolder(run);
2604
+ }
2605
+ catch (error) {
2606
+ warn(run.id, `its holder is not named on its row: ${error.message}`);
2607
+ }
2608
+ }, every).unref();
2609
+ return;
2610
+ }
2611
+ if (!(error instanceof AgentHomeError && error.code === "stale"))
2612
+ warn(run.id, `its holder is not named on its row: ${error.message}`);
2613
+ }
2614
+ run.naming = undefined;
2615
+ }
1880
2616
  /** Writes the run's launch mark before its process is spawned: a spawn that takes the server down leaves it, and the
1881
2617
  * next start fails the run rather than launch it again and go down with it. The file exists once the call returns,
1882
2618
  * which a server's death does not undo; no fsync, which would hold the event loop on the disk at every launch. */
@@ -1910,7 +2646,7 @@ export class Runs {
1910
2646
  run.submitted = 1;
1911
2647
  this.refresh(run);
1912
2648
  // As it was first sent: the run never took it, so its work/inputs/ is as its start left it.
1913
- void firstMessage(first, join(run.dir, "work")).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => warn(run.id, `its first message did not land again: ${error.message}`));
2649
+ void firstMessage(first, join(run.dir, "work")).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS, originOf(run.meta.input_origin))).catch((error) => warn(run.id, `its first message did not land again: ${error.message}`));
1914
2650
  }
1915
2651
  /** After the run's process exited, or was found gone: its rows from its released store, then, when it is over, its
1916
2652
  * carry back. One at a time per run, and none once the run has its outcome. */
@@ -1921,7 +2657,7 @@ export class Runs {
1921
2657
  run.settling = (run.settling ?? Promise.resolve())
1922
2658
  .then(() => (run.outcome ? undefined : this.settleOnce(run, code, exited)))
1923
2659
  .catch((error) => {
1924
- if (!(storeBusy(error) || error instanceof PullPending) || this.closing)
2660
+ if (!(storeBusy(error) || error instanceof PullPending || error instanceof HolderUnknown) || this.closing)
1925
2661
  return warn(run.id, `not settled: ${error.message}; the next start tries again`);
1926
2662
  // A store still held past the run end's retries: settled again later, not left until the next start.
1927
2663
  const every = this.options.settleRetryMs ?? SETTLE_RETRY_MS;
@@ -1941,18 +2677,39 @@ export class Runs {
1941
2677
  run.feed?.abort();
1942
2678
  run.feed = undefined;
1943
2679
  run.working = false;
1944
- const record = await this.record(run);
2680
+ // What the run's process said in its store: a release (its status), and a workflow's end (its detail).
2681
+ const record = await this.runRecord(run);
1945
2682
  const released = RELEASED.has(String(record?.status));
1946
2683
  run.letGo = released;
1947
- const pid = holderPid(record);
1948
- // A process that is gone serves no door, whatever its last heartbeat says.
1949
- const gone = !this.live(run) && !(pid !== undefined && pid !== process.pid && alive(pid) && this.doorOf(record));
2684
+ // Gone unless another live process serves it (its row's holder, which has not released it): a holder that lives
2685
+ // but serves no door, or lives on after its release, is taken back, which kills it first (the disk's revoke).
2686
+ // This server's own process exited: nothing else holds the run. Any other settle asks the row, and a holder that
2687
+ // cannot be told (its row or the process listing unreadable) is never taken for gone: the settle is tried again.
2688
+ let door;
2689
+ if (!exited && !this.live(run)) {
2690
+ const view = this.holderView(run);
2691
+ if (view.unknown)
2692
+ throw new HolderUnknown("who holds it cannot be told now (its row or the process listing cannot be read)");
2693
+ const other = view.holder !== undefined && view.holder.pid !== process.pid && holderState(view.holder) === "alive" ? view.holder : undefined;
2694
+ // A live holder that has not let go and serves no door yet (a launch an earlier server left opening): watched, as
2695
+ // at a start, until it serves, goes, or is taken over past the ready time.
2696
+ if (other && !released && !run.orphan && !this.doorOf(run)) {
2697
+ this.adoptProcess(run, other, !run.meta.unshown);
2698
+ return;
2699
+ }
2700
+ door = !released && other ? this.doorOf(run) : undefined;
2701
+ }
2702
+ const gone = !this.live(run) && !door;
1950
2703
  // Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
1951
2704
  if (gone)
1952
2705
  await this.options.signIns?.markGone(run.agentId, run.id).catch((error) => warn(run.id, `its sign-in's lease is not marked: ${error.message}`));
1953
2706
  // Its metrics are this settle's read, or none: never an earlier end's.
1954
2707
  run.metrics = undefined;
1955
- if (released || gone)
2708
+ // Its process gone: the server takes the run back, its database checkpointed, before it reads it. A hidden run's
2709
+ // store is never read.
2710
+ if (gone)
2711
+ await this.takeBack(run);
2712
+ if ((released || gone) && !run.meta.unshown)
1956
2713
  await this.storeWhenFree(run, true);
1957
2714
  // Its process gone: an archived run's box is let go now, whatever comes next (an outcome, a wait for the person, a
1958
2715
  // relaunch), since nothing else would until the next start or archive. This is every archived end that can let a box
@@ -1964,6 +2721,9 @@ export class Runs {
1964
2721
  let ended;
1965
2722
  // A workflow run carries back how its workflow ended, through workflowCarry; cancelled before that, it stopped.
1966
2723
  // A cancel during the end-of-run turn ends the run's learning, never its job: the run keeps the outcome it had.
2724
+ // Even when another live holder still serves the run (!gone: its stop not through yet, kept pending), a cancel ends it
2725
+ // here: workflowEnd only reads the run's store lock-free and carries the end back, so it neither waits on nor writes
2726
+ // that holder's store, and the holder's exit later finds the run ended.
1967
2727
  if (run.cancel && !reflecting(run))
1968
2728
  ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
1969
2729
  else if (run.finishing)
@@ -1985,7 +2745,7 @@ export class Runs {
1985
2745
  run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
1986
2746
  ended = { outcome: "failed" };
1987
2747
  }
1988
- else if (!gone && this.doorOf(record))
2748
+ else if (!gone && door)
1989
2749
  ended = undefined;
1990
2750
  else if (run.kind === "workflow")
1991
2751
  ended = await this.workflowEnd(run, workflowEnding(record));
@@ -1996,8 +2756,17 @@ export class Runs {
1996
2756
  ended = end && { outcome: end.outcome };
1997
2757
  }
1998
2758
  if (!ended) {
1999
- // Work left and no process: opened again. A run that waits for the person waits without one, until a message.
2000
- const stalled = run.kind === "workflow" || statusOf(run).status !== "input_required";
2759
+ // Work left and no process: opened again. A run that waits for the person waits without one, until a message; but
2760
+ // one whose agent waits on its ask for the person in its browser is mid-turn (the tool call waits inside it), and its
2761
+ // next process takes the wait up: it reads the owner's answer, or writes the ask's expiry (browser-person.ts).
2762
+ // A raised run whose follow-up is still to go let its process go as a paused one does: its sign-in's lease goes too.
2763
+ if (gone)
2764
+ await runsTestHooks.beforeRestartCheck?.(run.dir);
2765
+ // A workflow run paused at its cap that let its process go waits for a raise, which opens it again (raiseCap).
2766
+ // One whose raise serve.json kept and a crash cut short: finished now (finishRaise opens it again), never left waiting.
2767
+ if (run.kind === "workflow" && gone && budgetWaiting(run) && (await this.finishRaise(run, { settling: true })))
2768
+ return this.refresh(run);
2769
+ const stalled = run.kind === "workflow" ? !budgetWaiting(run) : (statusOf(run).status !== "input_required" && !raisedToGo(run)) || askWaits(run);
2001
2770
  // Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
2002
2771
  // opened before its process went may still be live at the vendor, and would write back over another run's. One
2003
2772
  // that let go cleanly to wait for its person released its sessions first, so its lease goes now.
@@ -2013,10 +2782,13 @@ export class Runs {
2013
2782
  const never = neverFits(run.harness, this.memory);
2014
2783
  if (!never && run.relaunches < MAX_RELAUNCHES) {
2015
2784
  await this.pinNeeds(run);
2785
+ const refreshing = this.mcpFresh(run);
2786
+ if (refreshing)
2787
+ await refreshing;
2016
2788
  await this.pinSignIn(run);
2017
2789
  return this.relaunch(run);
2018
2790
  }
2019
- run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await this.lastLine(run)}`, retryable: false };
2791
+ run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${run.notOpened ?? (await this.lastLine(run))}`, retryable: false };
2020
2792
  ended = { outcome: "failed" };
2021
2793
  }
2022
2794
  await this.carryBack(run, ended.outcome, ended.state, ended.summary);
@@ -2030,15 +2802,19 @@ export class Runs {
2030
2802
  // A run's end waits for a busy store as long as its carry back does, not a request's 2 s.
2031
2803
  const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
2032
2804
  const at = { runId: run.id, storePath: this.storeFile(run), revision };
2033
- const { state, summary } = await workflowCarry(at, ending);
2805
+ // Lock-free reads of its store, as every server read of a run's database (run-db.ts): nothing made beside it.
2806
+ const { state, summary } = await workflowCarry(at, ending, { unlocked: true });
2034
2807
  if (state === "completed")
2035
- run.meta.output = (await readWorkflowRun(at)).output ?? null;
2808
+ run.meta.output = (await readWorkflowRun(at, { unlocked: true })).output ?? null;
2036
2809
  else if (state === "escalated") {
2037
- const { escalation, escalatedAt } = await readWorkflowRun(at);
2810
+ const { escalation, escalatedAt } = await readWorkflowRun(at, { unlocked: true });
2038
2811
  run.meta.review = { kind: escalation?.kind ?? null, node: escalation?.label ?? escalatedAt?.label ?? null, reason: escalation?.summary ?? summary };
2039
2812
  }
2040
- else if (state === "failed")
2041
- run.error = { code: "run_failed", message: `The workflow failed: ${summary}.`, retryable: false };
2813
+ else if (state === "failed") {
2814
+ // Stopped by its cap for good (budget.ts CapStop: a step with no price, a spend no one knows): in the cap's words.
2815
+ const capped = capStoppedIn(run.dir);
2816
+ run.error = capped ? { code: SPEND_CAP_REACHED, message: capped.node ? `${capped.node}: ${capped.words}` : capped.words, retryable: false } : { code: "run_failed", message: `The workflow failed: ${summary}.`, retryable: false };
2817
+ }
2042
2818
  await this.readDecisionCost(run);
2043
2819
  return { outcome: STATUS_OF[state], state, summary };
2044
2820
  }
@@ -2048,7 +2824,7 @@ export class Runs {
2048
2824
  const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
2049
2825
  // Not its `llm` calls: each completes on the run's marked models, so its cost is a REQUEST_COST entry its usage row
2050
2826
  // already sums (request-start.ts).
2051
- const paid = durableDecisions(this.storeFile(run)).map((row) => row.cost_usd);
2827
+ const paid = durableDecisions(this.storeFile(run), { unlocked: true }).map((row) => row.cost_usd);
2052
2828
  if (paid.length)
2053
2829
  run.decisionCost = paid.every((cost) => typeof cost === "number") ? paid.reduce((a, b) => a + b, 0) : null;
2054
2830
  if (paid.length)
@@ -2057,6 +2833,11 @@ export class Runs {
2057
2833
  /** Ends the run in the agent store, once: how it ended, its cost, a line for the list and its metrics. A store held by
2058
2834
  * another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
2059
2835
  async carryBack(run, outcome, state, summary) {
2836
+ // Its agent's asks for the person in its browser end with it: nobody is left to take them up.
2837
+ if (run.dir)
2838
+ dropAsks(run.dir);
2839
+ // Its reads ended with its end's read (settleOnce): their guard goes. A follow-up's process starts it again from none.
2840
+ this.reads.forget(run.id);
2060
2841
  // Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
2061
2842
  // left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
2062
2843
  await this.releaseSignIn(run, run.letGo !== false);
@@ -2065,16 +2846,21 @@ export class Runs {
2065
2846
  await this.dropBox(run, true);
2066
2847
  // Its end-of-run turn closed, and what the turn wrote set aside before the run reads ended (learning-run.ts).
2067
2848
  await this.learning.beforeSettle(run, outcome);
2068
- const cost = run.decisionCost === undefined ? costOf(run.rows) : costView(run.rows, undefined, run.decisionCost);
2849
+ // A run whose rows are not read (meta.unshown) has an unknown cost, never $0.
2850
+ const cost = run.meta.unshown ? null : run.decisionCost === undefined ? costOf(run.rows) : costView(run.rows, undefined, run.decisionCost);
2069
2851
  // An unknown cost keeps what it cost so far beside it, for the list row read from the store.
2070
2852
  const soFar = cost === null && !run.imported ? soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) : undefined;
2071
2853
  if (soFar)
2072
2854
  run.meta.cost_so_far = soFar;
2073
2855
  else
2074
2856
  delete run.meta.cost_so_far;
2075
- const line = summary ?? (outcome === "completed" ? answerOfRun(run) : outcome === "cancelled" ? "cancelled" : run.error?.message);
2857
+ // Cut of every value the run's answers and errors never show, as its served answer is (whole, never clipped): the
2858
+ // store keeps it for good, and a view of the run reads it back as its answer.
2859
+ const said = summary ?? (outcome === "completed" ? answerOfRun(run) : outcome === "cancelled" ? "cancelled" : run.error?.message);
2860
+ const line = said ? redactedAnswer(said, this.refusedValues(run)) : said;
2861
+ // Kept cut too, as its line is: a later server that can no longer read the pointer back serves it as kept.
2076
2862
  if (run.error)
2077
- run.meta.error = { code: run.error.code, message: run.error.message, ...(run.error.details ? { details: run.error.details } : {}) };
2863
+ run.meta.error = { code: run.error.code, message: redacted(run.error.message, this.refusedValues(run)), ...(run.error.details ? { details: cutStrings(run.error.details, (text) => redacted(text, this.refusedValues(run))) } : {}) };
2078
2864
  // Its end's time, chosen once and given to the store: the row, a retry of the write and its run.ended all name this one
2079
2865
  // time. A server that settles the run after a kill chooses its own: nothing was sent before the store had an end.
2080
2866
  const endedAt = (run.endedAt ??= new Date().toISOString());
@@ -2121,6 +2907,8 @@ export class Runs {
2121
2907
  run.finishing = undefined;
2122
2908
  run.settled = true;
2123
2909
  run.updatedAt = new Date().toISOString();
2910
+ // Its rows as an ended run's (its usage row says its cost) before its status wakes a reader: see below.
2911
+ this.show(run);
2124
2912
  this.refresh(run);
2125
2913
  this.persistLater(run, persist);
2126
2914
  return;
@@ -2137,6 +2925,10 @@ export class Runs {
2137
2925
  run.finishing = undefined;
2138
2926
  run.settled = true;
2139
2927
  run.updatedAt = new Date().toISOString();
2928
+ // Its rows were last shown while it ran (its end's read), so its usage row said "so far". Shown again as an ended run's
2929
+ // before refresh() marks its status: a reader following with a cursor gets the row's change with the final page,
2930
+ // never a final page over the running wording.
2931
+ this.show(run);
2140
2932
  this.refresh(run);
2141
2933
  this.notice(run, "run.ended", run.endedAt);
2142
2934
  // Only once the run has ended as it would without learning: a slow or failing check never holds the job.
@@ -2156,11 +2948,14 @@ export class Runs {
2156
2948
  return counted;
2157
2949
  }
2158
2950
  const body = revision.kind === "agentic" ? revision.body : undefined;
2159
- const harness = body?.harness ?? DEFAULT_HARNESS;
2160
- // As its process chose it (app.ts): the run's effort, else its revision's thinking, else the host's, else medium.
2951
+ // The run's harness, as it was resolved when the run was made (blank).
2952
+ const facts = builtinHarness(run.harness)?.facts;
2953
+ // As its process chose it (app.ts): the run's effort, else its revision's thinking, else the host's, else medium; on
2954
+ // an adapter, at the level its harness takes.
2161
2955
  const launched = run.meta.launch_thinking;
2162
- const level = launched && thinkingFor(harness, thinkingOf({ [EFFORT_ENV]: launched.effort, AGENT_THINKING: launched.host }, body?.thinking));
2163
- return { ...counted, ...(level ? { effort: level } : {}), ...(harness !== DEFAULT_HARNESS && body?.model ? { model: body.model } : {}) };
2956
+ const thinking = launched && thinkingOf({ [EFFORT_ENV]: launched.effort, AGENT_THINKING: launched.host }, body?.thinking);
2957
+ const level = thinking && (facts ? thinkingFor(facts, thinking) : thinking);
2958
+ return { ...counted, ...(level ? { effort: level } : {}), ...(facts && body?.model ? { model: body.model } : {}) };
2164
2959
  }
2165
2960
  /** Tries `persist` again every settleRetryMs while the server lives, until it lands. */
2166
2961
  persistLater(run, persist) {
@@ -2214,7 +3009,10 @@ export class Runs {
2214
3009
  if (never)
2215
3010
  throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness } });
2216
3011
  for (const deadline = Date.now() + this.killAfterMs() + 1_000;; await sleep(50)) {
2217
- const holding = [...this.runs.values()].filter((run) => this.live(run));
3012
+ // A run whose launch waits on its claim (launch) keeps the place it had, nothing else taking it meanwhile, until it is
3013
+ // cancelled or ends.
3014
+ // So does one that waits for its harness's install (waitsInstall), until that launch, a cancel or its end.
3015
+ const holding = [...this.runs.values()].filter((run) => this.live(run) || ((run.claimWait === true || run.waitsInstall === true) && !run.cancel && !run.outcome && !run.finishing));
2218
3016
  const counted = max === undefined || holding.length + this.starting < max;
2219
3017
  const held = holding.reduce((sum, run) => sum + runMibOf(run.harness), this.startingMib);
2220
3018
  // With nothing held, a run that fits at all starts: pi's one place on a host smaller than a pi run (host.ts).
@@ -2244,6 +3042,7 @@ export class Runs {
2244
3042
  const now = await this.options.agents.get(entry.agent.id);
2245
3043
  if (now?.agent.archivedAt)
2246
3044
  throw new ApiError("agent_not_runnable", `The agent ${entry.agent.id} is archived: unarchive it to run it.`, { details: { archived_at: now.agent.archivedAt } });
3045
+ // A run that waits for its harness's install from here holds its place itself (waitsInstall).
2247
3046
  return await this.start(entry, revision, version, options);
2248
3047
  }
2249
3048
  finally {
@@ -2273,32 +3072,63 @@ export class Runs {
2273
3072
  // Only another writer of the store gets here first under the same origin: its run is the one asked for, set up by it.
2274
3073
  if (started.existing)
2275
3074
  return (await this.get(started.runId));
2276
- const at = new Date().toISOString();
2277
- const meta = {
2278
- // Shown on the run list and its view: no held secret a person pasted into the message it is taken from.
2279
- title: clip(redacted(options.title.trim().replace(/\s+/g, " "), [...hostSecrets(process.env, this.options.storedKeys), this.options.token, this.options.doorToken]), 80),
2280
- created_at: at,
2281
- input: options.input,
2282
- place: options.place,
2283
- ...(options.effort ? { effort: options.effort } : {}),
2284
- ...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
2285
- ...(options.trigger ? { trigger: options.trigger } : {}),
2286
- ...(Object.keys(plane).length ? { tool_plane: plane } : {}),
2287
- };
2288
- // The run's input is saved first, as the store has it running: a server that goes down from here on leaves a run the
2289
- // next one relaunches with its first message.
2290
- await this.setUp(started.runId, started.dir, meta);
2291
- if (pin) {
2292
- // Then its seed copied and pinned, and its learning saved once the copy is whole or gone. A server that goes down
2293
- // during the copy leaves none saved, and the next one takes the copy back (learning-run.ts onLoad).
2294
- meta.learning = await pin(started, at);
3075
+ // Held as starting until the run is: a read in between waits for it (get, adopt) and never loads it from disk.
3076
+ let started_;
3077
+ this.startingRuns.set(started.runId, new Promise((resolve) => (started_ = resolve)));
3078
+ let held = null;
3079
+ try {
3080
+ const at = new Date().toISOString();
3081
+ const meta = {
3082
+ // Shown on the run list and its view: no held secret a person pasted into the message it is taken from.
3083
+ title: clip(redacted(options.title.trim().replace(/\s+/g, " "), this.options.serverSecrets()), 80),
3084
+ created_at: at,
3085
+ input: options.input,
3086
+ place: options.place,
3087
+ ...(options.effort ? { effort: options.effort } : {}),
3088
+ ...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
3089
+ ...(options.capMode !== undefined ? { cap_mode: options.capMode } : {}),
3090
+ ...(options.trigger ? { trigger: options.trigger } : {}),
3091
+ ...(options.from ? { input_origin: options.from } : {}),
3092
+ ...(Object.keys(plane).length ? { tool_plane: plane } : {}),
3093
+ };
3094
+ // The run's input is saved first, as the store has it running: a server that goes down from here on leaves a run the
3095
+ // next one relaunches with its first message.
2295
3096
  await this.setUp(started.runId, started.dir, meta);
3097
+ // The trigger's name as it fired (origin.name): its served rows name it with no store read, until a rename pushes
3098
+ // the new one (triggerChanged).
3099
+ if (options.trigger)
3100
+ this.triggerNames.set(options.trigger.id, options.trigger.name);
3101
+ if (pin) {
3102
+ // Then its seed copied and pinned, and its learning saved once the copy is whole or gone. A server that goes down
3103
+ // during the copy leaves none saved, and the next one takes the copy back (learning-run.ts onLoad). A copy that
3104
+ // throws is saved as failed in its own words, the copy taken back, before the start fails: every start that
3105
+ // ends leaves its learning said, so only a stopped server's leaves a copy with none.
3106
+ try {
3107
+ meta.learning = await pin(started, at);
3108
+ }
3109
+ catch (error) {
3110
+ meta.learning = await this.learning.copyThrew(started, at, error);
3111
+ await this.setUp(started.runId, started.dir, meta).catch(() => undefined);
3112
+ throw error;
3113
+ }
3114
+ await this.setUp(started.runId, started.dir, meta);
3115
+ }
3116
+ const run = this.blank({ id: started.runId, agent: entry.agent.id, revision: revision.id, kind: revision.kind }, started.dir, meta, version, harnessOfBody(revision.body), tooling, revision);
3117
+ // Before the run is known here, so nothing launches it first.
3118
+ await this.pinNeeds(run, revision);
3119
+ const refreshing = this.mcpFresh(run);
3120
+ if (refreshing)
3121
+ await refreshing;
3122
+ await this.pinSignIn(run);
3123
+ this.runs.set(run.id, run);
3124
+ held = run;
3125
+ }
3126
+ finally {
3127
+ this.startingRuns.delete(started.runId);
3128
+ started_(held);
2296
3129
  }
2297
- const run = this.blank({ id: started.runId, agent: entry.agent.id, revision: revision.id, kind: revision.kind }, started.dir, meta, version, harnessOfBody(revision.body), tooling, revision);
2298
- // Before the run is known here, so nothing launches it first.
2299
- await this.pinNeeds(run, revision);
2300
- await this.pinSignIn(run);
2301
- this.runs.set(run.id, run);
3130
+ const run = held;
3131
+ const meta = run.meta;
2302
3132
  // A seed that failed is a learning row from the start, and its learning's end is in the ledger.
2303
3133
  this.show(run);
2304
3134
  void this.learning.onSaved(run, meta.learning);
@@ -2315,11 +3145,13 @@ export class Runs {
2315
3145
  return run;
2316
3146
  }
2317
3147
  run.firstLaunch = true;
3148
+ // A harness installed on first use (claude-agent's Claude Code) is installed first, in the background (launch): the
3149
+ // start answers now, and the run shows the install while it waits.
2318
3150
  this.launch(run);
2319
3151
  if (revision.kind === "workflow")
2320
3152
  return run;
2321
3153
  // The first message names the files given to the run (run-manifest.ts), on every harness.
2322
- void firstMessage(options.input.content, started.workspace).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => {
3154
+ void firstMessage(options.input.content, started.workspace).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS, options.from)).catch((error) => {
2323
3155
  run.submitted = 0;
2324
3156
  // The run ended before its first message reached it (a process that crashed at its start): how it ended stands.
2325
3157
  if (run.outcome || run.finishing || run.cancel)
@@ -2366,7 +3198,7 @@ export class Runs {
2366
3198
  * turn that may end so; decided at the door's admission, past every wait here. */
2367
3199
  async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
2368
3200
  await this.beforeSubmit?.(run.id, content);
2369
- const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL], parks: [APPROVAL_ENTRY] }) }, readyMs);
3201
+ const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL], parks: [APPROVAL_ENTRY] }) }, readyMs, true);
2370
3202
  if (answer.status === 409 && answer.body?.error === "WAITING")
2371
3203
  throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
2372
3204
  if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
@@ -2376,7 +3208,7 @@ export class Runs {
2376
3208
  }
2377
3209
  /** Whether the run's harness takes a message mid-turn. */
2378
3210
  steers(run) {
2379
- return run.kind !== "agentic" || steersMidTurn(run.harness);
3211
+ return run.kind !== "agentic" || (builtinHarness(run.harness)?.steer ?? false);
2380
3212
  }
2381
3213
  /** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
2382
3214
  * down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
@@ -2390,14 +3222,25 @@ export class Runs {
2390
3222
  const file = this.storeFile(run);
2391
3223
  if (!(await stat(file).catch(() => null)))
2392
3224
  return false;
2393
- const { DatabaseSync } = await import("node:sqlite");
2394
- return whenFree(async () => {
2395
- const db = new DatabaseSync(file, { readOnly: true });
3225
+ // A fresh read-only, lock-free read (run-db.ts), after any take-back's checkpoint of this run.
3226
+ return this.runDb(run, async () => {
2396
3227
  try {
2397
- if (db.prepare("SELECT 1 FROM submissions WHERE request_id = ? LIMIT 1").get(JSON.stringify(requestId)) !== undefined)
2398
- return true;
2399
- const status = db.prepare("SELECT json_extract(e.record, '$.data.status') AS status FROM submissions s JOIN entries e ON e.id = json_extract(s.record, '$.entry') WHERE s.request_id = ? LIMIT 1");
2400
- return await doorTook(requestId, (key) => status.get(JSON.stringify(key))?.status ?? undefined);
3228
+ const statusOf = await readRunDb(file, this.live(run), (db) => {
3229
+ if (db.prepare("SELECT 1 FROM submissions WHERE request_id = ? LIMIT 1").get(JSON.stringify(requestId)) !== undefined)
3230
+ return true;
3231
+ const status = db.prepare("SELECT json_extract(e.record, '$.data.status') AS status FROM submissions s JOIN entries e ON e.id = json_extract(s.record, '$.entry') WHERE s.request_id = ? LIMIT 1");
3232
+ // The door's journal for it, key by key until the first it does not hold (pi-durable-disk doorKey).
3233
+ const journal = new Map();
3234
+ for (let n = 0;; n++) {
3235
+ const key = doorKey(requestId, n);
3236
+ const at = status.get(JSON.stringify(key))?.status ?? undefined;
3237
+ if (at === undefined)
3238
+ break;
3239
+ journal.set(key, at);
3240
+ }
3241
+ return journal;
3242
+ });
3243
+ return statusOf === true ? true : await doorTook(requestId, (key) => statusOf.get(key));
2401
3244
  }
2402
3245
  catch (error) {
2403
3246
  // A store that keeps no submissions has taken none.
@@ -2405,10 +3248,7 @@ export class Runs {
2405
3248
  return false;
2406
3249
  throw error;
2407
3250
  }
2408
- finally {
2409
- db.close();
2410
- }
2411
- }, this.busyDelays(), this.onBusy(run.id, "its store"));
3251
+ });
2412
3252
  }
2413
3253
  /** Raises the cap of an agentic run that names one, to `cap`: above its own (by more than CAP_TOLERANCE), or the same as
2414
3254
  * its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
@@ -2431,6 +3271,8 @@ export class Runs {
2431
3271
  const from = run.meta.max_cost_usd;
2432
3272
  if (from === undefined)
2433
3273
  throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
3274
+ if (run.kind === "workflow")
3275
+ return this.raiseWorkflow(run, from, cap);
2434
3276
  const last = run.meta.cap_raised?.at(-1);
2435
3277
  const pause = pauseOf(run);
2436
3278
  const next = continuationOf(run);
@@ -2469,12 +3311,177 @@ export class Runs {
2469
3311
  run.meta.cap_continue = follow;
2470
3312
  if (next && typeof run.resuming === "number")
2471
3313
  run.resuming = undefined;
3314
+ // The served view as the raise leaves it, now: the pause's waiting row goes at the raise, not at the next row a
3315
+ // process sends (a paused process being let go sends none).
3316
+ this.show(run);
2472
3317
  this.refresh(run);
2473
3318
  const answered = pause !== undefined ? run.meta.cap_continue : undefined;
2474
3319
  if (!answered)
2475
3320
  return { resumed: false, ...(this.live(run) ? { note: `The run's process keeps the ${money(from)} cap it was opened with; the ${money(cap)} cap holds from its next process.` } : {}) };
2476
3321
  return { resumed: true, messageId: answered.message_id };
2477
3322
  }
3323
+ /** A workflow run's raise (budget.ts): serve.json keeps it first, as an agentic run's does, then `cap.json` tells the
3324
+ * run's process, whose step waiting at its cap is judged again under it, and a run whose process the pause let go is
3325
+ * opened again (its pause's mark taken away first, so its settle does not hold it) under the raised cap (CAP_ENV),
3326
+ * resuming from its journal. A raise while it works holds from its next check. The same raise again changes nothing. */
3327
+ async raiseWorkflow(run, from, cap) {
3328
+ const last = run.meta.cap_raised?.at(-1);
3329
+ // The same raise again (a retry): what the first saved is finished, whatever a crash cut it at (finishRaise).
3330
+ if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
3331
+ await this.finishRaise(run);
3332
+ this.refresh(run);
3333
+ return { resumed: last.pause === "budget" };
3334
+ }
3335
+ if (!(cap > from + CAP_TOLERANCE))
3336
+ throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
3337
+ const paused = budgetWaiting(run);
3338
+ const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(paused ? { pause: "budget" } : {}) }];
3339
+ await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised }));
3340
+ run.meta.max_cost_usd = cap;
3341
+ run.meta.cap_raised = raised;
3342
+ await this.finishRaise(run);
3343
+ this.refresh(run);
3344
+ return { resumed: paused };
3345
+ }
3346
+ /** Finishes the raise serve.json keeps (`max_cost_usd`), in its steps' order, each one done again harmlessly: `cap.json`
3347
+ * takes it (a waiting process wakes on it), then a pause it answers (budget.json under a lower cap) is taken away and
3348
+ * its run, with no process, opened again under it. A raise, its retry and a restart's settle all finish it here, so a
3349
+ * crash between serve.json and the rest never leaves a raised run waiting for a raise. True when it took a pause away. */
3350
+ async finishRaise(run, { settling = false } = {}) {
3351
+ const cap = run.meta.max_cost_usd;
3352
+ const mark = run.kind === "workflow" && run.dir ? budgetPausedIn(run.dir) : undefined;
3353
+ if (cap === undefined || run.outcome || run.cancel)
3354
+ return false;
3355
+ if (run.meta.cap_raised?.length)
3356
+ writeRaisedCap(run.dir, cap);
3357
+ if (!raiseFinishes(cap, mark))
3358
+ return false;
3359
+ if (this.live(run))
3360
+ return false;
3361
+ // One finish at a time per run: a settle under way decides the run's next process (it may be reading the run as gone
3362
+ // and launching), so a raise meanwhile leaves the launch to it and finishes again once it is through. Never two.
3363
+ if (!settling && run.settles > 0) {
3364
+ void run.settling?.then(() => this.finishRaise(run)).catch(() => undefined);
3365
+ return true;
3366
+ }
3367
+ // A place under the server's limits first (max_concurrent_runs, the memory its harness takes), as every start takes
3368
+ // one (takePlace): the pause let its place go. With none free the run waits for one, queued, its pause's mark kept,
3369
+ // and opens once one frees (waitForPlace): never a process past the limits, never the raise refused or lost.
3370
+ let release;
3371
+ try {
3372
+ release = await this.takePlace(run.harness);
3373
+ }
3374
+ catch (error) {
3375
+ if (error instanceof ApiError && error.code === "rate_limited") {
3376
+ this.waitForPlace(run, cap);
3377
+ return true;
3378
+ }
3379
+ // A run this host never holds (agent_not_runnable) waits for nothing: off the queue, still paused, saying why.
3380
+ this.leavePlaceQueue(run);
3381
+ throw error;
3382
+ }
3383
+ try {
3384
+ // Read again: the place may have been waited for, and the run ended, cancelled, opened or finished meanwhile, or the
3385
+ // server begun to close (its mark stays, for the next server's settle to finish the raise).
3386
+ if (this.raiseMoot(run))
3387
+ return true;
3388
+ // What its launch needs, pinned while its pause's mark still stands: a pin that fails leaves the run waiting, its
3389
+ // mark kept, at the back of the queue (or off it after RAISE_TRIES), never queued for good with neither.
3390
+ try {
3391
+ await this.beforeRaiseLaunch?.(run.id);
3392
+ await this.pinNeeds(run);
3393
+ await this.pinSignIn(run);
3394
+ }
3395
+ catch (error) {
3396
+ this.raiseFailed(run, cap, error);
3397
+ return true;
3398
+ }
3399
+ // Read again after the pins, then the mark goes and the launch follows with nothing awaited between them.
3400
+ if (this.raiseMoot(run))
3401
+ return true;
3402
+ this.leavePlaceQueue(run);
3403
+ run.raiseFailedRow = undefined;
3404
+ clearBudgetPause(run.dir);
3405
+ this.launch(run);
3406
+ this.show(run);
3407
+ this.refresh(run);
3408
+ }
3409
+ finally {
3410
+ // Launched, it holds its place as a live run.
3411
+ release();
3412
+ }
3413
+ return true;
3414
+ }
3415
+ /** A raised run that found no place: queued, saying it waits for one, and tried again every PLACE_RETRY_MS until it
3416
+ * opens (finishRaise), ends or is cancelled. */
3417
+ waitForPlace(run, cap) {
3418
+ // A run another path has opened, ended or let go of its pause meanwhile (a retry that won the place while this raise
3419
+ // was refused one), or a server that is closing, waits for nothing.
3420
+ if (this.closing || run.outcome || run.cancel || run.finishing || this.live(run) || !budgetPausedIn(run.dir))
3421
+ return;
3422
+ run.placeWait ??= { at: new Date().toISOString(), words: `The cap was raised to ${money(cap)}. The run opens again once this server has a free place for it: it is at its limit of runs at once, or of memory for them.` };
3423
+ this.placeWaiters.add(run);
3424
+ this.show(run);
3425
+ this.refresh(run);
3426
+ this.placeRetry ??= setInterval(() => void this.retryPlaces(), PLACE_RETRY_MS).unref();
3427
+ }
3428
+ /** Whether a raise that took a place has nothing to open now: the server is closing (the mark stays, for the next
3429
+ * server), or the run ended, was cancelled, opened, or has no pause left. Off the queue then, unless closing. */
3430
+ raiseMoot(run) {
3431
+ if (this.closing)
3432
+ return true;
3433
+ if (!(run.outcome || run.cancel || run.finishing || this.live(run) || !budgetPausedIn(run.dir)))
3434
+ return false;
3435
+ this.leavePlaceQueue(run);
3436
+ return true;
3437
+ }
3438
+ /** `run` off the queue for a place: what it reserved is free, and it shows no wait for one. */
3439
+ leavePlaceQueue(run) {
3440
+ const queued = this.placeWaiters.delete(run) || run.placeWait !== undefined;
3441
+ run.placeWait = undefined;
3442
+ run.raiseTries = undefined;
3443
+ if (queued) {
3444
+ this.show(run);
3445
+ this.refresh(run);
3446
+ }
3447
+ }
3448
+ /** A raised run whose launch failed after its place was taken: to the back of the queue, its mark kept, and off it
3449
+ * after RAISE_TRIES failures in a row (still paused at its cap; a raise retried, or the server's next start, finishes it
3450
+ * then), so it never holds a place reserved for good. */
3451
+ raiseFailed(run, cap, error) {
3452
+ const tries = (run.raiseTries ?? 0) + 1;
3453
+ warn(run.id, `its raise did not open it (${tries} of ${RAISE_TRIES}): ${error.message}`);
3454
+ this.placeWaiters.delete(run);
3455
+ if (tries >= RAISE_TRIES) {
3456
+ run.raiseFailedRow = { at: new Date().toISOString(), words: `The cap was raised to ${money(cap)}, but the run could not be started: ${error.message.slice(0, 300)}. It stays paused; the same raise again, or the server's next start, tries once more.` };
3457
+ return this.leavePlaceQueue(run);
3458
+ }
3459
+ run.raiseTries = tries;
3460
+ this.waitForPlace(run, cap);
3461
+ }
3462
+ async retryPlaces() {
3463
+ if (this.placeRetrying)
3464
+ return;
3465
+ this.placeRetrying = true;
3466
+ try {
3467
+ for (const run of [...this.placeWaiters]) {
3468
+ if (this.closing)
3469
+ break;
3470
+ if (run.outcome || run.cancel || run.finishing) {
3471
+ this.leavePlaceQueue(run);
3472
+ continue;
3473
+ }
3474
+ await this.finishRaise(run).catch((error) => warn(run.id, `its raise is not finished yet: ${error.message}`));
3475
+ }
3476
+ }
3477
+ finally {
3478
+ this.placeRetrying = false;
3479
+ if (!this.placeWaiters.size || this.closing) {
3480
+ clearInterval(this.placeRetry);
3481
+ this.placeRetry = undefined;
3482
+ }
3483
+ }
3484
+ }
2478
3485
  /** Sends a raised run its pause's follow-up, under its id (the door takes one id once), at the run's cap now: as a
2479
3486
  * follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
2480
3487
  * new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
@@ -2536,16 +3543,21 @@ export class Runs {
2536
3543
  }
2537
3544
  /** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
2538
3545
  * id in the run's store, which takes one message per id (a trigger's firing key); default a new one. */
2539
- async message(run, content, requestId, { answers = true } = {}) {
3546
+ /** `origin`: who the message is from when its person did not write it (a trigger's firing). */
3547
+ async message(run, content, requestId, { answers = true, origin } = {}) {
2540
3548
  if (run.imported)
2541
3549
  throw this.importedRefusal(run);
2542
3550
  // A cancelled run takes no message, whether or not its end is written yet.
2543
3551
  if (run.cancel)
2544
3552
  throw this.finished(run);
2545
- // A message while a tool call waits for approval declines it, with the message as the reason (as Claude Code takes
2546
- // what is typed at its permission prompt): the gate's resume carries the refusal and their words in one turn, and
2547
- // nothing else is sent, so no second turn races the parked call.
2548
- const read = run.kind === "agentic" ? waitingApproval(run) : undefined;
3553
+ // A message that may not answer a person (a trigger's) is refused while the run waits on one, before anything else,
3554
+ // as the door refuses it (WAITING): it never declines a parked approval, nor answers a question or a cap's pause.
3555
+ if (!answers && waitsOnPerson(run))
3556
+ throw waitingRefusal();
3557
+ // A person's message while a tool call waits for approval declines it, with the message as the reason (as Claude Code
3558
+ // takes what is typed at its permission prompt): the gate's resume carries the refusal and their words in one turn,
3559
+ // and nothing else is sent, so no second turn races the parked call.
3560
+ const read = run.kind === "agentic" && answers ? waitingApproval(run) : undefined;
2549
3561
  if (read) {
2550
3562
  await this.personsTurn(run);
2551
3563
  // Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
@@ -2596,11 +3608,13 @@ export class Runs {
2596
3608
  throw new ApiError("budget_reached", `The run is paused at its ${money(run.meta.max_cost_usd ?? 0)} cap: raise the cap first. ${paused}`, { details: { cap_usd: run.meta.max_cost_usd ?? null } });
2597
3609
  // A harness that cannot take a message mid-turn (any but pi, harness.ts) queues it for the turn's end: a new turn of
2598
3610
  // the same run, which the contract calls follow_up, never a steer it does not do.
2599
- const working = status === "queued" || (status === "working" && state === "working");
3611
+ // A run whose agent waits on the person in its browser (browser-person.ts) is mid-turn: a message is no answer to it
3612
+ // (the hand-back is), and goes to that turn as one to a working run does.
3613
+ const working = status === "queued" || (status === "working" && state === "working") || browserAsk(run) !== undefined;
2600
3614
  const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
2601
3615
  // A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
2602
3616
  if (mode === "answer" && !answers)
2603
- throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
3617
+ throw waitingRefusal();
2604
3618
  const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
2605
3619
  // A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
2606
3620
  // starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
@@ -2613,7 +3627,11 @@ export class Runs {
2613
3627
  // After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
2614
3628
  // one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
2615
3629
  await this.personsTurn(run);
2616
- await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, answers ? this.messageOrigin?.(run.id, content) : undefined, answers);
3630
+ // Read again after the last wait, with nothing awaited from here to the door: a call parked or a cap paused
3631
+ // meanwhile is still never answered by it (the door's own check also refuses a parked call or a question).
3632
+ if (!answers && (waitingApproval(run) !== undefined || pausedAt(run, { inFlight: false }) !== undefined))
3633
+ throw waitingRefusal();
3634
+ await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, origin ?? (answers ? this.messageOrigin?.(run.id, content) : undefined), answers);
2617
3635
  }
2618
3636
  catch (error) {
2619
3637
  run.submitted = Math.max(0, run.submitted - 1);
@@ -2646,9 +3664,16 @@ export class Runs {
2646
3664
  async reopen(run) {
2647
3665
  await this.sweepOnce();
2648
3666
  await this.pinNeeds(run);
3667
+ // Before its place is taken: the launch below follows the place with no wait.
3668
+ const refreshing = this.mcpFresh(run);
3669
+ if (refreshing)
3670
+ await refreshing;
2649
3671
  const row = this.store.readRun(run.id);
2650
3672
  if (row?.archivedAt)
2651
3673
  throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
3674
+ // Nothing it said can be cut here, so nothing it goes on to say could be shown: it is not opened again.
3675
+ if (run.meta.unshown)
3676
+ throw new ApiError("not_continuable", WITHHELD_SIGN_IN);
2652
3677
  // Its end could not be written yet (persistLater tries again): it opens once the store has it.
2653
3678
  if (row?.state === "running")
2654
3679
  throw new ApiError("unavailable", "The run's end is still being written to the agent store; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
@@ -2739,7 +3764,7 @@ export class Runs {
2739
3764
  this.restate(run);
2740
3765
  this.refresh(run);
2741
3766
  if (!run.outcome && !run.finishing && !run.cancel)
2742
- void this.ensureLive(run).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
3767
+ void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
2743
3768
  return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
2744
3769
  }
2745
3770
  /** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
@@ -2803,6 +3828,13 @@ export class Runs {
2803
3828
  this.refresh(run);
2804
3829
  return false;
2805
3830
  }
3831
+ // The stopped turn is over from here, and the run reads stopped: a request it cut is a charge with no price
3832
+ // (costsofar/1), never one in flight, before the turn's end reaches this server through the door's events.
3833
+ if (run.timeline && run.submitted === 0 && stopped(run)) {
3834
+ run.timeline.idle();
3835
+ const rows = run.timeline.rows();
3836
+ this.take(run, rows, keepCommitted(run.live, rows, run.timeline.isLive));
3837
+ }
2806
3838
  this.refresh(run);
2807
3839
  return true;
2808
3840
  }
@@ -2823,7 +3855,7 @@ export class Runs {
2823
3855
  this.restate(run);
2824
3856
  this.refresh(run);
2825
3857
  if (!run.outcome && !run.finishing && !run.cancel)
2826
- void this.ensureLive(run).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
3858
+ void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
2827
3859
  }
2828
3860
  /** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
2829
3861
  * its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
@@ -2883,40 +3915,6 @@ export class Runs {
2883
3915
  this.mark(run);
2884
3916
  return { run_id: run.id, paused, status: statusOf(run).status };
2885
3917
  }
2886
- /** A workflow run's graph as it stands (graph-view.ts), live while it runs. */
2887
- async graph(run) {
2888
- if (run.kind !== "workflow")
2889
- throw new ApiError("not_found", `the run ${run.id} is an agentic run; only a workflow run has a graph`);
2890
- // A revision never changes: read once, waiting out a busy store as a run's end does, never failing a poll on it.
2891
- let workflow = this.workflows.get(run.revision);
2892
- if (workflow === undefined) {
2893
- const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
2894
- this.workflows.set(run.revision, (workflow = revision.body.workflow));
2895
- }
2896
- // The run's status as this server holds it, with no read of the agent store, which the run's process may be writing.
2897
- const { status } = statusOf(run);
2898
- const ended = TERMINAL.has(status);
2899
- const { runGraph } = await import("./graph-view.js");
2900
- const given = {
2901
- run: { id: run.id, agent: run.agentId, revision: run.revision, status, paused: status === "paused", startedAt: run.meta.created_at, endedAt: ended ? (run.endedAt ?? run.updatedAt) : null },
2902
- ended, workflow, storeFile: this.storeFile(run), root: run.dir, input: run.meta.input ?? {}, modelCost: costOf(run.rows), llmRead: run.llmRead ?? 0,
2903
- };
2904
- // A poll never answers home_busy: a store still held answers the live view, or the last whole one, marked stale.
2905
- try {
2906
- const view = await runGraph(given);
2907
- this.graphCache.set(`view:${run.id}`, view, Buffer.byteLength(JSON.stringify(view)));
2908
- return this.servedGraph(run, { ...view, stale: false });
2909
- }
2910
- catch (error) {
2911
- if (!storeBusy(error))
2912
- throw error;
2913
- warn(run.id, "its store is busy; the graph answers its live view, stale");
2914
- const held = this.graphCache.get(`view:${run.id}`);
2915
- if (held)
2916
- return this.servedGraph(run, { ...held, run: given.run, stale: true });
2917
- return this.servedGraph(run, { ...(await runGraph({ ...given, liveOnly: true })), stale: true });
2918
- }
2919
- }
2920
3918
  /** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
2921
3919
  killAfterMs() {
2922
3920
  return (durationMs(this.options.drainTimeout ?? DRAIN) ?? 30_000) + 1_000;
@@ -2927,11 +3925,14 @@ export class Runs {
2927
3925
  stopping() {
2928
3926
  const all = [...this.runs.values()];
2929
3927
  const started = all.filter((run) => run.child).length;
2930
- const adopted = all.filter((run) => !run.child && run.orphan && alive(run.orphan)).length;
3928
+ const adopted = all.filter((run) => !run.child && run.orphanHolder && holderLives(run.orphanHolder)).length;
2931
3929
  return { runs: started + adopted, boundMs: (started ? this.killAfterMs() : 0) + (adopted ? this.killAfterMs() : 0) };
2932
3930
  }
2933
3931
  async close() {
2934
3932
  this.closing = true;
3933
+ // The retry for raised runs waiting for a place stops now: nothing is launched past the close.
3934
+ clearInterval(this.placeRetry);
3935
+ this.placeRetry = undefined;
2935
3936
  this.learning.close();
2936
3937
  const live = [...this.runs.values()].filter((run) => run.child);
2937
3938
  for (const run of live) {
@@ -2940,16 +3941,19 @@ export class Runs {
2940
3941
  }
2941
3942
  await Promise.all(live.map((run) => new Promise((resolve) => (run.child ? run.child.once("exit", resolve) : resolve(undefined)))));
2942
3943
  // An adopted process is stopped the same way, and watched by its pid.
2943
- const adopted = [...this.runs.values()].filter((run) => run.orphan && alive(run.orphan));
3944
+ const adopted = [...this.runs.values()].filter((run) => run.orphanHolder && holderLives(run.orphanHolder));
2944
3945
  for (const run of adopted)
2945
3946
  this.terminate(run);
2946
- for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphan && alive(run.orphan)) && Date.now() < deadline;)
3947
+ for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphanHolder && holderLives(run.orphanHolder)) && Date.now() < deadline;)
2947
3948
  await sleep(100);
2948
3949
  await sleep(0);
2949
3950
  await Promise.all([...this.runs.values()].map((run) => run.settling));
2950
3951
  await this.learning.idle();
2951
- for (const run of this.runs.values())
3952
+ for (const run of this.runs.values()) {
2952
3953
  run.feed?.abort();
3954
+ clearTimeout(run.stopPending);
3955
+ run.stopPending = undefined;
3956
+ }
2953
3957
  this.closed = true;
2954
3958
  }
2955
3959
  // ---- views ------------------------------------------------------------------------------------------------------------
@@ -2960,19 +3964,26 @@ export class Runs {
2960
3964
  // Unknown: what it cost so far and how many charges have no price (costsofar/1), from its rows, else what it said at
2961
3965
  // its end (a run carried back with no rows read since).
2962
3966
  const soFar = usd === null && !run.imported ? (soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) ?? (run.rows.length ? undefined : soFarOfMeta(run.meta))) : undefined;
2963
- return { usd, basis: "estimate", charge_state: null, cap_usd: run.meta.max_cost_usd ?? null, ...(soFar ?? {}) };
2964
- }
2965
- /** `Run`, as the contract shows it. `known`: its stored row as the caller already has it, so nothing is read; a run
2966
- * just written has none worth reading (`{ stored: null }`: it is neither archived nor ended), and its start's answer
2967
- * must not read the store once the run exists, since a busy store would then refuse a run that runs. */
2968
- async view(run, known) {
3967
+ // Under a cap, the most a cache miss could make its requests in flight cost beyond what they are held at (cap.ts):
3968
+ // none without a live process, which every request in flight needs.
3969
+ const bound = run.meta.max_cost_usd === undefined ? {} : { overshoot_bound_usd: this.live(run) ? microUp(run.bounds?.inFlight() ?? 0) : 0 };
3970
+ return { usd, basis: "estimate", charge_state: null, cap_usd: run.meta.max_cost_usd ?? null, ...bound, ...(soFar ?? {}) };
3971
+ }
3972
+ /** `Run`, as the contract shows it, its console page at `origin` (server.ts linkOrigin). `known`: its stored row as the
3973
+ * caller already has it, so nothing is read; a run just written has none worth reading (`{ stored: null }`: it is
3974
+ * neither archived nor ended), and its start's answer must not read the store once the run exists, since a busy store
3975
+ * would then refuse a run that runs. */
3976
+ async view(run, origin, known) {
2969
3977
  const stored = known ? (known.stored ?? undefined) : await this.options.agents.request(() => this.store.readRun(run.id));
2970
3978
  // After the read: the run may have moved on while it waited, and every field below is of this one moment.
2971
3979
  const { status, state } = statusOf(run);
2972
3980
  const row = TERMINAL.has(status) ? stored : undefined;
3981
+ // What it held for its owner's OK as it reads now: approved or retired since, it waits no more (learning-run.ts current).
3982
+ const learning = await this.learning.current(run.agentId, run.meta.learning);
2973
3983
  // The whole text of the answer the run's turn ended on (answerOfRun), never the line the store keeps, which is cut;
2974
3984
  // the store's line only for a run whose rows are not read (an import's).
2975
- const finalAnswer = run.kind === "workflow" ? null : (answerOfRun(run) ?? row?.summary ?? null);
3985
+ // A run whose words are withheld (meta.unshown) answers nothing: its row's line is its own words too.
3986
+ const finalAnswer = run.kind === "workflow" || run.meta.unshown ? null : (answerOfRun(run) ?? row?.summary ?? null);
2976
3987
  // When the turn of a message still open last wrote: a run working shows it is moving, or not.
2977
3988
  const progress = TERMINAL.has(status) || run.kind === "workflow" ? undefined : run.turns.progressAt();
2978
3989
  // A run its cap stopped keeps the answer it paid for.
@@ -2982,6 +3993,7 @@ export class Runs {
2982
3993
  run_id: run.id,
2983
3994
  agent_id: run.agentId,
2984
3995
  agent_version: run.version,
3996
+ console_url: runLink(origin, run.id),
2985
3997
  revision: run.revision,
2986
3998
  kind: run.kind,
2987
3999
  sha: null,
@@ -2994,23 +4006,29 @@ export class Runs {
2994
4006
  updated_at: run.updatedAt,
2995
4007
  ended_at: endedAt,
2996
4008
  // An answer is served with no held secret in it, whole (key-refusal.ts redactedAnswer); the stored one stays as written.
2997
- result: status === "completed" ? { output: run.kind === "workflow" ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
2998
- error: status === "failed" ? (run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
2999
- review: endedAt === null ? null : reviewAt(run.meta.review ?? (row ? reviewOfRow(row, run.meta) : null), endedAt),
3000
- pending: status === "input_required" && state === "waiting" ? (approvalOf(run, this.redactor(run)) ?? budgetPending(run, this.spentNow(run)) ?? pendingOf(run.rows)) : null,
4009
+ result: status === "completed" ? { output: run.kind === "workflow" && !run.meta.unshown ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
4010
+ // Cut as its rows and answer are (shown): an error can quote what the run said, or a process's last line.
4011
+ error: status === "failed" ? this.servedRunError(run, run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
4012
+ review: endedAt === null ? null : this.servedReview(run, reviewAt(run.meta.review ?? (row ? reviewOfRow(row, run.meta) : null), endedAt)),
4013
+ pending: status === "input_required" && state === "waiting" ? (approvalOf(run, this.redactor(run)) ?? budgetPending(run, this.spentNow(run)) ?? workflowBudgetPending(run) ?? browserPending(browserAsk(run), this.redactor(run)) ?? pendingOf(run.rows)) : null,
3001
4014
  cost: this.cost(run),
4015
+ // How its cap prices a request (cap.ts CapMode): its own, else expected; null with no cap.
4016
+ cap_mode: run.meta.max_cost_usd === undefined ? null : (run.meta.cap_mode ?? "expected"),
4017
+ // Whether it ran unattended (its revision's approvals, as it started: a run keeps the revision it started on): never,
4018
+ // an ask allowed at its gate; ask, the default.
4019
+ approvals: approvalsOf(run.tooling?.approvals),
3002
4020
  archived_at: stored?.archivedAt ?? null,
3003
4021
  imported_from: run.imported ?? null,
3004
4022
  trigger: run.meta.trigger ?? null,
3005
4023
  // The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
3006
- learning: this.learning.view(run.meta.learning, TERMINAL.has(status) && run.settled),
4024
+ learning: this.learning.view(learning, TERMINAL.has(status) && run.settled),
3007
4025
  poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
3008
4026
  last_progress_at: progress === undefined ? null : new Date(progress).toISOString(),
3009
4027
  };
3010
4028
  }
3011
- async summary(run) {
3012
- const { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning } = await this.view(run);
3013
- return { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning: learning && shortOf(learning) };
4029
+ async summary(run, origin) {
4030
+ const { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning } = await this.view(run, origin);
4031
+ return { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning: learning && shortOf(learning) };
3014
4032
  }
3015
4033
  /** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
3016
4034
  async statusOfRow(row) {
@@ -3021,26 +4039,33 @@ export class Runs {
3021
4039
  }
3022
4040
  /** A run's summary for a list. An ended run this server holds no Run for is read from its row and its serve.json alone,
3023
4041
  * not its store; `versions` numbers its agent's revisions. */
3024
- async summaryOfRow(row, versions) {
4042
+ async summaryOfRow(row, versions, origin) {
3025
4043
  const known = this.runs.get(row.id) ?? (row.state === "running" ? await this.get(row.id) : null);
3026
4044
  if (known)
3027
- return this.summary(known);
3028
- const meta = (await readJson(join(this.options.agents.dir, "runs", row.id, RUN_META)));
4045
+ return this.summary(known, origin);
4046
+ const { stored: meta, damaged } = await readMeta(join(runDirIn(this.options.agents.dir, row.agent, row.id), RUN_META));
4047
+ const failed = STATUS_OF[row.state] === "failed" ? errorOfRow(row, meta) : null;
4048
+ const review = reviewOfRow(row, meta);
4049
+ // Its error and review are the run's words (its error can quote what it said; an escalation's reason is its own):
4050
+ // cut as its view's are, or withheld when the pointer they could hold can't be read back here.
4051
+ const shown = failed || review ? await this.rowShown(row.agent, meta, damaged) : undefined;
4052
+ const say = (text) => (shown === "withheld" ? WITHHELD_SIGN_IN : shown(text));
3029
4053
  return {
3030
- run_id: row.id, agent_id: row.agent, agent_version: versions.get(row.revision) ?? 0, revision: row.revision, kind: row.kind, sha: null,
4054
+ run_id: row.id, agent_id: row.agent, agent_version: versions.get(row.revision) ?? 0, console_url: runLink(origin, row.id), revision: row.revision, kind: row.kind, sha: null,
3031
4055
  status: STATUS_OF[row.state], state: "idle", title: typeof meta?.title === "string" ? meta.title : "",
3032
4056
  ...(typeof meta?.effort === "string" ? { effort: meta.effort } : {}),
3033
4057
  created_at: typeof meta?.created_at === "string" ? meta.created_at : row.startedAt, ended_at: row.endedAt ?? null,
3034
- error: STATUS_OF[row.state] === "failed" ? errorOfRow(row, meta) : null,
3035
- review: reviewAt(reviewOfRow(row, meta), row.endedAt ?? new Date(0).toISOString()),
3036
- cost: { usd: row.costUsd ?? null, basis: "estimate", charge_state: null, cap_usd: typeof meta?.max_cost_usd === "number" ? meta.max_cost_usd : null, ...(row.costUsd == null ? (soFarOfMeta(meta) ?? {}) : {}) },
4058
+ // Withheld as load withholds a held run's: its code too, which can be the run's own (errorOfRow).
4059
+ error: failed && (shown === "withheld" ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : { ...failed, message: say(failed.message), ...(failed.details ? { details: cutStrings(failed.details, say) } : {}) }),
4060
+ review: reviewAt(review && { ...review, reason: say(review.reason) }, row.endedAt ?? new Date(0).toISOString()),
4061
+ cost: { usd: row.costUsd ?? null, basis: "estimate", charge_state: null, cap_usd: typeof meta?.max_cost_usd === "number" ? meta.max_cost_usd : null, ...(typeof meta?.max_cost_usd === "number" ? { overshoot_bound_usd: 0 } : {}), ...(row.costUsd == null ? (soFarOfMeta(meta) ?? {}) : {}) },
3037
4062
  archived_at: row.archivedAt ?? null,
3038
4063
  // A run read from its row alone has ended: it waits on nothing.
3039
4064
  pending: null,
3040
4065
  imported_from: row.importedFrom ?? null,
3041
4066
  trigger: triggerOf(meta),
3042
4067
  // Its row says it ended: what serve.json holds of its learning is as it settled.
3043
- learning: this.learning.short(isObject(meta?.learning) ? meta.learning : null, true),
4068
+ learning: this.learning.short(isObject(meta?.learning) ? ((await this.learning.current(row.agent, meta.learning)) ?? null) : null, true),
3044
4069
  };
3045
4070
  }
3046
4071
  /** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
@@ -3061,6 +4086,11 @@ export class Runs {
3061
4086
  /** The timeline from change `after`, held up to `waitMs` for a change when there is none. */
3062
4087
  async page(run, after, waitMs, limit) {
3063
4088
  const deadline = Date.now() + waitMs;
4089
+ // A full read is of the served view as the run stands now: show() first, so a row only the view makes (a pause's
4090
+ // waiting row, the install row, the learning row) is as current state says, whatever change came with no show() after
4091
+ // it. One diff of the run's rows (RowLog.sync), on a full read only; a read from a cursor gets each change as it is shown.
4092
+ if (after <= 0)
4093
+ this.show(run);
3064
4094
  for (;;) {
3065
4095
  const page = run.log.page(after, limit);
3066
4096
  const { status, state } = statusOf(run);