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

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 (522) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +417 -219
  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-conformance-cli.d.ts +1 -0
  15. package/dist/attach-conformance-cli.js +18 -0
  16. package/dist/attach-conformance.d.ts +25 -0
  17. package/dist/attach-conformance.js +343 -0
  18. package/dist/attach-images.d.ts +15 -0
  19. package/dist/attach-images.js +59 -0
  20. package/dist/background.d.ts +0 -6
  21. package/dist/background.js +0 -28
  22. package/dist/box-image.d.ts +1 -97
  23. package/dist/box-image.js +4 -284
  24. package/dist/box-paths.d.ts +2 -7
  25. package/dist/box-paths.js +7 -13
  26. package/dist/box-settings.d.ts +0 -11
  27. package/dist/box-settings.js +4 -29
  28. package/dist/browser-commands.js +1 -1
  29. package/dist/browser-computer.d.ts +47 -3
  30. package/dist/browser-computer.js +286 -18
  31. package/dist/browser-cost.d.ts +1 -1
  32. package/dist/browser-live.d.ts +20 -8
  33. package/dist/browser-live.js +50 -27
  34. package/dist/browser-person.d.ts +19 -2
  35. package/dist/browser-person.js +55 -6
  36. package/dist/browser-wait-ended.d.ts +23 -0
  37. package/dist/browser-wait-ended.js +42 -0
  38. package/dist/cap.d.ts +12 -57
  39. package/dist/cap.js +20 -160
  40. package/dist/catalog.d.ts +1 -12
  41. package/dist/catalog.js +3 -33
  42. package/dist/cli.js +17 -26
  43. package/dist/composio-preset.d.ts +36 -0
  44. package/dist/composio-preset.js +179 -0
  45. package/dist/computer-attach.d.ts +125 -0
  46. package/dist/computer-attach.js +330 -0
  47. package/dist/computer-calls.d.ts +48 -0
  48. package/dist/computer-calls.js +126 -0
  49. package/dist/computer-channel.d.ts +57 -0
  50. package/dist/computer-channel.js +115 -0
  51. package/dist/computer-commands.d.ts +1 -1
  52. package/dist/computer-held-routes.d.ts +35 -0
  53. package/dist/computer-held-routes.js +106 -0
  54. package/dist/computer-held.d.ts +48 -0
  55. package/dist/computer-held.js +87 -0
  56. package/dist/computer-keys.d.ts +21 -1
  57. package/dist/computer-keys.js +53 -11
  58. package/dist/computer-live.d.ts +160 -0
  59. package/dist/computer-live.js +643 -0
  60. package/dist/computer-routes.d.ts +1 -4
  61. package/dist/computer-routes.js +3 -5
  62. package/dist/computer-setting.d.ts +2 -0
  63. package/dist/computer-setting.js +38 -1
  64. package/dist/computer-view.d.ts +24 -2
  65. package/dist/computer-view.js +51 -3
  66. package/dist/computer-viewer.d.ts +6 -0
  67. package/dist/computer-viewer.js +297 -0
  68. package/dist/computers.d.ts +79 -12
  69. package/dist/computers.js +147 -28
  70. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  71. package/dist/console/assets/index-DRN62V5v.css +1 -0
  72. package/dist/console/index.html +2 -2
  73. package/dist/docker-daemon.d.ts +2 -2
  74. package/dist/docker-daemon.js +2 -2
  75. package/dist/errors.js +5 -5
  76. package/dist/faux-computers.d.ts +9 -20
  77. package/dist/faux-computers.js +56 -24
  78. package/dist/files.d.ts +1 -9
  79. package/dist/files.js +1 -9
  80. package/dist/github-connection.d.ts +10 -2
  81. package/dist/github-connection.js +65 -2
  82. package/dist/github-faux.js +1 -1
  83. package/dist/github.d.ts +22 -2
  84. package/dist/github.js +42 -8
  85. package/dist/gpu-words.d.ts +14 -0
  86. package/dist/gpu-words.js +21 -0
  87. package/dist/graph-view.d.ts +3 -1
  88. package/dist/graph-view.js +25 -1
  89. package/dist/handed-values.d.ts +1 -1
  90. package/dist/handed-values.js +1 -1
  91. package/dist/harness-install.d.ts +60 -3
  92. package/dist/harness-install.js +322 -34
  93. package/dist/harness.d.ts +1 -0
  94. package/dist/harness.js +36 -2
  95. package/dist/host-tools.d.ts +9 -10
  96. package/dist/host-tools.js +7 -7
  97. package/dist/hosted-search.d.ts +5 -4
  98. package/dist/hosted-search.js +2 -7
  99. package/dist/import-sources.d.ts +10 -0
  100. package/dist/import-sources.js +44 -2
  101. package/dist/import.d.ts +3 -3
  102. package/dist/import.js +37 -6
  103. package/dist/index.d.ts +1 -3
  104. package/dist/index.js +1 -2
  105. package/dist/key-refusal.d.ts +1 -1
  106. package/dist/key-refusal.js +2 -2
  107. package/dist/learn/check.d.ts +11 -2
  108. package/dist/learn/check.js +124 -6
  109. package/dist/learn/commit.d.ts +43 -7
  110. package/dist/learn/commit.js +166 -22
  111. package/dist/learn/folder.d.ts +11 -0
  112. package/dist/learn/folder.js +37 -1
  113. package/dist/learn/general.d.ts +66 -0
  114. package/dist/learn/general.js +73 -0
  115. package/dist/learn/grade.d.ts +22 -1
  116. package/dist/learn/grade.js +107 -16
  117. package/dist/learn/index.d.ts +1 -1
  118. package/dist/learn/index.js +1 -1
  119. package/dist/learn/learning.sh +12 -1
  120. package/dist/learn/notes.d.ts +3 -0
  121. package/dist/learn/notes.js +3 -0
  122. package/dist/learn/reflect.d.ts +14 -2
  123. package/dist/learn/reflect.js +54 -30
  124. package/dist/learn/skills.d.ts +37 -5
  125. package/dist/learn/skills.js +60 -7
  126. package/dist/learned-nodes.d.ts +6 -2
  127. package/dist/learned-workflow.d.ts +43 -9
  128. package/dist/learned-workflow.js +128 -37
  129. package/dist/learning-batch.d.ts +283 -0
  130. package/dist/learning-batch.js +574 -0
  131. package/dist/learning-cost.d.ts +79 -0
  132. package/dist/learning-cost.js +69 -0
  133. package/dist/learning-evals.d.ts +33 -0
  134. package/dist/learning-evals.js +98 -0
  135. package/dist/learning-routes.d.ts +32 -4
  136. package/dist/learning-routes.js +48 -12
  137. package/dist/learning-words.d.ts +9 -0
  138. package/dist/learning-words.js +12 -2
  139. package/dist/learning.d.ts +39 -19
  140. package/dist/learning.js +88 -46
  141. package/dist/live/stream.js +6 -3
  142. package/dist/live/translate.d.ts +4 -3
  143. package/dist/live/translate.js +8 -4
  144. package/dist/live-reach.d.ts +37 -0
  145. package/dist/live-reach.js +62 -0
  146. package/dist/mcp-gateway.d.ts +9 -0
  147. package/dist/mcp-gateway.js +60 -11
  148. package/dist/mcp-oauth.d.ts +57 -7
  149. package/dist/mcp-oauth.js +133 -18
  150. package/dist/mcp-private-hosts.d.ts +4 -4
  151. package/dist/mcp-private-hosts.js +20 -12
  152. package/dist/mcp-probe.d.ts +27 -3
  153. package/dist/mcp-probe.js +106 -29
  154. package/dist/mcp-secret-writes.js +8 -0
  155. package/dist/mcp-servers-store.d.ts +38 -15
  156. package/dist/mcp-servers-store.js +120 -23
  157. package/dist/mcp-store.d.ts +10 -4
  158. package/dist/mcp-store.js +17 -6
  159. package/dist/model-form.d.ts +26 -0
  160. package/dist/model-form.js +80 -0
  161. package/dist/model.d.ts +5 -5
  162. package/dist/model.js +29 -16
  163. package/dist/openapi.d.ts +2 -0
  164. package/dist/openapi.js +586 -64
  165. package/dist/owner.d.ts +0 -1
  166. package/dist/owner.js +0 -2
  167. package/dist/page.d.ts +18 -0
  168. package/dist/page.js +48 -20
  169. package/dist/paid-calls.d.ts +1 -1
  170. package/dist/paid-calls.js +1 -1
  171. package/dist/place-offers.d.ts +96 -0
  172. package/dist/place-offers.js +202 -0
  173. package/dist/place.d.ts +9 -13
  174. package/dist/place.js +21 -32
  175. package/dist/port-models.d.ts +2 -1
  176. package/dist/port-models.js +5 -3
  177. package/dist/print.d.ts +16 -9
  178. package/dist/print.js +15 -17
  179. package/dist/propose.d.ts +4 -0
  180. package/dist/propose.js +34 -11
  181. package/dist/provider.js +3 -2
  182. package/dist/reflect-range.d.ts +8 -1
  183. package/dist/reflect-range.js +1 -1
  184. package/dist/run-cut.d.ts +5 -0
  185. package/dist/run-cut.js +19 -0
  186. package/dist/run-launch.d.ts +28 -3
  187. package/dist/run-launch.js +14 -4
  188. package/dist/run-learning-served.d.ts +2 -2
  189. package/dist/run-manifest.d.ts +2 -2
  190. package/dist/run-manifest.js +2 -2
  191. package/dist/run-reads-over-store.d.ts +1 -1
  192. package/dist/run-repo.d.ts +20 -0
  193. package/dist/run-repo.js +63 -0
  194. package/dist/run-secrets.js +3 -3
  195. package/dist/run-timeline-served.d.ts +1 -1
  196. package/dist/run-timeline-served.js +56 -44
  197. package/dist/run-view.d.ts +8 -5
  198. package/dist/run-view.js +18 -10
  199. package/dist/runnable.d.ts +2 -2
  200. package/dist/runnable.js +6 -2
  201. package/dist/runner/adapter-loop.d.ts +39 -8
  202. package/dist/runner/adapter-loop.js +770 -83
  203. package/dist/runner/adapter-run-spec.d.ts +36 -7
  204. package/dist/runner/adapter-run-spec.js +171 -37
  205. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  206. package/dist/runner/adapters/pi-computer.js +43 -0
  207. package/dist/runner/adapters/pi.d.ts +20 -7
  208. package/dist/runner/adapters/pi.js +111 -26
  209. package/dist/runner/beside.d.ts +7 -3
  210. package/dist/runner/beside.js +26 -12
  211. package/dist/runner/claim-secrets.d.ts +4 -0
  212. package/dist/runner/claim-secrets.js +6 -1
  213. package/dist/runner/cli-run-spec.d.ts +27 -3
  214. package/dist/runner/cli-run-spec.js +198 -74
  215. package/dist/runner/commands.d.ts +8 -2
  216. package/dist/runner/commands.js +31 -6
  217. package/dist/runner/computer-channel.d.ts +34 -0
  218. package/dist/runner/computer-channel.js +61 -0
  219. package/dist/runner/conformance/harness.d.ts +0 -1
  220. package/dist/runner/conformance/harness.js +87 -18
  221. package/dist/runner/conformance/subject.d.ts +1 -1
  222. package/dist/runner/dispatch.js +3 -0
  223. package/dist/runner/end-of-run.d.ts +22 -12
  224. package/dist/runner/end-of-run.js +38 -16
  225. package/dist/runner/github-app.d.ts +2 -1
  226. package/dist/runner/github-app.js +6 -4
  227. package/dist/runner/harness-loops.js +16 -2
  228. package/dist/runner/held-run.d.ts +65 -0
  229. package/dist/runner/held-run.js +158 -0
  230. package/dist/runner/journal-kinds.d.ts +35 -6
  231. package/dist/runner/journal-kinds.js +20 -1
  232. package/dist/runner/journal-reader.d.ts +5 -4
  233. package/dist/runner/journal-reader.js +12 -10
  234. package/dist/runner/learning-ask.d.ts +7 -1
  235. package/dist/runner/learning-ask.js +21 -6
  236. package/dist/runner/learning-dispatch.d.ts +22 -0
  237. package/dist/runner/learning-dispatch.js +77 -10
  238. package/dist/runner/learning-end.d.ts +37 -1
  239. package/dist/runner/learning-end.js +115 -14
  240. package/dist/runner/learning-factory.d.ts +1 -1
  241. package/dist/runner/learning-factory.js +15 -5
  242. package/dist/runner/learning-loop.d.ts +139 -7
  243. package/dist/runner/learning-loop.js +369 -32
  244. package/dist/runner/learning-seed.d.ts +9 -0
  245. package/dist/runner/learning-seed.js +14 -1
  246. package/dist/runner/live-ticker.js +1 -0
  247. package/dist/runner/loop-contract.d.ts +16 -1
  248. package/dist/runner/loop-contract.js +6 -0
  249. package/dist/runner/loop.d.ts +10 -2
  250. package/dist/runner/loop.js +22 -1
  251. package/dist/runner/main.d.ts +13 -1
  252. package/dist/runner/main.js +38 -6
  253. package/dist/runner/mcp-claim.d.ts +11 -4
  254. package/dist/runner/mcp-claim.js +140 -23
  255. package/dist/runner/mcp-github.d.ts +4 -2
  256. package/dist/runner/mcp-github.js +1 -8
  257. package/dist/runner/mcp-run.d.ts +6 -4
  258. package/dist/runner/mcp-run.js +16 -3
  259. package/dist/runner/metrics.d.ts +15 -2
  260. package/dist/runner/metrics.js +21 -2
  261. package/dist/runner/model-route.d.ts +3 -0
  262. package/dist/runner/model-route.js +5 -2
  263. package/dist/runner/pr-checkout.d.ts +60 -0
  264. package/dist/runner/pr-checkout.js +176 -0
  265. package/dist/runner/reflect-hook.d.ts +19 -0
  266. package/dist/runner/reflect-hook.js +20 -8
  267. package/dist/runner/runner.d.ts +26 -0
  268. package/dist/runner/runner.js +231 -27
  269. package/dist/runner/scratch-sweep.d.ts +13 -0
  270. package/dist/runner/scratch-sweep.js +62 -0
  271. package/dist/runner/sessions.d.ts +1 -1
  272. package/dist/runner/spec-holds.d.ts +8 -3
  273. package/dist/runner/spec-holds.js +12 -10
  274. package/dist/runner/store-port.d.ts +7 -2
  275. package/dist/runner/store-secrets.js +21 -4
  276. package/dist/runner/subagent.d.ts +44 -0
  277. package/dist/runner/subagent.js +190 -0
  278. package/dist/runner/workflow-host.d.ts +24 -3
  279. package/dist/runner/workflow-host.js +24 -4
  280. package/dist/runner/workflow-loop.d.ts +6 -3
  281. package/dist/runner/workflow-loop.js +9 -8
  282. package/dist/runner/workflow-spec.d.ts +39 -15
  283. package/dist/runner/workflow-spec.js +143 -40
  284. package/dist/runs-over-store.d.ts +16 -6
  285. package/dist/runs-over-store.js +145 -29
  286. package/dist/seal-key.js +3 -3
  287. package/dist/sealed-settings-store.d.ts +5 -2
  288. package/dist/sealed-settings-store.js +10 -4
  289. package/dist/sealing.js +1 -2
  290. package/dist/secret-cut.d.ts +1 -1
  291. package/dist/secret-cut.js +1 -1
  292. package/dist/secret-writes.d.ts +5 -4
  293. package/dist/secret-writes.js +5 -4
  294. package/dist/server-secrets-store.d.ts +4 -3
  295. package/dist/server-secrets-store.js +15 -9
  296. package/dist/server-secrets.js +3 -2
  297. package/dist/server.d.ts +75 -63
  298. package/dist/server.js +712 -316
  299. package/dist/settings-wake.d.ts +21 -0
  300. package/dist/settings-wake.js +59 -0
  301. package/dist/standard-webhooks.d.ts +4 -1
  302. package/dist/standard-webhooks.js +8 -4
  303. package/dist/store/agent-body.d.ts +9 -2
  304. package/dist/store/agent-body.js +16 -8
  305. package/dist/store/command-wake.d.ts +12 -0
  306. package/dist/store/command-wake.js +37 -0
  307. package/dist/store/deadline.js +9 -5
  308. package/dist/store/dialect.d.ts +6 -0
  309. package/dist/store/dialect.js +5 -0
  310. package/dist/store/index.d.ts +4 -4
  311. package/dist/store/index.js +2 -2
  312. package/dist/store/journal/storage.d.ts +3 -2
  313. package/dist/store/journal/storage.js +15 -6
  314. package/dist/store/postgres/connection.js +9 -4
  315. package/dist/store/postgres/dialect.js +4 -0
  316. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  317. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  318. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  319. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  320. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  321. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  322. package/dist/store/schema.d.ts +2 -1
  323. package/dist/store/schema.js +85 -13
  324. package/dist/store/seal.d.ts +13 -0
  325. package/dist/store/seal.js +19 -0
  326. package/dist/store/sqlite/connection.d.ts +5 -0
  327. package/dist/store/sqlite/connection.js +88 -47
  328. package/dist/store/sqlite/run-patch.d.ts +25 -7
  329. package/dist/store/sqlite/run-patch.js +58 -14
  330. package/dist/store/sqlite/store.js +331 -59
  331. package/dist/store/store.d.ts +330 -21
  332. package/dist/store/store.js +34 -2
  333. package/dist/store-reads/analytics.js +3 -2
  334. package/dist/store-reads/cap.d.ts +2 -4
  335. package/dist/store-reads/cap.js +16 -7
  336. package/dist/store-reads/decisions.d.ts +3 -3
  337. package/dist/store-reads/decisions.js +3 -6
  338. package/dist/store-reads/import-summary.d.ts +1 -1
  339. package/dist/store-reads/journal.d.ts +5 -4
  340. package/dist/store-reads/journal.js +118 -27
  341. package/dist/store-reads/learning.d.ts +34 -4
  342. package/dist/store-reads/learning.js +137 -23
  343. package/dist/store-reads/runs.d.ts +7 -5
  344. package/dist/store-reads/runs.js +17 -10
  345. package/dist/store-reads/stats.js +5 -1
  346. package/dist/store-reads/workflow.d.ts +1 -1
  347. package/dist/store-view.d.ts +5 -0
  348. package/dist/store-view.js +70 -29
  349. package/dist/template-eval.js +8 -5
  350. package/dist/template-github-permissions.d.ts +22 -8
  351. package/dist/template-github-permissions.js +35 -15
  352. package/dist/templates.d.ts +64 -0
  353. package/dist/templates.js +101 -16
  354. package/dist/timeline/timeline.d.ts +30 -1
  355. package/dist/timeline/timeline.js +29 -13
  356. package/dist/timeline/util.d.ts +4 -0
  357. package/dist/timeline/util.js +14 -0
  358. package/dist/tool-blurbs.js +1 -0
  359. package/dist/tool-budget.d.ts +27 -7
  360. package/dist/tool-budget.js +21 -9
  361. package/dist/tool-gate.d.ts +23 -10
  362. package/dist/tool-gate.js +60 -44
  363. package/dist/tool-plane.d.ts +46 -28
  364. package/dist/tool-plane.js +73 -31
  365. package/dist/tools.d.ts +31 -38
  366. package/dist/tools.js +117 -74
  367. package/dist/trigger-adapter.d.ts +4 -0
  368. package/dist/trigger-secrets-shown.d.ts +2 -2
  369. package/dist/trigger-secrets-shown.js +1 -1
  370. package/dist/trigger-signatures.d.ts +26 -6
  371. package/dist/trigger-signatures.js +44 -8
  372. package/dist/trigger-targets.d.ts +2 -0
  373. package/dist/trigger-targets.js +1 -0
  374. package/dist/trigger-webhook.js +5 -2
  375. package/dist/triggers.d.ts +10 -6
  376. package/dist/triggers.js +37 -7
  377. package/dist/turn-end.d.ts +0 -3
  378. package/dist/turn-end.js +0 -3
  379. package/dist/turns.js +16 -1
  380. package/dist/usage-lines.d.ts +1 -1
  381. package/dist/validate.d.ts +6 -0
  382. package/dist/validate.js +41 -4
  383. package/dist/web-fetch.d.ts +1 -1
  384. package/dist/web-search.d.ts +10 -5
  385. package/dist/web-search.js +7 -6
  386. package/dist/webhooks.d.ts +147 -103
  387. package/dist/webhooks.js +564 -324
  388. package/dist/workflow/decision-recovery.d.ts +23 -0
  389. package/dist/workflow/decision-recovery.js +80 -0
  390. package/dist/workflow/decisions.d.ts +134 -0
  391. package/dist/workflow/decisions.js +46 -0
  392. package/dist/workflow/host-session.d.ts +5 -0
  393. package/dist/workflow/host-session.js +85 -0
  394. package/dist/workflow/host-tools.d.ts +3 -0
  395. package/dist/workflow/host-tools.js +3 -0
  396. package/dist/workflow/node-runner.d.ts +113 -0
  397. package/dist/workflow/node-runner.js +270 -0
  398. package/dist/workflow/node.d.ts +89 -0
  399. package/dist/workflow/node.js +101 -0
  400. package/dist/workflow/operator-error.d.ts +4 -0
  401. package/dist/workflow/operator-error.js +4 -0
  402. package/dist/workflow/pi-versions.d.ts +32 -0
  403. package/dist/workflow/pi-versions.js +65 -0
  404. package/dist/workflow/record-file.d.ts +10 -0
  405. package/dist/workflow/record-file.js +56 -0
  406. package/dist/workflow/record-tool.d.ts +77 -0
  407. package/dist/workflow/record-tool.js +126 -0
  408. package/dist/workflow/record.d.ts +151 -0
  409. package/dist/workflow/record.js +401 -0
  410. package/dist/workflow/run-error.d.ts +16 -0
  411. package/dist/workflow/run-error.js +26 -0
  412. package/dist/workflow/runner.d.ts +6 -0
  413. package/dist/workflow/runner.js +240 -0
  414. package/dist/workflow/store.d.ts +23 -0
  415. package/dist/workflow/store.js +242 -0
  416. package/dist/workflow/task.d.ts +133 -0
  417. package/dist/workflow/task.js +412 -0
  418. package/dist/workflow/thinking.d.ts +3 -0
  419. package/dist/workflow/thinking.js +7 -0
  420. package/dist/workflow/tool-context.d.ts +21 -0
  421. package/dist/workflow/tool-context.js +13 -0
  422. package/dist/workflow/types.d.ts +126 -0
  423. package/dist/workflow/types.js +1 -0
  424. package/dist/workflow-run.d.ts +2 -2
  425. package/dist/workspace/agent-computer.d.ts +137 -0
  426. package/dist/workspace/agent-computer.js +292 -0
  427. package/dist/workspace/archil-claim.d.ts +11 -0
  428. package/dist/workspace/archil-claim.js +18 -10
  429. package/dist/workspace/archil-disks.d.ts +49 -0
  430. package/dist/workspace/archil-disks.js +185 -0
  431. package/dist/workspace/archil-exec.js +2 -3
  432. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  433. package/dist/workspace/archil-mount-credential.js +13 -4
  434. package/dist/workspace/attached-computers.d.ts +41 -0
  435. package/dist/workspace/attached-computers.js +114 -0
  436. package/dist/workspace/computer-deps.d.ts +32 -17
  437. package/dist/workspace/computer-deps.js +37 -14
  438. package/dist/workspace/computer-for-claim.d.ts +58 -13
  439. package/dist/workspace/computer-for-claim.js +267 -26
  440. package/dist/workspace/computer-hold.d.ts +11 -27
  441. package/dist/workspace/computer-hold.js +36 -56
  442. package/dist/workspace/computer-janitor.d.ts +3 -2
  443. package/dist/workspace/computer-janitor.js +43 -9
  444. package/dist/workspace/computer-ledger.d.ts +5 -1
  445. package/dist/workspace/computer-ledger.js +11 -0
  446. package/dist/workspace/computer-mcp.d.ts +25 -0
  447. package/dist/workspace/computer-mcp.js +41 -0
  448. package/dist/workspace/computer-ports.d.ts +4 -13
  449. package/dist/workspace/computer-ports.js +4 -107
  450. package/dist/workspace/computer-script.d.ts +37 -0
  451. package/dist/workspace/computer-script.js +138 -0
  452. package/dist/workspace/executors.d.ts +1 -1
  453. package/dist/workspace/index.d.ts +7 -4
  454. package/dist/workspace/index.js +4 -1
  455. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  456. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  457. package/dist/workspace/resolve-computer.d.ts +45 -11
  458. package/dist/workspace/resolve-computer.js +72 -14
  459. package/dist/workspace/run-disk.d.ts +34 -0
  460. package/dist/workspace/run-disk.js +91 -0
  461. package/dist/workspace/run-tools.d.ts +35 -18
  462. package/dist/workspace/run-tools.js +24 -29
  463. package/dist/workspace/server-run-workspace.d.ts +3 -2
  464. package/dist/workspace/server-run-workspace.js +17 -4
  465. package/dist/workspace.js +1 -1
  466. package/package.json +19 -21
  467. package/templates/README.md +9 -6
  468. package/templates/code-review/agent.md +27 -11
  469. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  470. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  471. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  472. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  473. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  474. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  475. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  476. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  477. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  478. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  479. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  480. package/templates/code-review/evals/re-review/prompt.md +1 -1
  481. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  482. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  483. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  484. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  485. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  486. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  487. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  488. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  489. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  490. package/templates/code-review/findings.schema.json +131 -27
  491. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  492. package/templates/code-review/skills/review/DEEP.md +130 -0
  493. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  494. package/templates/code-review/skills/review/SKILL.md +104 -154
  495. package/templates/market-monitor/agent.md +1 -1
  496. package/dist/box/record.d.ts +0 -6
  497. package/dist/box/record.js +0 -41
  498. package/dist/box/sweep.d.ts +0 -53
  499. package/dist/box/sweep.js +0 -193
  500. package/dist/box-egress-vm.d.ts +0 -118
  501. package/dist/box-egress-vm.js +0 -354
  502. package/dist/box-egress.d.ts +0 -105
  503. package/dist/box-egress.js +0 -256
  504. package/dist/box-relay-vm.d.ts +0 -84
  505. package/dist/box-relay-vm.js +0 -437
  506. package/dist/box-relay.d.ts +0 -36
  507. package/dist/box-relay.js +0 -207
  508. package/dist/boxes.d.ts +0 -109
  509. package/dist/boxes.js +0 -249
  510. package/dist/budget.d.ts +0 -71
  511. package/dist/budget.js +0 -199
  512. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  513. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  514. package/dist/daytona-api.d.ts +0 -10
  515. package/dist/daytona-api.js +0 -20
  516. package/dist/egress-proxy.d.ts +0 -45
  517. package/dist/egress-proxy.js +0 -416
  518. package/dist/egress-table.d.ts +0 -24
  519. package/dist/egress-table.js +0 -165
  520. package/dist/run-db.d.ts +0 -53
  521. package/dist/run-db.js +0 -116
  522. package/templates/code-review/rules/REVIEW.md +0 -41
package/dist/server.js CHANGED
@@ -31,19 +31,21 @@ 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";
35
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
34
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
35
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, 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
- import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
42
+ import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
43
43
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
44
- import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
44
+ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
45
45
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
- import { computerView } from "./computer-view.js";
46
+ import { computerView, sessionIn } from "./computer-view.js";
47
+ import { liveReachOf } from "./live-reach.js";
48
+ import { screenWaitEnded } from "./browser-wait-ended.js";
47
49
  import { durationMs, logLine } from "./print.js";
48
50
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
49
51
  import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
@@ -62,21 +64,17 @@ import { watchRun } from "./live/stream.js";
62
64
  import { stats as statsOverStore } from "./store-reads/stats.js";
63
65
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
64
66
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
65
- import { openStore, StoreOwned, storeTarget } from "./store/index.js";
67
+ import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
66
68
  import { answerOf, logged } from "./agents.js";
67
- import { FINAL_STATES } from "./store/store.js";
69
+ import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
68
70
  import { runModelRef } from "./model.js";
69
71
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
70
72
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
71
73
  import { runLines } from "./usage-lines.js";
72
- import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
74
+ import { boxesByDefault, boxesLog, enabledBoxes, placeOffers, withNetworks } from "./place-offers.js";
75
+ import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
73
76
  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
77
  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
78
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
81
79
  import { CAP_MODES } from "./cap.js";
82
80
  import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
@@ -86,17 +84,21 @@ import { bootSealKey, withSealKey } from "./seal-key.js";
86
84
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
87
85
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
88
86
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
89
- import { agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
87
+ import { agentCostOverStore, agentLearningOverStore, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
88
+ import { figuresOf, LearningBatches } from "./learning-batch.js";
89
+ import { costCsv, learningCostQuery } from "./learning-cost.js";
90
+ import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
90
91
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
91
92
  import { toolKeysOverStore } from "./tool-keys-store.js";
92
93
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
93
94
  import { signInsOverStore } from "./sign-ins-store.js";
94
- import { MCP_AUTH_TYPES } from "./mcp-probe.js";
95
+ import { MCP_AUTH_TYPES, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
96
+ import { composioSave, composioTools } from "./composio-preset.js";
95
97
  import { mcpServersOverStore } from "./mcp-servers-store.js";
96
98
  import { privateHostsRoute } from "./mcp-private-hosts.js";
97
99
  import { metaToolOf } from "./mcp-meta.js";
98
100
  import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
99
- import { OUTBOUND_WEBHOOK, WEBHOOK_EVENTS, waitMarkerOf, Webhooks } from "./webhooks.js";
101
+ import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
100
102
  import { appPermissionWarnings } from "./template-github-permissions.js";
101
103
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
102
104
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
@@ -104,29 +106,34 @@ import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
104
106
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
105
107
  import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
106
108
  import { GITHUB_API } from "./github.js";
109
+ import { bindingOf, REPO_NAME } from "./run-repo.js";
107
110
  import { HookCut, receivePush } from "./push-handler.js";
108
111
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
109
112
  import { webhook } from "./trigger-webhook.js";
110
113
  import { SCHEME_NAMES } from "./trigger-signatures.js";
111
114
  import { permissionFrom } from "./tool-gate.js";
112
115
  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";
116
+ import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
114
117
  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";
118
+ import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
119
+ import { wakeAnsweredBySetting } from "./settings-wake.js";
116
120
  import { toolSettingsOverStore } from "./tool-settings-store.js";
117
121
  import { readApprovers, writeApprovers } from "./server-approvers.js";
118
122
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
119
123
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
120
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
121
- import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
122
- import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
123
- import { archilRoute, createArchilRoutes } from "./archil-routes.js";
124
+ import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
125
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
126
+ import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
127
+ import { createAttachRoutes, pairedView } from "./computer-attach.js";
128
+ import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
129
+ import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
130
+ import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
131
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
124
132
  import { computerOfPlace } from "./computer-setting.js";
125
- import { computerCapabilities, createComputerRoutes, folderModeOf, settingsComputerRoute } from "./computers.js";
126
- import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
127
- import { runComputerField } from "./run-computer.js";
133
+ import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
134
+ import { fauxComputers } from "./faux-computers.js";
128
135
  import { writesHeld } from "./workspace.js";
129
- import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
136
+ import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
137
  import { keyReader } from "./key-meta.js";
131
138
  export const CONTRACT = "agentrun.v2/0";
132
139
  /** 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 +149,6 @@ const MAX_MESSAGE = 20_000;
142
149
  const MAX_WAIT_MS = 25_000;
143
150
  const PAGE_ROWS = 500;
144
151
  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
152
  /** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
152
153
  const noticeOf = (options) => (line) => {
153
154
  try {
@@ -163,7 +164,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
163
164
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
164
165
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
165
166
  * 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]];
167
+ 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
168
  /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
168
169
  * takes the same (test/support.mjs startInProcessRunner). */
169
170
  export function fauxEnvOf(options) {
@@ -190,8 +191,6 @@ async function tokenIn(file) {
190
191
  return { token, made: true };
191
192
  }
192
193
  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
194
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
196
195
  const SESSION_S = SESSION_MS / 1000;
197
196
  export const ROUTES = [
@@ -209,6 +208,9 @@ export const ROUTES = [
209
208
  { method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
210
209
  { method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
211
210
  { method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
211
+ // The agent's Archil disk (archil-routes.ts): read, and removed for an archived agent.
212
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/archil$/, name: "getAgentArchil" },
213
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)\/archil$/, name: "deleteAgentArchil" },
212
214
  { method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
213
215
  { method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
214
216
  { method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files$/, name: "listHomeFiles" },
@@ -238,11 +240,24 @@ export const ROUTES = [
238
240
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
239
241
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
240
242
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
243
+ // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
244
+ // protocol calls, and keeps its computer after its agent's end until released.
245
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/start$/, name: "startRun" },
246
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/call$/, name: "callRunComputer" },
247
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/release$/, name: "releaseRunComputer" },
241
248
  // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
242
249
  // archilRoute): the server switch dispatches them, once the server opens its store.
243
250
  { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
244
251
  { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
245
252
  { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
253
+ { method: "GET", pattern: /^\/computers\/([^/]+)\/choices$/, name: "listComputerChoices" },
254
+ // A person's own computer paired with this server (computer-attach.ts): the owner's code, the driver's trade of it for
255
+ // its token (no token of the server's: the code is the credential), the attach socket (a WebSocket: the server's
256
+ // upgrade takes it; a plain GET is told so), and a computer's removal.
257
+ { method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
258
+ { method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
259
+ { method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
260
+ { method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
246
261
  { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
247
262
  { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
248
263
  { method: "DELETE", pattern: /^\/workspace\/archil$/, name: "deleteWorkspaceArchil" },
@@ -261,8 +276,10 @@ export const ROUTES = [
261
276
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
262
277
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
263
278
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
279
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
264
280
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
265
281
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
282
+ { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
266
283
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
267
284
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
268
285
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -300,6 +317,13 @@ export const ROUTES = [
300
317
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
301
318
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
302
319
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
320
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
321
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
322
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
323
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
324
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
325
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
326
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
303
327
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
304
328
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
305
329
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
@@ -307,6 +331,7 @@ export const ROUTES = [
307
331
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
308
332
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
309
333
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
334
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
310
335
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
311
336
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
312
337
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
@@ -315,9 +340,12 @@ export const ROUTES = [
315
340
  * learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
316
341
  /** A run's computer as GET /computer reads it with no viewer open: kind browser where its agent has the browser tool, its
317
342
  * 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.
343
+ * launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
344
+ * computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
319
345
  * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
320
346
  function computerOf(kept, env, family = "computer") {
347
+ if (kept === ON_COMPUTER)
348
+ return { kind: "browser" };
321
349
  const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
322
350
  if (browser === undefined)
323
351
  return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
@@ -326,18 +354,24 @@ function computerOf(kept, env, family = "computer") {
326
354
  /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
327
355
  * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
328
356
  * 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. */
357
+ * the browser tool, else none. A revision that grants the tool to an agent whose computer is a browser is ON_COMPUTER:
358
+ * the tool's sessions are that computer's (tools.ts browserComputer), whatever the plane says. */
330
359
  async function keptBrowserOf(store, runId) {
360
+ const runRow = await store.runs.get(runId);
361
+ const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
362
+ const body = revision?.body;
363
+ const granted = (body?.tools ?? []).includes("browser");
364
+ if (granted && body?.computer?.kind === "browser")
365
+ return ON_COMPUTER;
331
366
  const row = await store.runs.launch(runId).catch(() => undefined);
332
367
  const plane = row ? readLaunchBody(row.body)?.plane : undefined;
333
368
  const kept = plane ? keptVendor(plane).browser : undefined;
334
369
  if (kept !== undefined)
335
370
  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
371
  return granted ? "browserbase" : undefined;
340
372
  }
373
+ /** keptBrowserOf's answer for a run whose browser is its agent's browser computer. */
374
+ const ON_COMPUTER = Symbol("the agent's browser computer");
341
375
  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
376
  /** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
343
377
  export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
@@ -378,7 +412,7 @@ async function needsOf(env) {
378
412
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
379
413
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
380
414
  * 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
415
+ * box offers (`boxes`, what the server found at the start, place-offers.ts), with whether a revision that names no
382
416
  * model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
383
417
  * (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
384
418
  * `gradeModel` is its `--grade-model`. */
@@ -393,8 +427,6 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
393
427
  * `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
394
428
  * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
395
429
  * `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
430
  export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
399
431
  return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
400
432
  }
@@ -419,7 +451,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
419
451
  backend: "local",
420
452
  contract: CONTRACT,
421
453
  server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
422
- runtimes: ["pi-durable-disk"],
454
+ /** What runs a run here (the contract's `runtimes`, informational): this server's runners, over its one store. */
455
+ runtimes: ["runner"],
423
456
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
424
457
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
425
458
  harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
@@ -464,8 +497,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
464
497
  efforts: [...EFFORTS],
465
498
  thinking: [...THINKING_LEVELS],
466
499
  /** 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",
500
+ * available here (tools[]), a browser provider's id (tool-plane.ts BROWSER_VENDOR_IDS), else none. */
501
+ browser: browser?.available ? ((resolved) => (BROWSER_VENDOR_IDS.includes(resolved ?? "") ? resolved : "browserbase"))(browser.resolves?.[DEFAULT_HARNESS]) : "none",
469
502
  /** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
470
503
  * gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
471
504
  tool_permissions: true,
@@ -545,7 +578,7 @@ export async function startServe(options) {
545
578
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
546
579
  delete process.env[HARNESS_TABLE_ENV];
547
580
  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).
581
+ // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
549
582
  const data = await realpath(resolve(options.data));
550
583
  if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
551
584
  throw new Error("the token must be 32 characters or more, with no whitespace");
@@ -557,6 +590,9 @@ export async function startServe(options) {
557
590
  dockerLimitsOf(process.env);
558
591
  // The Docker host's addresses an operator names (workspace/computer-deps.ts): a bad entry stops the start, in words.
559
592
  dockerHostAddressesOf(process.env);
593
+ // The Archil settings an operator sets (archil-settings.ts ARCHIL_SETTINGS_ENV): one of the region and S3 URL without the
594
+ // other, or a value the PUT would refuse, stops the start, in words naming each variable.
595
+ archilSettingsFromEnv(process.env);
560
596
  const boxAllow = boxAllowOf(process.env);
561
597
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
562
598
  const learning = learningOf(process.env, options.learning);
@@ -609,7 +645,7 @@ async function startHolding(options, data, checked, stops) {
609
645
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
610
646
  * read (the view never fails for it). */
611
647
  const learningOfAgent = async (entry) => {
612
- if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning !== true)
648
+ if (learning === "off" || entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
613
649
  return undefined;
614
650
  const pending = await pendingCount(data, entry.agent.id);
615
651
  return pending === undefined ? undefined : { pending };
@@ -654,6 +690,11 @@ async function startHolding(options, data, checked, stops) {
654
690
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
655
691
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
656
692
  stops.push(() => store.close());
693
+ // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
694
+ // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
695
+ // store is refused above (its owner lock).
696
+ const attachHub = new AttachHub();
697
+ const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
657
698
  // The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
658
699
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
659
700
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -779,138 +820,45 @@ async function startHolding(options, data, checked, stops) {
779
820
  else
780
821
  await probe("key");
781
822
  };
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).
823
+ // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
824
+ // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
825
+ // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
826
+ const fauxDocker = Boolean(options.faux) && options.fauxDocker === true;
827
+ const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker });
828
+ const docker = found.some((offer) => offer.id === "docker" && offer.available);
793
829
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
794
830
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
795
831
  // server is on a host.
796
832
  const fauxMountinfo = options.faux ? (options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV]) : undefined;
797
833
  // Where Docker has this server's files (box-paths.ts): its own, on a host; its container's mount of the data directory,
798
834
  // 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;
835
+ // host's unless the test gives a container's mountinfo. Only on Linux: a container of a Docker's own is a Linux one.
836
+ 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
837
  if ("reason" in dockerPaths)
807
838
  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
839
  // 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
840
  // its Docker's own host, or as its named data volume's subpaths from a container of that Docker's (compose.yaml).
818
841
  // Any other layout, or a daemon of another machine (DOCKER_HOST, or the current context's endpoint: box-paths.ts
819
842
  // remoteDockerOnce), can't run one, and says so here (dockerComputerRefusal), where capabilities, the run's start
820
843
  // (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));
844
+ const dockerElsewhere = fauxDocker || !docker ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
822
845
  // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
823
846
  // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
824
847
  // 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;
848
+ const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
826
849
  if (hostAddresses)
827
850
  log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
828
851
  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
- }
852
+ // Each box with what it reaches (place-offers.ts withNetworks).
853
+ const boxOffers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
908
854
  log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
909
- if (image)
910
- imageLog(image.state());
911
855
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
912
856
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
913
857
  const sealKey = seal.key;
858
+ // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
859
+ // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
860
+ const reach = liveReachOf(env, sealKey);
861
+ const answers = (handover) => viewerAnswers(handover, reach);
914
862
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
915
863
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
916
864
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -919,12 +867,12 @@ async function startHolding(options, data, checked, stops) {
919
867
  const browserToolNames = (await import("@parcha/pi-browser")).BROWSER_TOOLS.map((tool) => tool.name);
920
868
  const localTools = new Set(hostToolDefs({ maxExecS: 600, shell: "local" }).map((def) => def.name));
921
869
  const kindTools = (kind) => kind === "none" ? [] : kind === "sandbox" ? hostToolDefs({ maxExecS: 600, shell: "computer" }).map((def) => def.name).filter((name) => !localTools.has(name))
922
- : kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
870
+ : kind === "browser" ? browserToolNames : [...COMPUTER_TOOLS];
923
871
  let faux;
924
- const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
872
+ const fauxOf = () => (faux ??= fauxComputers());
925
873
  /** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
926
874
  * 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
875
+ * Docker, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
928
876
  * daemon that stops after the start is seen, and one that is gone says so in noDockerWords); once it answers, the
929
877
  * box's start-time answer stands. A box the start did not make keeps its reason ("start Docker, then restart
930
878
  * AgentRun"): the start's checks of Docker (Docker elsewhere, this server's paths, host addresses, its network) ran
@@ -935,7 +883,7 @@ async function startHolding(options, data, checked, stops) {
935
883
  const dockerAnswers = async (provider) => {
936
884
  const box = boxAvailability(boxOffers).find((one) => one.id === provider);
937
885
  const local = COMPUTER_PROVIDERS.find((one) => one.id === provider)?.local === true;
938
- if (local && !fauxBox && enabledBoxes(env).has(provider)) {
886
+ if (local && !fauxDocker && enabledBoxes(env).has(provider)) {
939
887
  const daemon = await dockerDaemon();
940
888
  if (!daemon.up || box?.available)
941
889
  return daemon;
@@ -945,12 +893,17 @@ async function startHolding(options, data, checked, stops) {
945
893
  return { up: false, absent: false, reason: box?.reason ?? `${provider} is not a box this server has` };
946
894
  };
947
895
  let computerRoutes;
896
+ // The programs a provider runs on this machine (the phone's adb), looked for on PATH once, at the start, as the boxes
897
+ // probe Docker: a provider whose program is missing is not ready, and its words say what to install.
898
+ const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
948
899
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
949
- store, sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
900
+ store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
901
+ paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
950
902
  ...(options.faux
951
903
  // --faux's providers stand in for every vendor's, a local one's daemon included.
952
904
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
953
905
  : {
906
+ hostWhy,
954
907
  kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
955
908
  // The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
956
909
  factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
@@ -959,29 +912,58 @@ async function startHolding(options, data, checked, stops) {
959
912
  }));
960
913
  /** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
961
914
  * computerReadiness): over the registry the claim reads (workspace/computer-deps.ts claimKinds, asked with what the
962
- * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
963
- * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
915
+ * runner composes with: under --faux, faux's, as runner/main.ts runnerComputers gives its runs' faux; else the
916
+ * package's), in the folder mode of now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
964
917
  * 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'. */
918
+ * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers', and whether a
919
+ * provider's program is on this machine is hostWhy's, read at the start. */
966
920
  /** 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);
921
+ const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
922
+ /** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
923
+ const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
924
+ // A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
925
+ // attached to this process's hub.
926
+ const computerReady = async (setting) => {
927
+ const paired = await store.pairedComputers.list();
928
+ const row = paired.find((one) => one.id === setting.provider);
929
+ const offline = row ? pairedRefusal(row, attachHub) : undefined;
930
+ if (offline)
931
+ return { refused: offline };
932
+ return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
933
+ };
969
934
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
970
935
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
971
936
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
972
- const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
973
- const archil = createArchilRoutes({ store, sealKey, env: process.env });
974
- /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
975
- const runComputerOf = async (runId, view) => {
976
- const run = await store.runs.get(runId);
977
- const body = run ? (await store.agents.revision(run.revisionId))?.body : undefined;
978
- const setting = body?.computer ?? (body?.place ? computerOfPlace(body.place) : undefined);
979
- if (!setting)
980
- return {};
981
- const error = view.error;
982
- const field = runComputerField(setting, { id: runId, status: String(view.status), ...(error && typeof error.code === "string" ? { error: { code: error.code, message: String(error.message ?? "") } } : {}) });
983
- return field ? { computer: field } : {};
937
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
938
+ /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
939
+ * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
940
+ * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
941
+ * is no shell), whose shell runs the shell tools; else none, and why. */
942
+ const shellHere = async () => {
943
+ if ((await shellOf({ kind: "none" })) === "local")
944
+ return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
945
+ const fresh = newAgentPlace(boxOffers);
946
+ let why = "why" in fresh ? fresh.why : "it is not set up";
947
+ if ("place" in fresh && fresh.place.mode === "sandbox") {
948
+ const computer = { kind: "sandbox", provider: fresh.place.box };
949
+ const ready = await computerReady(computer);
950
+ if ("refused" in ready)
951
+ why = ready.refused;
952
+ else if ((await shellOf(computer)) === "computer")
953
+ return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
954
+ }
955
+ 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})` };
984
956
  };
957
+ const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
958
+ /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
959
+ * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
960
+ * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
961
+ const shellOfRevision = async (revision) => {
962
+ const body = revision.body;
963
+ return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
964
+ };
965
+ /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
966
+ const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
985
967
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
986
968
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
987
969
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -1011,11 +993,17 @@ async function startHolding(options, data, checked, stops) {
1011
993
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
1012
994
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
1013
995
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
1014
- // The outbound webhook and its outbox, in the store; its signing secret among the server's sealed settings, which list it
1015
- // (and each one it held before) with the server's own secrets.
1016
- const webhooks = new Webhooks(store, triggerSettings.get(OUTBOUND_WEBHOOK.id), (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
1017
- await webhooks.load();
996
+ const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
997
+ ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
998
+ privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
999
+ });
1000
+ // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
1018
1001
  stops.push(() => webhooks.close());
1002
+ await webhooks.load();
1003
+ // Where an earlier version kept the webhook: no longer read.
1004
+ if (existsSync(join(data, WEBHOOK_FILE)))
1005
+ log?.(logLine("webhook", { condition: "webhook_left_over", file: join(data, WEBHOOK_FILE), effect: "not read: the webhook is kept in the store now; set it again with PUT /v2/settings/webhook" }));
1006
+ secretStores.add("webhook", () => webhooks.signingSecrets());
1019
1007
  const uploads = new Uploads(join(data, UPLOADS_DIR));
1020
1008
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
1021
1009
  // temp file found now is a crashed one's.
@@ -1070,6 +1058,7 @@ async function startHolding(options, data, checked, stops) {
1070
1058
  const modelOf = (_entry, revision) => runModelRef(env, revision);
1071
1059
  const startDeps = {
1072
1060
  runBodyIssues,
1061
+ boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
1073
1062
  pinnedOf,
1074
1063
  inputIssuesOf,
1075
1064
  explainRun,
@@ -1080,6 +1069,22 @@ async function startHolding(options, data, checked, stops) {
1080
1069
  readyFiles: (ids) => uploads.readyFiles(ids),
1081
1070
  files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1082
1071
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
1072
+ // The run's Archil disk for its launch record (run-launch.ts archilDisk): the body's, else its agent's when it has one.
1073
+ // A disk the body names is read at Archil once, before the run is made (archil-routes.ts checkLaunchDisk): one that is
1074
+ // 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
1075
+ // (archil-routes.ts removeAgentDisk) starts no run on it: 409 until the removal is done.
1076
+ launchDiskOf: async (agentId, named) => {
1077
+ if (named !== undefined) {
1078
+ await archil.checkLaunchDisk(named);
1079
+ return { diskId: named, kind: "launch" };
1080
+ }
1081
+ if (!(await inArchilMode(store, process.env)))
1082
+ return undefined;
1083
+ const own = await agentDiskOf(store, agentId);
1084
+ if (own?.removing)
1085
+ 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.`);
1086
+ return own ? { diskId: own.diskId, kind: "agent" } : undefined;
1087
+ },
1083
1088
  workflowTitle,
1084
1089
  serverSecrets,
1085
1090
  toolSettings: () => settings.get(),
@@ -1113,6 +1118,59 @@ async function startHolding(options, data, checked, stops) {
1113
1118
  },
1114
1119
  shown: () => secretsShown(serverSecrets(), { local: true }),
1115
1120
  };
1121
+ /** What a learning batch's loop reads of a run, from its view. */
1122
+ const batchRunView = async (runId) => {
1123
+ const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1124
+ if (!v)
1125
+ return undefined;
1126
+ return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1127
+ };
1128
+ // Learn from a CSV (learning-batch.ts): a batch's loop runs in this process over the run write half and the run view; its
1129
+ // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
1130
+ // (create's answer, read, list, cancel) cut its text as the learning routes do (learningShown, below).
1131
+ const batches = new LearningBatches({
1132
+ settings: store.settings,
1133
+ learning: async (agentId) => {
1134
+ const entry = await needAgent(agentId);
1135
+ if (entry.agent.archivedAt)
1136
+ return { learns: false, why: "it is archived." };
1137
+ if (learning === "off")
1138
+ return { learns: false, why: "this server's learning is off (--learning)." };
1139
+ if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1140
+ return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1141
+ return { learns: true };
1142
+ },
1143
+ // A row's run starts under the row's key (the store's run origin, as an Idempotency-Key's run does), so a start the
1144
+ // server stopped before its row kept the id is found again, never started twice.
1145
+ find: async (key) => (await agents.request(() => agents.store.runOfOrigin(key)))?.runId,
1146
+ start: async (agentId, body, key) => (await startRunOf(await needAgent(agentId), body, { origin: { key } })).id,
1147
+ view: (runId) => batchRunView(runId),
1148
+ // Sent already: a steer the run's commands hold with these words, not refused (a follow-up to an ended run is one too,
1149
+ // its reopen's).
1150
+ sent: async (runId, content) => (await store.commands(runId, 0)).some((c) => c.kind === "steer" && c.refused === null && c.body?.text === content),
1151
+ message: async (runId, content) => void (await message(store, await needRun(runId), content)),
1152
+ // A run that is not there has nothing to stop; any other failure is the loop's (the row stays live and owned).
1153
+ cancel: async (runId) => {
1154
+ const moment = ID.test(runId) ? await momentOverStore(store, runId, viewDepsFor(ownOriginOf())) : undefined;
1155
+ if (moment)
1156
+ await cancel(store, moment);
1157
+ },
1158
+ figures: async (runId) => {
1159
+ const stored = await store.runs.get(runId);
1160
+ if (!stored)
1161
+ return undefined;
1162
+ // A run still going has no stored cost yet (its column is written at its end): its live cost, from its view, stands in,
1163
+ // so a batch's cost now and the cost it books are costRunOf both.
1164
+ const run = FINAL_STATES.includes(stored.state) ? stored : { ...stored, costUsd: (await batchRunView(runId))?.cost_usd ?? null };
1165
+ // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1166
+ const newest = await store.learning.proposal(runId);
1167
+ const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1168
+ return figuresOf(await costRunOf(store, run, 0), ends);
1169
+ },
1170
+ // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1171
+ shown: (agentId) => learningShown(agentId),
1172
+ ...(options.batchPollMs ? { pollMs: options.batchPollMs } : {}),
1173
+ });
1116
1174
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1117
1175
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1118
1176
  // request) use the server's public address, else its own.
@@ -1136,13 +1194,13 @@ async function startHolding(options, data, checked, stops) {
1136
1194
  // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1137
1195
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1138
1196
  const runReadsDeps = {
1139
- runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
1197
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
1140
1198
  env,
1141
1199
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1142
1200
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1143
1201
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1144
1202
  context: ctx,
1145
- liveViewer: (runId) => liveViewerLink(store, sealKey, runId),
1203
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers),
1146
1204
  };
1147
1205
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1148
1206
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
@@ -1158,6 +1216,7 @@ async function startHolding(options, data, checked, stops) {
1158
1216
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1159
1217
  });
1160
1218
  const triggerDeps = {
1219
+ ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}),
1161
1220
  start: startDeps,
1162
1221
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1163
1222
  needAgent,
@@ -1189,6 +1248,8 @@ async function startHolding(options, data, checked, stops) {
1189
1248
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1190
1249
  const openSetup = options.openSetup === true && isLoopback(host);
1191
1250
  const owner = options.accounts ? new Owner(data, openSetup, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
1251
+ // With no accounts, the console's sessions: made by the link this start prints, never from the token (page.ts).
1252
+ const consoleSessions = owner ? undefined : new ConsoleSessions();
1192
1253
  // Who a sign-in comes from, for its limit: the socket's peer, or, from a trusted proxy only, the client it forwards for.
1193
1254
  const trusted = (() => {
1194
1255
  if (!options.trustedProxies?.length)
@@ -1291,6 +1352,7 @@ async function startHolding(options, data, checked, stops) {
1291
1352
  stops.push(async () => triggers.close());
1292
1353
  // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1293
1354
  // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1355
+ void batches.resume().catch((error) => void process.stderr.write(`agentrun-serve: the learning batches' resume: ${error.message}\n`));
1294
1356
  void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1295
1357
  // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1296
1358
  // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
@@ -1439,7 +1501,24 @@ async function startHolding(options, data, checked, stops) {
1439
1501
  // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1440
1502
  const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1441
1503
  // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1442
- return { tools, gated, deniedBy, ask: { asked, fits: learnedAskFits } };
1504
+ const ask = { asked, fits: learnedAskFits };
1505
+ // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1506
+ // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1507
+ const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1508
+ const providers = await decisionProvidersIn(env);
1509
+ if (!providers)
1510
+ return { tools, gated, deniedBy, ask };
1511
+ const decided = {};
1512
+ const decisionDeniedBy = {};
1513
+ for (const provider of DECISION_PROVIDER_KEYS) {
1514
+ const { permission, from } = gate(provider);
1515
+ if (permission === "allow")
1516
+ continue;
1517
+ decided[provider] = permission;
1518
+ if (permission === "deny")
1519
+ decisionDeniedBy[provider] = from;
1520
+ }
1521
+ return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1443
1522
  }
1444
1523
  async function needAgent(id) {
1445
1524
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1453,7 +1532,21 @@ async function startHolding(options, data, checked, stops) {
1453
1532
  const agentExtra = async (entry) => {
1454
1533
  const learning = await learningOfAgent(entry);
1455
1534
  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 } };
1535
+ return {
1536
+ signIns: await signIns.view(entry.agent.id),
1537
+ ...(learning ? { learning } : {}),
1538
+ runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
1539
+ // The agent's own computer (a persistent setting), as this server records it: the view's own_computer.
1540
+ ownComputer: agentComputerView(await agentComputerOf(store, entry.agent.id)),
1541
+ };
1542
+ };
1543
+ /** Deletes an agent's own computer once the agent has no use for it (archived, persistent turned off, another provider
1544
+ * or image: workspace/agent-computer.ts), after the write that made it so, in the background: a vendor's delete can
1545
+ * take minutes. Until the provider has deleted it, the agent's view shows it deleting, with why where a delete failed. */
1546
+ const reconcileComputer = (agentId) => {
1547
+ void reconcileAgentComputer(store, agentId, (provider, image) => computersOf().providerFor(provider, image))
1548
+ .then((done) => (done ? log?.(logLine("agent_computer", { agent: agentId, ...("deleted" in done ? { deleted: done.deleted } : { failed: done.failed }) })) : undefined))
1549
+ .catch((error) => log?.(logLine("agent_computer", { agent: agentId, failed: error instanceof Error ? error.message : String(error) })));
1457
1550
  };
1458
1551
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
1459
1552
  // routes read from the store + the run view now, not a live Run.
@@ -1468,9 +1561,6 @@ async function startHolding(options, data, checked, stops) {
1468
1561
  const v = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1469
1562
  return { status: v?.status ?? "queued", state: v?.state ?? "idle" };
1470
1563
  };
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
1564
  const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
1475
1565
  /** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
1476
1566
  * origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
@@ -1658,6 +1748,13 @@ async function startHolding(options, data, checked, stops) {
1658
1748
  const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1659
1749
  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
1750
  }
1751
+ // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
1752
+ // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
1753
+ // whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
1754
+ const pick = pickComputer(pkg, await shellHere());
1755
+ if (pick && "refused" in pick)
1756
+ throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
1757
+ const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1661
1758
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1662
1759
  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
1760
  const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
@@ -1665,7 +1762,9 @@ async function startHolding(options, data, checked, stops) {
1665
1762
  const model = picked.model;
1666
1763
  // 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
1764
  // 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 }] : [];
1765
+ // The model of each tier its subagents run on (packageTiers): the package's where this server runs it.
1766
+ const tiers = await packageTiers(env, pkg.model, harness ?? DEFAULT_HARNESS, model);
1767
+ const modelWarnings = [...("warning" in picked && picked.warning ? [picked.warning] : []), ...(tiers.warning ? [tiers.warning] : [])].map((message) => ({ field: "model", reason: "not_an_option", message }));
1669
1768
  const defaultTools = "place" in newAgentPlace(boxOffers) ? NEW_AGENT_TOOLS : [];
1670
1769
  // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1671
1770
  const server = settings.get();
@@ -1674,7 +1773,7 @@ async function startHolding(options, data, checked, stops) {
1674
1773
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1675
1774
  // never), else ask. Deny and pins hold either way.
1676
1775
  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);
1776
+ 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
1777
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1679
1778
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1680
1779
  const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
@@ -1727,9 +1826,10 @@ async function startHolding(options, data, checked, stops) {
1727
1826
  }
1728
1827
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1729
1828
  const unpinned = made.unpinned.map(({ tool, parameters: named }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: `${tool}'s arguments are fixed by ${named.map((one) => `the ${one} parameter`).join(" and ")}, which was not given, so the agent was made with ${tool} set to deny: it can't call it at all. Apply again with ${named.join(" and ")} set to let it.` }));
1730
- // A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
1731
- // MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
1732
- const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
1829
+ // A GitHub tool the package grants that an installation of Connect GitHub's App does not hold the permission for (read
1830
+ // from GitHub, never assumed), where the github MCP server runs on the App's tokens: said now, before a run's first
1831
+ // call is refused; or that the check could not be made (template-github-permissions.ts).
1832
+ const appShort = await appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
1733
1833
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
1734
1834
  const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1735
1835
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
@@ -1739,7 +1839,7 @@ async function startHolding(options, data, checked, stops) {
1739
1839
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1740
1840
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1741
1841
  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] };
1842
+ 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
1843
  return { applied, minted };
1744
1844
  }
1745
1845
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
@@ -1788,11 +1888,39 @@ async function startHolding(options, data, checked, stops) {
1788
1888
  * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
1789
1889
  * at the public URL or the server's own address. */
1790
1890
  const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
1891
+ /** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
1892
+ * its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
1893
+ * timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
1894
+ * seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
1895
+ * each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
1896
+ * entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
1897
+ * answer even when the server has since changed or gone, since it does no new work. */
1898
+ function handedMcpAuth(body) {
1899
+ if (body.mcp_auth === undefined)
1900
+ return { body, sealer: async () => undefined };
1901
+ const { mcp_auth, ...rest } = body;
1902
+ const sealer = async () => {
1903
+ const issues = [];
1904
+ const handed = mcpAuthOf(mcp_auth, issues);
1905
+ const auth = {};
1906
+ for (const [server, headers] of Object.entries(handed ?? {})) {
1907
+ const row = await store.mcp.server(server);
1908
+ if (row?.auth !== "per_run")
1909
+ 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.` });
1910
+ else
1911
+ auth[server] = { headers, origin: new URL(row.url).origin };
1912
+ }
1913
+ if (issues.length)
1914
+ throw invalid(issues);
1915
+ return (runId) => sealRunMcpAuth(sealKey, runId, auth);
1916
+ };
1917
+ return { body: rest, sealer };
1918
+ }
1791
1919
  async function createRun(req, agentId) {
1792
1920
  const entry = await needAgent(agentId);
1793
1921
  if (entry.agent.archivedAt)
1794
1922
  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);
1923
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
1796
1924
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
1797
1925
  // 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
1926
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -1802,7 +1930,8 @@ async function startHolding(options, data, checked, stops) {
1802
1930
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1803
1931
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1804
1932
  }
1805
- const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
1933
+ const seal = await sealer();
1934
+ const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
1806
1935
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
1807
1936
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
1808
1937
  });
@@ -1813,7 +1942,7 @@ async function startHolding(options, data, checked, stops) {
1813
1942
  * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
1814
1943
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
1815
1944
  async function createInlineRun(req) {
1816
- const body = await bodyOf(req);
1945
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
1817
1946
  const { external, definition, skills, note, revision: pinned, ...run } = body;
1818
1947
  const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
1819
1948
  const issues = [
@@ -1847,7 +1976,8 @@ async function startHolding(options, data, checked, stops) {
1847
1976
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1848
1977
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1849
1978
  }
1850
- const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}) });
1979
+ const seal = await sealer();
1980
+ const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
1851
1981
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
1852
1982
  });
1853
1983
  }
@@ -1901,7 +2031,18 @@ async function startHolding(options, data, checked, stops) {
1901
2031
  }
1902
2032
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
1903
2033
  function runBodyIssues(body) {
1904
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id"]);
2034
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "learning", "archil_disk", "repo", "hold", "hold_minutes"]);
2035
+ issues.push(...holdIssues(body));
2036
+ if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2037
+ issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
2038
+ if (body.archil_disk !== undefined) {
2039
+ const disk = body.archil_disk;
2040
+ const extra = isObject(disk) ? Object.keys(disk).filter((key) => key !== "disk_id") : [];
2041
+ if (!isObject(disk) || typeof disk.disk_id !== "string" || !ARCHIL_DISK_ID.test(disk.disk_id))
2042
+ 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" });
2043
+ else if (extra.length)
2044
+ 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 ")}.` });
2045
+ }
1905
2046
  if (!isObject(body.input))
1906
2047
  issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
1907
2048
  if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
@@ -1914,6 +2055,8 @@ async function startHolding(options, data, checked, stops) {
1914
2055
  issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
1915
2056
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
1916
2057
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2058
+ if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2059
+ issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
1917
2060
  return issues;
1918
2061
  }
1919
2062
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
@@ -2043,30 +2186,12 @@ async function startHolding(options, data, checked, stops) {
2043
2186
  // 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
2187
  // again. A run whose journal cannot be read leaves it all tokens.
2045
2188
  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
2189
  const metersOf = async (row) => {
2064
2190
  const key = `${row.id} ${row.endedAt}`;
2065
2191
  let meters = endedMeters.get(key);
2066
2192
  if (!meters) {
2067
2193
  // 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).
2194
+ // folded back from the paid-tools session (store-reads/journal withPaidCosts).
2070
2195
  meters = await metersOverStore(store, row.id, ctx);
2071
2196
  endedMeters.set(key, meters);
2072
2197
  }
@@ -2121,7 +2246,7 @@ async function startHolding(options, data, checked, stops) {
2121
2246
  // 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
2247
  // 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
2248
  // 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);
2249
+ const soFar = usd !== null || !read ? 0 : read.known.tokens + read.known.browser + read.known.others;
2125
2250
  const meters = group === "meter" && usd !== 0 ? read : undefined;
2126
2251
  if (meters && meters.browser.usd !== 0)
2127
2252
  browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
@@ -2393,6 +2518,10 @@ async function startHolding(options, data, checked, stops) {
2393
2518
  const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, /^\/hooks\/([^/]+)$/.exec(path)[1]);
2394
2519
  return send(res, answer.status, answer.body, answer.headers ?? {});
2395
2520
  }
2521
+ // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
2522
+ // limited by source address before anything in the body is checked.
2523
+ if (found.name === "pairComputer")
2524
+ return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
2396
2525
  // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2397
2526
  // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2398
2527
  if (found.name === "mcpOAuthCallback") {
@@ -2522,7 +2651,9 @@ async function startHolding(options, data, checked, stops) {
2522
2651
  case "getAgent": {
2523
2652
  const entry = await needAgent(id);
2524
2653
  // 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)) : [];
2654
+ // A tool of bash's family the agent's computer gives no shell for reads unavailable (runShellOf).
2655
+ const revision = entry.revision;
2656
+ const tools = revision ? agentTools(env, settings.get(), await toolingOf(revision), caps.tools.map((tool) => tool.name), await shellOfRevision(revision)) : [];
2526
2657
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
2527
2658
  }
2528
2659
  case "updateDefinition": {
@@ -2546,6 +2677,7 @@ async function startHolding(options, data, checked, stops) {
2546
2677
  let warnings = [];
2547
2678
  const check = async (revision) => void (warnings = await saveable(revision));
2548
2679
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
2680
+ reconcileComputer(id);
2549
2681
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
2550
2682
  }
2551
2683
  case "listRevisions": {
@@ -2569,6 +2701,7 @@ async function startHolding(options, data, checked, stops) {
2569
2701
  if (!(await agents.revision(id, revision)))
2570
2702
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
2571
2703
  const moved = await agents.setCurrent(entry, revision);
2704
+ reconcileComputer(id);
2572
2705
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
2573
2706
  }
2574
2707
  case "archiveAgent":
@@ -2581,9 +2714,22 @@ async function startHolding(options, data, checked, stops) {
2581
2714
  // which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
2582
2715
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
2583
2716
  const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
2717
+ // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
2718
+ if (found.name === "archiveAgent")
2719
+ reconcileComputer(id);
2584
2720
  const entry = await needAgent(id);
2585
2721
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), triggers_off: triggersOff }, { etag: etagOf(entry) });
2586
2722
  }
2723
+ case "getAgentArchil":
2724
+ case "deleteAgentArchil": {
2725
+ // The agent's Archil disk (archil-routes.ts): its rules are the handler's; the dispatch reads the agent (archived, or
2726
+ // managed by its source) and how to count the live runs on a disk.
2727
+ const entry = await needAgent(id);
2728
+ const controller = new AbortController();
2729
+ req.once("close", () => controller.abort());
2730
+ const agent = { id, archived: entry.agent.archivedAt != null, external: entry.agent.externalRef !== null, liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
2731
+ return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
2732
+ }
2587
2733
  case "forgetSignIn": {
2588
2734
  await needAgent(id);
2589
2735
  let key;
@@ -2626,8 +2772,9 @@ async function startHolding(options, data, checked, stops) {
2626
2772
  const run = await needRun(id);
2627
2773
  if (run.kind === "workflow")
2628
2774
  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);
2775
+ const { body, sealer } = handedMcpAuth(await bodyOf(req));
2630
2776
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
2777
+ const seal = await sealer();
2631
2778
  const extra = unknownFields(body, ["content"]);
2632
2779
  if (extra.length)
2633
2780
  throw invalid(extra);
@@ -2636,7 +2783,8 @@ async function startHolding(options, data, checked, stops) {
2636
2783
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
2637
2784
  if (content.length > MAX_MESSAGE)
2638
2785
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
2639
- const { mode, messageId } = await message(store, run, content);
2786
+ // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
2787
+ const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal(run.id) } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
2640
2788
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
2641
2789
  const { status, state } = await runStatusState(run.id);
2642
2790
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -2703,19 +2851,29 @@ async function startHolding(options, data, checked, stops) {
2703
2851
  const run = await needRun(id);
2704
2852
  const family = found.name === "getRunBrowser" ? "browser" : "computer";
2705
2853
  // The run's open viewer, from the store's sealed viewer rows the runner publishes its hand-over into (browser-live.ts
2706
- // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store.
2707
- const hold = await computerHoldOf(store, run.id);
2854
+ // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store,
2855
+ // and where a computer with no viewer is (sessionIn), both over one read of the run's journal.
2856
+ const entries = (await runEntries(store, run.id, ctx));
2857
+ const hold = await computerHoldOf(store, run.id, { entries: async () => entries });
2708
2858
  const kept = await keptBrowserOf(store, run.id);
2859
+ // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
2860
+ // none with its kind, never off as if the agent had none (#2170).
2861
+ const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
2709
2862
  const view = await computerView({
2710
2863
  viewer: async () => {
2711
2864
  if (family === "browser") {
2712
- const link = await liveViewerLink(store, sealKey, run.id);
2865
+ const link = await liveViewerLink(store, sealKey, run.id, answers);
2713
2866
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
2714
2867
  }
2715
- return computerViewerLink(store, sealKey, run.id);
2868
+ return computerViewerLink(store, sealKey, run.id, answers);
2716
2869
  },
2717
- computer: () => computerOf(kept, env, family),
2870
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
2871
+ session: (kind) => sessionIn(kind, entries),
2718
2872
  hold: () => hold,
2873
+ // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
2874
+ // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
2875
+ // For an ended run, nothing, and its row goes.
2876
+ ended: () => screenWaitEnded(store.settings, run.id, run.terminal),
2719
2877
  });
2720
2878
  if (family === "browser")
2721
2879
  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" });
@@ -2751,9 +2909,25 @@ async function startHolding(options, data, checked, stops) {
2751
2909
  }, store, { context: ctx });
2752
2910
  return send(res, 200, answer, { "cache-control": "no-store" });
2753
2911
  }
2912
+ case "startRun":
2913
+ case "callRunComputer":
2914
+ case "releaseRunComputer": {
2915
+ // A call on a run's computer (the computer call channel) and a held computer's start and release
2916
+ // (computer-held-routes.ts), over the store: each a command row the run's runner applies.
2917
+ const run = await needRun(id);
2918
+ return send(res, 200, await heldRoute(found.name, run.id, await bodyOf(req), store, { context: ctx }), { "cache-control": "no-store" });
2919
+ }
2920
+ case "createPairing":
2921
+ return send(res, 201, await attach.createPairing(), { "cache-control": "no-store" });
2922
+ case "attachComputer":
2923
+ throw new ApiError("bad_request", `${ATTACH_PATH} is the attach WebSocket: a paired computer's driver dials it with Upgrade: websocket and its own token`);
2924
+ case "deleteComputer":
2925
+ await attach.remove(id);
2926
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
2754
2927
  case "listComputers":
2755
2928
  case "saveComputerKeys":
2756
- case "testComputer": {
2929
+ case "testComputer":
2930
+ case "listComputerChoices": {
2757
2931
  // Settings → Computers (computers.ts): the rules are the handler's; this sends its answer.
2758
2932
  const provider = found.name === "listComputers" ? undefined : id;
2759
2933
  const body = found.name === "saveComputerKeys" ? await bodyOf(req) : undefined;
@@ -2956,6 +3130,17 @@ async function startHolding(options, data, checked, stops) {
2956
3130
  await refreshMcpMeta();
2957
3131
  return send(res, 200, saved);
2958
3132
  }
3133
+ // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
3134
+ case "listComposioTools":
3135
+ return send(res, 200, await composioTools(await bodyOf(req), options.composioControl ?? {}, stopping.signal), { "cache-control": "no-store" });
3136
+ case "saveComposioServer": {
3137
+ // The name is checked before Composio is called: a refused name leaves nothing made there.
3138
+ mcpNameOf(id);
3139
+ const body = await bodyOf(req);
3140
+ const answer = await composioSave(body, options.composioControl ?? {}, (mcp) => mcpServers.save(id, mcp, stopping.signal), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3141
+ await refreshMcpMeta();
3142
+ return send(res, 200, answer, { "cache-control": "no-store" });
3143
+ }
2959
3144
  case "refreshMcpServer": {
2960
3145
  const refreshed = await mcpServers.refresh(id, stopping.signal);
2961
3146
  await refreshMcpMeta();
@@ -3013,9 +3198,15 @@ async function startHolding(options, data, checked, stops) {
3013
3198
  const issues = settingsIssues(body);
3014
3199
  if (issues.length)
3015
3200
  throw invalid(issues);
3201
+ const before = settings.get();
3016
3202
  await settings.put(body);
3017
3203
  // A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
3018
3204
  recompose();
3205
+ // A run parked on a call whose tool reads allow now, on its pinned revision: woken, so its next claim's gate answers
3206
+ // the ask by the setting (settings-wake.ts), before this answer. The settings as the runner's gate reads them.
3207
+ const woken = await wakeAnsweredBySetting(store, await loadToolSettings(store), before);
3208
+ if (woken.length)
3209
+ log?.(logLine("tool_settings", { condition: "runs_woken", runs: woken.join(",") }));
3019
3210
  return send(res, 200, withDefaults(settings.get()));
3020
3211
  }
3021
3212
  // A person's view and control of what an agent learned (learning-routes.ts). Every text cut of the host's secrets as
@@ -3029,6 +3220,50 @@ async function startHolding(options, data, checked, stops) {
3029
3220
  const { counts, impact, notes } = await agentLearningOverStore(store, id);
3030
3221
  return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, notes));
3031
3222
  }
3223
+ case "getLearningCost": {
3224
+ await needAgent(id);
3225
+ // The agent's cost per run over the one store (agentCostOverStore): each ended run's figures and path, aggregates only.
3226
+ const { limit, csv } = learningCostQuery(url);
3227
+ const read = await agentCostOverStore(store, id, limit);
3228
+ // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
3229
+ const shown = await learningShown(id);
3230
+ const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })) };
3231
+ if (csv) {
3232
+ 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"` });
3233
+ return void res.end(costCsv(cost.runs));
3234
+ }
3235
+ return send(res, 200, { agent: id, ...cost });
3236
+ }
3237
+ case "createLearningBatch": {
3238
+ await needAgent(id);
3239
+ const made = await batches.create(id, await bodyOf(req));
3240
+ return send(res, 202, await batches.read(id, made.id), { location: `/v2/agents/${encodeURIComponent(id)}/learning/batches/${made.id}` });
3241
+ }
3242
+ case "listLearningBatches":
3243
+ await needAgent(id);
3244
+ return send(res, 200, await batches.list(id));
3245
+ case "getLearningBatch":
3246
+ await needAgent(id);
3247
+ return send(res, 200, await batches.read(id, second));
3248
+ case "cancelLearningBatch":
3249
+ await needAgent(id);
3250
+ return send(res, 200, await batches.cancel(id, second));
3251
+ case "listLearningEvals": {
3252
+ await needAgent(id);
3253
+ // The agent's eval records (learning-evals.ts), newest first, the latest the one shown: only ever what was posted.
3254
+ const evals = await evalsOf(store, id);
3255
+ return send(res, 200, { agent: id, latest: evals[0] ?? null, evals });
3256
+ }
3257
+ case "recordLearningEval": {
3258
+ const body = await bodyOf(req);
3259
+ await needAgent(id);
3260
+ const answer = await idempotent(req, `/agents/${id}/learning/evals`, body, async () => {
3261
+ const result = evalOf(body, new Date());
3262
+ await recordEval(store, id, result);
3263
+ return { status: 201, body: result };
3264
+ });
3265
+ return send(res, answer.status, answer.body, answer.headers);
3266
+ }
3032
3267
  case "listLearningNotes":
3033
3268
  case "listLearningLog":
3034
3269
  await needAgent(id);
@@ -3038,6 +3273,9 @@ async function startHolding(options, data, checked, stops) {
3038
3273
  return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
3039
3274
  }
3040
3275
  return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
3276
+ case "listLearnedWorkflowRevisions":
3277
+ await needAgent(id);
3278
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
3041
3279
  case "readLearningFile":
3042
3280
  await needAgent(id);
3043
3281
  return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
@@ -3094,7 +3332,7 @@ async function startHolding(options, data, checked, stops) {
3094
3332
  case "testWebhook":
3095
3333
  return send(res, 200, await webhooks.test());
3096
3334
  case "listWebhookDeliveries":
3097
- return send(res, 200, webhooks.attemptsView());
3335
+ return send(res, 200, await webhooks.attemptsView());
3098
3336
  case "redeliverWebhook":
3099
3337
  return send(res, 200, await webhooks.redeliver(id));
3100
3338
  case "listTriggers":
@@ -3107,15 +3345,27 @@ async function startHolding(options, data, checked, stops) {
3107
3345
  const answer = await idempotent(req, "/triggers", body, async () => {
3108
3346
  const { secret: shown, ...made } = await triggers.create(body);
3109
3347
  secret = shown;
3110
- return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : made, headers: { location: `/v2/triggers/${made.id}` } };
3348
+ // A secret the sender gave is not shown: the trigger answers its metadata, as a read does.
3349
+ return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : withSecretOf(made), headers: { location: `/v2/triggers/${made.id}` } };
3111
3350
  });
3112
3351
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
3113
3352
  const { note: _, ...first } = answer.body;
3114
3353
  // Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets secret_set and the words.
3115
3354
  return send(res, answer.status, secret && !replayed ? triggerMade(first, secret, mayHoldSecrets(req), new Date().toISOString()) : answer.body, answer.headers);
3116
3355
  }
3117
- case "listTemplates":
3118
- return send(res, 200, { templates: templates.map(packageView) });
3356
+ case "listTemplates": {
3357
+ // Each package's computer list read against this server now: what an apply here would pick (pickComputer).
3358
+ const here = templates.some((one) => one.computer) ? await shellHere() : undefined;
3359
+ const pickView = (pkg) => {
3360
+ const pick = here && pickComputer(pkg, here);
3361
+ if (!pick)
3362
+ return null;
3363
+ if ("refused" in pick)
3364
+ return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
3365
+ return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
3366
+ };
3367
+ return send(res, 200, { templates: templates.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
3368
+ }
3119
3369
  case "applyTemplate": {
3120
3370
  const pkg = templates.find((t) => t.name === id);
3121
3371
  if (!pkg)
@@ -3137,11 +3387,20 @@ async function startHolding(options, data, checked, stops) {
3137
3387
  }
3138
3388
  case "rotateTriggerSecret":
3139
3389
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
3140
- return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3390
+ // A trigger whose sender gives its secret (Composio's) takes it as the body's `secret`; any other is made one.
3391
+ return send(res, 200, await (async () => {
3392
+ const empty = req.headers["transfer-encoding"] === undefined && !Number(req.headers["content-length"]);
3393
+ const body = empty ? {} : await bodyOf(req);
3394
+ const extra = Object.keys(body).filter((key) => key !== "secret");
3395
+ if (extra.length)
3396
+ throw invalid(extra.map((field) => ({ field, reason: "unknown_field", message: `${field} is not a field of this request: only secret` })));
3397
+ return triggerRotated(id, (await triggers.rotate(id, body.secret)).secret, new Date().toISOString());
3398
+ })());
3141
3399
  case "getTrigger":
3142
3400
  return send(res, 200, withSecretOf(await triggers.get(id)));
3143
3401
  case "updateTrigger":
3144
- return send(res, 200, await triggers.update(id, await bodyOf(req)));
3402
+ // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3403
+ return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3145
3404
  case "deleteTrigger":
3146
3405
  await triggers.remove(id);
3147
3406
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -3181,7 +3440,8 @@ async function startHolding(options, data, checked, stops) {
3181
3440
  const handover = await liveViewerFor(store, sealKey, runId, rest);
3182
3441
  if (handover === undefined || !familyReaches(family, handover))
3183
3442
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
3184
- await serveViewerFile(req, res, rest);
3443
+ // A desktop's or a phone's viewer gets the computer viewer's page (computer-viewer.ts), a browser's pi-browser's.
3444
+ await serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
3185
3445
  }
3186
3446
  /** The origin of the address people open (`publicUrl`, AGENTRUN_PUBLIC_URL), lowercased; none, undefined. */
3187
3447
  const publicOrigin = (() => {
@@ -3242,17 +3502,8 @@ async function startHolding(options, data, checked, stops) {
3242
3502
  return void mcp(req, res).catch(fail);
3243
3503
  if (raw === "/llms.txt")
3244
3504
  return void answerLlms(req, res).catch(fail);
3245
- if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3246
- return;
3247
- // Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
3248
- // a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
3249
- if (options.faux && raw.startsWith(`${FAUX_VIEW_PATH}/`)) {
3250
- const page = fauxOf().viewPage(raw);
3251
- if (page === undefined)
3252
- return fail(new ApiError("not_found", `no faux desktop at ${raw}`));
3253
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(req.method === "HEAD" ? undefined : page);
3505
+ if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3254
3506
  return;
3255
- }
3256
3507
  if (!raw.startsWith("/v2/"))
3257
3508
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3258
3509
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -3277,9 +3528,18 @@ async function startHolding(options, data, checked, stops) {
3277
3528
  // away. Its name alone, on any port, as the HTTP routes check it.
3278
3529
  if (names && !names.has(hostName(req.headers.host) ?? ""))
3279
3530
  return deny("403 Forbidden");
3280
- // API-only: a run's live view is the console's, and refused with it.
3531
+ // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings).
3281
3532
  if (options.apiOnly)
3282
3533
  return deny("404 Not Found");
3534
+ // A paired computer's driver dialing its attach socket (computer-attach.ts): its token, not the owner's, lets it in.
3535
+ if (raw === ATTACH_PATH) {
3536
+ return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
3537
+ if (status.startsWith("401"))
3538
+ authFailed(raw, "attach_token");
3539
+ const lines = Object.entries({ ...headers, "content-type": "text/plain; charset=utf-8", "content-length": String(Buffer.byteLength(words)) }).map(([name, value]) => `${name}: ${value}\r\n`).join("");
3540
+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n${lines}\r\n${words}`);
3541
+ });
3542
+ }
3283
3543
  if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3284
3544
  return deny("404 Not Found");
3285
3545
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
@@ -3310,7 +3570,7 @@ async function startHolding(options, data, checked, stops) {
3310
3570
  if (!admitted())
3311
3571
  return deny("401 Unauthorized");
3312
3572
  viewers.watch(socket, admitted);
3313
- proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; });
3573
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
3314
3574
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
3315
3575
  });
3316
3576
  const first = options.port ?? DEFAULT_PORT;
@@ -3353,16 +3613,19 @@ async function startHolding(options, data, checked, stops) {
3353
3613
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
3354
3614
  owner?.attach(options.publicUrl ?? url);
3355
3615
  webhooks.attach(options.publicUrl ?? url);
3356
- mcpServers.attach(options.publicUrl ?? url, url);
3616
+ // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
3617
+ // other services: mcp-oauth.ts mcpServerAt), and only as its operator says (mcpLoopback), never inferred from where it
3618
+ // listens: a hosted container listens on loopback behind its proxy too.
3619
+ const localInstall = options.mcpLoopback === true;
3620
+ mcpServers.attach(options.publicUrl ?? url, url, localInstall);
3357
3621
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
3358
- // to the store and this server runs no run, so it follows the store: each read takes the runs not final yet and the
3359
- // newest runs (one that started and ended between two reads is among them). It tells each end it has not told once the
3360
- // run reads final, and each wait of a run a runner left parked (or let go of) once it reads input_required. The markers
3361
- // are main's (an end's time, a wait's last row), so each webhook-id is the one it always had, and the ledger tells each
3362
- // once across restarts; a start first catches up the ends the ledger lacks, which no server was up to see. A store read
3363
- // of the runs ended (or parked) since a mark would be the cleaner seam than this read of the open runs every 250 ms.
3364
- const RUN_ENDS_POLL_MS = 250;
3365
- const RUN_ENDS_NEWEST = 50;
3622
+ // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
3623
+ // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
3624
+ // kept in this process. It tells each end once the run reads final, and each wait of a run let go once it reads
3625
+ // input_required. The markers are an end's time and a wait's ask (webhooks.ts waitMarkerOf), so each webhook-id is the
3626
+ // same on every read, and the ledger tells each once across restarts. The feed is read every 250 ms; a store that woke its readers on a
3627
+ // change would be the next seam.
3628
+ const RUN_CHANGES_POLL_MS = 250;
3366
3629
  const final = (row) => FINAL_STATES.includes(row.state);
3367
3630
  const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
3368
3631
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
@@ -3373,6 +3636,16 @@ async function startHolding(options, data, checked, stops) {
3373
3636
  return null;
3374
3637
  return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
3375
3638
  };
3639
+ /** 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
3640
+ * endNotice. The run's view redacts the run's words (its title, its output) on every build, and the newest runs are
3641
+ * read every RUN_ENDS_POLL_MS, so only an end still to tell builds one. */
3642
+ const endToTell = async (id) => {
3643
+ const row = await store.runs.get(id);
3644
+ if (!row)
3645
+ return null;
3646
+ const end = endOf(row);
3647
+ return !end.endedAt || toldEnds.get(id) === end.endedAt ? end : endNotice(id);
3648
+ };
3376
3649
  const toldEnds = new Map();
3377
3650
  /** 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
3651
  * is not read again, and a new wait comes with a new claim, so a new epoch. */
@@ -3382,82 +3655,203 @@ async function startHolding(options, data, checked, stops) {
3382
3655
  const HELD_WAIT_REREAD_MS = 1_000;
3383
3656
  const waitKinds = new Set(["question", "approval", "budget", "browser"]);
3384
3657
  /** The wait of a run its runner left parked (or let go of), or holds in its claim, told once per ask: its marker the
3385
- * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). */
3658
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). False when it
3659
+ * is not done (a read that failed, or its notice not saved): it is read again. */
3386
3660
  const tellWait = async (row) => {
3387
3661
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
3388
3662
  if (readWaits.get(row.id) === seen)
3389
- return;
3663
+ return true;
3390
3664
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
3391
3665
  if (view?.status !== "input_required")
3392
- return void readWaits.set(row.id, seen);
3666
+ return (readWaits.set(row.id, seen), true);
3393
3667
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3394
3668
  // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3395
3669
  const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3396
3670
  if (!marker)
3397
- return void readWaits.set(row.id, seen);
3671
+ return (readWaits.set(row.id, seen), true);
3398
3672
  const card = view.pending?.kind;
3399
3673
  const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3400
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
3401
- if ((await webhooks.emit("run.needs_input", notice, marker)) !== "unsaved")
3402
- readWaits.set(row.id, seen);
3674
+ const wait = { kind };
3675
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: wait };
3676
+ if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3677
+ return false;
3678
+ readWaits.set(row.id, seen);
3679
+ return true;
3403
3680
  };
3404
- let openRuns = new Set();
3405
- let endsTimer;
3406
- let endsRead = Promise.resolve();
3407
- const readEnds = async () => {
3408
- const open = new Set();
3409
- for (const state of ["queued", "running", "parked"]) {
3410
- for (const row of await store.runs.list({ state })) {
3411
- open.add(row.id);
3412
- // A run waits on its person once its runner has let it go: parked, or running with no runner. Or held in its claim
3413
- // waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its browser hand-over,
3414
- // tools.ts), which its row's summary says (HELD_WAITS); a new ask sets it anew, so each is read and told once.
3415
- const waitsInClaim = row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3416
- // A held run's next ask in the same claim reads the same row as its last (state, epoch, runner, summary), and the
3417
- // answer between may come and go within one read: so a held wait is read again now and then (HELD_WAIT_REREAD_MS),
3418
- // and told once per ask all the same, since each ask's notice is keyed to its own last row (webhooks.ts emit).
3419
- if (waitsInClaim && Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3420
- heldReadAt.set(row.id, Date.now());
3421
- readWaits.delete(row.id);
3422
- }
3423
- if (!closing && (row.state === "parked" || (row.state === "running" && row.runner === null) || waitsInClaim))
3424
- await tellWait(row).catch(() => undefined);
3681
+ /** Who hears of each run's end and each wait the follower reads (runNotices): the outbound webhook first. Each is called
3682
+ * once a run reads final (onEnded) or is let go waiting on a person (onWaits), and again on a later read while any of
3683
+ * them threw (said once, run_notice_unread): so at least once, and the same moment always comes with the same `marker`
3684
+ * (an end's time, a wait's ask), on which each dedupes in a ledger of its own. An end from while no server was up
3685
+ * reaches the webhook alone, through its own catch-up (webhooks.ts catchUp). */
3686
+ const endedSubscribers = [];
3687
+ const waitSubscribers = [];
3688
+ const runNotices = {
3689
+ onEnded: (tell) => void endedSubscribers.push(tell),
3690
+ onWaits: (tell) => void waitSubscribers.push(tell),
3691
+ };
3692
+ runNotices.onEnded(async (run, marker) => {
3693
+ if ((await webhooks.emit("run.ended", run, marker)) === "unsaved")
3694
+ throw new Error("its run.ended is not saved yet");
3695
+ });
3696
+ runNotices.onWaits(async (run, _wait, marker) => {
3697
+ if ((await webhooks.emit("run.needs_input", run, marker)) === "unsaved")
3698
+ throw new Error("its run.needs_input is not saved yet");
3699
+ });
3700
+ /** Every call of `calls` made: false when one threw (said once for the run), so the run is told again. */
3701
+ const toldAll = async (id, calls) => {
3702
+ let done = true;
3703
+ for (const call of calls) {
3704
+ try {
3705
+ await call();
3706
+ }
3707
+ catch (error) {
3708
+ sayUnread(id, error.message);
3709
+ done = false;
3425
3710
  }
3426
3711
  }
3427
- const newest = await store.runs.list({ limit: RUN_ENDS_NEWEST });
3428
- for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
3429
- if (open.has(id) || closing)
3430
- continue;
3431
- const now = await endNotice(id).catch(() => undefined);
3432
- // Unread (a busy store): read again at the next turn, never lost.
3433
- if (now === undefined) {
3434
- open.add(id);
3712
+ return done;
3713
+ };
3714
+ /** Why a run's notice is not done yet, said once for the run (until it is done): one that stays undone shows. */
3715
+ const unreadSaid = new Set();
3716
+ const sayUnread = (id, error) => {
3717
+ if (unreadSaid.has(id))
3718
+ return;
3719
+ unreadSaid.add(id);
3720
+ log?.(logLine("webhook", { condition: "run_notice_unread", run: id, error }));
3721
+ };
3722
+ /** A run's end, told once the run reads final. False when it is not done (a read that failed, or its notice not saved). */
3723
+ const tellEnd = async (id) => {
3724
+ const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
3725
+ if (now === undefined)
3726
+ return false;
3727
+ readWaits.delete(id);
3728
+ heldReadAt.delete(id);
3729
+ if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3730
+ return (unreadSaid.delete(id), true);
3731
+ if (!(await toldAll(id, endedSubscribers.map((tell) => () => tell(now.notice, now.endedAt)))))
3732
+ return false;
3733
+ toldEnds.set(id, now.endedAt);
3734
+ unreadSaid.delete(id);
3735
+ return true;
3736
+ };
3737
+ /** A run's row as the store holds it now: undefined when there is no such run, UNREAD when the read failed. */
3738
+ const UNREAD = Symbol("unread");
3739
+ const rowNow = (id) => store.runs.get(id).catch(() => UNREAD);
3740
+ /** A run held in its claim waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its
3741
+ * browser hand-over, tools.ts), which its row's summary says (HELD_WAITS). Its row's state and runner do not move, so
3742
+ * the feed has no change for it: each read looks for these among the running runs. */
3743
+ const heldWait = (row) => row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3744
+ /** A run waiting on its person: let go by its runner (parked, or running with none), or held in its claim (heldWait). */
3745
+ const letGo = (row) => row.state === "parked" || (row.state === "running" && row.runner === null) || heldWait(row);
3746
+ /** One change of the feed, handled: an end told, a wait told, or nothing to tell. One not done goes to endsLeft or
3747
+ * waitsLeft, by its run, which each read tries first until it is: a run that stays undone holds back no other. A wait is
3748
+ * read from the run as it is now (a run gone since, or moved on, has none to tell). */
3749
+ const handle = async (change) => {
3750
+ if (final(change)) {
3751
+ if (!(await tellEnd(change.id)))
3752
+ endsLeft.add(change.id);
3753
+ return;
3754
+ }
3755
+ if (change.state === "parked" || (change.state === "running" && change.runner === null)) {
3756
+ if (!(await tellLetGo(change.id)))
3757
+ waitsLeft.add(change.id);
3758
+ }
3759
+ };
3760
+ /** The wait of run `id` if it is let go now: false when not done (its read failed, or its wait not told). */
3761
+ const tellLetGo = async (id) => {
3762
+ const row = await rowNow(id);
3763
+ if (row === UNREAD)
3764
+ return (sayUnread(id, "its row could not be read"), false);
3765
+ if (row === undefined || !letGo(row))
3766
+ return true;
3767
+ const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
3768
+ if (told)
3769
+ unreadSaid.delete(id);
3770
+ return told;
3771
+ };
3772
+ /** Where the feed is read on from: past each page once its changes are handled, each told or left in endsLeft or
3773
+ * waitsLeft. None is dropped (a run left is tried again on each read), none is skipped, and none is read twice. */
3774
+ let changesCursor;
3775
+ /** The runs whose end, or whose wait, is not told yet (a read that failed, or a notice not saved): from the feed, or from
3776
+ * the start. Each read tries them first, until each is done. */
3777
+ const endsLeft = new Set();
3778
+ const waitsLeft = new Set();
3779
+ const readChanges = async () => {
3780
+ for (const id of [...endsLeft]) {
3781
+ if (closing)
3782
+ return;
3783
+ if (await tellEnd(id))
3784
+ endsLeft.delete(id);
3785
+ }
3786
+ for (const id of [...waitsLeft]) {
3787
+ if (closing)
3788
+ return;
3789
+ if (await tellLetGo(id))
3790
+ waitsLeft.delete(id);
3791
+ }
3792
+ for (;;) {
3793
+ if (closing)
3794
+ return;
3795
+ const page = await store.runs.changedSince(changesCursor, { limit: RUN_CHANGES_PAGE });
3796
+ for (const change of page.changes)
3797
+ await handle(change);
3798
+ changesCursor = page.next;
3799
+ if (page.changes.length < RUN_CHANGES_PAGE)
3800
+ break;
3801
+ }
3802
+ // The held waits, which the feed has no change for. A held run's next ask in the same claim reads the same row as its
3803
+ // last (state, epoch, runner, summary), and the answer between may come and go within one read: so a held wait is read
3804
+ // again now and then (HELD_WAIT_REREAD_MS), and told once per ask all the same, each ask's notice keyed to the ask
3805
+ // itself (webhooks.ts waitMarkerOf), never to the row that shows last.
3806
+ for (const row of await store.runs.list({ state: "running" })) {
3807
+ if (closing)
3808
+ return;
3809
+ if (!heldWait(row))
3435
3810
  continue;
3811
+ if (Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3812
+ heldReadAt.set(row.id, Date.now());
3813
+ readWaits.delete(row.id);
3436
3814
  }
3437
- readWaits.delete(id);
3438
- heldReadAt.delete(id);
3439
- if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3440
- continue;
3441
- if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
3442
- toldEnds.set(id, now.endedAt);
3815
+ if (!(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
3816
+ waitsLeft.add(row.id);
3443
3817
  }
3444
- openRuns = open;
3445
3818
  };
3446
- const followEnds = () => {
3819
+ let endsTimer;
3820
+ let endsRead = Promise.resolve();
3821
+ /** Whether the start (startFollowing) is done: until it is, each turn runs it again before it reads the feed, so the ends
3822
+ * and waits from while no server was up are told whatever failed it. Said once. */
3823
+ let started = false;
3824
+ let startSaid = false;
3825
+ const followChanges = () => {
3447
3826
  if (closing)
3448
3827
  return;
3449
- endsRead = readEnds()
3450
- .catch((error) => log?.(logLine("webhook", { condition: "run_ends_unread", error: error.message })))
3828
+ const turn = started
3829
+ ? readChanges()
3830
+ : startFollowing().then(() => ((started = true), readChanges()), (error) => void (startSaid || ((startSaid = true), log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))));
3831
+ endsRead = turn
3832
+ .catch((error) => log?.(logLine("webhook", { condition: "run_changes_unread", error: error.message })))
3451
3833
  .finally(() => {
3452
3834
  if (!closing)
3453
- (endsTimer = setTimeout(followEnds, RUN_ENDS_POLL_MS)).unref();
3835
+ (endsTimer = setTimeout(followChanges, RUN_CHANGES_POLL_MS)).unref();
3454
3836
  });
3455
3837
  };
3456
- void store.runs
3457
- .list({})
3458
- .then((rows) => webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), endNotice))
3459
- .catch((error) => log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))
3460
- .finally(followEnds);
3838
+ /** The start, in this order, so no change is lost between its steps: the feed's head first (one read, untold),
3839
+ * then what the store holds now (the ends the ledger lacks, webhooks.ts catchUp, and the waits of the runs let go: the
3840
+ * feed has none from before its table, and none from a time no server read it), then the feed from that head. A change
3841
+ * after the head is read by the feed even when the store's rows already showed it, and the ledger tells it once. */
3842
+ const startFollowing = async () => {
3843
+ changesCursor = await store.runs.changesHead();
3844
+ const rows = await store.runs.list({});
3845
+ // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
3846
+ // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
3847
+ const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
3848
+ for (const id of unsaved)
3849
+ endsLeft.add(id);
3850
+ for (const row of rows)
3851
+ if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
3852
+ waitsLeft.add(row.id);
3853
+ };
3854
+ followChanges();
3461
3855
  const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
3462
3856
  /** The server's stop: once (`close` keeps its promise). */
3463
3857
  let stopped;
@@ -3485,16 +3879,15 @@ async function startHolding(options, data, checked, stops) {
3485
3879
  await Promise.all([...workers.values()].map((w) => w.exit));
3486
3880
  await importing;
3487
3881
  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
3882
  // The ends' follower stops before the webhooks it feeds and the store it reads.
3493
3883
  clearTimeout(endsTimer);
3494
3884
  await endsRead;
3885
+ // A learning batch's loop ends where it stands, still running: it takes up when a server starts on this data again.
3886
+ await batches.halt();
3495
3887
  await webhooks.close();
3496
3888
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
3497
3889
  viewers.close();
3890
+ await attach.close();
3498
3891
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
3499
3892
  await mcpStopped;
3500
3893
  await githubStopped;
@@ -3513,7 +3906,10 @@ async function startHolding(options, data, checked, stops) {
3513
3906
  tokenFile,
3514
3907
  tokenMade: stored?.made ?? false,
3515
3908
  ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
3909
+ ...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
3516
3910
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
3911
+ attachHub,
3912
+ localInstall,
3517
3913
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
3518
3914
  // never writes this data root's record again (the next server's, by then).
3519
3915
  close: () => (stopped ??= stop()),