@parcha/agentrun-serve 0.1.0-beta.35 → 0.1.0-beta.36

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 (372) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +260 -168
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-images.d.ts +15 -0
  15. package/dist/attach-images.js +59 -0
  16. package/dist/background.d.ts +0 -6
  17. package/dist/background.js +0 -28
  18. package/dist/box-image.d.ts +1 -97
  19. package/dist/box-image.js +4 -284
  20. package/dist/box-paths.d.ts +2 -7
  21. package/dist/box-paths.js +7 -13
  22. package/dist/box-settings.d.ts +0 -11
  23. package/dist/box-settings.js +4 -29
  24. package/dist/browser-commands.js +1 -1
  25. package/dist/browser-computer.d.ts +47 -3
  26. package/dist/browser-computer.js +286 -18
  27. package/dist/browser-person.d.ts +19 -2
  28. package/dist/browser-person.js +55 -6
  29. package/dist/browser-wait-ended.d.ts +23 -0
  30. package/dist/browser-wait-ended.js +42 -0
  31. package/dist/cap.d.ts +13 -41
  32. package/dist/cap.js +24 -73
  33. package/dist/cli.js +4 -22
  34. package/dist/computer-routes.d.ts +1 -4
  35. package/dist/computer-routes.js +3 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +38 -1
  38. package/dist/computer-view.d.ts +11 -2
  39. package/dist/computer-view.js +2 -1
  40. package/dist/computers.d.ts +48 -7
  41. package/dist/computers.js +100 -23
  42. package/dist/console/assets/index-BI4Byidu.js +550 -0
  43. package/dist/console/assets/index-C19gUF2n.css +1 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/docker-daemon.d.ts +2 -2
  46. package/dist/docker-daemon.js +2 -2
  47. package/dist/errors.js +5 -5
  48. package/dist/faux-computers.js +4 -0
  49. package/dist/files.d.ts +1 -9
  50. package/dist/files.js +1 -9
  51. package/dist/github.d.ts +22 -2
  52. package/dist/github.js +42 -8
  53. package/dist/gpu-words.d.ts +14 -0
  54. package/dist/gpu-words.js +21 -0
  55. package/dist/graph-view.d.ts +2 -0
  56. package/dist/graph-view.js +25 -1
  57. package/dist/handed-values.d.ts +1 -1
  58. package/dist/handed-values.js +1 -1
  59. package/dist/harness-install.d.ts +60 -3
  60. package/dist/harness-install.js +322 -34
  61. package/dist/harness.js +1 -1
  62. package/dist/host-tools.d.ts +8 -9
  63. package/dist/host-tools.js +7 -7
  64. package/dist/index.d.ts +1 -3
  65. package/dist/index.js +1 -2
  66. package/dist/key-refusal.d.ts +1 -1
  67. package/dist/key-refusal.js +2 -2
  68. package/dist/learn/check.d.ts +7 -1
  69. package/dist/learn/check.js +123 -5
  70. package/dist/learn/commit.d.ts +40 -6
  71. package/dist/learn/commit.js +164 -20
  72. package/dist/learn/folder.d.ts +5 -0
  73. package/dist/learn/folder.js +33 -0
  74. package/dist/learn/grade.d.ts +18 -1
  75. package/dist/learn/grade.js +86 -16
  76. package/dist/learn/index.d.ts +1 -1
  77. package/dist/learn/index.js +1 -1
  78. package/dist/learn/learning.sh +12 -1
  79. package/dist/learn/notes.d.ts +3 -0
  80. package/dist/learn/notes.js +3 -0
  81. package/dist/learn/reflect.d.ts +5 -2
  82. package/dist/learn/reflect.js +43 -29
  83. package/dist/learn/skills.d.ts +4 -0
  84. package/dist/learn/skills.js +7 -0
  85. package/dist/learned-nodes.d.ts +6 -2
  86. package/dist/learned-workflow.d.ts +19 -9
  87. package/dist/learned-workflow.js +62 -34
  88. package/dist/learning-cost.d.ts +79 -0
  89. package/dist/learning-cost.js +69 -0
  90. package/dist/learning-routes.d.ts +8 -3
  91. package/dist/learning-routes.js +9 -6
  92. package/dist/learning-words.d.ts +3 -0
  93. package/dist/learning-words.js +6 -2
  94. package/dist/learning.d.ts +13 -6
  95. package/dist/learning.js +4 -2
  96. package/dist/mcp-probe.d.ts +8 -1
  97. package/dist/mcp-probe.js +62 -20
  98. package/dist/mcp-secret-writes.js +4 -0
  99. package/dist/mcp-servers-store.js +8 -3
  100. package/dist/model.d.ts +5 -5
  101. package/dist/model.js +6 -6
  102. package/dist/openapi.d.ts +2 -0
  103. package/dist/openapi.js +204 -47
  104. package/dist/owner.d.ts +0 -1
  105. package/dist/owner.js +0 -2
  106. package/dist/paid-calls.js +1 -1
  107. package/dist/place-offers.d.ts +97 -0
  108. package/dist/place-offers.js +206 -0
  109. package/dist/place.d.ts +9 -13
  110. package/dist/place.js +22 -32
  111. package/dist/port-models.d.ts +2 -1
  112. package/dist/port-models.js +5 -3
  113. package/dist/print.d.ts +1 -8
  114. package/dist/print.js +1 -14
  115. package/dist/propose.d.ts +1 -0
  116. package/dist/propose.js +25 -10
  117. package/dist/run-cut.d.ts +5 -0
  118. package/dist/run-cut.js +19 -0
  119. package/dist/run-db.js +3 -3
  120. package/dist/run-launch.d.ts +14 -1
  121. package/dist/run-launch.js +7 -2
  122. package/dist/run-learning-served.d.ts +1 -1
  123. package/dist/run-manifest.d.ts +2 -2
  124. package/dist/run-manifest.js +2 -2
  125. package/dist/run-secrets.js +3 -3
  126. package/dist/run-timeline-served.js +56 -44
  127. package/dist/run-view.d.ts +5 -2
  128. package/dist/run-view.js +4 -3
  129. package/dist/runnable.d.ts +2 -2
  130. package/dist/runnable.js +6 -2
  131. package/dist/runner/adapter-loop.d.ts +16 -1
  132. package/dist/runner/adapter-loop.js +131 -30
  133. package/dist/runner/adapter-run-spec.d.ts +25 -4
  134. package/dist/runner/adapter-run-spec.js +103 -24
  135. package/dist/runner/adapters/pi.d.ts +11 -3
  136. package/dist/runner/adapters/pi.js +35 -12
  137. package/dist/runner/beside.js +6 -2
  138. package/dist/runner/cli-run-spec.d.ts +7 -0
  139. package/dist/runner/cli-run-spec.js +92 -38
  140. package/dist/runner/commands.d.ts +5 -1
  141. package/dist/runner/commands.js +3 -3
  142. package/dist/runner/conformance/harness.d.ts +0 -1
  143. package/dist/runner/conformance/harness.js +8 -5
  144. package/dist/runner/github-app.js +2 -2
  145. package/dist/runner/harness-loops.js +1 -1
  146. package/dist/runner/journal-kinds.d.ts +15 -5
  147. package/dist/runner/journal-kinds.js +6 -1
  148. package/dist/runner/learning-end.d.ts +15 -0
  149. package/dist/runner/learning-end.js +26 -5
  150. package/dist/runner/learning-factory.js +6 -2
  151. package/dist/runner/learning-loop.d.ts +73 -1
  152. package/dist/runner/learning-loop.js +203 -18
  153. package/dist/runner/learning-seed.d.ts +2 -0
  154. package/dist/runner/learning-seed.js +1 -1
  155. package/dist/runner/loop-contract.d.ts +8 -0
  156. package/dist/runner/loop-contract.js +6 -0
  157. package/dist/runner/loop.d.ts +5 -1
  158. package/dist/runner/loop.js +20 -0
  159. package/dist/runner/main.js +12 -2
  160. package/dist/runner/mcp-claim.d.ts +4 -0
  161. package/dist/runner/mcp-claim.js +29 -1
  162. package/dist/runner/mcp-github.d.ts +4 -2
  163. package/dist/runner/mcp-github.js +0 -7
  164. package/dist/runner/mcp-run.d.ts +2 -0
  165. package/dist/runner/mcp-run.js +1 -0
  166. package/dist/runner/metrics.d.ts +4 -0
  167. package/dist/runner/metrics.js +9 -0
  168. package/dist/runner/model-route.d.ts +3 -0
  169. package/dist/runner/model-route.js +5 -2
  170. package/dist/runner/pr-checkout.d.ts +59 -0
  171. package/dist/runner/pr-checkout.js +176 -0
  172. package/dist/runner/reflect-hook.d.ts +1 -0
  173. package/dist/runner/reflect-hook.js +3 -3
  174. package/dist/runner/runner.js +47 -12
  175. package/dist/runner/spec-holds.d.ts +8 -3
  176. package/dist/runner/spec-holds.js +12 -10
  177. package/dist/runner/store-port.d.ts +4 -1
  178. package/dist/runner/store-secrets.js +17 -1
  179. package/dist/runner/subagent.d.ts +44 -0
  180. package/dist/runner/subagent.js +188 -0
  181. package/dist/runner/workflow-host.d.ts +18 -2
  182. package/dist/runner/workflow-host.js +23 -3
  183. package/dist/runner/workflow-loop.d.ts +5 -2
  184. package/dist/runner/workflow-loop.js +9 -8
  185. package/dist/runner/workflow-spec.d.ts +26 -14
  186. package/dist/runner/workflow-spec.js +97 -30
  187. package/dist/runs-over-store.d.ts +11 -6
  188. package/dist/runs-over-store.js +111 -24
  189. package/dist/sealing.js +1 -2
  190. package/dist/secret-cut.d.ts +1 -1
  191. package/dist/secret-cut.js +1 -1
  192. package/dist/server.d.ts +32 -49
  193. package/dist/server.js +249 -199
  194. package/dist/store/agent-body.d.ts +9 -2
  195. package/dist/store/agent-body.js +16 -8
  196. package/dist/store/deadline.js +9 -5
  197. package/dist/store/index.d.ts +3 -3
  198. package/dist/store/index.js +2 -2
  199. package/dist/store/journal/storage.js +2 -1
  200. package/dist/store/postgres/connection.js +9 -4
  201. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  202. package/dist/store/schema.d.ts +2 -1
  203. package/dist/store/schema.js +11 -8
  204. package/dist/store/seal.d.ts +13 -0
  205. package/dist/store/seal.js +19 -0
  206. package/dist/store/sqlite/connection.d.ts +5 -0
  207. package/dist/store/sqlite/connection.js +88 -47
  208. package/dist/store/sqlite/run-patch.d.ts +18 -2
  209. package/dist/store/sqlite/run-patch.js +31 -2
  210. package/dist/store/sqlite/store.js +65 -11
  211. package/dist/store/store.d.ts +62 -12
  212. package/dist/store/store.js +22 -1
  213. package/dist/store-reads/analytics.js +3 -2
  214. package/dist/store-reads/cap.d.ts +1 -3
  215. package/dist/store-reads/cap.js +8 -6
  216. package/dist/store-reads/decisions.d.ts +2 -2
  217. package/dist/store-reads/decisions.js +3 -6
  218. package/dist/store-reads/journal.js +45 -12
  219. package/dist/store-reads/learning.d.ts +15 -1
  220. package/dist/store-reads/learning.js +68 -10
  221. package/dist/store-reads/runs.d.ts +6 -4
  222. package/dist/store-reads/runs.js +17 -10
  223. package/dist/store-reads/stats.js +5 -1
  224. package/dist/store-view.js +45 -19
  225. package/dist/template-eval.js +2 -1
  226. package/dist/templates.d.ts +64 -0
  227. package/dist/templates.js +101 -16
  228. package/dist/timeline/timeline.d.ts +3 -1
  229. package/dist/timeline/timeline.js +19 -4
  230. package/dist/tool-blurbs.js +1 -0
  231. package/dist/tool-budget.d.ts +8 -0
  232. package/dist/tool-budget.js +7 -1
  233. package/dist/tool-gate.d.ts +7 -1
  234. package/dist/tool-gate.js +7 -2
  235. package/dist/tool-plane.d.ts +33 -19
  236. package/dist/tool-plane.js +64 -27
  237. package/dist/tools.d.ts +18 -34
  238. package/dist/tools.js +104 -70
  239. package/dist/trigger-signatures.d.ts +1 -0
  240. package/dist/trigger-signatures.js +3 -1
  241. package/dist/triggers.d.ts +3 -3
  242. package/dist/triggers.js +2 -2
  243. package/dist/turn-end.d.ts +0 -3
  244. package/dist/turn-end.js +0 -3
  245. package/dist/usage-lines.d.ts +1 -1
  246. package/dist/validate.d.ts +6 -0
  247. package/dist/validate.js +30 -3
  248. package/dist/webhooks.d.ts +2 -1
  249. package/dist/webhooks.js +5 -2
  250. package/dist/workflow/decision-recovery.d.ts +23 -0
  251. package/dist/workflow/decision-recovery.js +80 -0
  252. package/dist/workflow/decisions.d.ts +134 -0
  253. package/dist/workflow/decisions.js +46 -0
  254. package/dist/workflow/host-session.d.ts +5 -0
  255. package/dist/workflow/host-session.js +85 -0
  256. package/dist/workflow/host-tools.d.ts +3 -0
  257. package/dist/workflow/host-tools.js +3 -0
  258. package/dist/workflow/node-runner.d.ts +112 -0
  259. package/dist/workflow/node-runner.js +270 -0
  260. package/dist/workflow/node.d.ts +88 -0
  261. package/dist/workflow/node.js +99 -0
  262. package/dist/workflow/operator-error.d.ts +4 -0
  263. package/dist/workflow/operator-error.js +4 -0
  264. package/dist/workflow/pi-versions.d.ts +9 -0
  265. package/dist/workflow/pi-versions.js +8 -0
  266. package/dist/workflow/readers.d.ts +36 -0
  267. package/dist/workflow/readers.js +145 -0
  268. package/dist/workflow/record-file.d.ts +10 -0
  269. package/dist/workflow/record-file.js +56 -0
  270. package/dist/workflow/record-tool.d.ts +76 -0
  271. package/dist/workflow/record-tool.js +126 -0
  272. package/dist/workflow/record.d.ts +151 -0
  273. package/dist/workflow/record.js +401 -0
  274. package/dist/workflow/run-error.d.ts +16 -0
  275. package/dist/workflow/run-error.js +26 -0
  276. package/dist/workflow/runner.d.ts +6 -0
  277. package/dist/workflow/runner.js +240 -0
  278. package/dist/workflow/store.d.ts +23 -0
  279. package/dist/workflow/store.js +242 -0
  280. package/dist/workflow/task.d.ts +133 -0
  281. package/dist/workflow/task.js +411 -0
  282. package/dist/workflow/thinking.d.ts +3 -0
  283. package/dist/workflow/thinking.js +7 -0
  284. package/dist/workflow/tool-context.d.ts +21 -0
  285. package/dist/workflow/tool-context.js +13 -0
  286. package/dist/workflow/types.d.ts +126 -0
  287. package/dist/workflow/types.js +1 -0
  288. package/dist/workflow/wal.d.ts +11 -0
  289. package/dist/workflow/wal.js +106 -0
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/agent-computer.d.ts +137 -0
  292. package/dist/workspace/agent-computer.js +292 -0
  293. package/dist/workspace/archil-claim.d.ts +11 -0
  294. package/dist/workspace/archil-claim.js +18 -10
  295. package/dist/workspace/archil-disks.d.ts +49 -0
  296. package/dist/workspace/archil-disks.js +185 -0
  297. package/dist/workspace/archil-exec.js +2 -3
  298. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  299. package/dist/workspace/archil-mount-credential.js +13 -4
  300. package/dist/workspace/computer-deps.d.ts +16 -8
  301. package/dist/workspace/computer-deps.js +18 -7
  302. package/dist/workspace/computer-for-claim.d.ts +42 -6
  303. package/dist/workspace/computer-for-claim.js +209 -9
  304. package/dist/workspace/computer-janitor.d.ts +3 -2
  305. package/dist/workspace/computer-janitor.js +43 -9
  306. package/dist/workspace/computer-ledger.d.ts +3 -1
  307. package/dist/workspace/computer-ledger.js +7 -0
  308. package/dist/workspace/index.d.ts +3 -2
  309. package/dist/workspace/index.js +1 -0
  310. package/dist/workspace/resolve-computer.d.ts +42 -11
  311. package/dist/workspace/resolve-computer.js +65 -13
  312. package/dist/workspace/run-disk.d.ts +34 -0
  313. package/dist/workspace/run-disk.js +91 -0
  314. package/dist/workspace/run-tools.d.ts +4 -4
  315. package/dist/workspace/run-tools.js +8 -6
  316. package/dist/workspace/server-run-workspace.d.ts +3 -2
  317. package/dist/workspace/server-run-workspace.js +17 -4
  318. package/dist/workspace.js +1 -1
  319. package/package.json +10 -15
  320. package/templates/README.md +9 -6
  321. package/templates/code-review/agent.md +27 -11
  322. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  323. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  324. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  325. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  326. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  327. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  328. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  329. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  330. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  331. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  332. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  333. package/templates/code-review/evals/re-review/prompt.md +1 -1
  334. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  335. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  336. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  337. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  338. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  339. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  340. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  341. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  342. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  343. package/templates/code-review/findings.schema.json +131 -27
  344. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  345. package/templates/code-review/skills/review/DEEP.md +130 -0
  346. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  347. package/templates/code-review/skills/review/SKILL.md +104 -154
  348. package/dist/box/record.d.ts +0 -6
  349. package/dist/box/record.js +0 -41
  350. package/dist/box/sweep.d.ts +0 -53
  351. package/dist/box/sweep.js +0 -193
  352. package/dist/box-egress-vm.d.ts +0 -118
  353. package/dist/box-egress-vm.js +0 -354
  354. package/dist/box-egress.d.ts +0 -105
  355. package/dist/box-egress.js +0 -256
  356. package/dist/box-relay-vm.d.ts +0 -84
  357. package/dist/box-relay-vm.js +0 -437
  358. package/dist/box-relay.d.ts +0 -36
  359. package/dist/box-relay.js +0 -207
  360. package/dist/boxes.d.ts +0 -109
  361. package/dist/boxes.js +0 -249
  362. package/dist/budget.d.ts +0 -71
  363. package/dist/budget.js +0 -199
  364. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  365. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  366. package/dist/daytona-api.d.ts +0 -10
  367. package/dist/daytona-api.js +0 -20
  368. package/dist/egress-proxy.d.ts +0 -45
  369. package/dist/egress-proxy.js +0 -416
  370. package/dist/egress-table.d.ts +0 -24
  371. package/dist/egress-table.js +0 -165
  372. package/templates/code-review/rules/REVIEW.md +0 -41
package/dist/server.js CHANGED
@@ -31,12 +31,12 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
31
31
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
32
32
  import { IMPORT_ASKED } from "./import.js";
33
33
  import { answerStoreCall } from "./import-proxy.js";
34
- import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
34
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, seedOf } from "./learning.js";
35
35
  import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
36
36
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
37
37
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
38
- import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
39
- import { BOX_ALLOW_ENV, boxAllowOf, boxAllowSetIn, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./box-settings.js";
38
+ import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
39
+ import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
40
40
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
41
41
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
42
42
  import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
@@ -44,6 +44,7 @@ import { hostFix, hostName, loopbackNames } from "./host-check.js";
44
44
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
45
45
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
46
  import { computerView } from "./computer-view.js";
47
+ import { screenWaitEnded } from "./browser-wait-ended.js";
47
48
  import { durationMs, logLine } from "./print.js";
48
49
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
49
50
  import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
@@ -62,21 +63,17 @@ import { watchRun } from "./live/stream.js";
62
63
  import { stats as statsOverStore } from "./store-reads/stats.js";
63
64
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
64
65
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
65
- import { openStore, StoreOwned, storeTarget } from "./store/index.js";
66
+ import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
66
67
  import { answerOf, logged } from "./agents.js";
67
68
  import { FINAL_STATES } from "./store/store.js";
68
69
  import { runModelRef } from "./model.js";
69
70
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
70
71
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
71
72
  import { runLines } from "./usage-lines.js";
72
- import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
73
+ import { boxesByDefault, boxesLog, enabledBoxes, placeOffers, withNetworks } from "./place-offers.js";
74
+ import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
73
75
  import { dockerDaemonCheck } from "./docker-daemon.js";
74
- import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
75
- import { startEgressContainer } from "./box-egress-vm.js";
76
- import { dockerComputerRefusal, dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
77
76
  import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
78
- import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
79
- import { vmRelay } from "./box-relay-vm.js";
80
77
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
81
78
  import { CAP_MODES } from "./cap.js";
82
79
  import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
@@ -86,12 +83,13 @@ import { bootSealKey, withSealKey } from "./seal-key.js";
86
83
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
87
84
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
88
85
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
89
- import { agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
86
+ import { agentCostOverStore, agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
87
+ import { costCsv, learningCostQuery } from "./learning-cost.js";
90
88
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
91
89
  import { toolKeysOverStore } from "./tool-keys-store.js";
92
90
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
93
91
  import { signInsOverStore } from "./sign-ins-store.js";
94
- import { MCP_AUTH_TYPES } from "./mcp-probe.js";
92
+ import { MCP_AUTH_TYPES, mcpAuthOf } from "./mcp-probe.js";
95
93
  import { mcpServersOverStore } from "./mcp-servers-store.js";
96
94
  import { privateHostsRoute } from "./mcp-private-hosts.js";
97
95
  import { metaToolOf } from "./mcp-meta.js";
@@ -110,9 +108,9 @@ import { webhook } from "./trigger-webhook.js";
110
108
  import { SCHEME_NAMES } from "./trigger-signatures.js";
111
109
  import { permissionFrom } from "./tool-gate.js";
112
110
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
113
- import { applyBodyOf, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
111
+ import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
114
112
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
115
- import { agentTools, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
113
+ import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
116
114
  import { toolSettingsOverStore } from "./tool-settings-store.js";
117
115
  import { readApprovers, writeApprovers } from "./server-approvers.js";
118
116
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
@@ -120,13 +118,14 @@ import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run
120
118
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
121
119
  import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
122
120
  import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
123
- import { archilRoute, createArchilRoutes } from "./archil-routes.js";
121
+ import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
122
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
124
123
  import { computerOfPlace } from "./computer-setting.js";
125
- import { computerCapabilities, createComputerRoutes, folderModeOf, settingsComputerRoute } from "./computers.js";
124
+ import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
126
125
  import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
127
126
  import { runComputerField } from "./run-computer.js";
128
127
  import { writesHeld } from "./workspace.js";
129
- import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
128
+ import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
129
  import { keyReader } from "./key-meta.js";
131
130
  export const CONTRACT = "agentrun.v2/0";
132
131
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
@@ -142,12 +141,6 @@ const MAX_MESSAGE = 20_000;
142
141
  const MAX_WAIT_MS = 25_000;
143
142
  const PAGE_ROWS = 500;
144
143
  const FILE_LIST_CAP = 2_000;
145
- /** What a stopping server's record allows past its runs' kill bound, the cap a start waits under: the runs' carry backs,
146
- * retried while the agent store is held (about 15.5 s), their boxes' cleanup (up to a minute), and the deliveries', the
147
- * listener's and the stores' stop. A start stops waiting sooner once the stopping server's process is gone. */
148
- const STOP_MARGIN_MS = 120_000;
149
- /** A wait, as the stop's lines give it: whole seconds, rounded up, one at least. */
150
- const seconds = (ms) => `${Math.max(1, Math.ceil(ms / 1000))} s`;
151
144
  /** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
152
145
  const noticeOf = (options) => (line) => {
153
146
  try {
@@ -163,7 +156,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
163
156
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
164
157
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
165
158
  * harness's, which scripts the harnesses with or without it. */
166
- const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
159
+ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
167
160
  /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
168
161
  * takes the same (test/support.mjs startInProcessRunner). */
169
162
  export function fauxEnvOf(options) {
@@ -190,8 +183,6 @@ async function tokenIn(file) {
190
183
  return { token, made: true };
191
184
  }
192
185
  const digest = (text) => createHash("sha256").update(text).digest();
193
- /** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
194
- const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
195
186
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
196
187
  const SESSION_S = SESSION_MS / 1000;
197
188
  export const ROUTES = [
@@ -209,6 +200,9 @@ export const ROUTES = [
209
200
  { method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
210
201
  { method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
211
202
  { method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
203
+ // The agent's Archil disk (archil-routes.ts): read, and removed for an archived agent.
204
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/archil$/, name: "getAgentArchil" },
205
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)\/archil$/, name: "deleteAgentArchil" },
212
206
  { method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
213
207
  { method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
214
208
  { method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files$/, name: "listHomeFiles" },
@@ -300,6 +294,7 @@ export const ROUTES = [
300
294
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
301
295
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
302
296
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
297
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
303
298
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
304
299
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
305
300
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
@@ -315,9 +310,12 @@ export const ROUTES = [
315
310
  * learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
316
311
  /** A run's computer as GET /computer reads it with no viewer open: kind browser where its agent has the browser tool, its
317
312
  * kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
318
- * launch would be; off, saying why, where it has none or its browser resolves unavailable here.
313
+ * launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
314
+ * computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
319
315
  * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
320
316
  function computerOf(kept, env, family = "computer") {
317
+ if (kept === ON_COMPUTER)
318
+ return { kind: "browser" };
321
319
  const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
322
320
  if (browser === undefined)
323
321
  return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
@@ -326,18 +324,24 @@ function computerOf(kept, env, family = "computer") {
326
324
  /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
327
325
  * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
328
326
  * a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
329
- * the browser tool, else none. */
327
+ * the browser tool, else none. A revision that grants the tool to an agent whose computer is a browser is ON_COMPUTER:
328
+ * the tool's sessions are that computer's (tools.ts browserComputer), whatever the plane says. */
330
329
  async function keptBrowserOf(store, runId) {
330
+ const runRow = await store.runs.get(runId);
331
+ const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
332
+ const body = revision?.body;
333
+ const granted = (body?.tools ?? []).includes("browser");
334
+ if (granted && body?.computer?.kind === "browser")
335
+ return ON_COMPUTER;
331
336
  const row = await store.runs.launch(runId).catch(() => undefined);
332
337
  const plane = row ? readLaunchBody(row.body)?.plane : undefined;
333
338
  const kept = plane ? keptVendor(plane).browser : undefined;
334
339
  if (kept !== undefined)
335
340
  return kept;
336
- const runRow = await store.runs.get(runId);
337
- const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
338
- const granted = (revision?.body?.tools ?? []).includes("browser");
339
341
  return granted ? "browserbase" : undefined;
340
342
  }
343
+ /** keptBrowserOf's answer for a run whose browser is its agent's browser computer. */
344
+ const ON_COMPUTER = Symbol("the agent's browser computer");
341
345
  const ownedReadAt = (agentId) => (owned) => (owned === SIGN_INS_DIR ? `/v2/agents/${agentId}` : ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
342
346
  /** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
343
347
  export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
@@ -378,7 +382,7 @@ async function needsOf(env) {
378
382
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
379
383
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
380
384
  * AGENTRUN_SERVE_LEARNING's when not given), its tool settings (`toolSettings`, what each web tool resolves to) and the
381
- * box offers (`boxes`, what the box registry set up at the start, boxes.ts), with whether a revision that names no
385
+ * box offers (`boxes`, what the server found at the start, place-offers.ts), with whether a revision that names no
382
386
  * model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
383
387
  * (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
384
388
  * `gradeModel` is its `--grade-model`. */
@@ -393,8 +397,6 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
393
397
  * `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
394
398
  * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
395
399
  * `gradeModel`, its `--grade-model`. */
396
- /** Why a Daytona box has no network although AGENTRUN_BOX_ALLOW names hosts: Daytona refused its domain list (`code`). */
397
- const noListReason = (code) => `Daytona did not keep a sandbox's domain list (${code}), so this server's Daytona boxes have no network until it starts again: Daytona takes a domain list on its tier 3 and 4 only. To keep them closed without trying, set ${BOX_ALLOW_ENV}=none`;
398
400
  export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
399
401
  return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
400
402
  }
@@ -419,7 +421,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
419
421
  backend: "local",
420
422
  contract: CONTRACT,
421
423
  server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
422
- runtimes: ["pi-durable-disk"],
424
+ /** What runs a run here (the contract's `runtimes`, informational): this server's runners, over its one store. */
425
+ runtimes: ["runner"],
423
426
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
424
427
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
425
428
  harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
@@ -464,8 +467,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
464
467
  efforts: [...EFFORTS],
465
468
  thinking: [...THINKING_LEVELS],
466
469
  /** The browser a run's `browser` tool drives: the vendor it resolves to under the server's settings when the tool is
467
- * available here (tools[]), Browserbase's or Kernel's, else none. */
468
- browser: browser?.available ? (browser.resolves?.[DEFAULT_HARNESS] === "kernel" ? "kernel" : "browserbase") : "none",
470
+ * available here (tools[]), a browser provider's id (tool-plane.ts BROWSER_VENDOR_IDS), else none. */
471
+ browser: browser?.available ? ((resolved) => (BROWSER_VENDOR_IDS.includes(resolved ?? "") ? resolved : "browserbase"))(browser.resolves?.[DEFAULT_HARNESS]) : "none",
469
472
  /** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
470
473
  * gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
471
474
  tool_permissions: true,
@@ -545,7 +548,7 @@ export async function startServe(options) {
545
548
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
546
549
  delete process.env[HARNESS_TABLE_ENV];
547
550
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
548
- // Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
551
+ // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
549
552
  const data = await realpath(resolve(options.data));
550
553
  if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
551
554
  throw new Error("the token must be 32 characters or more, with no whitespace");
@@ -557,6 +560,9 @@ export async function startServe(options) {
557
560
  dockerLimitsOf(process.env);
558
561
  // The Docker host's addresses an operator names (workspace/computer-deps.ts): a bad entry stops the start, in words.
559
562
  dockerHostAddressesOf(process.env);
563
+ // The Archil settings an operator sets (archil-settings.ts ARCHIL_SETTINGS_ENV): one of the region and S3 URL without the
564
+ // other, or a value the PUT would refuse, stops the start, in words naming each variable.
565
+ archilSettingsFromEnv(process.env);
560
566
  const boxAllow = boxAllowOf(process.env);
561
567
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
562
568
  const learning = learningOf(process.env, options.learning);
@@ -609,7 +615,7 @@ async function startHolding(options, data, checked, stops) {
609
615
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
610
616
  * read (the view never fails for it). */
611
617
  const learningOfAgent = async (entry) => {
612
- if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning !== true)
618
+ if (learning === "off" || entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
613
619
  return undefined;
614
620
  const pending = await pendingCount(data, entry.agent.id);
615
621
  return pending === undefined ? undefined : { pending };
@@ -779,135 +785,38 @@ async function startHolding(options, data, checked, stops) {
779
785
  else
780
786
  await probe("key");
781
787
  };
782
- // The boxes AGENTRUN_BOXES lists, docker when it is not set, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
783
- // box stands in for Docker, and nothing asks Docker.
784
- // Under --faux, the tests' fake stands in for the VM provider's SDK (startServe's `fauxVm`), never the provider.
785
- const boxes = await boxRegistry(env, options.faux && options.fauxVm ? { vmSdk: () => import(pathToFileURL(resolve(options.fauxVm)).href) } : {});
786
- const fauxBox = options.faux && options.fauxBox ? await fauxBoxes(resolve(options.fauxBox), data) : undefined;
787
- // The Docker box's image, asked of Docker now and pulled in the background when Docker has none (box-image.ts): docker
788
- // is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
789
- // box here there is none, so no run waits on one an earlier start left.
790
- let image;
791
- // What a Docker box's programs reach, resolved once here (box-settings.ts boxNetworkOf): the setting's list, on a Docker
792
- // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
788
+ // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
789
+ // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
790
+ // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
791
+ const fauxDocker = Boolean(options.faux) && options.fauxDocker === true;
792
+ const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker });
793
+ const docker = found.some((offer) => offer.id === "docker" && offer.available);
793
794
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
794
795
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
795
796
  // server is on a host.
796
797
  const fauxMountinfo = options.faux ? (options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV]) : undefined;
797
798
  // Where Docker has this server's files (box-paths.ts): its own, on a host; its container's mount of the data directory,
798
799
  // for a server in a container given Docker's socket; or none, and docker is unavailable, saying why. Under --faux, a
799
- // host's unless the test gives a container's mountinfo.
800
- // Only on Linux: a container of a Docker's own is a Linux one, and a Mac server's boxes take its proxy container's network
801
- // (box-egress-vm.ts), never a volume's subpath of its data.
802
- const platform = options.faux && options.fauxPlatform ? options.fauxPlatform : process.platform;
803
- const dockerPaths = fauxBox || !boxes.provider("docker") || platform !== "linux" ? { here: true } : options.faux ? (fauxMountinfo ? await dockerPathsOf(env, data, { mountinfo: await readFile(fauxMountinfo, "utf8"), inContainer: true }) : { here: true }) : await dockerPathsOf(env, data);
804
- const boxPaths = "paths" in dockerPaths ? dockerPaths.paths : undefined;
805
- const egressParent = boxPaths ? egressParentOf(data) : undefined;
800
+ // host's unless the test gives a container's mountinfo. Only on Linux: a container of a Docker's own is a Linux one.
801
+ const dockerPaths = fauxDocker || !docker || process.platform !== "linux" ? { here: true } : options.faux ? (fauxMountinfo ? await dockerPathsOf(env, data, { mountinfo: await readFile(fauxMountinfo, "utf8"), inContainer: true }) : { here: true }) : await dockerPathsOf(env, data);
806
802
  if ("reason" in dockerPaths)
807
803
  log?.(logLine("box_paths", { reason: dockerPaths.reason }));
808
- const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : !boxes.provider("docker") ? { allow: "none", reason: "no Docker box on this server" } : "reason" in dockerPaths ? { allow: "none", reason: dockerPaths.reason } : egressParent && egressParentTooLong(egressParent) ? { allow: "none", reason: `the data directory's path is too long for a box's network socket (${egressParent} is over ${MAX_EGRESS_PARENT} bytes): give the server a shorter --data` } : await boxNetworkOf(env, { ...(boxPaths ? { mapped: true } : {}), ...(options.faux && options.fauxPlatform ? { platform: options.fauxPlatform } : {}) });
809
- // The proxy directories runs that are gone left in /tmp, or, in a container, on the data directory's mount
810
- // (box-egress.ts): a live run's, any server's, stays.
811
- if (!fauxBox && boxes.provider("docker"))
812
- await sweepEgressDirs(undefined, undefined, egressParent).catch(() => 0);
813
- // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
814
- // (box-egress-vm.ts): a box's network is the list once it is ready, and none, saying why, until then or when it can't start.
815
- let egress;
816
804
  // A run's Docker computer mounts the run's folder, and the computer's daemon, by this server's paths: as they are on
817
805
  // its Docker's own host, or as its named data volume's subpaths from a container of that Docker's (compose.yaml).
818
806
  // Any other layout, or a daemon of another machine (DOCKER_HOST, or the current context's endpoint: box-paths.ts
819
807
  // remoteDockerOnce), can't run one, and says so here (dockerComputerRefusal), where capabilities, the run's start
820
808
  // (dockerAnswers) and a place's box check all read it: no run starts only to fail at its create.
821
- const dockerElsewhere = fauxBox || !boxes.provider("docker") ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
809
+ const dockerElsewhere = fauxDocker || !docker ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
822
810
  // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
823
811
  // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
824
812
  // runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
825
- const hostAddresses = dockerElsewhere === undefined && boxPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
813
+ const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
826
814
  if (hostAddresses)
827
815
  log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
828
816
  const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
829
- // The addresses found, where an operator looks: capabilities' Docker entry.
830
- const hostShown = hostAddresses && hostAddresses.addresses.length > 0 ? { host_addresses: hostAddresses.addresses } : {};
831
- const dockerNetwork = (offer) => {
832
- if (!offer.available)
833
- return offer;
834
- if (dockerRefused !== undefined)
835
- return { id: offer.id, available: false, state: "unavailable", reason: dockerRefused };
836
- if (boxNetwork.allow === "none")
837
- return { ...offer, network: "none", network_reason: boxNetwork.reason };
838
- const proxy = egress?.state();
839
- return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist", ...hostShown };
840
- };
841
- // A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
842
- // one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
843
- let daytonaNoList;
844
- const daytonaNetwork = (offer) => !offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : daytonaNoList ? { ...offer, network: "none", network_reason: noListReason(daytonaNoList) } : { ...offer, network: "allowlist" };
845
- // The VM box has no network whatever AGENTRUN_BOX_ALLOW names: its provider takes a host list, but has no read of a
846
- // box's list back, so the server cannot check one held (run-box.ts ensureRemoteBox makes it blocked). Said, with why.
847
- const vmNetwork = (offer) => (!offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : { ...offer, network: "none", network_reason: VM_NO_LIST });
848
- const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? dockerNetwork({ id: "docker", available: true, reason: "a faux box (tests)" }) : offer.id === "docker" ? dockerNetwork(image ? withImage(offer, image.state()) : offer) : offer.id === "daytona" ? daytonaNetwork(offer) : offer.id === VM_PROVIDER.id ? vmNetwork(offer) : offer));
849
- const imageLog = (state, more = {}) => log?.(logLine("box_image", { image: image.image, state: state.state, ...more, ...("reason" in state ? { reason: state.reason } : {}) }));
850
- let boxOffers = offersNow();
851
- const boxImage = !fauxBox && boxes.provider("docker") ? boxImageOf(env) : undefined;
852
- if (boxImage) {
853
- image = await dockerImage(env, data, boxImage, {
854
- warn: (message) => (log ? log(logLine("box_image", { image: boxImage, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
855
- onChange: (state, ms) => {
856
- boxOffers = offersNow();
857
- imageLog(state, { ms });
858
- options.onBoxImage?.(state);
859
- // The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
860
- // has not ended, by that probe, which reads the box offers when it does.
861
- if (offers)
862
- recompose();
863
- },
864
- });
865
- stops.push(async () => void (await image?.close()));
866
- options.onBoxImage?.(image.state());
867
- }
868
- else
869
- await clearImage(data);
870
- boxOffers = offersNow();
871
- const runBoxes = fauxBox ?? boxes.provider("docker");
872
- // Daytona's boxes are made, seeded, pulled and destroyed here, with the key this server holds; a run's process reaches
873
- // its own through the relay below, which holds the key for it (box-relay.ts).
874
- const remoteBoxes = boxes.provider("daytona");
875
- // And the VM box's, the same way, with this server's SDK client: the relay's VM half makes a run's calls with it.
876
- const vmBoxes = boxes.provider(VM_PROVIDER.id);
877
- const vmClient = boxes.vmClient();
878
- // What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
879
- // process sees it.
880
- const vmSecrets = () => [...serverSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
881
- const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
882
- // Daytona could not keep a run's box's domain list: said in the log and in capabilities, which recompose now.
883
- // Daytona's own words go to the log, so a refusal for another cause is not taken silently for a tier that takes no list.
884
- const onNoBoxList = (code, message) => {
885
- daytonaNoList = code;
886
- log?.(logLine("box_network", { box: "daytona", network: "none", refused: code, message }));
887
- boxOffers = offersNow();
888
- if (offers)
889
- recompose();
890
- };
891
- if (boxNetwork.allow !== "none" && boxNetwork.vm) {
892
- const allow = boxNetwork.allow;
893
- const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
894
- egress = await startEgressContainer({
895
- env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
896
- warn: (message) => (log ? log(logLine("box_egress", { runtime: boxNetwork.vm, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
897
- onChange: (state) => {
898
- egressLog(state);
899
- boxOffers = offersNow();
900
- if (offers)
901
- recompose();
902
- },
903
- });
904
- stops.push(() => egress.close());
905
- egressLog(egress.state());
906
- boxOffers = offersNow();
907
- }
817
+ // Each box with what it reaches (place-offers.ts withNetworks).
818
+ const boxOffers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
908
819
  log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
909
- if (image)
910
- imageLog(image.state());
911
820
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
912
821
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
913
822
  const sealKey = seal.key;
@@ -924,7 +833,7 @@ async function startHolding(options, data, checked, stops) {
924
833
  const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
925
834
  /** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
926
835
  * Computers' view and a run's start check (below) both ask it. Where AGENTRUN_BOXES lists Docker and it is no faux
927
- * box, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
836
+ * Docker, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
928
837
  * daemon that stops after the start is seen, and one that is gone says so in noDockerWords); once it answers, the
929
838
  * box's start-time answer stands. A box the start did not make keeps its reason ("start Docker, then restart
930
839
  * AgentRun"): the start's checks of Docker (Docker elsewhere, this server's paths, host addresses, its network) ran
@@ -935,7 +844,7 @@ async function startHolding(options, data, checked, stops) {
935
844
  const dockerAnswers = async (provider) => {
936
845
  const box = boxAvailability(boxOffers).find((one) => one.id === provider);
937
846
  const local = COMPUTER_PROVIDERS.find((one) => one.id === provider)?.local === true;
938
- if (local && !fauxBox && enabledBoxes(env).has(provider)) {
847
+ if (local && !fauxDocker && enabledBoxes(env).has(provider)) {
939
848
  const daemon = await dockerDaemon();
940
849
  if (!daemon.up || box?.available)
941
850
  return daemon;
@@ -945,12 +854,16 @@ async function startHolding(options, data, checked, stops) {
945
854
  return { up: false, absent: false, reason: box?.reason ?? `${provider} is not a box this server has` };
946
855
  };
947
856
  let computerRoutes;
857
+ // The programs a provider runs on this machine (the phone's adb), looked for on PATH once, at the start, as the boxes
858
+ // probe Docker: a provider whose program is missing is not ready, and its words say what to install.
859
+ const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
948
860
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
949
- store, sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
861
+ store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
950
862
  ...(options.faux
951
863
  // --faux's providers stand in for every vendor's, a local one's daemon included.
952
864
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
953
865
  : {
866
+ hostWhy,
954
867
  kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
955
868
  // The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
956
869
  factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
@@ -962,15 +875,42 @@ async function startHolding(options, data, checked, stops) {
962
875
  * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
963
876
  * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
964
877
  * runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
965
- * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers'. */
878
+ * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers', and whether a
879
+ * provider's program is on this machine is hostWhy's, read at the start. */
966
880
  /** The server's folder mode now: 2 when the owner's Archil settings are saved (the run's folder on the disk), else 1. */
967
- const modeNow = async () => ((await folderModeOf(store)()) === "disk" ? 2 : 1);
968
- const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow);
881
+ const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
882
+ const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
969
883
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
970
884
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
971
885
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
972
886
  const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
973
- const archil = createArchilRoutes({ store, sealKey, env: process.env });
887
+ /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
888
+ * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
889
+ * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
890
+ * is no shell), whose shell runs the shell tools; else none, and why. */
891
+ const shellHere = async () => {
892
+ if ((await shellOf({ kind: "none" })) === "local")
893
+ return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
894
+ const fresh = newAgentPlace(boxOffers);
895
+ let why = "why" in fresh ? fresh.why : "it is not set up";
896
+ if ("place" in fresh && fresh.place.mode === "sandbox") {
897
+ const computer = { kind: "sandbox", provider: fresh.place.box };
898
+ const ready = await computerReady(computer);
899
+ if ("refused" in ready)
900
+ why = ready.refused;
901
+ else if ((await shellOf(computer)) === "computer")
902
+ return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
903
+ }
904
+ return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
905
+ };
906
+ const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
907
+ /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
908
+ * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
909
+ * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
910
+ const shellOfRevision = async (revision) => {
911
+ const body = revision.body;
912
+ return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
913
+ };
974
914
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
975
915
  const runComputerOf = async (runId, view) => {
976
916
  const run = await store.runs.get(runId);
@@ -1080,6 +1020,22 @@ async function startHolding(options, data, checked, stops) {
1080
1020
  readyFiles: (ids) => uploads.readyFiles(ids),
1081
1021
  files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1082
1022
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
1023
+ // The run's Archil disk for its launch record (run-launch.ts archilDisk): the body's, else its agent's when it has one.
1024
+ // A disk the body names is read at Archil once, before the run is made (archil-routes.ts checkLaunchDisk): one that is
1025
+ // not there or not in the key's region is a 422 here, and Mode 1 is too. An agent whose disk is being removed
1026
+ // (archil-routes.ts removeAgentDisk) starts no run on it: 409 until the removal is done.
1027
+ launchDiskOf: async (agentId, named) => {
1028
+ if (named !== undefined) {
1029
+ await archil.checkLaunchDisk(named);
1030
+ return { diskId: named, kind: "launch" };
1031
+ }
1032
+ if (!(await inArchilMode(store, process.env)))
1033
+ return undefined;
1034
+ const own = await agentDiskOf(store, agentId);
1035
+ if (own?.removing)
1036
+ throw new ApiError("agent_not_runnable", `The agent ${agentId}'s Archil disk ${own.diskId} is being removed (DELETE /v2/agents/${agentId}/archil): start the run once that is done, and it gets a new disk.`);
1037
+ return own ? { diskId: own.diskId, kind: "agent" } : undefined;
1038
+ },
1083
1039
  workflowTitle,
1084
1040
  serverSecrets,
1085
1041
  toolSettings: () => settings.get(),
@@ -1136,7 +1092,7 @@ async function startHolding(options, data, checked, stops) {
1136
1092
  // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1137
1093
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1138
1094
  const runReadsDeps = {
1139
- runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
1095
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
1140
1096
  env,
1141
1097
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1142
1098
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
@@ -1453,7 +1409,21 @@ async function startHolding(options, data, checked, stops) {
1453
1409
  const agentExtra = async (entry) => {
1454
1410
  const learning = await learningOfAgent(entry);
1455
1411
  const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1456
- return { signIns: await signIns.view(entry.agent.id), ...(learning ? { learning } : {}), runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length } };
1412
+ return {
1413
+ signIns: await signIns.view(entry.agent.id),
1414
+ ...(learning ? { learning } : {}),
1415
+ runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
1416
+ // The agent's own computer (a persistent setting), as this server records it: the view's own_computer.
1417
+ ownComputer: agentComputerView(await agentComputerOf(store, entry.agent.id)),
1418
+ };
1419
+ };
1420
+ /** Deletes an agent's own computer once the agent has no use for it (archived, persistent turned off, another provider
1421
+ * or image: workspace/agent-computer.ts), after the write that made it so, in the background: a vendor's delete can
1422
+ * take minutes. Until the provider has deleted it, the agent's view shows it deleting, with why where a delete failed. */
1423
+ const reconcileComputer = (agentId) => {
1424
+ void reconcileAgentComputer(store, agentId, (provider, image) => computersOf().providerFor(provider, image))
1425
+ .then((done) => (done ? log?.(logLine("agent_computer", { agent: agentId, ...("deleted" in done ? { deleted: done.deleted } : { failed: done.failed }) })) : undefined))
1426
+ .catch((error) => log?.(logLine("agent_computer", { agent: agentId, failed: error instanceof Error ? error.message : String(error) })));
1457
1427
  };
1458
1428
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
1459
1429
  // routes read from the store + the run view now, not a live Run.
@@ -1468,9 +1438,6 @@ async function startHolding(options, data, checked, stops) {
1468
1438
  const v = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1469
1439
  return { status: v?.status ?? "queued", state: v?.state ?? "idle" };
1470
1440
  };
1471
- /** The run read routes (timeline, files, graph, browser, live viewer) over the store are E2c's run-reads-over-store.ts
1472
- * (watchRun + run-workspace + store-view), not committed yet. TODO(E2c): replace each call with its function on that sha. */
1473
- const runReadsTodo = () => { throw new ApiError("unsupported_here", "run reads over the store (timeline, files, graph, browser) are being wired (run-reads-over-store); not available on this build yet"); };
1474
1441
  const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
1475
1442
  /** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
1476
1443
  * origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
@@ -1658,6 +1625,13 @@ async function startHolding(options, data, checked, stops) {
1658
1625
  const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1659
1626
  throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server }))] });
1660
1627
  }
1628
+ // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
1629
+ // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
1630
+ // whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
1631
+ const pick = pickComputer(pkg, await shellHere());
1632
+ if (pick && "refused" in pick)
1633
+ throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
1634
+ const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1661
1635
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1662
1636
  const skipped = unsaved.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server, so the agent was made without its tools (${need.tools.join(", ")}). Save it in Settings → MCP servers and apply again to grant them.` }));
1663
1637
  const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
@@ -1665,7 +1639,9 @@ async function startHolding(options, data, checked, stops) {
1665
1639
  const model = picked.model;
1666
1640
  // Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
1667
1641
  // choice was not an option here (not_set_up_here would read as a run refused until the host has something).
1668
- const modelWarnings = "warning" in picked && picked.warning ? [{ field: "model", reason: "not_an_option", message: picked.warning }] : [];
1642
+ // The model of each tier its subagents run on (packageTiers): the package's where this server runs it.
1643
+ const tiers = await packageTiers(env, pkg.model, harness ?? DEFAULT_HARNESS, model);
1644
+ const modelWarnings = [...("warning" in picked && picked.warning ? [picked.warning] : []), ...(tiers.warning ? [tiers.warning] : [])].map((message) => ({ field: "model", reason: "not_an_option", message }));
1669
1645
  const defaultTools = "place" in newAgentPlace(boxOffers) ? NEW_AGENT_TOOLS : [];
1670
1646
  // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1671
1647
  const server = settings.get();
@@ -1674,7 +1650,7 @@ async function startHolding(options, data, checked, stops) {
1674
1650
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1675
1651
  // never), else ask. Deny and pins hold either way.
1676
1652
  const chosenApprovals = approvals ?? pkg.approvals;
1677
- const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
1653
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
1678
1654
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1679
1655
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1680
1656
  const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
@@ -1739,7 +1715,7 @@ async function startHolding(options, data, checked, stops) {
1739
1715
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1740
1716
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1741
1717
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
1742
- const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1718
+ const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1743
1719
  return { applied, minted };
1744
1720
  }
1745
1721
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
@@ -1788,11 +1764,39 @@ async function startHolding(options, data, checked, stops) {
1788
1764
  * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
1789
1765
  * at the public URL or the server's own address. */
1790
1766
  const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
1767
+ /** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
1768
+ * its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
1769
+ * timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
1770
+ * seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
1771
+ * each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
1772
+ * entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
1773
+ * answer even when the server has since changed or gone, since it does no new work. */
1774
+ function handedMcpAuth(body) {
1775
+ if (body.mcp_auth === undefined)
1776
+ return { body, sealer: async () => undefined };
1777
+ const { mcp_auth, ...rest } = body;
1778
+ const sealer = async () => {
1779
+ const issues = [];
1780
+ const handed = mcpAuthOf(mcp_auth, issues);
1781
+ const auth = {};
1782
+ for (const [server, headers] of Object.entries(handed ?? {})) {
1783
+ const row = await store.mcp.server(server);
1784
+ if (row?.auth !== "per_run")
1785
+ issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
1786
+ else
1787
+ auth[server] = { headers, origin: new URL(row.url).origin };
1788
+ }
1789
+ if (issues.length)
1790
+ throw invalid(issues);
1791
+ return (runId) => sealRunMcpAuth(sealKey, runId, auth);
1792
+ };
1793
+ return { body: rest, sealer };
1794
+ }
1791
1795
  async function createRun(req, agentId) {
1792
1796
  const entry = await needAgent(agentId);
1793
1797
  if (entry.agent.archivedAt)
1794
1798
  throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
1795
- const body = await bodyOf(req);
1799
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
1796
1800
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
1797
1801
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
1798
1802
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -1802,7 +1806,8 @@ async function startHolding(options, data, checked, stops) {
1802
1806
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1803
1807
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1804
1808
  }
1805
- const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
1809
+ const seal = await sealer();
1810
+ const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
1806
1811
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
1807
1812
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
1808
1813
  });
@@ -1813,7 +1818,7 @@ async function startHolding(options, data, checked, stops) {
1813
1818
  * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
1814
1819
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
1815
1820
  async function createInlineRun(req) {
1816
- const body = await bodyOf(req);
1821
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
1817
1822
  const { external, definition, skills, note, revision: pinned, ...run } = body;
1818
1823
  const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
1819
1824
  const issues = [
@@ -1847,7 +1852,8 @@ async function startHolding(options, data, checked, stops) {
1847
1852
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1848
1853
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1849
1854
  }
1850
- const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}) });
1855
+ const seal = await sealer();
1856
+ const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
1851
1857
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
1852
1858
  });
1853
1859
  }
@@ -1901,7 +1907,15 @@ async function startHolding(options, data, checked, stops) {
1901
1907
  }
1902
1908
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
1903
1909
  function runBodyIssues(body) {
1904
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id"]);
1910
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "archil_disk"]);
1911
+ if (body.archil_disk !== undefined) {
1912
+ const disk = body.archil_disk;
1913
+ const extra = isObject(disk) ? Object.keys(disk).filter((key) => key !== "disk_id") : [];
1914
+ if (!isObject(disk) || typeof disk.disk_id !== "string" || !ARCHIL_DISK_ID.test(disk.disk_id))
1915
+ issues.push({ field: "archil_disk.disk_id", reason: "wrong_type", message: "archil_disk is { disk_id }: the disk id Archil returned when the disk was made (dsk- and 16 hex digits; Archil's API addresses disks by id, not owner/name), in this server's Archil region" });
1916
+ else if (extra.length)
1917
+ issues.push({ field: `archil_disk.${extra[0]}`, reason: "not_allowed", message: "archil_disk names a disk by its id alone: its region is this server's Archil key's, and no key is ever sent with a run", fix: `Remove ${extra.map((key) => `archil_disk.${key}`).join(" and ")}.` });
1918
+ }
1905
1919
  if (!isObject(body.input))
1906
1920
  issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
1907
1921
  if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
@@ -2043,30 +2057,12 @@ async function startHolding(options, data, checked, stops) {
2043
2057
  // kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
2044
2058
  // again. A run whose journal cannot be read leaves it all tokens.
2045
2059
  const endedMeters = new Map();
2046
- // Each ended run's spend so far as it saved it at its end (serve.json's cost_so_far: every conversation's charges and
2047
- // its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
2048
- // none (a run whose cost is known, or one ended before the figure was kept).
2049
- const endedSoFar = new Map();
2050
- const savedSoFarOf = (row) => {
2051
- const key = `${row.id} ${row.endedAt}`;
2052
- if (!endedSoFar.has(key)) {
2053
- // TODO(E3/store-reads): a run's kept so-far cost comes from the store (its row/journal), not a per-run RUN_META file
2054
- // (runStorePath is gone). Undefined until the usage route reads it over the store.
2055
- let usd;
2056
- {
2057
- usd = undefined;
2058
- }
2059
- endedSoFar.set(key, usd);
2060
- }
2061
- return endedSoFar.get(key);
2062
- };
2063
2060
  const metersOf = async (row) => {
2064
2061
  const key = `${row.id} ${row.endedAt}`;
2065
2062
  let meters = endedMeters.get(key);
2066
2063
  if (!meters) {
2067
2064
  // An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
2068
- // folded back from the paid-tools session (store-reads/journal withPaidCosts), as meterFiguresIn read a file-backed
2069
- // run's own database — the same figures (the money-parity rule).
2065
+ // folded back from the paid-tools session (store-reads/journal withPaidCosts).
2070
2066
  meters = await metersOverStore(store, row.id, ctx);
2071
2067
  endedMeters.set(key, meters);
2072
2068
  }
@@ -2121,7 +2117,7 @@ async function startHolding(options, data, checked, stops) {
2121
2117
  // A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
2122
2118
  // total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
2123
2119
  // the lower bound unpriced_runs says it is.
2124
- const soFar = usd !== null || !read ? 0 : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
2120
+ const soFar = usd !== null || !read ? 0 : read.known.tokens + read.known.browser + read.known.others;
2125
2121
  const meters = group === "meter" && usd !== 0 ? read : undefined;
2126
2122
  if (meters && meters.browser.usd !== 0)
2127
2123
  browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
@@ -2522,7 +2518,9 @@ async function startHolding(options, data, checked, stops) {
2522
2518
  case "getAgent": {
2523
2519
  const entry = await needAgent(id);
2524
2520
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
2525
- const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
2521
+ // A tool of bash's family the agent's computer gives no shell for reads unavailable (runShellOf).
2522
+ const revision = entry.revision;
2523
+ const tools = revision ? agentTools(env, settings.get(), await toolingOf(revision), caps.tools.map((tool) => tool.name), await shellOfRevision(revision)) : [];
2526
2524
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
2527
2525
  }
2528
2526
  case "updateDefinition": {
@@ -2546,6 +2544,7 @@ async function startHolding(options, data, checked, stops) {
2546
2544
  let warnings = [];
2547
2545
  const check = async (revision) => void (warnings = await saveable(revision));
2548
2546
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
2547
+ reconcileComputer(id);
2549
2548
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
2550
2549
  }
2551
2550
  case "listRevisions": {
@@ -2569,6 +2568,7 @@ async function startHolding(options, data, checked, stops) {
2569
2568
  if (!(await agents.revision(id, revision)))
2570
2569
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
2571
2570
  const moved = await agents.setCurrent(entry, revision);
2571
+ reconcileComputer(id);
2572
2572
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
2573
2573
  }
2574
2574
  case "archiveAgent":
@@ -2581,9 +2581,22 @@ async function startHolding(options, data, checked, stops) {
2581
2581
  // which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
2582
2582
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
2583
2583
  const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
2584
+ // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
2585
+ if (found.name === "archiveAgent")
2586
+ reconcileComputer(id);
2584
2587
  const entry = await needAgent(id);
2585
2588
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), triggers_off: triggersOff }, { etag: etagOf(entry) });
2586
2589
  }
2590
+ case "getAgentArchil":
2591
+ case "deleteAgentArchil": {
2592
+ // The agent's Archil disk (archil-routes.ts): its rules are the handler's; the dispatch reads the agent (archived, or
2593
+ // managed by its source) and how to count the live runs on a disk.
2594
+ const entry = await needAgent(id);
2595
+ const controller = new AbortController();
2596
+ req.once("close", () => controller.abort());
2597
+ const agent = { id, archived: entry.agent.archivedAt != null, external: entry.agent.externalRef !== null, liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
2598
+ return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
2599
+ }
2587
2600
  case "forgetSignIn": {
2588
2601
  await needAgent(id);
2589
2602
  let key;
@@ -2626,8 +2639,9 @@ async function startHolding(options, data, checked, stops) {
2626
2639
  const run = await needRun(id);
2627
2640
  if (run.kind === "workflow")
2628
2641
  throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
2629
- const body = await bodyOf(req);
2642
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
2630
2643
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
2644
+ const seal = await sealer();
2631
2645
  const extra = unknownFields(body, ["content"]);
2632
2646
  if (extra.length)
2633
2647
  throw invalid(extra);
@@ -2636,7 +2650,8 @@ async function startHolding(options, data, checked, stops) {
2636
2650
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
2637
2651
  if (content.length > MAX_MESSAGE)
2638
2652
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
2639
- const { mode, messageId } = await message(store, run, content);
2653
+ // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
2654
+ const { mode, messageId } = await message(store, run, content, seal ? { launchSealed: seal(run.id) } : {});
2640
2655
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
2641
2656
  const { status, state } = await runStatusState(run.id);
2642
2657
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -2716,6 +2731,10 @@ async function startHolding(options, data, checked, stops) {
2716
2731
  },
2717
2732
  computer: () => computerOf(kept, env, family),
2718
2733
  hold: () => hold,
2734
+ // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
2735
+ // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
2736
+ // For an ended run, nothing, and its row goes.
2737
+ ended: () => screenWaitEnded(store.settings, run.id, run.terminal),
2719
2738
  });
2720
2739
  if (family === "browser")
2721
2740
  return send(res, 200, view.state === "live" ? { state: "live", viewer: view.viewer } : view.state === "none" ? { state: "none" } : { state: "off", reason: view.why }, { "cache-control": "no-store" });
@@ -3029,6 +3048,20 @@ async function startHolding(options, data, checked, stops) {
3029
3048
  const { counts, impact, notes } = await agentLearningOverStore(store, id);
3030
3049
  return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, notes));
3031
3050
  }
3051
+ case "getLearningCost": {
3052
+ await needAgent(id);
3053
+ // The agent's cost per run over the one store (agentCostOverStore): each ended run's figures and path, aggregates only.
3054
+ const { limit, csv } = learningCostQuery(url);
3055
+ const read = await agentCostOverStore(store, id, limit);
3056
+ // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
3057
+ const shown = await learningShown(id);
3058
+ const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })) };
3059
+ if (csv) {
3060
+ res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-disposition": `attachment; filename="${id}-cost-per-run.csv"` });
3061
+ return void res.end(costCsv(cost.runs));
3062
+ }
3063
+ return send(res, 200, { agent: id, ...cost });
3064
+ }
3032
3065
  case "listLearningNotes":
3033
3066
  case "listLearningLog":
3034
3067
  await needAgent(id);
@@ -3114,8 +3147,19 @@ async function startHolding(options, data, checked, stops) {
3114
3147
  // Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets secret_set and the words.
3115
3148
  return send(res, answer.status, secret && !replayed ? triggerMade(first, secret, mayHoldSecrets(req), new Date().toISOString()) : answer.body, answer.headers);
3116
3149
  }
3117
- case "listTemplates":
3118
- return send(res, 200, { templates: templates.map(packageView) });
3150
+ case "listTemplates": {
3151
+ // Each package's computer list read against this server now: what an apply here would pick (pickComputer).
3152
+ const here = templates.some((one) => one.computer) ? await shellHere() : undefined;
3153
+ const pickView = (pkg) => {
3154
+ const pick = here && pickComputer(pkg, here);
3155
+ if (!pick)
3156
+ return null;
3157
+ if ("refused" in pick)
3158
+ return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
3159
+ return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
3160
+ };
3161
+ return send(res, 200, { templates: templates.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
3162
+ }
3119
3163
  case "applyTemplate": {
3120
3164
  const pkg = templates.find((t) => t.name === id);
3121
3165
  if (!pkg)
@@ -3373,6 +3417,16 @@ async function startHolding(options, data, checked, stops) {
3373
3417
  return null;
3374
3418
  return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
3375
3419
  };
3420
+ /** The run-end read's look at a run: its end from its row alone when it has none, or one told already; else its
3421
+ * endNotice. The run's view redacts the run's words (its title, its output) on every build, and the newest runs are
3422
+ * read every RUN_ENDS_POLL_MS, so only an end still to tell builds one. */
3423
+ const endToTell = async (id) => {
3424
+ const row = await store.runs.get(id);
3425
+ if (!row)
3426
+ return null;
3427
+ const end = endOf(row);
3428
+ return !end.endedAt || toldEnds.get(id) === end.endedAt ? end : endNotice(id);
3429
+ };
3376
3430
  const toldEnds = new Map();
3377
3431
  /** Each waiting run's row as it was last read for its wait (its state, epoch and runner): a row that has not moved since
3378
3432
  * is not read again, and a new wait comes with a new claim, so a new epoch. */
@@ -3428,7 +3482,7 @@ async function startHolding(options, data, checked, stops) {
3428
3482
  for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
3429
3483
  if (open.has(id) || closing)
3430
3484
  continue;
3431
- const now = await endNotice(id).catch(() => undefined);
3485
+ const now = await endToTell(id).catch(() => undefined);
3432
3486
  // Unread (a busy store): read again at the next turn, never lost.
3433
3487
  if (now === undefined) {
3434
3488
  open.add(id);
@@ -3436,7 +3490,7 @@ async function startHolding(options, data, checked, stops) {
3436
3490
  }
3437
3491
  readWaits.delete(id);
3438
3492
  heldReadAt.delete(id);
3439
- if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3493
+ if (!now?.endedAt || !("notice" in now) || toldEnds.get(id) === now.endedAt)
3440
3494
  continue;
3441
3495
  if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
3442
3496
  toldEnds.set(id, now.endedAt);
@@ -3485,10 +3539,6 @@ async function startHolding(options, data, checked, stops) {
3485
3539
  await Promise.all([...workers.values()].map((w) => w.exit));
3486
3540
  await importing;
3487
3541
  await installStopped;
3488
- // Before the store closes: the image's last record lands first (box-image.ts), never after the next server's start.
3489
- await image?.close();
3490
- // The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
3491
- await egress?.close();
3492
3542
  // The ends' follower stops before the webhooks it feeds and the store it reads.
3493
3543
  clearTimeout(endsTimer);
3494
3544
  await endsRead;