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

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 (816) hide show
  1. package/CHANGELOG.md +459 -0
  2. package/NOTICE +18 -0
  3. package/README.md +941 -263
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -143
  7. package/dist/adapters.js +153 -384
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +4 -2
  11. package/dist/agents.js +37 -17
  12. package/dist/api-only.d.ts +14 -0
  13. package/dist/api-only.js +33 -0
  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/box-egress-vm.d.ts +2 -9
  22. package/dist/box-egress-vm.js +20 -16
  23. package/dist/box-egress.d.ts +15 -9
  24. package/dist/box-egress.js +26 -29
  25. package/dist/box-paths.d.ts +82 -0
  26. package/dist/box-paths.js +160 -0
  27. package/dist/box-relay-vm.js +28 -1
  28. package/dist/box-relay.d.ts +1 -10
  29. package/dist/box-relay.js +1 -21
  30. package/dist/box-settings.d.ts +46 -0
  31. package/dist/box-settings.js +107 -0
  32. package/dist/boxes.d.ts +17 -2
  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 +277 -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 +166 -0
  41. package/dist/browser-person.js +767 -0
  42. package/dist/budget.d.ts +76 -0
  43. package/dist/budget.js +204 -0
  44. package/dist/cap.d.ts +267 -64
  45. package/dist/cap.js +587 -199
  46. package/dist/cli.js +220 -21
  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-Dn0ngwG9.js +535 -0
  65. package/dist/console/assets/index-DvW6Aled.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/daytona-api.d.ts +0 -11
  70. package/dist/daytona-api.js +1 -82
  71. package/dist/decision-cap.d.ts +63 -0
  72. package/dist/decision-cap.js +163 -0
  73. package/dist/decision-rows.d.ts +5 -2
  74. package/dist/decision-rows.js +8 -6
  75. package/dist/decisions.d.ts +28 -1
  76. package/dist/decisions.js +63 -6
  77. package/dist/docker-host-addresses.d.ts +37 -0
  78. package/dist/docker-host-addresses.js +110 -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 -43
  93. package/dist/files.js +8 -136
  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-install.d.ts +143 -0
  107. package/dist/harness-install.js +454 -0
  108. package/dist/harness-opencode/adapter.js +42 -8
  109. package/dist/harness-opencode/facts.d.ts +2 -0
  110. package/dist/harness-opencode/facts.js +28 -0
  111. package/dist/harness-opencode/harness.d.ts +4 -0
  112. package/dist/harness-opencode/harness.js +38 -5
  113. package/dist/harness-opencode/host/policy.js +11 -3
  114. package/dist/harness-opencode/transcript.d.ts +25 -0
  115. package/dist/harness-opencode/transcript.js +81 -0
  116. package/dist/harness-table.d.ts +75 -0
  117. package/dist/harness-table.js +145 -0
  118. package/dist/harness.d.ts +11 -31
  119. package/dist/harness.js +30 -41
  120. package/dist/heard.d.ts +12 -0
  121. package/dist/heard.js +45 -0
  122. package/dist/helper-env.d.ts +4 -0
  123. package/dist/helper-env.js +14 -0
  124. package/dist/home-path.d.ts +0 -4
  125. package/dist/home-path.js +3 -17
  126. package/dist/host-check.d.ts +4 -3
  127. package/dist/host-check.js +5 -4
  128. package/dist/host-tools.d.ts +51 -8
  129. package/dist/host-tools.js +108 -117
  130. package/dist/host.d.ts +12 -6
  131. package/dist/host.js +30 -24
  132. package/dist/hosted-search.d.ts +3 -0
  133. package/dist/hosted-search.js +5 -3
  134. package/dist/import-proxy.d.ts +42 -0
  135. package/dist/import-proxy.js +105 -0
  136. package/dist/import-summary.js +4 -8
  137. package/dist/import-worker.d.ts +2 -3
  138. package/dist/import-worker.js +18 -16
  139. package/dist/import.d.ts +37 -17
  140. package/dist/import.js +249 -224
  141. package/dist/key-meta.d.ts +26 -0
  142. package/dist/key-meta.js +30 -0
  143. package/dist/key-refusal.d.ts +4 -1
  144. package/dist/key-refusal.js +20 -7
  145. package/dist/learn/check.d.ts +3 -1
  146. package/dist/learn/check.js +2 -2
  147. package/dist/learn/commit.d.ts +86 -0
  148. package/dist/learn/commit.js +182 -0
  149. package/dist/learn/folder.d.ts +296 -0
  150. package/dist/learn/folder.js +796 -0
  151. package/dist/learn/grade.d.ts +22 -9
  152. package/dist/learn/grade.js +95 -49
  153. package/dist/learn/index.d.ts +2 -2
  154. package/dist/learn/index.js +2 -2
  155. package/dist/learn/learning.sh +366 -0
  156. package/dist/learn/reflect.d.ts +12 -5
  157. package/dist/learn/reflect.js +70 -41
  158. package/dist/learn/secrets.d.ts +16 -7
  159. package/dist/learn/secrets.js +80 -17
  160. package/dist/learn/seed-check.d.ts +74 -0
  161. package/dist/learn/seed-check.js +103 -0
  162. package/dist/learn/skills.d.ts +5 -1
  163. package/dist/learn/skills.js +5 -4
  164. package/dist/learned-workflow.d.ts +15 -4
  165. package/dist/learned-workflow.js +13 -6
  166. package/dist/learning-routes.d.ts +56 -46
  167. package/dist/learning-routes.js +350 -553
  168. package/dist/learning-run.d.ts +8 -228
  169. package/dist/learning-run.js +26 -713
  170. package/dist/learning-words.d.ts +3 -5
  171. package/dist/learning-words.js +3 -5
  172. package/dist/learning.d.ts +177 -112
  173. package/dist/learning.js +289 -380
  174. package/dist/live/stream.d.ts +30 -0
  175. package/dist/live/stream.js +175 -0
  176. package/dist/live/translate.d.ts +52 -0
  177. package/dist/live/translate.js +276 -0
  178. package/dist/llm.js +3 -0
  179. package/dist/llms.txt +1 -0
  180. package/dist/local-models.d.ts +23 -0
  181. package/dist/local-models.js +35 -0
  182. package/dist/mcp-gateway.d.ts +45 -15
  183. package/dist/mcp-gateway.js +140 -53
  184. package/dist/mcp-meta.d.ts +3 -0
  185. package/dist/mcp-meta.js +14 -2
  186. package/dist/mcp-oauth.d.ts +172 -0
  187. package/dist/mcp-oauth.js +403 -0
  188. package/dist/mcp-private-hosts.d.ts +48 -0
  189. package/dist/mcp-private-hosts.js +141 -0
  190. package/dist/mcp-probe.d.ts +101 -0
  191. package/dist/mcp-probe.js +359 -0
  192. package/dist/mcp-secret-writes.d.ts +23 -0
  193. package/dist/mcp-secret-writes.js +60 -0
  194. package/dist/mcp-servers-store.d.ts +251 -0
  195. package/dist/mcp-servers-store.js +447 -0
  196. package/dist/mcp-servers.d.ts +180 -50
  197. package/dist/mcp-servers.js +284 -321
  198. package/dist/mcp-store.d.ts +103 -0
  199. package/dist/mcp-store.js +123 -0
  200. package/dist/mcp.js +22 -21
  201. package/dist/model.d.ts +77 -59
  202. package/dist/model.js +237 -98
  203. package/dist/monid.d.ts +8 -6
  204. package/dist/monid.js +39 -25
  205. package/dist/openapi.d.ts +22 -1
  206. package/dist/openapi.js +921 -110
  207. package/dist/owner.d.ts +46 -10
  208. package/dist/owner.js +123 -43
  209. package/dist/page.d.ts +10 -0
  210. package/dist/page.js +29 -4
  211. package/dist/paid-calls.d.ts +71 -2
  212. package/dist/paid-calls.js +127 -6
  213. package/dist/pause.d.ts +0 -2
  214. package/dist/pause.js +1 -8
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -18
  218. package/dist/place.js +25 -25
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/print.d.ts +2 -1
  222. package/dist/print.js +4 -2
  223. package/dist/propose.d.ts +9 -8
  224. package/dist/propose.js +82 -49
  225. package/dist/provider.d.ts +85 -0
  226. package/dist/provider.js +178 -0
  227. package/dist/push-handler.d.ts +52 -0
  228. package/dist/push-handler.js +165 -0
  229. package/dist/refusal-words.d.ts +23 -0
  230. package/dist/refusal-words.js +25 -0
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-computer.d.ts +24 -0
  234. package/dist/run-computer.js +15 -0
  235. package/dist/run-cut.d.ts +33 -0
  236. package/dist/run-cut.js +42 -0
  237. package/dist/run-db.d.ts +62 -0
  238. package/dist/run-db.js +151 -0
  239. package/dist/run-files.d.ts +31 -0
  240. package/dist/run-files.js +125 -0
  241. package/dist/run-launch.d.ts +72 -0
  242. package/dist/run-launch.js +108 -0
  243. package/dist/run-learning-served.d.ts +81 -0
  244. package/dist/run-learning-served.js +25 -0
  245. package/dist/run-manifest.d.ts +7 -6
  246. package/dist/run-manifest.js +20 -10
  247. package/dist/run-reads-over-store.d.ts +102 -0
  248. package/dist/run-reads-over-store.js +151 -0
  249. package/dist/run-secrets.d.ts +33 -0
  250. package/dist/run-secrets.js +53 -0
  251. package/dist/run-timeline-served.d.ts +13 -0
  252. package/dist/run-timeline-served.js +72 -0
  253. package/dist/run-view.d.ts +432 -0
  254. package/dist/run-view.js +602 -0
  255. package/dist/runnable.d.ts +30 -5
  256. package/dist/runnable.js +149 -72
  257. package/dist/runner/adapter-loop.d.ts +243 -0
  258. package/dist/runner/adapter-loop.js +1657 -0
  259. package/dist/runner/adapter-run-spec.d.ts +224 -0
  260. package/dist/runner/adapter-run-spec.js +538 -0
  261. package/dist/runner/adapters/index.d.ts +37 -0
  262. package/dist/runner/adapters/index.js +66 -0
  263. package/dist/runner/adapters/pi.d.ts +103 -0
  264. package/dist/runner/adapters/pi.js +263 -0
  265. package/dist/runner/beside.d.ts +12 -0
  266. package/dist/runner/beside.js +41 -0
  267. package/dist/runner/claim-secrets.d.ts +30 -0
  268. package/dist/runner/claim-secrets.js +90 -0
  269. package/dist/runner/cli-run-spec.d.ts +17 -0
  270. package/dist/runner/cli-run-spec.js +385 -0
  271. package/dist/runner/commands.d.ts +23 -0
  272. package/dist/runner/commands.js +67 -0
  273. package/dist/runner/computer-journal.d.ts +38 -0
  274. package/dist/runner/computer-journal.js +120 -0
  275. package/dist/runner/conformance/child.d.ts +1 -0
  276. package/dist/runner/conformance/child.js +78 -0
  277. package/dist/runner/conformance/harness.d.ts +89 -0
  278. package/dist/runner/conformance/harness.js +928 -0
  279. package/dist/runner/conformance/subject.d.ts +83 -0
  280. package/dist/runner/conformance/subject.js +1 -0
  281. package/dist/runner/dispatch.d.ts +30 -0
  282. package/dist/runner/dispatch.js +99 -0
  283. package/dist/runner/end-of-run.d.ts +32 -0
  284. package/dist/runner/end-of-run.js +56 -0
  285. package/dist/runner/github-app.d.ts +16 -0
  286. package/dist/runner/github-app.js +37 -0
  287. package/dist/runner/hand-back.d.ts +43 -0
  288. package/dist/runner/hand-back.js +69 -0
  289. package/dist/runner/harness-loops.d.ts +10 -0
  290. package/dist/runner/harness-loops.js +70 -0
  291. package/dist/runner/journal-kinds.d.ts +217 -0
  292. package/dist/runner/journal-kinds.js +116 -0
  293. package/dist/runner/journal-reader.d.ts +44 -0
  294. package/dist/runner/journal-reader.js +127 -0
  295. package/dist/runner/learning-ask.d.ts +37 -0
  296. package/dist/runner/learning-ask.js +99 -0
  297. package/dist/runner/learning-dispatch.d.ts +38 -0
  298. package/dist/runner/learning-dispatch.js +75 -0
  299. package/dist/runner/learning-end.d.ts +31 -0
  300. package/dist/runner/learning-end.js +136 -0
  301. package/dist/runner/learning-factory.d.ts +13 -0
  302. package/dist/runner/learning-factory.js +37 -0
  303. package/dist/runner/learning-loop.d.ts +150 -0
  304. package/dist/runner/learning-loop.js +246 -0
  305. package/dist/runner/learning-seed.d.ts +30 -0
  306. package/dist/runner/learning-seed.js +41 -0
  307. package/dist/runner/live-ticker.d.ts +18 -0
  308. package/dist/runner/live-ticker.js +112 -0
  309. package/dist/runner/loop-contract.d.ts +154 -0
  310. package/dist/runner/loop-contract.js +26 -0
  311. package/dist/runner/loop.d.ts +79 -0
  312. package/dist/runner/loop.js +185 -0
  313. package/dist/runner/main.d.ts +96 -0
  314. package/dist/runner/main.js +311 -0
  315. package/dist/runner/mcp-claim.d.ts +67 -0
  316. package/dist/runner/mcp-claim.js +403 -0
  317. package/dist/runner/mcp-github.d.ts +53 -0
  318. package/dist/runner/mcp-github.js +91 -0
  319. package/dist/runner/mcp-run.d.ts +116 -0
  320. package/dist/runner/mcp-run.js +152 -0
  321. package/dist/runner/metrics.d.ts +18 -0
  322. package/dist/runner/metrics.js +24 -0
  323. package/dist/runner/model-route.d.ts +111 -0
  324. package/dist/runner/model-route.js +202 -0
  325. package/dist/runner/pi-stop.d.ts +6 -0
  326. package/dist/runner/pi-stop.js +8 -0
  327. package/dist/runner/redact.d.ts +32 -0
  328. package/dist/runner/redact.js +60 -0
  329. package/dist/runner/reflect-hook.d.ts +81 -0
  330. package/dist/runner/reflect-hook.js +111 -0
  331. package/dist/runner/runner.d.ts +114 -0
  332. package/dist/runner/runner.js +672 -0
  333. package/dist/runner/sessions.d.ts +9 -0
  334. package/dist/runner/sessions.js +145 -0
  335. package/dist/runner/side-effects.d.ts +19 -0
  336. package/dist/runner/side-effects.js +20 -0
  337. package/dist/runner/spec-holds.d.ts +41 -0
  338. package/dist/runner/spec-holds.js +58 -0
  339. package/dist/runner/store-port.d.ts +9 -0
  340. package/dist/runner/store-port.js +7 -0
  341. package/dist/runner/store-secrets.d.ts +11 -0
  342. package/dist/runner/store-secrets.js +105 -0
  343. package/dist/runner/workflow-adapters.d.ts +1 -0
  344. package/dist/runner/workflow-adapters.js +4 -0
  345. package/dist/runner/workflow-host.d.ts +88 -0
  346. package/dist/runner/workflow-host.js +66 -0
  347. package/dist/runner/workflow-loop.d.ts +126 -0
  348. package/dist/runner/workflow-loop.js +372 -0
  349. package/dist/runner/workflow-spec.d.ts +157 -0
  350. package/dist/runner/workflow-spec.js +797 -0
  351. package/dist/runs-over-store.d.ts +203 -0
  352. package/dist/runs-over-store.js +407 -0
  353. package/dist/seal-key.d.ts +69 -0
  354. package/dist/seal-key.js +329 -0
  355. package/dist/sealed-settings-store.d.ts +71 -0
  356. package/dist/sealed-settings-store.js +205 -0
  357. package/dist/sealed-settings.d.ts +60 -0
  358. package/dist/sealed-settings.js +171 -0
  359. package/dist/secret-writes.d.ts +147 -0
  360. package/dist/secret-writes.js +144 -0
  361. package/dist/secrets.d.ts +7 -8
  362. package/dist/secrets.js +24 -5
  363. package/dist/server-approvers.d.ts +8 -0
  364. package/dist/server-approvers.js +12 -0
  365. package/dist/server-fs.d.ts +40 -0
  366. package/dist/server-fs.js +138 -0
  367. package/dist/server-keys.d.ts +18 -0
  368. package/dist/server-keys.js +31 -0
  369. package/dist/server-lock.js +1 -1
  370. package/dist/server-secrets-store.d.ts +18 -0
  371. package/dist/server-secrets-store.js +54 -0
  372. package/dist/server-secrets.d.ts +23 -0
  373. package/dist/server-secrets.js +76 -0
  374. package/dist/server.d.ts +148 -75
  375. package/dist/server.js +1740 -605
  376. package/dist/sessions.d.ts +3 -1
  377. package/dist/sessions.js +8 -4
  378. package/dist/sign-ins-secrets.d.ts +35 -0
  379. package/dist/sign-ins-secrets.js +109 -0
  380. package/dist/sign-ins-store.d.ts +200 -0
  381. package/dist/sign-ins-store.js +373 -0
  382. package/dist/sign-ins.d.ts +43 -7
  383. package/dist/sign-ins.js +94 -18
  384. package/dist/skills.d.ts +6 -5
  385. package/dist/skills.js +18 -14
  386. package/dist/standard-webhooks.d.ts +30 -0
  387. package/dist/standard-webhooks.js +72 -0
  388. package/dist/stats.d.ts +5 -7
  389. package/dist/stats.js +8 -24
  390. package/dist/stop-signals.d.ts +22 -0
  391. package/dist/stop-signals.js +38 -0
  392. package/dist/store/agent-body.d.ts +103 -0
  393. package/dist/store/agent-body.js +126 -0
  394. package/dist/store/dialect.d.ts +59 -0
  395. package/dist/store/dialect.js +32 -0
  396. package/dist/store/fence.d.ts +22 -0
  397. package/dist/store/fence.js +15 -0
  398. package/dist/store/index.d.ts +17 -0
  399. package/dist/store/index.js +17 -0
  400. package/dist/store/journal/storage.d.ts +137 -0
  401. package/dist/store/journal/storage.js +1021 -0
  402. package/dist/store/open.d.ts +44 -0
  403. package/dist/store/open.js +50 -0
  404. package/dist/store/postgres/connection.d.ts +74 -0
  405. package/dist/store/postgres/connection.js +532 -0
  406. package/dist/store/postgres/dialect.d.ts +9 -0
  407. package/dist/store/postgres/dialect.js +39 -0
  408. package/dist/store/postgres/migrate.d.ts +21 -0
  409. package/dist/store/postgres/migrate.js +123 -0
  410. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  411. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  412. package/dist/store/postgres/store.d.ts +37 -0
  413. package/dist/store/postgres/store.js +48 -0
  414. package/dist/store/prompts.d.ts +11 -0
  415. package/dist/store/prompts.js +112 -0
  416. package/dist/store/schema.d.ts +26 -0
  417. package/dist/store/schema.js +522 -0
  418. package/dist/store/seal.d.ts +48 -0
  419. package/dist/store/seal.js +69 -0
  420. package/dist/store/sqlite/connection.d.ts +105 -0
  421. package/dist/store/sqlite/connection.js +309 -0
  422. package/dist/store/sqlite/memory.d.ts +2 -0
  423. package/dist/store/sqlite/memory.js +4 -0
  424. package/dist/store/sqlite/run-launch.d.ts +8 -0
  425. package/dist/store/sqlite/run-launch.js +20 -0
  426. package/dist/store/sqlite/run-patch.d.ts +54 -0
  427. package/dist/store/sqlite/run-patch.js +114 -0
  428. package/dist/store/sqlite/store.d.ts +33 -0
  429. package/dist/store/sqlite/store.js +1352 -0
  430. package/dist/store/sqlite/worker.d.ts +78 -0
  431. package/dist/store/sqlite/worker.js +242 -0
  432. package/dist/store/store.d.ts +1256 -0
  433. package/dist/store/store.js +190 -0
  434. package/dist/store-reads/analytics.d.ts +55 -0
  435. package/dist/store-reads/analytics.js +135 -0
  436. package/dist/store-reads/cap.d.ts +17 -0
  437. package/dist/store-reads/cap.js +17 -0
  438. package/dist/store-reads/decisions.d.ts +5 -0
  439. package/dist/store-reads/decisions.js +31 -0
  440. package/dist/store-reads/import-summary.d.ts +6 -0
  441. package/dist/store-reads/import-summary.js +14 -0
  442. package/dist/store-reads/journal.d.ts +46 -0
  443. package/dist/store-reads/journal.js +196 -0
  444. package/dist/store-reads/learning.d.ts +93 -0
  445. package/dist/store-reads/learning.js +202 -0
  446. package/dist/store-reads/runs.d.ts +42 -0
  447. package/dist/store-reads/runs.js +84 -0
  448. package/dist/store-reads/stats.d.ts +30 -0
  449. package/dist/store-reads/stats.js +59 -0
  450. package/dist/store-reads/workflow.d.ts +7 -0
  451. package/dist/store-reads/workflow.js +14 -0
  452. package/dist/store-view.d.ts +37 -0
  453. package/dist/store-view.js +338 -0
  454. package/dist/template-eval.d.ts +239 -0
  455. package/dist/template-eval.js +1020 -0
  456. package/dist/template-github-permissions.d.ts +18 -0
  457. package/dist/template-github-permissions.js +32 -0
  458. package/dist/templates.d.ts +199 -0
  459. package/dist/templates.js +637 -0
  460. package/dist/tool-blurbs.d.ts +4 -0
  461. package/dist/tool-blurbs.js +27 -0
  462. package/dist/tool-gate.d.ts +166 -35
  463. package/dist/tool-gate.js +411 -91
  464. package/dist/tool-keys-store.d.ts +110 -0
  465. package/dist/tool-keys-store.js +291 -0
  466. package/dist/tool-keys.d.ts +29 -15
  467. package/dist/tool-keys.js +27 -6
  468. package/dist/tool-plane.d.ts +113 -27
  469. package/dist/tool-plane.js +229 -76
  470. package/dist/tool-settings-store.d.ts +30 -0
  471. package/dist/tool-settings-store.js +53 -0
  472. package/dist/tools.d.ts +95 -24
  473. package/dist/tools.js +341 -62
  474. package/dist/trigger-accept.d.ts +36 -0
  475. package/dist/trigger-accept.js +152 -0
  476. package/dist/trigger-adapter.d.ts +143 -0
  477. package/dist/trigger-adapter.js +31 -0
  478. package/dist/trigger-adapters.d.ts +2 -0
  479. package/dist/trigger-adapters.js +4 -0
  480. package/dist/trigger-github.d.ts +2 -0
  481. package/dist/trigger-github.js +85 -0
  482. package/dist/trigger-schedule.d.ts +6 -0
  483. package/dist/trigger-schedule.js +116 -0
  484. package/dist/trigger-secrets-shown.d.ts +66 -0
  485. package/dist/trigger-secrets-shown.js +81 -0
  486. package/dist/trigger-signatures.d.ts +58 -0
  487. package/dist/trigger-signatures.js +79 -0
  488. package/dist/trigger-targets.d.ts +46 -0
  489. package/dist/trigger-targets.js +95 -0
  490. package/dist/trigger-webhook.d.ts +2 -0
  491. package/dist/trigger-webhook.js +92 -0
  492. package/dist/triggers.d.ts +282 -237
  493. package/dist/triggers.js +720 -608
  494. package/dist/turn-end.d.ts +3 -0
  495. package/dist/turn-end.js +3 -0
  496. package/dist/uploads.d.ts +10 -8
  497. package/dist/uploads.js +45 -45
  498. package/dist/usage.d.ts +33 -3
  499. package/dist/usage.js +38 -4
  500. package/dist/validate.d.ts +6 -0
  501. package/dist/validate.js +42 -12
  502. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  503. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  504. package/dist/web-fetch.d.ts +17 -9
  505. package/dist/web-fetch.js +53 -18
  506. package/dist/web-search.d.ts +1 -1
  507. package/dist/web-search.js +1 -1
  508. package/dist/webhooks.d.ts +33 -23
  509. package/dist/webhooks.js +69 -56
  510. package/dist/wires.d.ts +11 -0
  511. package/dist/wires.js +7 -0
  512. package/dist/workspace/archil-claim.d.ts +57 -0
  513. package/dist/workspace/archil-claim.js +154 -0
  514. package/dist/workspace/archil-disk.d.ts +104 -0
  515. package/dist/workspace/archil-disk.js +254 -0
  516. package/dist/workspace/archil-exec.d.ts +59 -0
  517. package/dist/workspace/archil-exec.js +218 -0
  518. package/dist/workspace/archil-key.d.ts +17 -0
  519. package/dist/workspace/archil-key.js +30 -0
  520. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  521. package/dist/workspace/archil-mount-credential.js +165 -0
  522. package/dist/workspace/archil.d.ts +59 -0
  523. package/dist/workspace/archil.js +676 -0
  524. package/dist/workspace/attach.d.ts +48 -0
  525. package/dist/workspace/attach.js +439 -0
  526. package/dist/workspace/computer-deps.d.ts +87 -0
  527. package/dist/workspace/computer-deps.js +160 -0
  528. package/dist/workspace/computer-for-claim.d.ts +119 -0
  529. package/dist/workspace/computer-for-claim.js +198 -0
  530. package/dist/workspace/computer-hold.d.ts +145 -0
  531. package/dist/workspace/computer-hold.js +258 -0
  532. package/dist/workspace/computer-ledger.d.ts +22 -0
  533. package/dist/workspace/computer-ledger.js +19 -0
  534. package/dist/workspace/computer-ports.d.ts +13 -0
  535. package/dist/workspace/computer-ports.js +108 -0
  536. package/dist/workspace/computer-providers.d.ts +16 -0
  537. package/dist/workspace/computer-providers.js +17 -0
  538. package/dist/workspace/computer-serves.d.ts +12 -0
  539. package/dist/workspace/computer-serves.js +15 -0
  540. package/dist/workspace/executors.d.ts +38 -0
  541. package/dist/workspace/executors.js +150 -0
  542. package/dist/workspace/glob.d.ts +2 -0
  543. package/dist/workspace/glob.js +25 -0
  544. package/dist/workspace/grep-worker.d.ts +11 -0
  545. package/dist/workspace/grep-worker.js +91 -0
  546. package/dist/workspace/hands.d.ts +25 -0
  547. package/dist/workspace/hands.js +121 -0
  548. package/dist/workspace/index.d.ts +23 -0
  549. package/dist/workspace/index.js +25 -0
  550. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  551. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  552. package/dist/workspace/kind-skills.d.ts +11 -0
  553. package/dist/workspace/kind-skills.js +16 -0
  554. package/dist/workspace/learning-workspace.d.ts +24 -0
  555. package/dist/workspace/learning-workspace.js +107 -0
  556. package/dist/workspace/local.d.ts +6 -0
  557. package/dist/workspace/local.js +632 -0
  558. package/dist/workspace/paths.d.ts +48 -0
  559. package/dist/workspace/paths.js +134 -0
  560. package/dist/workspace/pi-env.d.ts +39 -0
  561. package/dist/workspace/pi-env.js +397 -0
  562. package/dist/workspace/place.d.ts +7 -0
  563. package/dist/workspace/place.js +3 -0
  564. package/dist/workspace/resolve-computer.d.ts +106 -0
  565. package/dist/workspace/resolve-computer.js +188 -0
  566. package/dist/workspace/revision-skills.d.ts +15 -0
  567. package/dist/workspace/revision-skills.js +42 -0
  568. package/dist/workspace/run-tools.d.ts +173 -0
  569. package/dist/workspace/run-tools.js +172 -0
  570. package/dist/workspace/run-workspace.d.ts +25 -0
  571. package/dist/workspace/run-workspace.js +56 -0
  572. package/dist/workspace/server-run-workspace.d.ts +24 -0
  573. package/dist/workspace/server-run-workspace.js +84 -0
  574. package/dist/workspace/workspace.d.ts +169 -0
  575. package/dist/workspace/workspace.js +54 -0
  576. package/dist/workspace-paths.d.ts +1 -10
  577. package/dist/workspace-paths.js +3 -37
  578. package/dist/workspace.d.ts +0 -17
  579. package/dist/workspace.js +3 -74
  580. package/harnesses/claude-agent/package-lock.json +1533 -0
  581. package/harnesses/claude-agent/package.json +7 -0
  582. package/harnesses/codex/package-lock.json +135 -0
  583. package/harnesses/codex/package.json +7 -0
  584. package/launcher/agentrun-serve +10 -27
  585. package/package.json +37 -22
  586. package/skills/agentrun-serve/SKILL.md +2 -0
  587. package/templates/README.md +211 -0
  588. package/templates/code-review/agent.md +50 -0
  589. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  590. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  591. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  592. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  593. package/templates/code-review/evals/injection/case.yaml +3 -0
  594. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  595. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  596. package/templates/code-review/evals/injection/prompt.md +23 -0
  597. package/templates/code-review/evals/null-name/case.yaml +3 -0
  598. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  599. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  600. package/templates/code-review/evals/null-name/prompt.md +17 -0
  601. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  602. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  603. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  604. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  605. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  606. package/templates/code-review/evals/re-review/case.yaml +3 -0
  607. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  608. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  609. package/templates/code-review/evals/re-review/prompt.md +23 -0
  610. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  611. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  612. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  613. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  614. package/templates/code-review/findings.schema.json +125 -0
  615. package/templates/code-review/rules/REVIEW.md +41 -0
  616. package/templates/code-review/skills/review/SKILL.md +162 -0
  617. package/templates/inbound-lead/agent.md +76 -0
  618. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  619. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  620. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  621. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  622. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  623. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  624. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  626. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  627. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  629. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  630. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  631. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  632. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  633. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  634. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  635. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  636. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  637. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  638. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  639. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  640. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  641. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  644. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  645. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  646. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  647. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  648. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  649. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  650. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  652. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  654. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  656. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  657. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  658. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  659. package/templates/inbound-lead/lead.schema.json +587 -0
  660. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  661. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  662. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  663. package/templates/kyb/agent.md +44 -0
  664. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  665. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  666. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  667. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  668. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  669. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  670. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  671. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  672. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  673. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  674. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  675. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  676. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  677. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  678. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  679. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  680. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  681. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  682. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  683. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  684. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  685. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  686. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  687. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  688. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  689. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  690. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  691. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  692. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  693. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  694. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  695. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  696. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  697. package/templates/kyb/kyb.schema.json +274 -0
  698. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  699. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  700. package/templates/kyb/rules/SANCTIONS.md +140 -0
  701. package/templates/kyb/rules/SOURCES.md +92 -0
  702. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  703. package/templates/market-monitor/agent.md +58 -0
  704. package/templates/market-monitor/digest.schema.json +194 -0
  705. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  706. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  707. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  708. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  709. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  710. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  711. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  712. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  713. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  714. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  715. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  716. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  717. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  719. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  720. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  721. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  722. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  723. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  724. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  725. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  726. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  727. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  728. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  729. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  730. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  731. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  733. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  734. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  735. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  736. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  737. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  739. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  741. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  742. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  743. package/templates/market-monitor/rules/MONITOR.md +33 -0
  744. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  745. package/templates/release-notes/agent.md +47 -0
  746. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  747. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  748. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  749. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  750. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  751. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  752. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  753. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  754. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  755. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  756. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  757. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  758. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  759. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  760. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  761. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  762. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  763. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  764. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  765. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  766. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  767. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  768. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  769. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  770. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  771. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  772. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  773. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  774. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  775. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  776. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  777. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  778. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  779. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  780. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  781. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  782. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  783. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  784. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  785. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  786. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  787. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  788. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  789. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  790. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  791. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  792. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  793. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  794. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  795. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  796. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  797. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  798. package/templates/release-notes/notes.schema.json +145 -0
  799. package/templates/release-notes/rules/STYLE.md +47 -0
  800. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  801. package/dist/app.d.ts +0 -7
  802. package/dist/app.js +0 -399
  803. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  804. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  805. package/dist/content-filter.d.ts +0 -7
  806. package/dist/content-filter.js +0 -23
  807. package/dist/harness-app.d.ts +0 -40
  808. package/dist/harness-app.js +0 -717
  809. package/dist/request-start.d.ts +0 -22
  810. package/dist/request-start.js +0 -350
  811. package/dist/run-box.d.ts +0 -186
  812. package/dist/run-box.js +0 -600
  813. package/dist/runs.d.ts +0 -1069
  814. package/dist/runs.js +0 -3073
  815. package/dist/trigger-secrets.d.ts +0 -32
  816. package/dist/trigger-secrets.js +0 -143
package/dist/runs.js DELETED
@@ -1,3073 +0,0 @@
1
- // Runs: each one a child process (`pi-durable-disk run` on `<data>/runs/<id>` with serve's app), pinned to a revision in
2
- // the agent store. An agentic run is read live through the door its process serves on loopback; a workflow run is
3
- // working while its process lives. Once the process has exited the run is read from its store, read-only, and carried
4
- // back to the agent store (`carryBack`), and it is finished. A run whose process went before the run ended is opened
5
- // again on its directory, and resumes from its store.
6
- import { spawn } from "node:child_process";
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";
10
- import { join } from "node:path";
11
- import { fileURLToPath } from "node:url";
12
- import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
13
- 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";
17
- import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
18
- import { DEFAULT_HARNESS, harnessOfBody, steersMidTurn } from "./harness.js";
19
- import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
20
- 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";
23
- import { META_REASON, metaToolOf } from "./mcp-meta.js";
24
- import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
25
- import { LEARNING_LABEL, shortOf } from "./learning.js";
26
- import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
27
- import { settleBox, sweepBoxes } from "./box/sweep.js";
28
- import { rowPaths } from "./workspace-paths.js";
29
- import { ASK_TOOL, toolingOf, workflowTools } from "./tools.js";
30
- import { withDecisions } from "./decision-rows.js";
31
- import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
32
- import { ApiError, invalid, unsupported } from "./errors.js";
33
- 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";
35
- import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
36
- import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
37
- import { durationMs } from "./print.js";
38
- 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";
40
- import { ChangeClock, RowLog } from "./rows.js";
41
- import { TOOL_KEYS } from "./tool-keys.js";
42
- import { isObject } from "./validate.js";
43
- import { firstMessage } from "./run-manifest.js";
44
- 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";
46
- 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";
49
- import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
50
- import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
51
- 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";
54
- import { removeEgressDir, RUN_BOX_ALLOW_ENV } from "./box-egress.js";
55
- import { RUN_BOX_VOLUME_ENV } from "./box-egress-vm.js";
56
- import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
57
- export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
58
- const TERMINAL = new Set(["completed", "failed", "cancelled"]);
59
- const RELEASED = new Set(["sleeping", "paused", "done", "failed"]);
60
- const LEASE_MS = 90_000;
61
- /** How long an agentic run's process may finish its turn after SIGTERM, unless the server says otherwise. */
62
- 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. */
64
- const PROCESS_LOG = "process.log";
65
- /** How long a request waits for a run's door: its process coming up, or a settle in progress. */
66
- const READY_TIMEOUT_MS = 45_000;
67
- /** The reducer's live "Run started" and "Run finished" rows: a turn's edges, which no store entry makes on any harness,
68
- * 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
- const QUIET = /:run:(start|end)$/;
70
- const RETRY_CODES = ["OPENING", "PARKING", "RELEASED"];
71
- /** How often one server opens a run again whose process went before the run ended, before it fails the run. */
72
- const MAX_RELAUNCHES = 3;
73
- /** How often a run's end that the agent store refused is written again. */
74
- const SETTLE_RETRY_MS = 30_000;
75
- /** How a run ended in the store, as its status: the store's `stopped` is v2's `cancelled`, and an escalated workflow
76
- * completed its work and waits for a person (its `review`), which is not a failure. */
77
- const STATUS_OF = { completed: "completed", failed: "failed", escalated: "completed", stopped: "cancelled" };
78
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
79
- // A run's process that exited and was never reaped (a zombie, under a PID 1 that does not reap) is not alive.
80
- const alive = processAlive;
81
- /** Waits between carry backs that found the store busy: each attempt itself waits 5 s for the store's lock. */
82
- const CARRY_BACK_RETRIES_MS = [500, 1_000, 2_000, 4_000, 8_000];
83
- /** 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
- * store's exclusive lock until it exits. */
85
- 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
- const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
89
- /** How long serve's calls on a run's box (its destroy, the start's sweep) may take. */
90
- const BOX_CALL_MS = 60_000;
91
- const boxContext = (ms = BOX_CALL_MS) => withAbortSignal(AbortSignal.timeout(ms), BACKGROUND_CONTEXT);
92
- /** How long a remote box's making and seed, or one pull of its work/, may take: a sandbox's start, then the copy. */
93
- const REMOTE_SYNC_MS = 15 * 60_000;
94
- /** How long a read of a run's files waits for the pull its turn's end began. */
95
- const PULL_WAIT_MS = 120_000;
96
- /** A run's end that waits for its remote box's last pull: its settle is tried again until the pull lands. */
97
- class PullPending extends Error {
98
- }
99
- /** Run directory `dir`'s own door token, made now (mode 0600, never through a link) when it has none. */
100
- function ensureRunDoorToken(dir) {
101
- const held = runDoorToken(dir);
102
- if (held)
103
- return held;
104
- const token = `ar_door_${randomBytes(24).toString("base64url")}`;
105
- try {
106
- writeFileSync(join(dir, RUN_DOOR_TOKEN), `${token}\n`, { mode: 0o600, flag: "wx" });
107
- }
108
- catch (error) {
109
- // Made meanwhile: that one is the run's.
110
- if (error.code !== "EEXIST")
111
- throw error;
112
- const made = runDoorToken(dir);
113
- if (!made)
114
- throw new Error(`the run's door token at ${RUN_DOOR_TOKEN} is not one`);
115
- return made;
116
- }
117
- return token;
118
- }
119
- const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
120
- 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
- /** How a workflow run's workflow ended, as its app wrote it in the run's final status: absent until it ended. */
123
- function workflowEnding(record) {
124
- const detail = isObject(record?.detail) ? record.detail : undefined;
125
- if (!RELEASED.has(String(record?.status)) || !["complete", "escalated", "refused", "stopped"].includes(String(detail?.workflow)))
126
- return undefined;
127
- return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
128
- }
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
- /** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
132
- const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
133
- /** A failed run's error from its row and serve.json: its own, else the row's summary. */
134
- const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", message: meta?.error?.message ?? row.summary ?? "The run failed.", retryable: false, ...(meta?.error?.details ? { details: meta.error.details } : {}) });
135
- /** 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
- * reviews were kept) the row's summary; null for every other run. */
137
- const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
138
- /** A value's sha256, of its JSON. */
139
- 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
- }
172
- /** Notes the messages the run's turns took and how each turn ended, from `entries` (its root's), `submissions` (pi's
173
- * input submissions) and a reconnect's `snapshot` of them (the door's `inputs`, the run's whole state of them), and the
174
- * newest entry (learning-run.ts reads it). The end-of-run learning turn's entries are no turn of the run's: none of
175
- * them, its TURN_END and its settlement included, opens, closes or answers one of the run's messages. */
176
- function noteTurns(run, entries, submissions = [], snapshot) {
177
- for (const value of entries) {
178
- if (!isObject(value) || typeof value.id !== "number")
179
- continue;
180
- run.lastEntry = Math.max(run.lastEntry ?? 0, value.id);
181
- // A refusal for room's own start mark: what the cap counted as taken, and the least the request needed.
182
- const data = value.kind === REQUEST_STARTED && isObject(value.data) && value.data[CAP_REFUSED_FIELD] === true ? value.data : undefined;
183
- if (data)
184
- run.capMark = value.id;
185
- if (data)
186
- run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd } : undefined;
187
- // The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
188
- // (learning-run.ts). The ledger skips them; this is their only reader here.
189
- if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
190
- const content = value.model[0].content;
191
- (run.turnText ??= new Map()).set(value.id, typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isObject(b) && b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim() : "");
192
- }
193
- }
194
- const reflect = (id) => reflects(run.meta.reflect, id);
195
- run.turns.note(entries, submissions, reflect);
196
- if (snapshot)
197
- run.turns.snapshot(snapshot, reflect);
198
- }
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;
205
- };
206
- /** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
207
- * acted on. */
208
- function noteApprovals(run, entries) {
209
- for (const value of entries) {
210
- if (!isObject(value) || value.kind !== APPROVAL_ENTRY || !isObject(value.data) || typeof value.data.id !== "string")
211
- continue;
212
- const data = value.data;
213
- run.approvals ??= new Map();
214
- const known = run.approvals.get(data.id);
215
- if (data.phase === "requested" && !known)
216
- run.approvals.set(data.id, { id: data.id, tool: String(data.tool), call_id: String(data.call_id), args_json: "args" in data ? (JSON.stringify(data.args ?? {}) ?? "{}") : String(data.args_preview ?? ""), requested_at: String(data.requested_at), ...(typeof data.price === "number" || data.price === "not metered" ? { price: data.price } : {}) });
217
- else if (data.phase === "resolved" && known)
218
- known.resolved = true;
219
- }
220
- }
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));
226
- /** `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. */
228
- function redactGateMessages(entries, redact) {
229
- return entries.map((entry) => {
230
- const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
231
- if (!isObject(first) || first.role !== "user")
232
- return entry;
233
- const content = first.content;
234
- const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => (isObject(block) && block.type === "text" ? String(block.text ?? "") : "")).join("") : "";
235
- if (!text.startsWith(RESUME_PREFIX))
236
- return entry;
237
- const redacted = typeof content === "string" ? redact(content) : content.map((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: redact(block.text) } : block));
238
- return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
239
- });
240
- }
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]));
248
- /** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
249
- * (`redact`, the Timeline's own: no held key), before any cut. */
250
- function withApprovals(rows, run, redact) {
251
- if (!run.approvals?.size)
252
- return [...rows];
253
- const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
254
- const waiting = waitingApproval(run);
255
- return rows.flatMap((row) => {
256
- const approval = row.kind === "tool_result" && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
257
- if (!approval)
258
- return [row];
259
- const args = shownArgs(approval, redact);
260
- const said = run.meta.approvals?.[approval.id]?.decision;
261
- const byMessage = run.meta.approvals?.[approval.id]?.by === "message";
262
- const head = approval === waiting ? "Waiting for your approval" : byMessage ? "Declined by your message" : said === "withdrawn" ? "Withdrawn when the run was stopped" : said === "canceled" ? "Withdrawn when the run was cancelled" : "Asked your approval";
263
- const summary = `${head}: ${approval.tool} ${clip(args, 400)}`;
264
- // A message that would have declined the call, which a stop or a cancel overrode: its words were never sent, and
265
- // the row says so (the record keeps them whole).
266
- const dropped = run.meta.approvals?.[approval.id]?.superseded;
267
- 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 }];
269
- });
270
- }
271
- /** A dollar figure to a millionth, as the timeline's cost.usd is. */
272
- const micro = (usd) => Math.round(usd * 1e6) / 1e6;
273
- /** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
274
- const CONTINUE_TRIES = 3;
275
- 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)
296
- 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 };
302
- };
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
- }
312
- /** 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
- * last meaningful row is its answer when that row is one, a final answer's or a text row's. */
314
- const importAnswerOf = (rows) => {
315
- const last = meaningful(rows);
316
- return last?.kind === "final_answer" || last?.kind === "text_block" ? last : undefined;
317
- };
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
- }
361
- /** What a run's meta kept of its cost so far at its end, when it is well formed. */
362
- const soFarOfMeta = (meta) => {
363
- const kept = meta?.cost_so_far;
364
- return kept && typeof kept.so_far_usd === "number" && Number.isFinite(kept.so_far_usd) && Number.isInteger(kept.unpriced) && kept.unpriced > 0 ? { so_far_usd: kept.so_far_usd, unpriced: kept.unpriced } : undefined;
365
- };
366
- /** The whole text of the run's newest answer with text, paid for: an assistant message's, else its newest answer row's. */
367
- const lastAnswer = (run) => run.turns.newestText ?? run.rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL)?.text ?? null;
368
- /** A row's store entry, from its id (`<conversation>:<entry>[:...]`). */
369
- const entryOfRow = (id) => Number(id.split(":")[1]);
370
- /** The answer of a run that completed: the whole text of the entry its turn's end names, "" when that turn showed no text,
371
- * never an earlier turn's. Without such an end (a run still working, a workflow, a store an older server wrote): the
372
- * newest answer it gave, whole (lastAnswer); an import's, its last row's when that row is its answer. */
373
- function answerOfRun(run) {
374
- const end = run.turns.end();
375
- if (end?.status === "answered") {
376
- if (end.answer === null)
377
- return "";
378
- // The entry's row when its text was not read here: a final answer's, or a text row's (a stop at the length limit).
379
- return run.turns.text(end.answer) ?? run.rows.findLast((r) => (r.kind === "final_answer" || r.kind === "text_block") && entryOfRow(r.id) === end.answer)?.text ?? "";
380
- }
381
- const imported = run.imported ? importAnswerOf(run.rows) : undefined;
382
- return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
383
- }
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;
386
- 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
- };
434
- /** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
435
- function processIdentity(pid) {
436
- if (pid === undefined)
437
- return undefined;
438
- try {
439
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
440
- return `${pid}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
441
- }
442
- catch {
443
- return String(pid);
444
- }
445
- }
446
- const pausedAt = (run) => (raisedSince(run) ? undefined : refusedAt(run));
447
- /** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
448
- export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
449
- /** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
450
- * 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) {
452
- for (const row of rows)
453
- if (isLive(row.id))
454
- live.add(row.id);
455
- return (id) => !live.has(id) && !isLive(id);
456
- }
457
- /** A wait's mark: the stop it stands at, while that stop holds, else its newest row (the question it waits on). */
458
- const waitMark = (run) => (stopped(run) && run.meta.stopped_at) || meaningful(run.rows)?.id || "";
459
- /** Waits for `work`, or until `deadline` (ms since the epoch), whichever comes first. */
460
- async function untilDeadline(work, deadline) {
461
- let timer;
462
- await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))))]);
463
- clearTimeout(timer);
464
- }
465
- /** A run's status and state, by the contract's table. */
466
- 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" };
505
- }
506
- /** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
507
- function triggerOf(meta) {
508
- const trigger = meta?.trigger;
509
- return isObject(trigger) && typeof trigger.id === "string" && typeof trigger.firing_key === "string" ? { id: trigger.id, firing_key: trigger.firing_key } : null;
510
- }
511
- /** Why a message that may not answer a person's question is not sent. */
512
- export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
513
- /** 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]);
516
- /** The secrets a run's process is handed over its pipe (secrets.ts): every one but the server's own and the decision
517
- * keys, which go on their own descriptor. */
518
- export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
519
- /** The fields a run gets only when its revision names what they unlock: a `tool` key's. Any other kind's (a model key's)
520
- * is the model's to need, as every model key is. */
521
- const scopedOf = (rows) => rows.filter((row) => row.kind === "tool").flatMap((row) => row.fields);
522
- /** The model keys: every key of pi-ai's providers (model.ts' PROVIDER_KEYS) and the gateway's. A run gets those its model
523
- * needs and no other (secretsFor). A workflow's decision keys, OpenRouter's among them, go on its decision descriptor
524
- * (decisions.ts), whatever its model. */
525
- const MODEL_KEYS = [...new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV])];
526
- /** What a run whose revision was not read is handed: no tool key, and no model key. */
527
- const NO_TOOL_KEYS = RUN_SECRETS.filter((name) => !scopedOf(TOOL_KEYS).includes(name) && !MODEL_KEYS.includes(name));
528
- /** `revision`'s RunNeeds. */
529
- export async function needsOf(revision) {
530
- const workflow = revision.kind === "workflow" ? revision.body.workflow : undefined;
531
- const nodes = workflow ? workflowNodes(workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(workflow)) : undefined;
532
- const bound = nodes && workflowTools(nodes);
533
- return {
534
- harness: revision.body.harness ?? DEFAULT_HARNESS,
535
- ...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}),
536
- tools: bound ? [...bound.nodes, ...bound.calls] : [...(revision.body.tools ?? [])],
537
- ...(nodes ? { tiers: llmTiers(nodes, nodeTiers(nodes)) } : {}),
538
- decisionProviders: nodes ? providersNamed(nodes) : [],
539
- };
540
- }
541
- /** 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
- * `tool` row of `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does
543
- * 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
546
- * saved with no restart counts at the next. */
547
- export function keysFor(needs, env, rows = TOOL_KEYS) {
548
- const named = new Set(needs.tools);
549
- const unlocked = new Set(rows.filter((row) => row.unlocks.some((name) => named.has(name))).flatMap((row) => row.fields));
550
- 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));
552
- return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
553
- }
554
- /** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
555
- export async function secretsFor(revision, rows = TOOL_KEYS, env = process.env) {
556
- return keysFor(await needsOf(revision), env, rows);
557
- }
558
- /** The decision providers a run of `revision` needs keys for (needsOf). Its web tools' need, Parallel's where one
559
- * resolves to Parallel, is its tool plane's (tool-plane.ts' handsParallel), read at each launch. */
560
- export async function decisionProvidersFor(revision) {
561
- return (await needsOf(revision)).decisionProviders;
562
- }
563
- /** The module a run's process preloads (`--import`) to read its pipe before anything else; app.ts gets the same instance. */
564
- const SECRETS_MODULE = new URL("./secrets.js", import.meta.url).href;
565
- /** A run's process's environment: no secret in it (they go over its pipe), nor the token by value; the AGENT_MODEL
566
- * variables and the rest pass, and the door token goes by file. A test hook's name passes never (withoutFaux): the run
567
- * gets one only from startServe's options. */
568
- export const childEnv = (env, token) => Object.fromEntries(Object.entries(withoutSecrets(withoutFaux(env))).filter(([, value]) => value !== token));
569
- /** One line of the run process's log in words: pi-durable-disk writes JSON lines (`{at, event, message, ...}`). */
570
- function inWords(line) {
571
- let value;
572
- try {
573
- value = JSON.parse(line);
574
- }
575
- catch {
576
- return line;
577
- }
578
- if (!isObject(value))
579
- return line;
580
- const text = (key) => (typeof value[key] === "string" ? value[key] : undefined);
581
- return [text("event"), text("message") ?? text("error")].filter(Boolean).join(": ") || "the run's process left no message";
582
- }
583
- /** The line of the run process's log a failure's message is made of: its last, past any harness's own lines (a proxy's
584
- * refusal just before a crash says nothing of why the process went). */
585
- export function failureLine(log) {
586
- const lines = log.trim().split("\n");
587
- return ownLine(lines) ?? lines.at(-1) ?? "";
588
- }
589
- /** The last of `lines` that is not a harness's own line, if any. */
590
- function ownLine(lines) {
591
- return lines.findLast((line) => {
592
- if (line.trim() === "")
593
- return false;
594
- try {
595
- return JSON.parse(line)?.event !== HARNESS_LOG_EVENT;
596
- }
597
- catch {
598
- return true;
599
- }
600
- });
601
- }
602
- /** How far back from its end a failure's message is looked for in the run's log, in steps of LOG_STEP. */
603
- const LOG_STEP = 4096;
604
- const LOG_REACH = 1 << 20;
605
- /** The last line of the run process's log, in words, for a failure's message. */
606
- export async function lastLogLine(run) {
607
- const file = await openFile(join(run.dir, PROCESS_LOG)).catch(() => null);
608
- if (!file)
609
- return "";
610
- try {
611
- // Backward until a whole line is the process's own: harness lines after it may run past any one read, and a read
612
- // that starts inside a line has only its tail, which is no line at all. Each step looks only at the lines it
613
- // completes; what was read is joined once, and failureLine, the one rule, picks the line from it.
614
- const { size } = await file.stat();
615
- const chunks = [];
616
- let start = size;
617
- // The oldest line read so far, torn at the read's start unless that is the file's start.
618
- let head = Buffer.alloc(0);
619
- while (start > 0 && size - start < LOG_REACH) {
620
- const from = Math.max(0, start - LOG_STEP);
621
- const { buffer } = await file.read(Buffer.alloc(start - from), 0, start - from, from);
622
- start = from;
623
- chunks.unshift(buffer);
624
- const newline = buffer.indexOf(0x0a);
625
- const completed = start === 0 ? Buffer.concat([buffer, head]) : newline < 0 ? Buffer.alloc(0) : Buffer.concat([buffer.subarray(newline + 1), head]);
626
- head = start === 0 ? Buffer.alloc(0) : newline < 0 ? Buffer.concat([buffer, head]) : buffer.subarray(0, newline);
627
- if (ownLine(completed.toString("utf8").split("\n")) !== undefined)
628
- break;
629
- }
630
- return clip(inWords(failureLine(Buffer.concat(chunks).subarray(head.length).toString("utf8"))), 300);
631
- }
632
- finally {
633
- await file.close();
634
- }
635
- }
636
- /** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went. */
637
- export const runsTestHooks = {};
638
- export class Runs {
639
- options;
640
- 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();
643
- /** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
644
- * run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
645
- 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
- adopting = new Map();
650
- /** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
651
- remoteAllow;
652
- clock = new ChangeClock();
653
- cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
654
- app = fileURLToPath(new URL("./app.js", import.meta.url));
655
- closing = false;
656
- /** Set once `close` is done: the store is closed, so nothing settles after it. */
657
- closed = false;
658
- /** Runs past the cap's check whose process is not started yet. */
659
- starting = 0;
660
- /** The memory the starts counted in `starting` reserve, in MiB. */
661
- startingMib = 0;
662
- /** This host's memory, out of which each live run reserves what its harness takes (host.ts), beside `maxRuns`. */
663
- memory = hostMemory();
664
- /** The start sweep of the boxes runs left: once, before any run opens a box (sweepOnce). */
665
- swept;
666
- /** The runs' learning (learning-run.ts): a step this file calls as a run starts, ends, settles, opens again and is
667
- * recovered, handed what it moves of a run. */
668
- learning;
669
- /** When this server took the data root (one server a root): a run started since is its own, never one to recover. */
670
- bootedAt = new Date().toISOString();
671
- constructor(options) {
672
- this.options = options;
673
- this.learning = new LearningRuns(options, {
674
- held: (id) => this.runs.get(id),
675
- get: (id) => this.get(id),
676
- live: (run) => this.live(run),
677
- toLiveDoor: (run, path, body, turnOrigin) => this.toLiveDoor(run, path, body, turnOrigin),
678
- toDoor: (run, path, body) => this.toDoor(run, path, body),
679
- abortTurn: (run) => this.abortTurn(run),
680
- terminate: (run) => this.terminate(run),
681
- mark: (run) => this.mark(run),
682
- show: (run) => this.show(run),
683
- save: (run) => this.saveMeta(run),
684
- costOf,
685
- fauxEnv: () => this.fauxEnv(),
686
- });
687
- }
688
- /** A test's seam (startServe's `beforeAbort`): awaited by a stop between its mark and its abort, so a test can hold a
689
- * stop in flight there. */
690
- beforeAbort;
691
- /** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
692
- * launch, so a test can hold a reopen there. */
693
- beforeReopenLaunch;
694
- /** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
695
- onRunLoad;
696
- /** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
697
- beforeSubmit;
698
- /** A test's seam (startServe's `beforeMetaSave`): awaited before a run's serve.json is written; one that throws fails
699
- * the write, as a full disk would. */
700
- beforeMetaSave;
701
- /** A test's seam (startServe's `messageOrigin`): the origin a message sent through the messages route carries. */
702
- messageOrigin;
703
- get store() {
704
- return this.options.agents.store;
705
- }
706
- // ---- reading --------------------------------------------------------------------------------------------------------
707
- /** Run `id` when this process holds it, never read from disk. */
708
- held(id) {
709
- return this.runs.get(id);
710
- }
711
- /** Run `id`, read from the agent store the first time this process sees it. */
712
- async get(id) {
713
- const known = this.runs.get(id);
714
- if (known)
715
- return known;
716
- const row = await this.options.agents.request(() => this.store.readRun(id));
717
- return row ? this.adopt(row) : null;
718
- }
719
- /** One Run per run id, however many requests ask for it at once. */
720
- adopt(row) {
721
- const known = this.runs.get(row.id);
722
- if (known)
723
- return Promise.resolve(known);
724
- let pending = this.adopting.get(row.id);
725
- if (!pending) {
726
- pending = this.load(row).finally(() => this.adopting.delete(row.id));
727
- this.adopting.set(row.id, pending);
728
- }
729
- return pending;
730
- }
731
- async load(row) {
732
- this.onRunLoad?.(row.id);
733
- const dir = join(this.options.agents.dir, "runs", row.id);
734
- const stored = (await readJson(join(dir, RUN_META)));
735
- const trigger = triggerOf(stored);
736
- const meta = {
737
- title: typeof stored?.title === "string" ? stored.title : "",
738
- created_at: typeof stored?.created_at === "string" ? stored.created_at : row.startedAt,
739
- ...(isObject(stored?.input) ? { input: stored.input } : {}),
740
- ...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
741
- ...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
742
- // Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
743
- ...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
744
- ...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
745
- ...(stored?.error ? { error: stored.error } : {}),
746
- ...(stored && "output" in stored ? { output: stored.output } : {}),
747
- ...(isObject(stored?.review) ? { review: stored.review } : {}),
748
- ...(typeof stored?.stopped_at === "string" ? { stopped_at: stored.stopped_at } : {}),
749
- ...(typeof stored?.stopped_after === "number" ? { stopped_after: stored.stopped_after } : {}),
750
- ...(isObject(stored?.launch_thinking) ? { launch_thinking: stored.launch_thinking } : {}),
751
- ...(isObject(stored?.tool_plane) ? { tool_plane: stored.tool_plane } : {}),
752
- ...(stored?.place ? { place: storedPlace(stored.place) } : {}),
753
- ...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
754
- ...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
755
- ...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
756
- ...(trigger ? { trigger } : {}),
757
- };
758
- // A turn's origin a server before this one set is not known to be the turn running now: it goes.
759
- await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
760
- // 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).
762
- if (stored)
763
- await this.learning.onLoad(row, dir, meta, () => writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`));
764
- const known = await this.options.agents.revision(row.agent, row.revision);
765
- const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
766
- this.runs.set(row.id, run);
767
- run.launching = existsSync(join(dir, RUN_LAUNCHING));
768
- run.notSetUp = row.state === "running" && !isObject(stored?.input);
769
- const record = await this.record(run);
770
- // 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
- if (row.state !== "running")
772
- 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))
775
- await this.storeWhenFree(run);
776
- if (row.state !== "running") {
777
- run.endedAt = row.endedAt;
778
- // An ended run the store kept no cost for has an unknown cost, never $0.
779
- run.costUsd = row.costUsd ?? null;
780
- // A workflow run's decisions' cost too: an unknown one keeps the run's unknown after a restart. Unread, it is unknown.
781
- if (run.kind === "workflow")
782
- await this.readDecisionCost(run).catch(() => void (run.decisionCost = null));
783
- if (row.importedFrom)
784
- run.imported = row.importedFrom;
785
- if (run.outcome === "failed")
786
- run.error = errorOfRow(row, meta);
787
- run.settled = true;
788
- }
789
- else {
790
- // A cancel a server took and could not carry back before it went: its mark is written first (cancel()), so it is
791
- // the run's end, as it was from its 202 on, whatever the turn it cut reads.
792
- if (run.kind === "agentic" && existsSync(join(dir, RUN_CANCELLED))) {
793
- run.cancel = true;
794
- run.finishing = "cancelled";
795
- }
796
- const adopted = record && this.doorOf(record) ? record : null;
797
- if (adopted) {
798
- // A server that died between saving a stop and its abort reaching the run leaves the turn working.
799
- run.finishStop = run.meta.stopped_at !== undefined || run.meta.stopped_after !== undefined;
800
- this.adoptProcess(run, adopted);
801
- // Its cancel's SIGTERM may never have gone: it is let go now, its turn aborted first.
802
- if (run.cancel)
803
- void this.abortTurn(run).then(() => this.terminate(run));
804
- }
805
- // One a server left in its end-of-run turn finishes with its job's outcome, and its turn, when its process lives,
806
- // is asked again (learning-run.ts).
807
- this.learning.onAdopt(run, adopted !== null);
808
- }
809
- this.refresh(run);
810
- return run;
811
- }
812
- blank(row, dir, meta, version, harness, tooling, revision) {
813
- return {
814
- id: row.id, agentId: row.agent, kind: row.kind, revision: row.revision, version, dir, meta, log: new RowLog(this.clock), rows: [], harness,
815
- working: false, submitted: 0, users: new Set(), live: new Set(), cancel: false, relaunches: 0, settled: false, settles: 0, updatedAt: meta.created_at, turns: new Turns(),
816
- ...(tooling ? { tooling } : {}),
817
- };
818
- }
819
- /** Writes the run's serve.json as it is when its turn comes; then tells learning what it now holds (the ledger's line
820
- * once the run's learning ended). */
821
- /** Writes the run's serve.json, after any write already under way: `meta`, a copy its caller publishes to run.meta
822
- * only once this resolves (a raise, takeRaise), else run.meta, each as it stands when the write starts. */
823
- saveMeta(run, meta) {
824
- run.saving = (run.saving ?? Promise.resolve()).catch(() => undefined).then(async () => {
825
- // A copy is built as its write starts, from run.meta as it stands then.
826
- const written = meta ? meta() : run.meta;
827
- const { learning } = written;
828
- await this.beforeMetaSave?.(run.id, written);
829
- await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(written)}\n`);
830
- await this.learning.onSaved(run, learning);
831
- });
832
- return run.saving;
833
- }
834
- record(run) {
835
- return readJson(join(run.dir, "run.json"));
836
- }
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);
848
- return url?.protocol === "http:" && isLoopback(url.hostname) ? url.origin : undefined;
849
- }
850
- storeFile(run) {
851
- return join(run.dir, "store", "run.sqlite");
852
- }
853
- /** The run's rows from its store, opened read-only; only once its claim is released. An agentic run's rows are its
854
- * root conversation's; a workflow run's are its model nodes'. `atEnd`: a settle's read, which reads every
855
- * conversation (a workflow's nodes, a harness's session) once and counts the run's metrics from all of them. */
856
- async readStore(run, atEnd = false) {
857
- const file = this.storeFile(run);
858
- if (!(await stat(file).catch(() => null)))
859
- return;
860
- const { DatabaseSync } = await import("node:sqlite");
861
- const read = [];
862
- const submissions = [];
863
- const db = new DatabaseSync(file, { readOnly: true });
864
- try {
865
- const rows = run.kind === "workflow" || atEnd
866
- ? db.prepare("SELECT conversation_id, record FROM entries ORDER BY id").iterate()
867
- : db.prepare("SELECT conversation_id, record FROM entries WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").iterate();
868
- for (const row of rows)
869
- read.push({ conversation: Number(row.conversation_id), entry: JSON.parse(String(row.record)) });
870
- // pi's settlements of the person's messages, the root's (turns.ts): its turns' ends.
871
- if (run.kind === "agentic") {
872
- const inputs = db.prepare("SELECT record FROM submissions WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").all();
873
- for (const row of inputs)
874
- submissions.push(JSON.parse(String(row.record)));
875
- }
876
- }
877
- finally {
878
- db.close();
879
- }
880
- const root = read.reduce((min, r) => Math.min(min, r.conversation), Infinity);
881
- const entries = read.flatMap((r) => (run.kind === "workflow" || r.conversation === root ? [r.entry] : []));
882
- if (run.kind === "workflow") {
883
- const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
884
- // Decisions it cannot read add no rows, and leave the served usage row's total unknown, as the run's cost read
885
- // does (readDecisionCost): never its model nodes' total alone.
886
- try {
887
- run.decisions = durableDecisions(file);
888
- }
889
- catch {
890
- run.decisions = null;
891
- }
892
- run.llmRead = llmAnswers(await readNodeLog(run.dir)).length;
893
- }
894
- // Its decision requests count with its model requests: each receipt's tokens, or unmetered without them.
895
- if (atEnd)
896
- run.metrics = runMetricsWithDecisions(read.map((r) => r.entry), run.kind === "workflow" ? (run.decisions ?? []) : []);
897
- run.working = false;
898
- noteTurns(run, entries, submissions);
899
- noteApprovals(run, entries);
900
- this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
901
- }
902
- /** New rows in: into the log, then the run's status, then whatever the status asks for. */
903
- /** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
904
- 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);
906
- // Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
907
- // messages waiting, so a count of rows would leave the run working forever.
908
- const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
909
- for (const row of arrived)
910
- run.users.add(row.id);
911
- run.submitted = Math.max(0, run.submitted - arrived.length);
912
- run.keep = keep;
913
- this.show(run);
914
- this.refresh(run);
915
- }
916
- /** The approval rows as the run's answers say them now (a stop or a cancel withdraws a call, an answer settles one),
917
- * shown at once: an answer takes no new rows. */
918
- restate(run) {
919
- if (!run.approvals?.size)
920
- return;
921
- run.rows = withApprovals(run.rows.filter((row) => row.kind !== APPROVAL_ROW), run, this.redactor(run));
922
- this.show(run);
923
- }
924
- /** 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
925
- * only, never the run's own rows, which its cost and its answer are read from. */
926
- show(run) {
927
- // 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
- // 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));
930
- // 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));
932
- // A run paused at its cap says so after the refusal, as the row its status reads.
933
- 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))
936
- run.updatedAt = new Date().toISOString();
937
- }
938
- /** A live process: the child this server started, or one an earlier server started that still serves the run. */
939
- live(run) {
940
- return Boolean(run.child || run.orphan);
941
- }
942
- /** How an agentic run ends: over its cap, or as the turn of the person's newest message ended (turns.ts), once every
943
- * message the run took has had its turn. Undefined while one is open, or when the run stopped, waits, or its turn
944
- * ended interrupted (the run then waits for the person), or while its records name no message (a live process of an
945
- * older server: the run's next process writes its turn's end as it opens). Never from the order of its rows, or from
946
- * when its door said idle. A workflow run ends when its workflow does. */
947
- decide(run) {
948
- if (run.kind === "workflow")
949
- return undefined;
950
- // A cancel ends the run cancelled, by its settle (whatever the turn it cut wrote, a cost over the cap too): nothing
951
- // ends it otherwise meanwhile, so its first terminal status is its last. The cancel has aborted the turn already.
952
- if (run.cancel)
953
- return undefined;
954
- const cap = run.meta.max_cost_usd;
955
- 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 } };
958
- if (run.submitted > 0)
959
- return undefined;
960
- if (run.turns.open > 0 || stopped(run))
961
- return undefined;
962
- // A tool call waits for a person's approval, or for its answer to be acted on: the run goes on after it.
963
- if (waitingApproval(run) || actingOn(run))
964
- return undefined;
965
- const end = run.turns.end();
966
- if (end?.status === "answered")
967
- return { outcome: "completed" };
968
- if (end?.status !== "failed")
969
- return undefined;
970
- const message = end.error ?? "The run failed.";
971
- // The cap's refusal for room pauses the run instead (pausedAt): a raise sends what was refused.
972
- if (roomRefusal(message) !== undefined)
973
- return undefined;
974
- // The cap's refusal in the run's process (cap.ts); a provider error with this exact prefix would read as one too.
975
- // Its code is `spend_cap_reached: `, or with a note after it (`spend_cap_reached (out of budget): `, cap.ts); the message is
976
- // the words after it.
977
- const capped = CAP_REFUSAL_PREFIX.exec(message);
978
- if (capped)
979
- return { outcome: "failed", error: { code: SPEND_CAP_REACHED, message: message.slice(capped[0].length), retryable: false } };
980
- // The provider's content filter stopped the answer (content-filter.ts): moderated, in words a person can act on.
981
- if (contentFiltered(message))
982
- return { outcome: "failed", error: { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false } };
983
- return { outcome: "failed", error: { code: "run_failed", message: this.errorWords(run, message) ?? message, retryable: false } };
984
- }
985
- /** A run's error as a person reads it, in its error box and on its Timeline row alike: a refused key in plain words
986
- * (plainKey), else the harness's text with no loopback address (withoutLoopback: Codex names serve's own proxy). */
987
- errorWords(run, text) {
988
- return text ? this.shown(run, this.plainKey(run, text) ?? text) : text;
989
- }
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. */
992
- servedError(run, row) {
993
- const plain = this.plainKey(run, row.text ?? undefined);
994
- if (plain) {
995
- const words = this.shown(run, plain);
996
- return { ...row, summary: words, text: words };
997
- }
998
- return { ...row, ...(row.summary ? { summary: this.shown(run, row.summary) } : {}), ...(row.text ? { text: this.shown(run, row.text) } : {}) };
999
- }
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. */
1002
- shown(run, text) {
1003
- return withoutLoopback(redacted(text, this.refusedValues(run)));
1004
- }
1005
- /** A run's answer as serve serves it: no held secret, never cut (redactedAnswer). Loopback addresses stay: an answer is
1006
- * the model's own words, and a local address there can be what the person asked about. */
1007
- servedAnswer(run, text) {
1008
- return text ? this.servedOnce(run, "answer", text, (values) => redactedAnswer(text, values)) : text;
1009
- }
1010
- /** A workflow run's output as serve serves it: each string in it as servedAnswer, its shape kept. */
1011
- servedOutput(run, output) {
1012
- return output === null ? null : this.servedOnce(run, "output", output, (values) => redactedOutput(output, values));
1013
- }
1014
- /** `redact(values)` over the values `run` holds, read once per input and held value set: a console polls a run's
1015
- * view, and an answer a run was made to write can be large. The run keeps the one it served last, of each slot; a key
1016
- * saved or deleted changes the values' digest, and the next view redacts again. */
1017
- servedOnce(run, slot, input, redact) {
1018
- const values = this.refusedValues(run);
1019
- const keys = digestOf([...values].sort());
1020
- const last = run.served?.[slot];
1021
- if (last && last.keys === keys && last.input === input)
1022
- return last.out;
1023
- const out = redact(values);
1024
- run.served = { ...run.served, [slot]: { keys, input, out } };
1025
- return out;
1026
- }
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
- /** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
1048
- * before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
1049
- * redacted()'s SHOWN, so its window holds. */
1050
- /** How a run's decision rows show a text (decision-rows.ts Shown): the run's redactor, and as many characters held back
1051
- * from a text stored cut as a held value takes in its widest form. */
1052
- decisionShown(run) {
1053
- const values = this.refusedValues(run);
1054
- return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
1055
- }
1056
- redactor(run) {
1057
- return (text) => redacted(text, this.refusedValues(run));
1058
- }
1059
- /** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
1060
- * show cut out: its process may have written a secret or its sign-in's pointer there. */
1061
- async lastLine(run) {
1062
- return this.redactor(run)(await lastLogLine(run));
1063
- }
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. */
1067
- refusedValues(run) {
1068
- return [...hostSecrets(process.env, this.options.storedKeys), ...(run.handed ?? []), this.options.token, this.options.doorToken];
1069
- }
1070
- /** 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
- * harness's route sends, by this server's settings and keys, and no secret's value. */
1072
- plainKey(run, text) {
1073
- // A workflow's nodes run on their own tiers' models, and its error row does not say which one failed: naming the
1074
- // default tier's key could name the wrong one, so its error keeps the provider's own words.
1075
- if (!text || run.kind === "workflow")
1076
- return undefined;
1077
- const env = withSecrets(process.env, "all", this.options.storedKeys);
1078
- return keyRefusal(text, runKeyOf(env, run.harness ?? run.tooling?.harness, run.tooling?.model), this.refusedValues(run));
1079
- }
1080
- /** Records the run's status as a change when it moves, and lets go of a live run that answered, failed or is over its cap. */
1081
- /** What a run paused at its cap has spent once its process is gone: its store's spend as the cap reads it (spentIn),
1082
- * read once per pause (its refusal's row). None while its process lives, nor when the store says unknown or cannot
1083
- * be read: the refusal's own figure stands then. */
1084
- spentNow(run) {
1085
- const mark = meaningful(run.rows)?.id;
1086
- if (mark === undefined || !run.capRefusal || this.live(run) || pausedAt(run) === undefined)
1087
- return undefined;
1088
- // One read per pause, and a failed read again after a while, never kept until a restart.
1089
- if (run.capSpent?.mark !== mark || (run.capSpent.usd === null && Date.now() - (run.capSpent.at ?? 0) > 30_000)) {
1090
- let usd = null;
1091
- try {
1092
- usd = spentIn(this.storeFile(run));
1093
- }
1094
- catch (error) {
1095
- warn(run.id, `its store's spend was not read (${error.message}); its refusal's figure stands`);
1096
- }
1097
- run.capSpent = { mark, usd, at: Date.now() };
1098
- }
1099
- return run.capSpent.usd ?? undefined;
1100
- }
1101
- /** The run's live process, by its pid and start ticks (processIdentity). */
1102
- liveIdentity(run) {
1103
- return processIdentity(run.child?.pid ?? run.orphan);
1104
- }
1105
- refresh(run) {
1106
- this.mark(run);
1107
- // A run whose cap was raised at its pause goes on once the process paused there is gone (resumeRaised): with no
1108
- // process, or one another launch started (a server stopped between that launch and its message: the door takes the
1109
- // message once, by its id). Never while one waits to be tried again.
1110
- const next = continuationOf(run);
1111
- const letting = next !== undefined && next.paused !== undefined && this.live(run) && this.liveIdentity(run) === next.paused;
1112
- if (next && run.resuming === undefined && !this.closing && !run.cancel && !run.finishing && !run.outcome && !letting)
1113
- void this.resumeRaised(run, next);
1114
- if (!this.live(run) || run.finishing || run.outcome)
1115
- return;
1116
- const end = this.decide(run);
1117
- // Paused at its cap, its process is let go: it waits without one, holding no place, until its cap is raised. Once
1118
- // per pause (its refusal's row): SIGTERM drains and releases it, and the settle that follows leaves it waiting. A
1119
- // raised one's paused process is let go too (a server started again finds it so).
1120
- if (!end && (pausedAt(run) !== undefined || letting) && run.parked !== waitMark(run)) {
1121
- run.parked = waitMark(run);
1122
- this.terminate(run);
1123
- }
1124
- if (!end)
1125
- return;
1126
- if (end.error)
1127
- run.error = end.error;
1128
- // A run that learns is not let go yet: its end-of-run turn is asked first, unless learning skips it (learning-run.ts).
1129
- if (this.learning.beforeFinish(run, end))
1130
- return;
1131
- this.finish(run, end.outcome, end.abort);
1132
- }
1133
- /** The test hooks startServe's options name, as a run's process and this server's own calls get them. */
1134
- fauxEnv() {
1135
- return { ...this.options.fauxEnv };
1136
- }
1137
- /** Let go of a live run with `outcome`: SIGTERM, after aborting its turn when it is still working. */
1138
- finish(run, outcome, abortFirst = false) {
1139
- run.finishing = outcome;
1140
- run.endedAt = new Date().toISOString();
1141
- this.mark(run);
1142
- void (abortFirst ? this.abortTurn(run) : Promise.resolve()).then(() => this.terminate(run));
1143
- }
1144
- /** SIGTERM to the run's process: it drains, releases the run and exits. */
1145
- terminate(run) {
1146
- 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)
1156
- return;
1157
- run.orphan = pid;
1158
- this.reportedBack(run);
1159
- this.connect(run);
1160
- let releasedAt;
1161
- let unreadable = 0;
1162
- 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)
1178
- 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`);
1180
- }
1181
- clearInterval(timer);
1182
- run.orphan = undefined;
1183
- void this.settle(run, null, !alive(pid) && !RELEASED.has(String(now?.status)));
1184
- });
1185
- }, 500);
1186
- timer.unref();
1187
- }
1188
- /** At start: every run the store says is running is read, supervised when its process lives, carried back when it
1189
- * already ended, and opened again when its process went before it ended. */
1190
- /** Every run's box let go that nothing owns, and every run cgroup no record names: once, before any run of this server
1191
- * starts, opens again or relaunches, so a box or cgroup being made is never swept away. */
1192
- sweepOnce() {
1193
- const { box, runBoxes, remoteBoxes, vmBoxes } = this.options;
1194
- if (!box && !runBoxes && !remoteBoxes && !vmBoxes)
1195
- return Promise.resolve();
1196
- this.swept ??= (async () => {
1197
- const rows = await this.options.agents.request(() => this.store.listRuns());
1198
- // The boxes of sandbox runs, by their label: one whose run has ended, or is archived, is destroyed. A failure only
1199
- // warns: the next start sweeps again, and a box's lifetime bounds it.
1200
- const ended = new Set(rows.filter((row) => row.state !== "running" || row.archivedAt).map((row) => row.id));
1201
- if (runBoxes) {
1202
- await sweepRunBoxes(runBoxes, (id) => ended.has(id), boxContext()).catch((error) => warn("-", `its start's sweep of run boxes failed (${error.message}); the next start sweeps again`));
1203
- }
1204
- // 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
- // 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);
1207
- const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
1208
- warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
1209
- await this.keepBox(id, boxId, daytona);
1210
- return false;
1211
- });
1212
- if (vmBoxes) {
1213
- await sweepRunBoxes(vmBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(vmBoxes, false)).catch((error) => warn("-", `its start's sweep of Modal sandboxes failed (${error.message}); the next start sweeps again`));
1214
- }
1215
- if (remoteBoxes) {
1216
- // A box kept at a run's end that Daytona stopped once idle is woken first, so this sweep pulls it like the rest.
1217
- const api = this.options.remoteApi;
1218
- if (api)
1219
- await wakeBoxes(api, (id) => ended.has(id)).catch((error) => warn("-", `the stopped boxes of ended runs were not woken (${error.message}); the next start tries again`));
1220
- await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(remoteBoxes, true)).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
1221
- }
1222
- if (!box)
1223
- 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) })));
1225
- for (const [id, how] of Object.entries(settled))
1226
- if (how === "quarantined")
1227
- warn(id, "its box could not be emptied; it is quarantined, and tried again at each start");
1228
- })().catch((error) => {
1229
- // A sweep that failed is not kept: the next start, open or relaunch sweeps again, so one transient error never
1230
- // holds every run back until the server restarts. Nothing of this server's runs has started a box before it.
1231
- this.swept = undefined;
1232
- throw error;
1233
- });
1234
- return this.swept;
1235
- }
1236
- /** A sandbox run's box (run-box.ts), destroyed by its label: at every settle, a cancel included, and at archive. A
1237
- * remote box's work/ is pulled first, and its box goes only once that pull brought it back whole (or there is no box).
1238
- * A copy that stopped for good (an archive the extractor cannot read, a limit it cannot pass) keeps the box, said in
1239
- * the log, its lifetime bounding it, and the run ends. Any other failure at a run's end (`ending`) throws
1240
- * PullPending, and the end is tried again; at an archive it only warns, the box kept for the run's end or the next
1241
- * start's sweep. A destroy that fails only warns: the next start's sweep tries again, and the box's lifetime bounds it. */
1242
- async dropBox(run, ending = false) {
1243
- const place = run.meta.place;
1244
- if (place?.mode !== "sandbox")
1245
- return;
1246
- // The relay's hold on the run's programs (box-relay-vm.ts) ends with the run, whatever becomes of its box: one kept
1247
- // for a later pull, or one whose destroy failed, still lets them go, and their output with them.
1248
- this.options.vmRelay?.drop(run.id);
1249
- const remote = remotePlace(place);
1250
- const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
1251
- if (!boxes)
1252
- 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
- }
1266
- if (remote) {
1267
- try {
1268
- await this.pullBox(run, true);
1269
- }
1270
- catch (error) {
1271
- if (error instanceof PullIncomplete && error.lasting) {
1272
- await this.keepBox(run.id, error.box, place.box === "daytona");
1273
- return warn(run.id, `its box is kept, not destroyed: ${error.message}; what came back is in its files, and the box stops after ${KEPT_AUTOSTOP_MINUTES} idle minutes, its files kept for the next start's pull`);
1274
- }
1275
- const why = `its box's last pull failed (${error.message})`;
1276
- if (ending)
1277
- throw new PullPending(why);
1278
- return warn(run.id, `${why}; its box is kept for its end`);
1279
- }
1280
- }
1281
- try {
1282
- await destroyRunBoxes(boxes, run.id, boxContext());
1283
- // 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);
1285
- }
1286
- catch (error) {
1287
- warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
1288
- }
1289
- }
1290
- /** A remote box kept because its copy back is not whole: said in the log, and set to stop once idle, so it costs its
1291
- * disk alone until the next start's pull (which wakes it) or its lifetime. */
1292
- async keepBox(runId, boxId, daytona = true) {
1293
- this.options.log?.("box_kept", { run: runId, box: boxId, reason: "pull_incomplete" });
1294
- // A VM box keeps its lifetime alone: the provider has no idle stop to set.
1295
- const api = daytona ? this.options.remoteApi : undefined;
1296
- if (api)
1297
- await keepWhenIdle(api, boxId).catch((error) => warn(runId, `its kept box was not kept from deletion or set to stop when idle (${error.message})`));
1298
- }
1299
- /** What wakes run `runId`'s remote box when Daytona stopped or paused it (a class that pauses when idle, while the run
1300
- * waited for a person): how many it woke. */
1301
- wakeOf(runId, place) {
1302
- // Only Daytona stops or pauses a box: a VM box that ended is made again.
1303
- const api = place?.mode === "sandbox" && place.box !== "daytona" ? undefined : this.options.remoteApi;
1304
- return api && (() => wakeBoxes(api, (id) => id === runId));
1305
- }
1306
- /** Pulls run `run`'s remote box into its work/, after any pull already running: at a turn's end in the background (a
1307
- * failure warns, and the next pull brings it), or awaited (`strict`: a failure throws). */
1308
- pullBox(run, strict = false) {
1309
- const place = run.meta.place;
1310
- const boxes = place && remotePlace(place) ? this.remoteOf(place) : undefined;
1311
- if (!boxes || !place)
1312
- return Promise.resolve();
1313
- // After any pull already running, and after the box's making and seed when one is under way.
1314
- const pull = Promise.all([run.pulling, run.boxing?.catch(() => undefined)]).then(async () => {
1315
- const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id, place));
1316
- if (pulled)
1317
- this.options.log?.("box_pulled", { run: run.id, changed: pulled.changed, files: pulled.files, bytes: pulled.bytes, removed: pulled.removed });
1318
- });
1319
- const settled = pull.catch((error) => {
1320
- if (!strict)
1321
- warn(run.id, `its box's work/ was not pulled at its turn's end (${error.message}); the next pull brings it`);
1322
- });
1323
- run.pulling = settled;
1324
- void settled.finally(() => {
1325
- if (run.pulling === settled)
1326
- run.pulling = undefined;
1327
- });
1328
- return strict ? pull : settled;
1329
- }
1330
- /** Waits for the pull run `id`'s turn's end began, if any, up to PULL_WAIT_MS: its files then show what its box wrote. */
1331
- async pulled(id) {
1332
- const pulling = this.runs.get(id)?.pulling;
1333
- if (!pulling)
1334
- return;
1335
- let timer;
1336
- await Promise.race([pulling, new Promise((resolve) => (timer = setTimeout(resolve, PULL_WAIT_MS)))]);
1337
- clearTimeout(timer);
1338
- }
1339
- /** Whether run `id` is one this server holds in a remote box and has not ended: the relay serves no other. */
1340
- servesBox(id) {
1341
- const run = this.runs.get(id);
1342
- return Boolean(run && !run.outcome && run.meta.place && remotePlace(run.meta.place) && this.remoteOf(run.meta.place));
1343
- }
1344
- /** The server's provider of a remote place's boxes: the VM box's, or Daytona's. */
1345
- remoteOf(place) {
1346
- return place.mode === "sandbox" && place.box === VM_PROVIDER.id ? this.options.vmBoxes : this.options.remoteBoxes;
1347
- }
1348
- /** Run `id`'s remote box, found or made and seeded: what its process asks the relay for at its first tool call. */
1349
- ensureBox(id) {
1350
- const run = this.runs.get(id);
1351
- const place = run?.meta.place;
1352
- const boxes = place && this.remoteOf(place);
1353
- if (!run || !place || !boxes || !this.servesBox(id))
1354
- return Promise.reject(new Error(`no run ${id} of this server is in a remote box`));
1355
- // The VM box has no network (its provider's host list cannot be read back), and takes the box limits.
1356
- const vm = place.mode === "sandbox" && place.box === VM_PROVIDER.id;
1357
- // After any pull of this run's box, so a seed never meets a pull.
1358
- run.boxing ??= (run.pulling ?? Promise.resolve())
1359
- .then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), vm ? { allow: "none", ...(this.options.vmLimits ? { limits: this.options.vmLimits } : {}) } : {
1360
- wake: this.wakeOf(run.id, place),
1361
- allow: (this.remoteAllow ??= this.options.boxAllow ?? "none"),
1362
- onNoList: (code, message) => {
1363
- if (this.remoteAllow === "none")
1364
- return;
1365
- this.remoteAllow = "none";
1366
- this.options.onNoBoxList?.(code, message);
1367
- },
1368
- }))
1369
- .finally(() => void (run.boxing = undefined));
1370
- return run.boxing;
1371
- }
1372
- /** The run's box let go (archive, or its process gone after an archive): reaped by the box's own count. */
1373
- async teardown(run) {
1374
- const box = this.options.box;
1375
- if (!box || this.live(run))
1376
- return;
1377
- // Never in the way of the run's own end or an archive already saved: a box that could not be let go (its cgroup not
1378
- // removed, its record not marked) is said, and its unmarked record is tried again by the next start's sweep.
1379
- try {
1380
- if ((await settleBox(box.host, box.quarantine, run.id, run.dir)) === "quarantined")
1381
- warn(run.id, "its box could not be emptied; it is quarantined, and tried again at each start");
1382
- }
1383
- catch (error) {
1384
- warn(run.id, `its box was not let go (${error.message}); the next start tries again`);
1385
- }
1386
- }
1387
- /** After an archive (a run's, or an agent's, which archives its runs): the box of every run now archived is let go,
1388
- * now when its process is gone, else when it exits. */
1389
- async archived() {
1390
- if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes && !this.options.vmBoxes)
1391
- return;
1392
- for (const row of await this.options.agents.request(() => this.store.listRuns())) {
1393
- if (!row.archivedAt)
1394
- continue;
1395
- // A run's box needs only the runs this server holds: one it has not read has ended, or was swept at its start.
1396
- const run = this.options.box ? await this.get(row.id) : this.runs.get(row.id);
1397
- if (!run)
1398
- continue;
1399
- // A run's box goes at its archive, its process live or not (an ended run's went at its end): an archived run takes
1400
- // no message, and a call it still makes gets a fresh box, which its end or the next start's sweep destroys.
1401
- if (!run.outcome)
1402
- await this.dropBox(run);
1403
- await this.teardown(run);
1404
- }
1405
- }
1406
- async recover() {
1407
- // The learning a server left between steps, picked up once every running run is read (learning-run.ts).
1408
- const recoverLearning = this.learning.recover();
1409
- await this.sweepOnce();
1410
- // Only what an earlier server left: a store slow to answer here must not hand back a run a create is setting up now.
1411
- const rows = (await this.options.agents.request(() => this.store.listRuns())).filter((row) => row.startedAt < this.bootedAt);
1412
- for (const row of rows) {
1413
- if (row.state !== "running" || row.importedFrom)
1414
- continue;
1415
- const run = await this.adopt(row).catch((error) => (warn(row.id, `not recovered: ${error.message}; the next start tries again`), null));
1416
- if (run && !this.live(run) && !run.outcome)
1417
- await this.settle(run, null, false);
1418
- }
1419
- await recoverLearning(rows);
1420
- }
1421
- /** The run's status, state and whether its rows are all in, as one more change of its log when any of them moves. A wait
1422
- * is told each time it is seen: webhooks.ts queues each wait once, whichever server sees it first. */
1423
- mark(run) {
1424
- const { status, state } = statusOf(run);
1425
- // A turn's end, or a run first read waiting (a start that finds it so, whose last turn's pull may not have landed):
1426
- // what its remote box changed is pulled into work/ now, and a read of the files waits for it.
1427
- const waiting = status === "input_required";
1428
- if (waiting && run.waited !== true)
1429
- this.pullBox(run);
1430
- run.waited = waiting;
1431
- if (run.log.setState(`${status}/${state}/${run.settled}`))
1432
- run.updatedAt = new Date().toISOString();
1433
- // What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
1434
- 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" });
1436
- }
1437
- /** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
1438
- * has (settle, persistLater, reopen). What it already queued it queues no more. */
1439
- notice(run, event, marker, pending) {
1440
- if (!this.options.notify || !marker)
1441
- return undefined;
1442
- try {
1443
- return this.options.notify(event, { run_id: run.id, agent_id: run.agentId, status: statusOf(run).status, title: run.meta.title, ...(pending ? { pending } : {}) }, marker);
1444
- }
1445
- catch (error) {
1446
- warn(run.id, `its notice was not queued: ${error.message}`);
1447
- return undefined;
1448
- }
1449
- }
1450
- // ---- the door -------------------------------------------------------------------------------------------------------
1451
- /** A call to run `run`'s door: with its own door token, or, for a process an older server started, the server-wide one. */
1452
- headers(run, json = false) {
1453
- run.doorToken ??= runDoorToken(run.dir);
1454
- return { authorization: `Bearer ${run.doorToken ?? this.options.doorToken}`, ...(json ? { "content-type": "application/json" } : {}) };
1455
- }
1456
- /** Run `id`'s own door token, the one its calls to the box relay carry; none for a run it does not hold or that has none. */
1457
- relayToken(id) {
1458
- const run = this.runs.get(id);
1459
- if (!run)
1460
- return undefined;
1461
- run.doorToken ??= runDoorToken(run.dir);
1462
- return run.doorToken;
1463
- }
1464
- /** Follow the door's events into an agentic run's rows, again after each drop while the process lives. A workflow
1465
- * run is only watched: the door's events are a root conversation's, and a workflow run has none. */
1466
- connect(run) {
1467
- if (run.feed)
1468
- return;
1469
- const abort = new AbortController();
1470
- run.feed = abort;
1471
- void (async () => {
1472
- while (!abort.signal.aborted) {
1473
- const door = this.doorOf(await this.record(run));
1474
- if (door)
1475
- this.reportedBack(run);
1476
- if (door && run.kind === "workflow") {
1477
- if (!run.working && !run.outcome) {
1478
- run.working = true;
1479
- this.refresh(run);
1480
- }
1481
- }
1482
- else if (door)
1483
- await this.follow(run, door, abort.signal).catch(() => undefined);
1484
- if (abort.signal.aborted || (!this.live(run) && !this.doorOf(await this.record(run))))
1485
- break;
1486
- await sleep(run.kind === "workflow" ? 500 : 200);
1487
- }
1488
- if (run.feed === abort)
1489
- run.feed = undefined;
1490
- })();
1491
- }
1492
- async follow(run, door, signal) {
1493
- // 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
- const reducer = timelineReducer({ path: rowPaths(run.dir), redact: this.redactor(run), redactLive: (text) => redactedLive(text, this.refusedValues(run)) });
1495
- // `inputs=1`: the snapshot carries pi's newest input submissions, the settlements its turns end on (turns.ts).
1496
- const up = await fetch(new URL(`/events?inputs=1&skip=${encodeURIComponent(REFLECT_REQUEST)}`, door), { signal, headers: { ...this.headers(run), accept: "text/event-stream" } });
1497
- if (!up.ok || !up.body)
1498
- return;
1499
- const decoder = new TextDecoder();
1500
- let buffer = "";
1501
- for await (const chunk of up.body) {
1502
- buffer += decoder.decode(chunk, { stream: true });
1503
- for (let end; (end = buffer.indexOf("\n\n")) >= 0;) {
1504
- const frame = buffer.slice(0, end);
1505
- buffer = buffer.slice(end + 2);
1506
- let event = "message";
1507
- const data = [];
1508
- for (const line of frame.split("\n")) {
1509
- if (line.startsWith("event:"))
1510
- event = line.slice(6).trim();
1511
- else if (line.startsWith("data:"))
1512
- data.push(line.slice(5).replace(/^ /, ""));
1513
- }
1514
- let value;
1515
- try {
1516
- value = JSON.parse(data.join("\n"));
1517
- }
1518
- catch {
1519
- continue;
1520
- }
1521
- if (event === "end")
1522
- return;
1523
- const events = event === "snapshot" ? [value] : event === "events" && Array.isArray(value) ? value : [];
1524
- if (event === "snapshot")
1525
- run.working = Boolean(value.run);
1526
- for (const e of events)
1527
- if (e.type === "run_start" || e.type === "run_end")
1528
- run.working = e.type === "run_start";
1529
- // The settlements of pi's turns: each a submission event in the commit of its turn's last entry, and the door's
1530
- // snapshot of them on a (re)connect (pi-durable-disk's `inputs`), read as their whole state.
1531
- const submissions = events.flatMap((e) => (e.type === "submission" && e.record !== undefined ? [e.record] : []));
1532
- const inputs = events.find((e) => e.type === "snapshot" && Array.isArray(e.inputs))?.inputs;
1533
- const entries = events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : []));
1534
- noteTurns(run, entries, submissions, inputs);
1535
- noteApprovals(run, entries);
1536
- const redact = this.redactor(run);
1537
- 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)));
1538
- // 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))
1541
- reducer.idle();
1542
- // A snapshot rebuilds from the conversation's current view: after a compaction it holds fewer of the rows
1543
- // already shown, which stay; only live rows go when they end.
1544
- const rows = reducer.rows();
1545
- this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive));
1546
- if (event === "snapshot" && run.finishStop) {
1547
- run.finishStop = false;
1548
- if (run.working && stopped(run) && run.submitted === 0) {
1549
- // The run reads stopped already, so a message sent now would go in behind the turn this abort ends, and be
1550
- // withdrawn with it: it waits for the abort, as for a stop in flight.
1551
- run.stopping = true;
1552
- void this.abortTurn(run).catch(() => undefined).finally(() => (run.stopping = undefined));
1553
- }
1554
- }
1555
- }
1556
- }
1557
- }
1558
- /** 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;
1561
- // A run brought up by a request (a message before the start's recovery reached it) waits for the sweep as well.
1562
- await this.sweepOnce();
1563
- await this.pinNeeds(run);
1564
- // And for its files, which its start copies before it launches it: within the time left.
1565
- const copying = run.preparing;
1566
- if (copying) {
1567
- await untilDeadline(copying, deadline);
1568
- if (run.preparing === copying)
1569
- throw new ApiError("unavailable", "the run's files are still being copied into its workspace", { retry_after_ms: 1000 }, { "retry-after": "1" });
1570
- }
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.
1574
- if (run.outcome || run.finishing || run.cancel)
1575
- throw this.finished(run);
1576
- const door = this.doorOf(record);
1577
- if (door)
1578
- return door;
1579
- if (!this.live(run)) {
1580
- // A process that just went is being settled: its run may be over, so nothing starts it again before that.
1581
- if (run.settles > 0) {
1582
- // Within the time left: a settle waiting on a busy store must not hold this caller past its deadline.
1583
- await untilDeadline(run.settling, deadline);
1584
- if (Date.now() > deadline)
1585
- throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
1586
- continue;
1587
- }
1588
- if (launched)
1589
- 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));
1592
- // A run already going is never refused a place, but one whose harness this host's memory never holds (after a
1593
- // restart on a smaller one) is not started: said, never tried.
1594
- const never = fresh ? undefined : neverFits(run.harness, this.memory);
1595
- if (never)
1596
- 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.
1598
- if (!fresh) {
1599
- await this.pinSignIn(run);
1600
- if (run.outcome || run.finishing || run.cancel || this.live(run))
1601
- continue;
1602
- this.launch(run);
1603
- launched = true;
1604
- }
1605
- }
1606
- if (Date.now() > deadline)
1607
- throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
1608
- }
1609
- }
1610
- /** The refusal of a message to an imported run: it was run elsewhere, and is kept as history. */
1611
- importedRefusal(run) {
1612
- const source = run.imported?.source;
1613
- return new ApiError("not_continuable", `This run was imported from ${source}: it is history, not run here, so it takes no message. Start a new run of the agent.`, {
1614
- details: { reason: "imported", imported_from: source },
1615
- next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
1616
- });
1617
- }
1618
- finished(run) {
1619
- const status = run.cancel ? "cancelled" : statusOf(run).status;
1620
- const why = status === "completed" ? "This run is finished." : `This run ${status === "failed" ? "failed" : "was cancelled"}.`;
1621
- return new ApiError("not_continuable", `${why} Start a new run of the agent.`, {
1622
- next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
1623
- });
1624
- }
1625
- /** Abort an agentic run's turn running now through the door, when there is one; never wakes the run. A workflow run
1626
- * has no turn: the door's abort would give it a root conversation. */
1627
- async abortTurn(run) {
1628
- if (run.kind === "workflow")
1629
- return;
1630
- const door = this.doorOf(await this.record(run));
1631
- if (door)
1632
- await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
1633
- }
1634
- /** One request to the door of a run whose process lives, never waking it (toDoor wakes no run that is finishing): again
1635
- * while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), kept in
1636
- * the run's directory before it goes, where the tool gate reads it (tool-gate.ts NOTE_ONLY_TEXT); a person's message
1637
- * removes it. */
1638
- async toLiveDoor(run, path, body, turnOrigin) {
1639
- if (turnOrigin)
1640
- await (run.originWrite = writeWhole(join(run.dir, TURN_ORIGIN_FILE), `${JSON.stringify({ origin: turnOrigin })}\n`));
1641
- for (const deadline = Date.now() + 30_000;; await sleep(200)) {
1642
- if (!this.live(run) || run.cancel)
1643
- throw new Error("the run's process is gone");
1644
- const door = this.doorOf(await this.record(run));
1645
- 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
- const data = res ? (await res.json().catch(() => null)) : null;
1647
- if (res && res.status < 400)
1648
- return data;
1649
- if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
1650
- throw new Error(`the run's door answered ${res.status}`);
1651
- if (Date.now() > deadline)
1652
- throw new Error("the run's door did not answer");
1653
- }
1654
- }
1655
- async toDoor(run, path, body, readyMs) {
1656
- const deadline = Date.now() + 30_000;
1657
- for (;;) {
1658
- const door = await this.ensureLive(run, readyMs);
1659
- const res = await fetch(new URL(path, door), {
1660
- method: body === undefined ? "GET" : "POST",
1661
- headers: this.headers(run, body !== undefined),
1662
- body: body === undefined ? undefined : JSON.stringify(body),
1663
- signal: AbortSignal.timeout(15_000),
1664
- }).catch(() => null);
1665
- const data = res ? (await res.json().catch(() => null)) : null;
1666
- if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
1667
- return { status: res.status, body: data };
1668
- if (Date.now() > deadline)
1669
- throw new ApiError("unavailable", "the run's door did not answer", { retry_after_ms: 1000 }, { "retry-after": "1" });
1670
- await sleep(200);
1671
- }
1672
- }
1673
- /** Reads what decides the secrets runs of `run`'s revision are handed (needsOf), once per revision: from `given` (a
1674
- * start's, read from the store), else from the agent store, waiting out a busy one as a run's end does. */
1675
- async pinNeeds(run, given) {
1676
- if (this.needs.has(run.revision))
1677
- return;
1678
- const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
1679
- this.needs.set(run.revision, await needsOf(revision));
1680
- }
1681
- /** `run`'s pinned MCP tools: read from its directory, or at its first launch made from the granted `tools` and the
1682
- * servers saved now, and written before its process starts. Undefined when it grants none. */
1683
- mcpPin(run, tools) {
1684
- const file = join(run.dir, MCP_PIN);
1685
- if (existsSync(file)) {
1686
- const pinned = JSON.parse(readFileSync(file, "utf8"));
1687
- // A pin made before meta tools were refused (mcp-meta.ts) is checked at each launch, never rewritten: one it holds
1688
- // refuses the launch, as making the pin does.
1689
- for (const [server, { url, tools: listed }] of Object.entries(pinned)) {
1690
- for (const tool of listed)
1691
- if (metaToolOf(url, tool.name))
1692
- throw new Error(`mcp:${server}/${tool.name} can't be granted: ${META_REASON}`);
1693
- }
1694
- return pinned;
1695
- }
1696
- if (!tools?.some((name) => name.startsWith("mcp:")) || !this.options.mcpServers)
1697
- return undefined;
1698
- const pin = mcpPinOf(tools, this.options.mcpServers);
1699
- if (!Object.keys(pin).length)
1700
- return undefined;
1701
- writeDurableSync(file, JSON.stringify(pin));
1702
- return pin;
1703
- }
1704
- /** The saved sign-in the run's browser starts from (sign-ins.ts), resolved before each launch: made at the vendor when
1705
- * its agent has none, and leased to this run to save unless another run of the agent holds the lease. One that cannot
1706
- * be had (the vendor not answering, a seal key changed) leaves its browser signed out, said in its log. */
1707
- async pinSignIn(run) {
1708
- // Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
1709
- const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
1710
- 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;
1712
- // 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);
1715
- }
1716
- /** 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
- * (`clean`), else by the gone rule (sign-ins.ts). */
1718
- async releaseSignIn(run, clean = true) {
1719
- run.signIn = undefined;
1720
- 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
- }
1722
- launch(run, followUp = run.followUpOpen === true) {
1723
- if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing)
1724
- return;
1725
- // Taken by this launch only: a later launch (a relaunch after its process went) opens the run as any other.
1726
- run.followUpOpen = undefined;
1727
- // Its secrets go over fd 3, written whole and closed as it starts; it reads them first (secrets.ts). Each launch path
1728
- // reads its revision's needs first (pinNeeds); one that did not hands no tool key. Which keys, from the keys this
1729
- // server holds now (its launcher's and the saved ones, never its environment, which under the launcher holds none),
1730
- // in this same turn as the handover, so a key saved with no restart counts at the next launch, and none can change
1731
- // in between.
1732
- const served = withSecrets(process.env, "all", this.options.storedKeys);
1733
- const needs = this.needs.get(run.revision);
1734
- const handed = needs ? keysFor(needs, served) : NO_TOOL_KEYS;
1735
- // Its MCP servers: the tools it grants, pinned at its first launch in its directory (mcp-gateway.ts), and the
1736
- // credentials of those servers alone, read now, on the same pipe.
1737
- let pin;
1738
- try {
1739
- pin = this.mcpPin(run, needs?.tools);
1740
- }
1741
- catch (error) {
1742
- // A granted tool that cannot be pinned refuses the launch in words, rather than a run without the tool.
1743
- run.error = { code: "run_failed", message: error.message, retryable: false };
1744
- run.finishing = "failed";
1745
- void this.settle(run, 1, true);
1746
- return;
1747
- }
1748
- const mcp = pin && this.options.mcpServers ? mcpCredentialsOf(pin, this.options.mcpServers) : undefined;
1749
- // And its saved sign-in, on the same pipe after them (pinSignIn): a pointer its browser opens, never in its environment.
1750
- const secrets = Buffer.concat([handover(handed, this.options.storedKeys), ...(mcp ? [mcpHandover(mcp)] : []), ...(run.signIn ? [handoverSignIn(run.signIn)] : [])]);
1751
- // What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
1752
- this.learning.onLaunch(run, handed, mcpSecretValues(mcp ?? {}));
1753
- // And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
1754
- run.handed ??= new Set();
1755
- for (const name of handed) {
1756
- const value = secret(name, this.options.storedKeys);
1757
- if (value && value.length >= MIN_SECRET)
1758
- run.handed.add(value);
1759
- }
1760
- for (const value of mcpSecretValues(mcp ?? {}))
1761
- if (value.length >= MIN_SECRET)
1762
- run.handed.add(value);
1763
- if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
1764
- run.handed.add(run.signIn.ref);
1765
- const env = {
1766
- ...childEnv(process.env, this.options.token),
1767
- // The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
1768
- [RUN_BOX_ALLOW_ENV]: this.options.dockerAllow === undefined || this.options.dockerAllow === "none" ? "none" : this.options.dockerAllow.join(","),
1769
- // And, on a Mac, its proxy's volume: set always, empty for none, so a stale value in the server's own environment
1770
- // never reaches a run.
1771
- [RUN_BOX_VOLUME_ENV]: this.options.dockerVolume ?? "",
1772
- [SECRETS_FD_ENV]: "3",
1773
- [SECRETS_LEN_ENV]: String(secrets.length),
1774
- ...this.fauxEnv(),
1775
- ...(run.meta.effort ? { [EFFORT_ENV]: run.meta.effort } : {}),
1776
- ...(this.options.documents ? { [DOCUMENTS_ENV]: this.options.documents } : {}),
1777
- };
1778
- // Kept for its metrics: the host's level may change before the run ends.
1779
- run.meta.launch_thinking = { ...(env[EFFORT_ENV] ? { effort: env[EFFORT_ENV] } : {}), ...(env.AGENT_THINKING ? { host: env.AGENT_THINKING } : {}) };
1780
- void this.saveMeta(run).catch((error) => warn(run.id, `what its process thinks at is not saved: ${error.message}`));
1781
- delete env[CAP_ENV];
1782
- if (run.meta.max_cost_usd !== undefined)
1783
- env[CAP_ENV] = String(run.meta.max_cost_usd);
1784
- // A run on the host's default (its revision names no model) gets the model the server picks for its harness, never
1785
- // the key that gave it: behind a gateway its process holds the gateway's key alone (keysFor) and could not tell. It is
1786
- // the run's last choice (model.ts hostModel: the tier's variable, then AGENT_MODEL where the harness runs it, then a
1787
- // key the run holds, then this), so a host's setting the harness can run still wins; and one it cannot (AGENT_MODEL
1788
- // 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.
1790
- 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;
1793
- if (defaultModel)
1794
- env[DEFAULT_MODEL_ENV] = defaultModel;
1795
- // Opened for a person's follow-up to a run whose turn had ended: nothing it resumes was cut (app.ts markResumed).
1796
- delete env[FOLLOW_UP_OPEN_ENV];
1797
- if (followUp)
1798
- env[FOLLOW_UP_OPEN_ENV] = "1";
1799
- // Its tools' providers (tool-plane.ts): resolved at its first launch from its pinned revision and this server's
1800
- // settings, and kept in its serve.json, so a later change of the settings never changes a run's tools; at a later
1801
- // launch only checked again (a Parallel key gone makes Parallel unavailable, never another provider). A new run's are
1802
- // in the serve.json its start writes (start); resolving here is for a run made before that, whose browser stays
1803
- // Browserbase (keptFromBefore), the vendor it had then, kept as its choice and checked again at each launch like the
1804
- // rest; a vendor's missing-key refusal an earlier server saved reads as that vendor again (keptVendor), saved back. A
1805
- // description with no secret
1806
- // in it, read by the run's process, never by a request. A key saved through the settings API counts as the launcher's
1807
- // does (secrets.ts), so a saved Parallel key makes Parallel available, and a deleted one unavailable at the next launch.
1808
- // A capability set to ask or deny since resolves again (a harness's own search cannot wait for a person). Its first
1809
- // launch, from its start, is told a deny as under ask; a later one is told it denied (relaunchPlane).
1810
- const settings = this.options.toolSettings?.() ?? {};
1811
- const capped = run.meta.max_cost_usd !== undefined;
1812
- const first = run.firstLaunch === true;
1813
- run.firstLaunch = undefined;
1814
- const kept = run.meta.tool_plane ? keptVendor(run.meta.tool_plane) : run.tooling ? keptFromBefore(planeFor(served, run.tooling, settings, { capped })) : {};
1815
- const plane = relaunchPlane(kept, served, run.tooling, settings, { capped, first });
1816
- if (kept !== run.meta.tool_plane && Object.keys(kept).length) {
1817
- run.meta.tool_plane = kept;
1818
- void this.saveMeta(run).catch(() => undefined);
1819
- }
1820
- delete env[TOOL_PLANE_ENV];
1821
- if (Object.keys(plane).length)
1822
- env[TOOL_PLANE_ENV] = JSON.stringify(plane);
1823
- // No one can approve here (accounts off): the run's gate refuses an ask instead of parking it (tool-gate.ts).
1824
- delete env[NO_APPROVER_ENV];
1825
- if (this.options.approvers === false)
1826
- env[NO_APPROVER_ENV] = "1";
1827
- // The decision keys are never in a run's environment, which its tools and its model's provider read (childEnv leaves
1828
- // out every secret): a run's process gets those it needs once on an inherited pipe, by name: its decision
1829
- // providers' (decisionProvidersFor), and Parallel's where one of its web tools resolves to Parallel (its plane,
1830
- // handsParallel). A web tool reaches Parallel only where its own capability resolves there. A run that needs none
1831
- // gets no pipe at all, and one whose revision was not read gets none.
1832
- delete env[DECISION_KEY_FD_ENV];
1833
- // Chosen from the secrets this server holds: out of its environment once its launcher hands them over (secrets.ts).
1834
- const providers = needs?.decisionProviders;
1835
- const decisionKeys = providers ? decisionKeysFor(served, { providers, parallelWeb: handsParallel(plane) }) : {};
1836
- const handsKey = Object.keys(decisionKeys).length > 0;
1837
- this.markLaunching(run);
1838
- const log = openSync(join(run.dir, PROCESS_LOG), "a", 0o600);
1839
- const stdio = ["ignore", "ignore", log, "pipe"];
1840
- // The first descriptor after the others: macOS aborts the parent of a spawn with a pipe at 16 or above.
1841
- const keyFd = stdio.length;
1842
- if (handsKey) {
1843
- stdio.push("pipe");
1844
- env[DECISION_KEY_FD_ENV] = String(keyFd);
1845
- }
1846
- // A workflow run resumes from its journal when it opens again, so SIGTERM lets it go at once, undrained.
1847
- const drain = run.kind === "workflow" ? "0s" : (this.options.drainTimeout ?? DRAIN);
1848
- // Its own door token, which its door takes and its calls to the box relay carry: no other run's process holds it.
1849
- run.doorToken = ensureRunDoorToken(run.dir);
1850
- const doorTokenFile = join(run.dir, RUN_DOOR_TOKEN);
1851
- const child = spawn(process.execPath, [
1852
- // secrets.ts first, as a preload: the pipe is read and closed before pi-durable-disk's CLI loads or starts anything.
1853
- "--no-warnings=ExperimentalWarning", "--import", SECRETS_MODULE, this.cli, "run", "--dir", run.dir, "--app", this.app,
1854
- "--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
1855
- ], { stdio, env });
1856
- closeSync(log);
1857
- const pipe = child.stdio[3];
1858
- pipe?.on("error", () => { });
1859
- pipe?.end(secrets);
1860
- if (handsKey) {
1861
- const keyPipe = child.stdio[keyFd];
1862
- // A process that dies before it reads the key closes the pipe: that is its exit to settle, not an error here.
1863
- keyPipe?.on("error", () => undefined);
1864
- keyPipe?.end(JSON.stringify(decisionKeys));
1865
- }
1866
- run.child = child;
1867
- child.once("exit", (code) => {
1868
- if (run.child === child)
1869
- run.child = undefined;
1870
- this.reportedBack(run);
1871
- void this.settle(run, code, true);
1872
- });
1873
- child.once("error", () => {
1874
- if (run.child === child)
1875
- run.child = undefined;
1876
- this.reportedBack(run);
1877
- });
1878
- this.connect(run);
1879
- }
1880
- /** Writes the run's launch mark before its process is spawned: a spawn that takes the server down leaves it, and the
1881
- * next start fails the run rather than launch it again and go down with it. The file exists once the call returns,
1882
- * which a server's death does not undo; no fsync, which would hold the event loop on the disk at every launch. */
1883
- markLaunching(run) {
1884
- closeSync(openSync(join(run.dir, RUN_LAUNCHING), "w", 0o600));
1885
- run.launching = true;
1886
- }
1887
- /** The run's newest launch came through with the server up: its process serves, or exited while it was watched. Its
1888
- * callers are event handlers, so a mark that cannot be removed is logged, never thrown: a throw there stops the
1889
- * server and every run on it. The mark left behind fails the run at the next start, which never launches it again. */
1890
- reportedBack(run) {
1891
- if (!run.launching)
1892
- return;
1893
- run.launching = false;
1894
- try {
1895
- rmSync(join(run.dir, RUN_LAUNCHING), { force: true });
1896
- }
1897
- catch (error) {
1898
- this.options.log?.("launch_mark_kept", { run: run.id, code: error.code ?? "unknown" });
1899
- }
1900
- }
1901
- /** Opens the run again on its directory after its process went before the run ended: it resumes from its store. An
1902
- * agentic run whose first message never landed gets it again, under the same request id. */
1903
- relaunch(run) {
1904
- run.relaunches++;
1905
- warn(run.id, `its process went before the run ended; opening it again (${run.relaunches} of ${MAX_RELAUNCHES})`);
1906
- this.launch(run);
1907
- const first = run.meta.input?.content;
1908
- if (run.kind !== "agentic" || usersOf(run.rows) > 0 || typeof first !== "string")
1909
- return;
1910
- run.submitted = 1;
1911
- this.refresh(run);
1912
- // 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}`));
1914
- }
1915
- /** After the run's process exited, or was found gone: its rows from its released store, then, when it is over, its
1916
- * carry back. One at a time per run, and none once the run has its outcome. */
1917
- settle(run, code, exited) {
1918
- if (this.closed)
1919
- return Promise.resolve();
1920
- run.settles++;
1921
- run.settling = (run.settling ?? Promise.resolve())
1922
- .then(() => (run.outcome ? undefined : this.settleOnce(run, code, exited)))
1923
- .catch((error) => {
1924
- if (!(storeBusy(error) || error instanceof PullPending) || this.closing)
1925
- return warn(run.id, `not settled: ${error.message}; the next start tries again`);
1926
- // A store still held past the run end's retries: settled again later, not left until the next start.
1927
- const every = this.options.settleRetryMs ?? SETTLE_RETRY_MS;
1928
- warn(run.id, `not settled: ${error.message}; trying again in ${every / 1000} s`);
1929
- setTimeout(() => void this.settle(run, code, exited), every).unref();
1930
- })
1931
- .finally(() => void run.settles--);
1932
- return run.settling;
1933
- }
1934
- /** `exited`: the process this server supervised exited. Exiting on an error before it released fails the run; going
1935
- * any other way before the run ended (killed, or found gone at a start) opens it again. */
1936
- async settleOnce(run, code, exited) {
1937
- // A run whose files are still being copied has had no process yet: its start launches it, and only a cancel ends it
1938
- // first (a recovery that lists it meanwhile must not fail it for its launch mark).
1939
- if (run.preparing && !run.cancel)
1940
- return;
1941
- run.feed?.abort();
1942
- run.feed = undefined;
1943
- run.working = false;
1944
- const record = await this.record(run);
1945
- const released = RELEASED.has(String(record?.status));
1946
- 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));
1950
- // Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
1951
- if (gone)
1952
- 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
- // Its metrics are this settle's read, or none: never an earlier end's.
1954
- run.metrics = undefined;
1955
- if (released || gone)
1956
- await this.storeWhenFree(run, true);
1957
- // Its process gone: an archived run's box is let go now, whatever comes next (an outcome, a wait for the person, a
1958
- // relaunch), since nothing else would until the next start or archive. This is every archived end that can let a box
1959
- // go: a settle with the process not gone means another live holder of the run, whose box is its own. That holder is
1960
- // one this server neither started nor adopted (adoptProcess watches only the holder it adopts), so its later exit
1961
- // settles nothing here: its box stays held, fail-closed, until the next start's sweep or another archive lets it go.
1962
- if (gone && (await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined))?.archivedAt)
1963
- await this.teardown(run);
1964
- let ended;
1965
- // A workflow run carries back how its workflow ended, through workflowCarry; cancelled before that, it stopped.
1966
- // A cancel during the end-of-run turn ends the run's learning, never its job: the run keeps the outcome it had.
1967
- if (run.cancel && !reflecting(run))
1968
- ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
1969
- else if (run.finishing)
1970
- ended = { outcome: run.finishing };
1971
- else if (run.notSetUp && gone) {
1972
- run.error = { code: "run_failed", message: "The server went down while it set the run up, before it saved the run's input; the run never started, and a new one can.", retryable: false, details: { reason: SETUP_LOST } };
1973
- ended = { outcome: "failed" };
1974
- }
1975
- else if (run.launching && gone) {
1976
- run.error = { code: "run_failed", message: "The server went down while it started the run's process, which never came up; it is not started again, since starting it may be what took the server down.", retryable: false, details: { reason: LAUNCH_LOST } };
1977
- ended = { outcome: "failed" };
1978
- }
1979
- else if (exited && !released && code !== null && code !== 0 && (run.resuming !== undefined || continuationOf(run) !== undefined)) {
1980
- // A raised run's paused process held nothing (its turn had ended at the refusal): its exit without a release, at
1981
- // its drain's end, say, loses nothing, and the raise's follow-up goes (resumeRaised), never a failed run.
1982
- return this.refresh(run);
1983
- }
1984
- else if (exited && !released && code !== null && code !== 0) {
1985
- run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
1986
- ended = { outcome: "failed" };
1987
- }
1988
- else if (!gone && this.doorOf(record))
1989
- ended = undefined;
1990
- else if (run.kind === "workflow")
1991
- ended = await this.workflowEnd(run, workflowEnding(record));
1992
- else {
1993
- const end = this.decide(run);
1994
- if (end?.error)
1995
- run.error = end.error;
1996
- ended = end && { outcome: end.outcome };
1997
- }
1998
- 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";
2001
- // Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
2002
- // opened before its process went may still be live at the vendor, and would write back over another run's. One
2003
- // that let go cleanly to wait for its person released its sessions first, so its lease goes now.
2004
- if (gone && released && !stalled)
2005
- await this.releaseSignIn(run);
2006
- // A raised run's follow-up, under way or still to go, opens the run's next process itself (resumeRaised): its
2007
- // paused process going is no process lost, and no relaunch is counted for it.
2008
- const continuing = run.resuming !== undefined || continuationOf(run) !== undefined || run.child !== undefined;
2009
- if (!gone || !stalled || this.closing || continuing)
2010
- return this.refresh(run);
2011
- // Opened again without a place, as a run already going, unless its harness never fits this host (a restart on a
2012
- // smaller one): that run fails with why.
2013
- const never = neverFits(run.harness, this.memory);
2014
- if (!never && run.relaunches < MAX_RELAUNCHES) {
2015
- await this.pinNeeds(run);
2016
- await this.pinSignIn(run);
2017
- return this.relaunch(run);
2018
- }
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 };
2020
- ended = { outcome: "failed" };
2021
- }
2022
- await this.carryBack(run, ended.outcome, ended.state, ended.summary);
2023
- }
2024
- /** A workflow run's carry back, `workflowCarry` of @parcha/pi-durable-agent/workflow on its released store, and its
2025
- * output when it completed; undefined while its workflow has not ended. */
2026
- async workflowEnd(run, ending) {
2027
- if (!ending)
2028
- return undefined;
2029
- const { readWorkflowRun, workflowCarry } = await import("@parcha/pi-durable-agent/workflow");
2030
- // A run's end waits for a busy store as long as its carry back does, not a request's 2 s.
2031
- const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
2032
- const at = { runId: run.id, storePath: this.storeFile(run), revision };
2033
- const { state, summary } = await workflowCarry(at, ending);
2034
- if (state === "completed")
2035
- run.meta.output = (await readWorkflowRun(at)).output ?? null;
2036
- else if (state === "escalated") {
2037
- const { escalation, escalatedAt } = await readWorkflowRun(at);
2038
- run.meta.review = { kind: escalation?.kind ?? null, node: escalation?.label ?? escalatedAt?.label ?? null, reason: escalation?.summary ?? summary };
2039
- }
2040
- else if (state === "failed")
2041
- run.error = { code: "run_failed", message: `The workflow failed: ${summary}.`, retryable: false };
2042
- await this.readDecisionCost(run);
2043
- return { outcome: STATUS_OF[state], state, summary };
2044
- }
2045
- /** A workflow run's decisions' cost, from their receipts in its released store: a receipt whose cost is unknown leaves
2046
- * the run's unknown, never $0. Read at its end and again when a restarted server adopts it as ended. */
2047
- async readDecisionCost(run) {
2048
- const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
2049
- // Not its `llm` calls: each completes on the run's marked models, so its cost is a REQUEST_COST entry its usage row
2050
- // already sums (request-start.ts).
2051
- const paid = durableDecisions(this.storeFile(run)).map((row) => row.cost_usd);
2052
- if (paid.length)
2053
- run.decisionCost = paid.every((cost) => typeof cost === "number") ? paid.reduce((a, b) => a + b, 0) : null;
2054
- if (paid.length)
2055
- run.decisionsPriced = { known: paid.reduce((a, b) => a + (typeof b === "number" ? b : 0), 0), unpriced: paid.filter((cost) => typeof cost !== "number").length };
2056
- }
2057
- /** 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
- * another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
2059
- async carryBack(run, outcome, state, summary) {
2060
- // Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
2061
- // left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
2062
- await this.releaseSignIn(run, run.letGo !== false);
2063
- // Its process is gone: its box goes with its end, whatever the end (a follow-up after it gets a fresh box; work/ stays).
2064
- // A remote box's last pull lands first: the end is not recorded until its files are in work/.
2065
- await this.dropBox(run, true);
2066
- // Its end-of-run turn closed, and what the turn wrote set aside before the run reads ended (learning-run.ts).
2067
- await this.learning.beforeSettle(run, outcome);
2068
- const cost = run.decisionCost === undefined ? costOf(run.rows) : costView(run.rows, undefined, run.decisionCost);
2069
- // An unknown cost keeps what it cost so far beside it, for the list row read from the store.
2070
- const soFar = cost === null && !run.imported ? soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) : undefined;
2071
- if (soFar)
2072
- run.meta.cost_so_far = soFar;
2073
- else
2074
- delete run.meta.cost_so_far;
2075
- const line = summary ?? (outcome === "completed" ? answerOfRun(run) : outcome === "cancelled" ? "cancelled" : run.error?.message);
2076
- if (run.error)
2077
- run.meta.error = { code: run.error.code, message: run.error.message, ...(run.error.details ? { details: run.error.details } : {}) };
2078
- // 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
- // time. A server that settles the run after a kill chooses its own: nothing was sent before the store had an end.
2080
- const endedAt = (run.endedAt ??= new Date().toISOString());
2081
- const ending = { state: state ?? (outcome === "cancelled" ? "stopped" : outcome === "completed" ? "completed" : "failed"), ...(cost === null ? {} : { costUsd: cost }), ...(line ? { summary: line } : {}), endedAt };
2082
- const counted = run.metrics;
2083
- const end = (metrics) => {
2084
- try {
2085
- this.store.carryBack(run.id, metrics ? { ...ending, metrics } : ending);
2086
- }
2087
- catch (error) {
2088
- if (!(error instanceof AgentHomeError && error.code === "exists"))
2089
- throw error;
2090
- }
2091
- };
2092
- const persist = async () => {
2093
- await this.saveMeta(run);
2094
- await whenFree(() => {
2095
- const metrics = counted && this.storedMetrics(run, counted);
2096
- try {
2097
- end(metrics);
2098
- }
2099
- catch (error) {
2100
- // Metrics the store refuses (a name past its limit) never hold up the run's end: it ends without them.
2101
- if (!(metrics && error instanceof AgentHomeError && error.code === "invalid"))
2102
- throw error;
2103
- warn(run.id, `its metrics are not kept: ${error.message}`);
2104
- end();
2105
- }
2106
- }, this.busyDelays(), this.onBusy(run.id, "the agent store"));
2107
- };
2108
- try {
2109
- await persist();
2110
- }
2111
- catch (error) {
2112
- // A store that refuses the write (a full disk, a store fenced by it) must not leave the run unended: it ends here
2113
- // now, with its cost from its rows, and the write is tried again until it lands. A restart before then reads the
2114
- // run as it was in the store. Its run.ended waits for the store (persistLater), so a receiver that reads the run
2115
- // back on its notice reads it ended there too.
2116
- warn(run.id, `its end could not be written to the agent store (${error.message}); trying again every ${(this.options.settleRetryMs ?? SETTLE_RETRY_MS) / 1000} s`);
2117
- // An unknown cost stays unknown: never stored as 0.
2118
- if (cost !== null)
2119
- run.costUsd = cost;
2120
- run.outcome = outcome;
2121
- run.finishing = undefined;
2122
- run.settled = true;
2123
- run.updatedAt = new Date().toISOString();
2124
- this.refresh(run);
2125
- this.persistLater(run, persist);
2126
- return;
2127
- }
2128
- const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
2129
- // The store's time is the one it was given, unless an earlier end of the run's own landed first (a refused write that
2130
- // went through after all): the row's then. A read that fails keeps the chosen time, never a new one.
2131
- if (row?.endedAt)
2132
- run.endedAt = row.endedAt;
2133
- if (row?.costUsd !== undefined)
2134
- run.costUsd = row.costUsd;
2135
- this.options.log?.("run_ended", { run: run.id, agent: run.agentId, status: outcome, cost_usd: row?.costUsd ?? cost ?? "unknown" });
2136
- run.outcome = outcome;
2137
- run.finishing = undefined;
2138
- run.settled = true;
2139
- run.updatedAt = new Date().toISOString();
2140
- this.refresh(run);
2141
- this.notice(run, "run.ended", run.endedAt);
2142
- // Only once the run has ended as it would without learning: a slow or failing check never holds the job.
2143
- void this.learning.afterSettle(run);
2144
- }
2145
- /** The run's metrics as the store keeps them: what its entries say it used, the effort its newest process ran at (unknown
2146
- * for one an older server started), and on a harness other than pi the model its revision names (its entries name the
2147
- * harness). A busy store throws, for the write's retries; a revision that cannot be read otherwise adds nothing. */
2148
- storedMetrics(run, counted) {
2149
- let revision;
2150
- try {
2151
- revision = this.store.readRevision(run.revision);
2152
- }
2153
- catch (error) {
2154
- if (storeBusy(error))
2155
- throw error;
2156
- return counted;
2157
- }
2158
- 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.
2161
- 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 } : {}) };
2164
- }
2165
- /** Tries `persist` again every settleRetryMs while the server lives, until it lands. */
2166
- persistLater(run, persist) {
2167
- const timer = setTimeout(() => {
2168
- if (this.closing)
2169
- return;
2170
- persist().then(async () => {
2171
- const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
2172
- if (row?.endedAt)
2173
- run.endedAt = row.endedAt;
2174
- if (row?.costUsd !== undefined)
2175
- run.costUsd = row.costUsd;
2176
- // In the store at last: its run.ended goes now.
2177
- this.notice(run, "run.ended", run.endedAt);
2178
- await this.learning.afterSettle(run);
2179
- }, () => this.persistLater(run, persist));
2180
- }, this.options.settleRetryMs ?? SETTLE_RETRY_MS);
2181
- timer.unref();
2182
- }
2183
- /** How long a run's end waits for a busy store, step by step. */
2184
- busyDelays() {
2185
- return this.options.carryBackRetry?.delaysMs ?? CARRY_BACK_RETRIES_MS;
2186
- }
2187
- /** Hears that `what` was busy for run `runId`, and says so when another try follows. */
2188
- onBusy(runId, what) {
2189
- return (attempt, delay) => {
2190
- this.options.carryBackRetry?.onBusy?.(runId, attempt);
2191
- if (delay !== undefined)
2192
- warn(runId, `${what} is busy; trying again in ${delay} ms (${attempt + 1} of ${this.busyDelays().length})`);
2193
- };
2194
- }
2195
- /** The run's store, read again while another connection holds it, within the same retries. */
2196
- storeWhenFree(run, atEnd = false) {
2197
- return whenFree(() => this.readStore(run, atEnd), this.busyDelays(), this.onBusy(run.id, "its store"));
2198
- }
2199
- // ---- acting ---------------------------------------------------------------------------------------------------------
2200
- /** Start a run of `revision` (number `version`) of `entry`'s agent: `startRun` in the store, then its process, then an
2201
- * agentic run's first message, `input.content`. */
2202
- /** A place for one more live run of `harness`, taken for this start (counted in `starting` and `startingMib` from
2203
- * here, so two starts at once cannot both take the last place), or 429 rate_limited; the function returned gives it
2204
- * back once the run holds it as a live run, or did not start. A place is one under the cap on the count and the
2205
- * memory a run of its harness reserves (host.ts): both must be free. A run that has ended (failed, completed,
2206
- * cancelled) still holds its place until its process exits; a start that needs that place waits for it, up to that
2207
- * process's drain and kill, never refused for a place already being given back. A harness whose one run is more than
2208
- * the whole memory for runs is refused at once, never a 429 (capabilities say so too). From the read of what is held
2209
- * to the reservation nothing awaits, so two starts at once never both take the last of it. */
2210
- async takePlace(harness) {
2211
- const { memory, options: { maxRuns: max } } = this;
2212
- const need = runMibOf(harness);
2213
- const never = neverFits(harness, memory);
2214
- if (never)
2215
- throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness } });
2216
- for (const deadline = Date.now() + this.killAfterMs() + 1_000;; await sleep(50)) {
2217
- const holding = [...this.runs.values()].filter((run) => this.live(run));
2218
- const counted = max === undefined || holding.length + this.starting < max;
2219
- const held = holding.reduce((sum, run) => sum + runMibOf(run.harness), this.startingMib);
2220
- // With nothing held, a run that fits at all starts: pi's one place on a host smaller than a pi run (host.ts).
2221
- const fits = held === 0 || held + need <= runsMemoryMib(memory);
2222
- if (counted && fits)
2223
- break;
2224
- const leaving = holding.some((run) => run.outcome || run.finishing || run.cancel);
2225
- if (!leaving || Date.now() > deadline) {
2226
- if (!counted)
2227
- throw new ApiError("rate_limited", `This server runs at most ${max} runs at once (max_concurrent_runs); start this one when another ends.`, { retry_after_ms: 5_000, details: { max_concurrent_runs: max } }, { "retry-after": "5" });
2228
- throw new ApiError("rate_limited", memoryFull(harness, memory, held), { retry_after_ms: 5_000, details: { max_concurrent_runs: max ?? null, harness, needs_mb: need, free_mb: Math.max(0, runsMemoryMib(memory) - held) } }, { "retry-after": "5" });
2229
- }
2230
- }
2231
- this.starting++;
2232
- this.startingMib += need;
2233
- return () => {
2234
- this.starting--;
2235
- this.startingMib -= need;
2236
- };
2237
- }
2238
- /** `inputs` copies the run's files into its work/ (uploads.ts), after the store made it and before its process starts. */
2239
- async create(entry, revision, version, options) {
2240
- await this.sweepOnce();
2241
- const release = await this.takePlace(harnessOfBody(revision.body));
2242
- try {
2243
- // Read again: the place may have been waited for, and the agent archived meanwhile.
2244
- const now = await this.options.agents.get(entry.agent.id);
2245
- if (now?.agent.archivedAt)
2246
- throw new ApiError("agent_not_runnable", `The agent ${entry.agent.id} is archived: unarchive it to run it.`, { details: { archived_at: now.agent.archivedAt } });
2247
- return await this.start(entry, revision, version, options);
2248
- }
2249
- finally {
2250
- release();
2251
- }
2252
- }
2253
- /** Writes the serve.json of a run being set up. When it fails, the store has the run as running and no process will
2254
- * run it: it ends failed here, never left for a later start to open with half its files. */
2255
- async setUp(runId, dir, meta) {
2256
- try {
2257
- await writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`);
2258
- }
2259
- catch (error) {
2260
- const summary = `The run could not be set up: ${error.message}`;
2261
- await this.options.agents.request(() => this.store.carryBack(runId, { state: "failed", summary })).catch((undo) => warn(runId, `not ended after its setup failed: ${undo.message}`));
2262
- throw error;
2263
- }
2264
- }
2265
- async start(entry, revision, version, options) {
2266
- // Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in the serve.json its start writes first,
2267
- // so a launch after a crash reads them back, never the settings of that moment, and keeping them is no write of its own.
2268
- const tooling = await toolingOf(revision);
2269
- const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined, run: true }) : {};
2270
- // A run that learns: its seed read before it is made (learning-run.ts).
2271
- const pin = await this.learning.onStart(entry.agent.id, revision);
2272
- const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id, ...(options.origin ? { origin: options.origin } : {}) })).catch((error) => storeError(error, "revision"));
2273
- // 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
- if (started.existing)
2275
- 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);
2295
- await this.setUp(started.runId, started.dir, meta);
2296
- }
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);
2302
- // A seed that failed is a learning row from the start, and its learning's end is in the ledger.
2303
- this.show(run);
2304
- void this.learning.onSaved(run, meta.learning);
2305
- this.options.log?.("run_started", { run: run.id, agent: run.agentId, kind: run.kind });
2306
- if (revision.kind === "agentic")
2307
- run.submitted = 1;
2308
- this.refresh(run);
2309
- if (options.inputs) {
2310
- // Listed from here, so a request may reach it while it copies: `preparing` holds it until its files are in.
2311
- const prepared = this.prepare(run, started.workspace, options.inputs).finally(() => void (run.preparing = undefined));
2312
- // Never rejected: a request waiting on it reads how the start ended from the run; the start's own error is the create's.
2313
- run.preparing = prepared.then(() => undefined, () => undefined);
2314
- if (!(await prepared))
2315
- return run;
2316
- }
2317
- run.firstLaunch = true;
2318
- this.launch(run);
2319
- if (revision.kind === "workflow")
2320
- return run;
2321
- // 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) => {
2323
- run.submitted = 0;
2324
- // The run ended before its first message reached it (a process that crashed at its start): how it ended stands.
2325
- if (run.outcome || run.finishing || run.cancel)
2326
- return;
2327
- run.error = { code: "run_failed", message: error.message, retryable: false };
2328
- if (this.live(run))
2329
- this.finish(run, "failed");
2330
- else if (!run.cancel)
2331
- void this.settle(run, 1, true);
2332
- });
2333
- return run;
2334
- }
2335
- /** Copies the run's files into its work/ under the launch mark: a server that goes down while it copies leaves the
2336
- * mark, and the next start fails the run rather than run it on part of its files. Copied whole, the mark goes, and the
2337
- * launch makes its own. False when the copy failed, and the run ended so (or was cancelled meanwhile). */
2338
- async prepare(run, work, inputs) {
2339
- try {
2340
- // The mark itself may fail (a full disk): the run ends as when the copy does.
2341
- this.markLaunching(run);
2342
- await inputs(work);
2343
- }
2344
- catch (error) {
2345
- run.submitted = 0;
2346
- // Cancelled while it copied: it ends so.
2347
- if (!(run.outcome || run.cancel)) {
2348
- run.error = { code: "run_failed", message: `The run's files could not be copied into its workspace: ${error.message}`, retryable: false };
2349
- await this.carryBack(run, "failed");
2350
- }
2351
- // The mark goes only once the store has the run's end: a server that goes down before then finds it, and fails the
2352
- // run rather than launch it on part of its files.
2353
- const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
2354
- if (row && row.state !== "running")
2355
- this.reportedBack(run);
2356
- return false;
2357
- }
2358
- this.reportedBack(run);
2359
- return true;
2360
- }
2361
- /** One message to the run's door. `origin`: who wrote it when the person did not (a raised cap's follow-up, an
2362
- * approval's resume), carried to its user entry so the Timeline shows it as the server's (pi-durable-agent's
2363
- * MessageOrigin); the model reads the same text either way. `answers: false`: the run's door refuses the message
2364
- * (WAITING) when the run's turn ended on ask_person or a tool call of it waits for its owner's approval (the gate's
2365
- * park, APPROVAL_ENTRY), and when the run is busy (BUSY), so it is never queued behind a
2366
- * turn that may end so; decided at the door's admission, past every wait here. */
2367
- async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
2368
- 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);
2370
- if (answer.status === 409 && answer.body?.error === "WAITING")
2371
- throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
2372
- if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
2373
- throw new ApiError("rate_limited", "The run is working: a message that may not answer it waits until it is idle.", { retry_after_ms: 5_000, details: { reason: "working" } });
2374
- if (answer.status >= 400)
2375
- throw new ApiError(answer.status === 409 ? "not_continuable" : "internal", String(answer.body?.message ?? answer.body?.error ?? "the run refused the message"));
2376
- }
2377
- /** Whether the run's harness takes a message mid-turn. */
2378
- steers(run) {
2379
- return run.kind !== "agentic" || steersMidTurn(run.harness);
2380
- }
2381
- /** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
2382
- * down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
2383
- * already has. Only for a run with no live process: a live one holds its store, and takes the message through its
2384
- * door, which takes one per id anyway. The store keeps the id as JSON text, as pi submits it, or as a harness's door
2385
- * keeps its journal (doorKey), where a busy refusal is not a message taken (doorTook). A store held past the retries
2386
- * throws as busy. */
2387
- async tookMessage(run, requestId) {
2388
- if (this.live(run))
2389
- return false;
2390
- const file = this.storeFile(run);
2391
- if (!(await stat(file).catch(() => null)))
2392
- return false;
2393
- const { DatabaseSync } = await import("node:sqlite");
2394
- return whenFree(async () => {
2395
- const db = new DatabaseSync(file, { readOnly: true });
2396
- 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);
2401
- }
2402
- catch (error) {
2403
- // A store that keeps no submissions has taken none.
2404
- if (/no such table/.test(error.message))
2405
- return false;
2406
- throw error;
2407
- }
2408
- finally {
2409
- db.close();
2410
- }
2411
- }, this.busyDelays(), this.onBusy(run.id, "its store"));
2412
- }
2413
- /** 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
- * its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
2415
- * is undone, so the run's next process opens under it (CAP_ENV), as does a server started again. A run paused at its
2416
- * cap goes on: the raise names the pause it answers, and the pause gets one follow-up, "The cap was raised to $X;
2417
- * continue the task." under an id fixed now, which refresh sends once the paused process is gone (resumeRaised), here
2418
- * or after a restart; a second raise before it goes raises what it says. A run working keeps the cap its process was
2419
- * opened with until its next process. Raises of one run are taken one at a time. */
2420
- async raiseCap(run, cap) {
2421
- const before = run.raising ?? Promise.resolve();
2422
- const taking = before.catch(() => undefined).then(() => this.takeRaise(run, cap));
2423
- run.raising = taking.catch(() => undefined);
2424
- return taking;
2425
- }
2426
- async takeRaise(run, cap) {
2427
- if (run.imported)
2428
- throw this.importedRefusal(run);
2429
- if (run.cancel || run.finishing || TERMINAL.has(statusOf(run).status))
2430
- throw this.finished(run);
2431
- const from = run.meta.max_cost_usd;
2432
- if (from === undefined)
2433
- 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." }]);
2434
- const last = run.meta.cap_raised?.at(-1);
2435
- const pause = pauseOf(run);
2436
- const next = continuationOf(run);
2437
- // The same raise again (a retry): what the first one did stands.
2438
- if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
2439
- // Resumed, as the first answer said, unless the run has since paused anew at another refusal: no raise of that one.
2440
- const answered = last.pause !== undefined && run.meta.cap_continue?.pause === last.pause && (pause === undefined || pause === last.pause) ? run.meta.cap_continue : undefined;
2441
- return answered ? { resumed: true, messageId: answered.message_id } : { resumed: false };
2442
- }
2443
- if (!(cap > from + CAP_TOLERANCE))
2444
- throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
2445
- // Built on a copy and written first: nothing reads the raise (its cap, the pause it answers, its follow-up) before
2446
- // serve.json keeps it, so until then a message is still 409 budget_reached, the run reads its old cap and no
2447
- // follow-up goes; a raise the write fails leaves the run as it was, and a retry raises it again.
2448
- const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(pause ? { pause } : {}) }];
2449
- let follow = run.meta.cap_continue;
2450
- if (pause !== undefined && next === undefined) {
2451
- // The pause's one follow-up, by an id fixed now, and the process being let go then, which it waits out.
2452
- const paused = this.live(run) ? this.liveIdentity(run) : undefined;
2453
- follow = { pause, message_id: `cap-${raised.length}-${randomBytes(4).toString("hex")}`, sent: false, tries: 0, ...(paused ? { paused } : {}) };
2454
- }
2455
- else if (next) {
2456
- // A raise of a pause whose follow-up has not gone: that one follow-up goes, under this cap, with its tries anew.
2457
- const { error: _, ...rest } = next;
2458
- follow = { ...rest, tries: 0 };
2459
- }
2460
- await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised, ...(follow ? { cap_continue: follow } : {}) }));
2461
- run.meta.max_cost_usd = cap;
2462
- run.meta.cap_raised = raised;
2463
- if (next && follow) {
2464
- // The same follow-up object resumeRaised may hold, renewed in place.
2465
- next.tries = 0;
2466
- delete next.error;
2467
- }
2468
- else if (follow)
2469
- run.meta.cap_continue = follow;
2470
- if (next && typeof run.resuming === "number")
2471
- run.resuming = undefined;
2472
- this.refresh(run);
2473
- const answered = pause !== undefined ? run.meta.cap_continue : undefined;
2474
- if (!answered)
2475
- 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
- return { resumed: true, messageId: answered.message_id };
2477
- }
2478
- /** 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
- * follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
2480
- * new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
2481
- * again (CONTINUE_RETRY_MS), and after CONTINUE_TRIES the run fails, saying why: never a pause stuck in silence. */
2482
- async resumeRaised(run, next) {
2483
- run.resuming = "sending";
2484
- if (!this.live(run))
2485
- run.followUpOpen = true;
2486
- run.submitted++;
2487
- this.refresh(run);
2488
- const cap = run.meta.max_cost_usd ?? 0;
2489
- try {
2490
- // The server's line, shown as the server's (MessageOrigin), never as the person's: the model reads the same text.
2491
- await this.submit(run, `The cap was raised to ${money(cap)}; continue the task.`, "followUp", next.message_id, undefined, { kind: "server", reason: "cap_raised" });
2492
- // Marked sent once serve.json says so. Should that write fail, it went all the same (the door holds it), and its
2493
- // run no longer stands at the pause, so nothing sends it again.
2494
- await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, sent: true } })).then(() => void (next.sent = true), (error) => warn(run.id, `its raised cap's follow-up went, but is not marked sent: ${error.message}`));
2495
- run.resuming = undefined;
2496
- }
2497
- catch (error) {
2498
- run.submitted = Math.max(0, run.submitted - 1);
2499
- // The try counts here whether or not serve.json can say so, so its tries stay bounded.
2500
- const tried = { tries: next.tries + 1, error: error.message };
2501
- await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, ...tried } })).catch(() => undefined);
2502
- Object.assign(next, tried);
2503
- if (next.tries >= CONTINUE_TRIES) {
2504
- run.resuming = undefined;
2505
- warn(run.id, `its raised cap's follow-up was not sent in ${next.tries} tries (${next.error}); the run fails`);
2506
- return this.failRaised(run, cap, next.error);
2507
- }
2508
- const wait = CONTINUE_RETRY_MS[next.tries - 1] ?? CONTINUE_RETRY_MS.at(-1);
2509
- warn(run.id, `its raised cap's follow-up was not sent (${next.error}); tried again in ${wait / 1000} s`);
2510
- const at = Date.now() + wait;
2511
- run.resuming = at;
2512
- setTimeout(() => {
2513
- if (run.resuming !== at)
2514
- return;
2515
- run.resuming = undefined;
2516
- this.refresh(run);
2517
- }, wait).unref();
2518
- this.refresh(run);
2519
- }
2520
- finally {
2521
- run.followUpOpen = undefined;
2522
- }
2523
- }
2524
- /** Ends a raised run whose follow-up could not be sent: failed, in words a person can act on. */
2525
- async failRaised(run, cap, why) {
2526
- if (run.outcome || run.finishing || run.cancel)
2527
- return;
2528
- run.error = { code: "run_failed", message: `The run's cap was raised to ${money(cap)}, but the run could not be sent on (${why ?? "no answer"}). Start it again to go on.`, retryable: false };
2529
- run.finishing = "failed";
2530
- run.endedAt = new Date().toISOString();
2531
- this.mark(run);
2532
- if (this.live(run))
2533
- this.terminate(run);
2534
- else
2535
- await this.settle(run, null, false);
2536
- }
2537
- /** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
2538
- * 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 } = {}) {
2540
- if (run.imported)
2541
- throw this.importedRefusal(run);
2542
- // A cancelled run takes no message, whether or not its end is written yet.
2543
- if (run.cancel)
2544
- 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;
2549
- if (read) {
2550
- await this.personsTurn(run);
2551
- // Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
2552
- // cancel that landed meanwhile stands (the first answer wins, and a stop's withdrawal is never replaced), and the
2553
- // message is then a message, under the run's state now. It declines only the call it read, which the person saw:
2554
- // another parked since waits for its own answer.
2555
- const waiting = waitingApproval(run);
2556
- if (waiting?.id === read.id && !run.cancel && !run.stopping)
2557
- return this.declineBy(run, waiting, content);
2558
- if (run.cancel)
2559
- throw this.finished(run);
2560
- }
2561
- // Every wait first, then a last look for a stop in flight, again after any wait a stop came during: from that look
2562
- // to the count below nothing awaits, so no stop can begin in between.
2563
- do {
2564
- // A stop in flight is answered first. Sent between its mark and its abort, a message would read the run stopped, go
2565
- // to the turn the abort is cutting, and be dropped with it, its row never coming.
2566
- if (run.stopping)
2567
- await this.waitWhile(() => run.stopping === true, 50, "The run is being stopped");
2568
- // A run that reads finished before its end is written (its process still closing, or its carry back waiting on the
2569
- // store) is answered once the end is in: then it is completed and opens again, or it is failed or cancelled.
2570
- if (run.finishing && !run.outcome)
2571
- await this.waitWhile(() => Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
2572
- // A run another message is opening again is answered once that opening is done: reopen() clears the run's end
2573
- // before it lays the run's notes again (learning-run.ts onReopen), and a message read meanwhile would launch the run
2574
- // before they are back.
2575
- if (run.reopening)
2576
- await run.reopening.catch(() => undefined);
2577
- // A raised run whose follow-up has not gone yet (its paused process still letting go, or the follow-up being sent)
2578
- // takes a message once it has: after it, as the next turn, never into the process being let go.
2579
- const following = () => continuationOf(run) !== undefined || run.resuming === "sending";
2580
- if (following()) {
2581
- await this.waitWhile(following, 100, "The run's raised cap's follow-up is still being sent");
2582
- // Its follow-up's turn may have ended the run meanwhile (a quick answer): its end is written first, so the message
2583
- // then opens it again, as one to any ended run does, never refused for an end still being written.
2584
- await this.waitWhile(() => run.settles > 0 || Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
2585
- }
2586
- if (run.kind === "agentic" && statusOf(run).status === "completed")
2587
- await (run.reopening ??= this.reopen(run).finally(() => (run.reopening = undefined)));
2588
- } while (run.stopping);
2589
- const steers = this.steers(run);
2590
- const { status, state } = statusOf(run);
2591
- if (TERMINAL.has(status))
2592
- throw this.finished(run);
2593
- // Paused at its cap: a message would be refused for the same room, so the cap is raised first.
2594
- const paused = pausedAt(run);
2595
- if (paused !== undefined)
2596
- 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
- // 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
- // 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");
2600
- const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
2601
- // A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
2602
- if (mode === "answer" && !answers)
2603
- throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
2604
- const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
2605
- // A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
2606
- // starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
2607
- // under the message is a crash's, which keeps its row.
2608
- if (status === "input_required" && state === "idle" && !this.live(run))
2609
- run.followUpOpen = true;
2610
- run.submitted++;
2611
- this.refresh(run);
2612
- try {
2613
- // After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
2614
- // one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
2615
- await this.personsTurn(run);
2616
- await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, answers ? this.messageOrigin?.(run.id, content) : undefined, answers);
2617
- }
2618
- catch (error) {
2619
- run.submitted = Math.max(0, run.submitted - 1);
2620
- this.refresh(run);
2621
- throw error;
2622
- }
2623
- finally {
2624
- run.followUpOpen = undefined;
2625
- }
2626
- return { mode, messageId };
2627
- }
2628
- /** A person's turn is sent next: no turn from here on is the server's own end-of-run turn (tool-gate.ts NOTE_ONLY_TEXT),
2629
- * so its origin goes, right before the turn is sent. */
2630
- async personsTurn(run) {
2631
- // A write of the origin still in flight lands first, then goes: none starts from here (learning-run.ts reflectTurn).
2632
- await run.originWrite?.catch(() => undefined);
2633
- await rm(join(run.dir, TURN_ORIGIN_FILE), { force: true }).catch((error) => warn(run.id, `its turn's origin is not removed: ${error.message}`));
2634
- await runsTestHooks.personsTurn?.(run.dir);
2635
- }
2636
- /** Waits, up to a request's deadline, while `holds` (checked every `everyMs`): else 503 `unavailable`, saying `why`. */
2637
- async waitWhile(holds, everyMs, why) {
2638
- for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); holds(); await sleep(everyMs)) {
2639
- if (Date.now() > deadline)
2640
- throw new ApiError("unavailable", `${why}; try again.`, { retry_after_ms: 1000 }, { "retry-after": "1" });
2641
- }
2642
- }
2643
- /** A completed agentic run that gets a follow-up opens again: the same run on its own store and session, under its
2644
- * cap, taking a place under the server's. Launched here, with no wait after the place is taken, so no start takes
2645
- * it meanwhile. An archived run, or a run of an archived agent, stays closed. */
2646
- async reopen(run) {
2647
- await this.sweepOnce();
2648
- await this.pinNeeds(run);
2649
- const row = this.store.readRun(run.id);
2650
- if (row?.archivedAt)
2651
- throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
2652
- // Its end could not be written yet (persistLater tries again): it opens once the store has it.
2653
- if (row?.state === "running")
2654
- 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" });
2655
- const release = await this.takePlace(run.harness);
2656
- try {
2657
- // Read again: the place may have been waited for, and the run (or its agent) archived meanwhile.
2658
- const now = this.store.readRun(run.id);
2659
- if (now?.archivedAt)
2660
- throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
2661
- if (now?.state === "running")
2662
- 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" });
2663
- // Its end's run.ended in the outbox on disk before the run opens again, or not opened: once the row runs, no start finds
2664
- // the end to queue it.
2665
- if (now?.endedAt && this.notice(run, "run.ended", now.endedAt) === "unsaved")
2666
- throw new ApiError("unavailable", "The run's end is still being announced to its webhook; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
2667
- try {
2668
- this.store.reopenRun(run.id);
2669
- }
2670
- catch (error) {
2671
- storeError(error, "run");
2672
- }
2673
- run.outcome = undefined;
2674
- // With its outcome cleared the run reads open. Messages wait for this reopen (message()), so its launch below is
2675
- // the follow-up's; set here, with the outcome, whichever launch comes first carries the flag (launch() takes it).
2676
- run.followUpOpen = true;
2677
- run.settled = false;
2678
- run.endedAt = undefined;
2679
- run.error = undefined;
2680
- delete run.meta.error;
2681
- run.relaunches = 0;
2682
- // A run that learns finds its agent's notes in its work again (learning-run.ts).
2683
- await this.learning.onReopen(run);
2684
- await this.pinSignIn(run);
2685
- await this.beforeReopenLaunch?.(run.id);
2686
- this.refresh(run);
2687
- // Opened for the follow-up: the run had answered, so its open resumes nothing.
2688
- this.launch(run, true);
2689
- }
2690
- finally {
2691
- // Launched, it holds its place as a live run.
2692
- release();
2693
- }
2694
- // An end-of-run turn its process went in is aborted before the follow-up is sent (learning-run.ts).
2695
- await this.learning.afterReopen(run);
2696
- }
2697
- /** Waits, up to a request's deadline, until a live run's rows show every message sent to it, and any rows at all: its
2698
- * record has caught up with its process. Its end, a cancel or its process going ends the wait. */
2699
- async caughtUp(run) {
2700
- for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); run.submitted > 0 || !run.rows.length; await run.log.changed(100)) {
2701
- if (!this.live(run) || run.finishing || run.outcome || run.cancel || Date.now() > deadline)
2702
- return;
2703
- }
2704
- }
2705
- /** Abort the turn that is running; the run stays open, `input_required` and idle. A workflow run has no turn to stop. */
2706
- async stop(run) {
2707
- // The contract's stop has no refusal: an imported run answers as any ended one, stopped false, and nothing moves.
2708
- if (run.imported)
2709
- return false;
2710
- // A message sent to the run shows in its rows only once its door's events bring it: until then the run reads queued
2711
- // (state working), or holds a message not shown, however far its process is into the turn. The stop waits for its
2712
- // rows first, so the mark it saves (the person's last message) covers the message the turn answers; then it stops
2713
- // the turn as it stops any working run.
2714
- if (run.kind !== "workflow")
2715
- await this.caughtUp(run);
2716
- // A tool call that waits for approval is withdrawn by the stop (never run, an answer after is 409); then a turn that
2717
- // runs meanwhile is stopped as any working run's is, and with none the run is stopped as a stop leaves one.
2718
- const open = run.kind === "agentic" && !run.cancel && !run.outcome && !run.finishing;
2719
- const withdrawn = open && waitingApproval(run) ? await this.withdraw(run) : false;
2720
- // An answer the run's process has not acted on yet is overridden too: a stop wins, so nothing runs and nothing resumes.
2721
- const superseded = open ? await this.supersede(run, "withdrawn") : false;
2722
- const { status, state } = statusOf(run);
2723
- if (run.kind === "workflow" || !this.live(run) || !(status === "working" && state === "working") || run.submitted > 0)
2724
- return withdrawn || superseded ? this.stopIdle(run) : false;
2725
- run.stopping = true;
2726
- try {
2727
- return await this.stopTurn(run);
2728
- }
2729
- finally {
2730
- run.stopping = undefined;
2731
- }
2732
- }
2733
- /** message()'s decline of the tool call that waits for approval: a deny with the message as its note, which the
2734
- * run's gate acts on as any deny, resuming the session with the refusal and the person's words in one message. */
2735
- async declineBy(run, waiting, content) {
2736
- // The person's message, whole: it is the reason the model reads. Nothing shows the note, so nothing cuts it.
2737
- run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "deny", note: content, answered_at: new Date().toISOString(), args_shown: shownArgs(waiting, this.redactor(run)), by: "message" } };
2738
- await this.saveMeta(run);
2739
- this.restate(run);
2740
- this.refresh(run);
2741
- 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}`));
2743
- return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
2744
- }
2745
- /** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
2746
- * `withdrawn` or `canceled`, each keeping the answer it superseded, so nothing runs and nothing resumes, and the
2747
- * history shows what was given. The run's gate reads the answer again just before it acts (tool-gate.ts). */
2748
- async supersede(run, decision) {
2749
- const given = [...(run.approvals?.values() ?? [])].filter((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
2750
- if (!given.length)
2751
- return false;
2752
- const now = new Date().toISOString();
2753
- const overridden = given.map((a) => {
2754
- const was = run.meta.approvals[a.id];
2755
- return [a.id, { decision, answered_at: now, superseded: { decision: was.decision, answered_at: was.answered_at, ...(was.note !== undefined ? { note: was.note } : {}), ...(was.by ? { by: was.by } : {}) } }];
2756
- });
2757
- run.meta.approvals = { ...run.meta.approvals, ...Object.fromEntries(overridden) };
2758
- await this.saveMeta(run);
2759
- this.restate(run);
2760
- return true;
2761
- }
2762
- /** Until every tool call of the run that waited for approval is resolved in its store (its process acted on its answer,
2763
- * or cut it), or `ms` pass. */
2764
- async untilResolved(run, ms) {
2765
- for (const end = Date.now() + ms; [...(run.approvals?.values() ?? [])].some((approval) => !approval.resolved) && Date.now() < end;)
2766
- await sleep(50);
2767
- }
2768
- /** stop()'s withdrawal of the tool call that waits for approval: never run, and an answer after is 409. */
2769
- async withdraw(run) {
2770
- const waiting = waitingApproval(run);
2771
- run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "withdrawn", answered_at: new Date().toISOString() } };
2772
- await this.saveMeta(run);
2773
- this.restate(run);
2774
- return true;
2775
- }
2776
- /** stop() of a run with no turn to abort (parked on an approval it withdrew): the stop's mark, as a stop saves it. */
2777
- async stopIdle(run) {
2778
- delete run.meta.stopped_at;
2779
- delete run.meta.stopped_after;
2780
- Object.assign(run.meta, stopMark(run.rows));
2781
- await this.saveMeta(run);
2782
- this.refresh(run);
2783
- return true;
2784
- }
2785
- /** stop()'s mark and abort, once it took the stop. */
2786
- async stopTurn(run) {
2787
- // Set before the abort: the turn's end can arrive before the door answers, and must not read as an answer.
2788
- const before = { stopped_at: run.meta.stopped_at, stopped_after: run.meta.stopped_after };
2789
- delete run.meta.stopped_at;
2790
- delete run.meta.stopped_after;
2791
- Object.assign(run.meta, stopMark(run.rows));
2792
- await this.saveMeta(run).catch((error) => warn(run.id, `its stop is not saved, so a restart will not keep it: ${error.message}`));
2793
- await this.beforeAbort?.(run.id);
2794
- const answer = await this.toDoor(run, "/abort", {}).catch(() => null);
2795
- if (!answer || answer.status >= 400) {
2796
- if (before.stopped_at === undefined)
2797
- delete run.meta.stopped_at;
2798
- else
2799
- run.meta.stopped_at = before.stopped_at;
2800
- if (before.stopped_after !== undefined)
2801
- run.meta.stopped_after = before.stopped_after;
2802
- await this.saveMeta(run).catch(() => undefined);
2803
- this.refresh(run);
2804
- return false;
2805
- }
2806
- this.refresh(run);
2807
- return true;
2808
- }
2809
- /** A person's answer to the tool call `id` that waits for approval (tool-gate.ts): kept in the run's serve.json before
2810
- * it returns, the first answer winning (the same one again changes nothing; another is 409, `already_answered`). The
2811
- * run's process reads it there, runs or refuses the call, and resumes; a run with no process gets one. */
2812
- async approve(run, id, decision, note) {
2813
- const given = run.meta.approvals?.[id];
2814
- if (!given && !run.approvals?.has(id))
2815
- throw new ApiError("not_found", `The run ${run.id} has no tool call ${id} waiting for approval.`);
2816
- if (given) {
2817
- if (given.decision === decision)
2818
- return;
2819
- throw new ApiError("not_continuable", `The tool call ${id} was already ${given.decision === "canceled" ? "canceled with its run" : given.decision === "withdrawn" ? "withdrawn when its run was stopped" : `answered: ${given.decision}`}.`, { details: { reason: "already_answered", decision: given.decision } });
2820
- }
2821
- run.meta.approvals = { ...run.meta.approvals, [id]: { decision, ...(note ? { note } : {}), answered_at: new Date().toISOString(), args_shown: shownArgs(run.approvals.get(id), this.redactor(run)) } };
2822
- await this.saveMeta(run);
2823
- this.restate(run);
2824
- this.refresh(run);
2825
- 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}`));
2827
- }
2828
- /** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
2829
- * its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
2830
- * run reads it once it is carried back, with how its workflow stopped. */
2831
- async cancel(run) {
2832
- // As stop: already terminal, and no cancel mark is written.
2833
- if (run.imported)
2834
- return false;
2835
- // Finishing is already ending with its outcome (an answer, a failure, the cap): a run's first end is its last.
2836
- if (run.outcome || run.finishing)
2837
- return false;
2838
- run.cancel = true;
2839
- // A tool call that waits for approval is canceled with its run: an answer after this one is refused.
2840
- const waiting = waitingApproval(run);
2841
- if (waiting) {
2842
- run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "canceled", answered_at: new Date().toISOString() } };
2843
- await this.saveMeta(run).catch((error) => warn(run.id, `its canceled approval is not saved: ${error.message}`));
2844
- this.restate(run);
2845
- }
2846
- // An answer its process has not acted on yet is overridden too: nothing runs and nothing resumes.
2847
- const superseded = await this.supersede(run, "canceled").catch((error) => (warn(run.id, `its superseded approval is not saved: ${error.message}`), false));
2848
- if (run.kind === "agentic") {
2849
- run.finishing = "cancelled";
2850
- run.endedAt = new Date().toISOString();
2851
- this.mark(run);
2852
- }
2853
- // First, so no request leaves after the cancel landed, whether or not the process can be reached yet.
2854
- await writeWhole(join(run.dir, RUN_CANCELLED), "").catch((error) => warn(run.id, `its cancel mark is not written: ${error.message}`));
2855
- if (this.live(run)) {
2856
- // The turn is aborted first, so the drain that SIGTERM starts does not wait for it.
2857
- await this.abortTurn(run);
2858
- // An approved call in flight runs outside any turn: its process's gate cuts it once it reads the cancel (tool-gate.ts),
2859
- // which ending the process at once would forestall. A short wait for that, never a refusal.
2860
- if (superseded) {
2861
- run.meta.cancel_waits_for = [...(run.approvals?.values() ?? [])].filter((approval) => !approval.resolved).map((approval) => approval.id);
2862
- await this.saveMeta(run).catch((error) => warn(run.id, `its cancel's wait is not saved: ${error.message}`));
2863
- await this.untilResolved(run, 3_000);
2864
- }
2865
- this.terminate(run);
2866
- }
2867
- else
2868
- await this.settle(run, null, false);
2869
- return true;
2870
- }
2871
- /** Pause a workflow run (`paused` true) or resume it: the mark in its directory, which its process reads before each
2872
- * node starts. A run that has ended is not continuable. */
2873
- async pause(run, paused) {
2874
- if (run.kind !== "workflow")
2875
- throw unsupported("runs.pause", "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.");
2876
- if (TERMINAL.has(statusOf(run).status) || run.cancel)
2877
- throw this.finished(run);
2878
- const mark = join(run.dir, RUN_PAUSED);
2879
- if (paused)
2880
- await writeWhole(mark, `${new Date().toISOString()}\n`);
2881
- else
2882
- await rm(mark, { force: true });
2883
- this.mark(run);
2884
- return { run_id: run.id, paused, status: statusOf(run).status };
2885
- }
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
- /** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
2921
- killAfterMs() {
2922
- return (durationMs(this.options.drainTimeout ?? DRAIN) ?? 30_000) + 1_000;
2923
- }
2924
- /** What close() will wait on: the runs whose processes are left to finish their turn (those this server started, and
2925
- * those it adopted), and the longest it can wait on them: a kill bound for the started ones, and one more for the
2926
- * adopted ones, which it stops after them. */
2927
- stopping() {
2928
- const all = [...this.runs.values()];
2929
- const started = all.filter((run) => run.child).length;
2930
- const adopted = all.filter((run) => !run.child && run.orphan && alive(run.orphan)).length;
2931
- return { runs: started + adopted, boundMs: (started ? this.killAfterMs() : 0) + (adopted ? this.killAfterMs() : 0) };
2932
- }
2933
- async close() {
2934
- this.closing = true;
2935
- this.learning.close();
2936
- const live = [...this.runs.values()].filter((run) => run.child);
2937
- for (const run of live) {
2938
- run.child.kill("SIGTERM");
2939
- setTimeout(() => run.child?.exitCode === null && run.child.kill("SIGKILL"), this.killAfterMs()).unref();
2940
- }
2941
- await Promise.all(live.map((run) => new Promise((resolve) => (run.child ? run.child.once("exit", resolve) : resolve(undefined)))));
2942
- // 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));
2944
- for (const run of adopted)
2945
- this.terminate(run);
2946
- for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphan && alive(run.orphan)) && Date.now() < deadline;)
2947
- await sleep(100);
2948
- await sleep(0);
2949
- await Promise.all([...this.runs.values()].map((run) => run.settling));
2950
- await this.learning.idle();
2951
- for (const run of this.runs.values())
2952
- run.feed?.abort();
2953
- this.closed = true;
2954
- }
2955
- // ---- views ------------------------------------------------------------------------------------------------------------
2956
- /** A run's cost from its rows, else what the store recorded when it carried the run back. */
2957
- cost(run) {
2958
- // An imported run's cost is its source's, for the whole session: its requests may not each have a price.
2959
- const usd = run.imported ? (run.costUsd ?? null) : costView(run.rows, run.costUsd, run.decisionCost);
2960
- // Unknown: what it cost so far and how many charges have no price (costsofar/1), from its rows, else what it said at
2961
- // its end (a run carried back with no rows read since).
2962
- 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) {
2969
- const stored = known ? (known.stored ?? undefined) : await this.options.agents.request(() => this.store.readRun(run.id));
2970
- // After the read: the run may have moved on while it waited, and every field below is of this one moment.
2971
- const { status, state } = statusOf(run);
2972
- const row = TERMINAL.has(status) ? stored : undefined;
2973
- // The whole text of the answer the run's turn ended on (answerOfRun), never the line the store keeps, which is cut;
2974
- // 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);
2976
- // When the turn of a message still open last wrote: a run working shows it is moving, or not.
2977
- const progress = TERMINAL.has(status) || run.kind === "workflow" ? undefined : run.turns.progressAt();
2978
- // A run its cap stopped keeps the answer it paid for.
2979
- const kept = status === "failed" && run.error?.code === SPEND_CAP_REACHED ? lastAnswer(run) : null;
2980
- const endedAt = TERMINAL.has(status) ? (row?.endedAt ?? run.endedAt ?? run.updatedAt) : null;
2981
- return {
2982
- run_id: run.id,
2983
- agent_id: run.agentId,
2984
- agent_version: run.version,
2985
- revision: run.revision,
2986
- kind: run.kind,
2987
- sha: null,
2988
- status,
2989
- state,
2990
- title: run.meta.title,
2991
- place: run.meta.place ?? { mode: "runner" },
2992
- ...(run.meta.effort ? { effort: run.meta.effort } : {}),
2993
- created_at: run.meta.created_at,
2994
- updated_at: run.updatedAt,
2995
- ended_at: endedAt,
2996
- // 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,
3001
- cost: this.cost(run),
3002
- archived_at: stored?.archivedAt ?? null,
3003
- imported_from: run.imported ?? null,
3004
- trigger: run.meta.trigger ?? null,
3005
- // 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),
3007
- poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
3008
- last_progress_at: progress === undefined ? null : new Date(progress).toISOString(),
3009
- };
3010
- }
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) };
3014
- }
3015
- /** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
3016
- async statusOfRow(row) {
3017
- if (row.state !== "running")
3018
- return STATUS_OF[row.state];
3019
- const run = await this.get(row.id);
3020
- return run ? statusOf(run).status : "queued";
3021
- }
3022
- /** 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
- * not its store; `versions` numbers its agent's revisions. */
3024
- async summaryOfRow(row, versions) {
3025
- const known = this.runs.get(row.id) ?? (row.state === "running" ? await this.get(row.id) : null);
3026
- if (known)
3027
- return this.summary(known);
3028
- const meta = (await readJson(join(this.options.agents.dir, "runs", row.id, RUN_META)));
3029
- 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,
3031
- status: STATUS_OF[row.state], state: "idle", title: typeof meta?.title === "string" ? meta.title : "",
3032
- ...(typeof meta?.effort === "string" ? { effort: meta.effort } : {}),
3033
- 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) ?? {}) : {}) },
3037
- archived_at: row.archivedAt ?? null,
3038
- // A run read from its row alone has ended: it waits on nothing.
3039
- pending: null,
3040
- imported_from: row.importedFrom ?? null,
3041
- trigger: triggerOf(meta),
3042
- // 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),
3044
- };
3045
- }
3046
- /** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
3047
- * of the keys as they are now (learning-run.ts shown, decision-rows.ts), as its view and its lists already are from
3048
- * the next read on. */
3049
- keysChanged() {
3050
- this.learning.keysChanged();
3051
- // A run's learning row and its decision rows are shown again with the keys as they are now (show): a key saved after
3052
- // a workflow ended is redacted from its decisions on the next read, learning or not.
3053
- for (const run of this.runs.values())
3054
- if (run.meta.learning || run.decisions)
3055
- this.show(run);
3056
- }
3057
- /** A held run's learning, in short (learning-run.ts heldLearning). */
3058
- heldLearning(runId) {
3059
- return this.learning.heldLearning(runId);
3060
- }
3061
- /** The timeline from change `after`, held up to `waitMs` for a change when there is none. */
3062
- async page(run, after, waitMs, limit) {
3063
- const deadline = Date.now() + waitMs;
3064
- for (;;) {
3065
- const page = run.log.page(after, limit);
3066
- const { status, state } = statusOf(run);
3067
- const final = TERMINAL.has(status) && run.settled;
3068
- if (!page.unchanged || final || Date.now() >= deadline)
3069
- return { ...page, status, state, final };
3070
- await run.log.changed(deadline - Date.now());
3071
- }
3072
- }
3073
- }