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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (810) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/NOTICE +18 -0
  3. package/README.md +887 -241
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -140
  7. package/dist/adapters.js +153 -377
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +5 -3
  11. package/dist/agents.js +37 -17
  12. package/dist/app.d.ts +2 -4
  13. package/dist/app.js +207 -92
  14. package/dist/approvals.d.ts +4 -0
  15. package/dist/approvals.js +7 -0
  16. package/dist/archil-routes.d.ts +45 -0
  17. package/dist/archil-routes.js +150 -0
  18. package/dist/archil-settings.d.ts +30 -0
  19. package/dist/archil-settings.js +34 -0
  20. package/dist/background.js +28 -9
  21. package/dist/bounds.d.ts +26 -0
  22. package/dist/bounds.js +137 -0
  23. package/dist/box-egress-vm.d.ts +2 -1
  24. package/dist/box-egress-vm.js +20 -6
  25. package/dist/box-egress.d.ts +16 -6
  26. package/dist/box-egress.js +27 -15
  27. package/dist/box-paths.d.ts +59 -0
  28. package/dist/box-paths.js +92 -0
  29. package/dist/box-relay-vm.js +28 -1
  30. package/dist/box-relay.d.ts +2 -0
  31. package/dist/box-relay.js +2 -2
  32. package/dist/boxes.d.ts +13 -1
  33. package/dist/boxes.js +37 -3
  34. package/dist/browser-commands.d.ts +43 -0
  35. package/dist/browser-commands.js +154 -0
  36. package/dist/browser-cost.d.ts +30 -3
  37. package/dist/browser-cost.js +276 -21
  38. package/dist/browser-live.d.ts +124 -0
  39. package/dist/browser-live.js +324 -0
  40. package/dist/browser-person.d.ts +168 -0
  41. package/dist/browser-person.js +769 -0
  42. package/dist/budget.d.ts +80 -0
  43. package/dist/budget.js +211 -0
  44. package/dist/cap.d.ts +272 -62
  45. package/dist/cap.js +599 -189
  46. package/dist/cli.js +201 -17
  47. package/dist/coding-tools.d.ts +13 -1
  48. package/dist/coding-tools.js +107 -5
  49. package/dist/computer-adb.d.ts +12 -0
  50. package/dist/computer-adb.js +14 -0
  51. package/dist/computer-commands.d.ts +103 -0
  52. package/dist/computer-commands.js +256 -0
  53. package/dist/computer-keys.d.ts +68 -0
  54. package/dist/computer-keys.js +148 -0
  55. package/dist/computer-routes.d.ts +38 -0
  56. package/dist/computer-routes.js +56 -0
  57. package/dist/computer-setting.d.ts +37 -0
  58. package/dist/computer-setting.js +47 -0
  59. package/dist/computer-view.d.ts +38 -0
  60. package/dist/computer-view.js +14 -0
  61. package/dist/computers.d.ts +137 -0
  62. package/dist/computers.js +197 -0
  63. package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
  64. package/dist/console/assets/index-35-7aeIZ.js +519 -0
  65. package/dist/console/assets/index-Cejbov-Y.css +1 -0
  66. package/dist/console/index.html +2 -2
  67. package/dist/console-links.d.ts +2 -0
  68. package/dist/console-links.js +6 -0
  69. package/dist/decision-cap.d.ts +63 -0
  70. package/dist/decision-cap.js +163 -0
  71. package/dist/decision-rows.d.ts +5 -2
  72. package/dist/decision-rows.js +8 -6
  73. package/dist/decisions.d.ts +28 -1
  74. package/dist/decisions.js +63 -6
  75. package/dist/disk.d.ts +33 -0
  76. package/dist/disk.js +85 -0
  77. package/dist/door-line.d.ts +23 -0
  78. package/dist/door-line.js +83 -0
  79. package/dist/egress-proxy.d.ts +45 -0
  80. package/dist/egress-proxy.js +416 -0
  81. package/dist/egress-table.d.ts +24 -0
  82. package/dist/egress-table.js +165 -0
  83. package/dist/errors.d.ts +15 -0
  84. package/dist/errors.js +22 -2
  85. package/dist/exa-keyless.js +1 -1
  86. package/dist/explain.d.ts +22 -0
  87. package/dist/explain.js +207 -0
  88. package/dist/faux-computers.d.ts +35 -0
  89. package/dist/faux-computers.js +126 -0
  90. package/dist/file-types.d.ts +4 -0
  91. package/dist/file-types.js +11 -0
  92. package/dist/files.d.ts +3 -35
  93. package/dist/files.js +9 -120
  94. package/dist/github-connection.d.ts +207 -0
  95. package/dist/github-connection.js +595 -0
  96. package/dist/github.d.ts +64 -0
  97. package/dist/github.js +119 -0
  98. package/dist/grade.d.ts +9 -42
  99. package/dist/grade.js +42 -228
  100. package/dist/graph-served.d.ts +23 -2
  101. package/dist/graph-served.js +44 -3
  102. package/dist/graph-view.d.ts +7 -3
  103. package/dist/graph-view.js +26 -15
  104. package/dist/handed-values.d.ts +23 -0
  105. package/dist/handed-values.js +36 -0
  106. package/dist/harness-app.d.ts +33 -4
  107. package/dist/harness-app.js +530 -85
  108. package/dist/harness-install.d.ts +120 -0
  109. package/dist/harness-install.js +359 -0
  110. package/dist/harness-opencode/adapter.js +42 -8
  111. package/dist/harness-opencode/facts.d.ts +2 -0
  112. package/dist/harness-opencode/facts.js +28 -0
  113. package/dist/harness-opencode/harness.d.ts +4 -0
  114. package/dist/harness-opencode/harness.js +38 -5
  115. package/dist/harness-opencode/host/policy.js +11 -3
  116. package/dist/harness-opencode/transcript.d.ts +25 -0
  117. package/dist/harness-opencode/transcript.js +81 -0
  118. package/dist/harness-table.d.ts +75 -0
  119. package/dist/harness-table.js +145 -0
  120. package/dist/harness.d.ts +7 -28
  121. package/dist/harness.js +15 -41
  122. package/dist/heard.d.ts +12 -0
  123. package/dist/heard.js +45 -0
  124. package/dist/helper-env.d.ts +4 -0
  125. package/dist/helper-env.js +14 -0
  126. package/dist/home-path.d.ts +0 -4
  127. package/dist/home-path.js +3 -17
  128. package/dist/host-check.d.ts +4 -3
  129. package/dist/host-check.js +5 -4
  130. package/dist/host-tools.d.ts +51 -8
  131. package/dist/host-tools.js +108 -117
  132. package/dist/host.d.ts +12 -6
  133. package/dist/host.js +30 -24
  134. package/dist/hosted-search.d.ts +3 -0
  135. package/dist/hosted-search.js +5 -3
  136. package/dist/import-proxy.d.ts +42 -0
  137. package/dist/import-proxy.js +105 -0
  138. package/dist/import-summary.js +4 -8
  139. package/dist/import-worker.d.ts +2 -3
  140. package/dist/import-worker.js +18 -16
  141. package/dist/import.d.ts +37 -17
  142. package/dist/import.js +208 -222
  143. package/dist/key-meta.d.ts +26 -0
  144. package/dist/key-meta.js +30 -0
  145. package/dist/key-refusal.d.ts +4 -1
  146. package/dist/key-refusal.js +20 -7
  147. package/dist/learn/check.d.ts +3 -1
  148. package/dist/learn/check.js +2 -2
  149. package/dist/learn/commit.d.ts +86 -0
  150. package/dist/learn/commit.js +182 -0
  151. package/dist/learn/folder.d.ts +296 -0
  152. package/dist/learn/folder.js +796 -0
  153. package/dist/learn/grade.d.ts +22 -9
  154. package/dist/learn/grade.js +95 -49
  155. package/dist/learn/index.d.ts +2 -2
  156. package/dist/learn/index.js +2 -2
  157. package/dist/learn/learning.sh +366 -0
  158. package/dist/learn/reflect.d.ts +12 -5
  159. package/dist/learn/reflect.js +70 -41
  160. package/dist/learn/secrets.d.ts +15 -7
  161. package/dist/learn/secrets.js +66 -16
  162. package/dist/learn/seed-check.d.ts +74 -0
  163. package/dist/learn/seed-check.js +103 -0
  164. package/dist/learn/skills.d.ts +5 -1
  165. package/dist/learn/skills.js +5 -4
  166. package/dist/learned-workflow.d.ts +12 -2
  167. package/dist/learned-workflow.js +9 -5
  168. package/dist/learning-routes.d.ts +88 -41
  169. package/dist/learning-routes.js +340 -539
  170. package/dist/learning-run.d.ts +60 -53
  171. package/dist/learning-run.js +181 -224
  172. package/dist/learning-words.d.ts +3 -5
  173. package/dist/learning-words.js +3 -5
  174. package/dist/learning.d.ts +177 -112
  175. package/dist/learning.js +289 -380
  176. package/dist/live/stream.d.ts +30 -0
  177. package/dist/live/stream.js +175 -0
  178. package/dist/live/translate.d.ts +52 -0
  179. package/dist/live/translate.js +276 -0
  180. package/dist/llm.js +3 -0
  181. package/dist/llms.txt +1 -0
  182. package/dist/local-models.d.ts +23 -0
  183. package/dist/local-models.js +35 -0
  184. package/dist/mcp-gateway.d.ts +46 -13
  185. package/dist/mcp-gateway.js +145 -45
  186. package/dist/mcp-meta.d.ts +3 -0
  187. package/dist/mcp-meta.js +14 -2
  188. package/dist/mcp-oauth.d.ts +172 -0
  189. package/dist/mcp-oauth.js +403 -0
  190. package/dist/mcp-private-hosts.d.ts +48 -0
  191. package/dist/mcp-private-hosts.js +141 -0
  192. package/dist/mcp-probe.d.ts +101 -0
  193. package/dist/mcp-probe.js +359 -0
  194. package/dist/mcp-secret-writes.d.ts +23 -0
  195. package/dist/mcp-secret-writes.js +60 -0
  196. package/dist/mcp-servers-store.d.ts +251 -0
  197. package/dist/mcp-servers-store.js +447 -0
  198. package/dist/mcp-servers.d.ts +180 -50
  199. package/dist/mcp-servers.js +284 -321
  200. package/dist/mcp-store.d.ts +103 -0
  201. package/dist/mcp-store.js +123 -0
  202. package/dist/mcp.js +22 -21
  203. package/dist/model.d.ts +77 -59
  204. package/dist/model.js +237 -98
  205. package/dist/monid.d.ts +8 -6
  206. package/dist/monid.js +39 -25
  207. package/dist/openapi.d.ts +22 -1
  208. package/dist/openapi.js +919 -108
  209. package/dist/owner.d.ts +46 -10
  210. package/dist/owner.js +123 -43
  211. package/dist/page.d.ts +10 -0
  212. package/dist/page.js +27 -4
  213. package/dist/paid-calls.d.ts +71 -2
  214. package/dist/paid-calls.js +125 -5
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -13
  218. package/dist/place.js +25 -15
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/propose.d.ts +9 -8
  222. package/dist/propose.js +82 -49
  223. package/dist/provider.d.ts +85 -0
  224. package/dist/provider.js +178 -0
  225. package/dist/push-handler.d.ts +52 -0
  226. package/dist/push-handler.js +165 -0
  227. package/dist/refusal-words.d.ts +23 -0
  228. package/dist/refusal-words.js +25 -0
  229. package/dist/request-start.d.ts +6 -1
  230. package/dist/request-start.js +41 -10
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-box.d.ts +22 -3
  234. package/dist/run-box.js +78 -17
  235. package/dist/run-computer.d.ts +24 -0
  236. package/dist/run-computer.js +15 -0
  237. package/dist/run-cut.d.ts +33 -0
  238. package/dist/run-cut.js +42 -0
  239. package/dist/run-db.d.ts +64 -0
  240. package/dist/run-db.js +155 -0
  241. package/dist/run-files.d.ts +31 -0
  242. package/dist/run-files.js +125 -0
  243. package/dist/run-holder.d.ts +52 -0
  244. package/dist/run-holder.js +139 -0
  245. package/dist/run-launch.d.ts +72 -0
  246. package/dist/run-launch.js +108 -0
  247. package/dist/run-learning-served.d.ts +43 -0
  248. package/dist/run-learning-served.js +16 -0
  249. package/dist/run-manifest.d.ts +7 -6
  250. package/dist/run-manifest.js +20 -10
  251. package/dist/run-reads-over-store.d.ts +102 -0
  252. package/dist/run-reads-over-store.js +151 -0
  253. package/dist/run-timeline-served.d.ts +13 -0
  254. package/dist/run-timeline-served.js +69 -0
  255. package/dist/run-view.d.ts +436 -0
  256. package/dist/run-view.js +620 -0
  257. package/dist/runnable.d.ts +30 -5
  258. package/dist/runnable.js +149 -72
  259. package/dist/runner/adapter-loop.d.ts +237 -0
  260. package/dist/runner/adapter-loop.js +1625 -0
  261. package/dist/runner/adapter-run-spec.d.ts +216 -0
  262. package/dist/runner/adapter-run-spec.js +537 -0
  263. package/dist/runner/adapters/index.d.ts +37 -0
  264. package/dist/runner/adapters/index.js +66 -0
  265. package/dist/runner/adapters/pi.d.ts +99 -0
  266. package/dist/runner/adapters/pi.js +260 -0
  267. package/dist/runner/beside.d.ts +12 -0
  268. package/dist/runner/beside.js +30 -0
  269. package/dist/runner/claim-secrets.d.ts +30 -0
  270. package/dist/runner/claim-secrets.js +90 -0
  271. package/dist/runner/cli-run-spec.d.ts +17 -0
  272. package/dist/runner/cli-run-spec.js +371 -0
  273. package/dist/runner/commands.d.ts +23 -0
  274. package/dist/runner/commands.js +67 -0
  275. package/dist/runner/computer-journal.d.ts +38 -0
  276. package/dist/runner/computer-journal.js +120 -0
  277. package/dist/runner/conformance/child.d.ts +1 -0
  278. package/dist/runner/conformance/child.js +78 -0
  279. package/dist/runner/conformance/harness.d.ts +89 -0
  280. package/dist/runner/conformance/harness.js +928 -0
  281. package/dist/runner/conformance/subject.d.ts +83 -0
  282. package/dist/runner/conformance/subject.js +1 -0
  283. package/dist/runner/dispatch.d.ts +30 -0
  284. package/dist/runner/dispatch.js +99 -0
  285. package/dist/runner/end-of-run.d.ts +32 -0
  286. package/dist/runner/end-of-run.js +56 -0
  287. package/dist/runner/github-app.d.ts +16 -0
  288. package/dist/runner/github-app.js +37 -0
  289. package/dist/runner/hand-back.d.ts +43 -0
  290. package/dist/runner/hand-back.js +69 -0
  291. package/dist/runner/harness-loops.d.ts +10 -0
  292. package/dist/runner/harness-loops.js +70 -0
  293. package/dist/runner/journal-kinds.d.ts +211 -0
  294. package/dist/runner/journal-kinds.js +116 -0
  295. package/dist/runner/journal-reader.d.ts +44 -0
  296. package/dist/runner/journal-reader.js +127 -0
  297. package/dist/runner/learning-ask.d.ts +37 -0
  298. package/dist/runner/learning-ask.js +99 -0
  299. package/dist/runner/learning-dispatch.d.ts +38 -0
  300. package/dist/runner/learning-dispatch.js +75 -0
  301. package/dist/runner/learning-end.d.ts +31 -0
  302. package/dist/runner/learning-end.js +136 -0
  303. package/dist/runner/learning-factory.d.ts +13 -0
  304. package/dist/runner/learning-factory.js +37 -0
  305. package/dist/runner/learning-loop.d.ts +150 -0
  306. package/dist/runner/learning-loop.js +246 -0
  307. package/dist/runner/learning-seed.d.ts +30 -0
  308. package/dist/runner/learning-seed.js +41 -0
  309. package/dist/runner/live-ticker.d.ts +18 -0
  310. package/dist/runner/live-ticker.js +88 -0
  311. package/dist/runner/loop-contract.d.ts +153 -0
  312. package/dist/runner/loop-contract.js +26 -0
  313. package/dist/runner/loop.d.ts +79 -0
  314. package/dist/runner/loop.js +185 -0
  315. package/dist/runner/main.d.ts +89 -0
  316. package/dist/runner/main.js +282 -0
  317. package/dist/runner/mcp-claim.d.ts +67 -0
  318. package/dist/runner/mcp-claim.js +403 -0
  319. package/dist/runner/mcp-github.d.ts +53 -0
  320. package/dist/runner/mcp-github.js +91 -0
  321. package/dist/runner/mcp-run.d.ts +116 -0
  322. package/dist/runner/mcp-run.js +152 -0
  323. package/dist/runner/metrics.d.ts +18 -0
  324. package/dist/runner/metrics.js +24 -0
  325. package/dist/runner/model-route.d.ts +111 -0
  326. package/dist/runner/model-route.js +183 -0
  327. package/dist/runner/pi-stop.d.ts +6 -0
  328. package/dist/runner/pi-stop.js +8 -0
  329. package/dist/runner/redact.d.ts +26 -0
  330. package/dist/runner/redact.js +51 -0
  331. package/dist/runner/reflect-hook.d.ts +81 -0
  332. package/dist/runner/reflect-hook.js +111 -0
  333. package/dist/runner/runner.d.ts +114 -0
  334. package/dist/runner/runner.js +672 -0
  335. package/dist/runner/sessions.d.ts +9 -0
  336. package/dist/runner/sessions.js +145 -0
  337. package/dist/runner/side-effects.d.ts +19 -0
  338. package/dist/runner/side-effects.js +20 -0
  339. package/dist/runner/spec-holds.d.ts +41 -0
  340. package/dist/runner/spec-holds.js +58 -0
  341. package/dist/runner/store-port.d.ts +9 -0
  342. package/dist/runner/store-port.js +7 -0
  343. package/dist/runner/store-secrets.d.ts +11 -0
  344. package/dist/runner/store-secrets.js +105 -0
  345. package/dist/runner/workflow-adapters.d.ts +1 -0
  346. package/dist/runner/workflow-adapters.js +4 -0
  347. package/dist/runner/workflow-host.d.ts +88 -0
  348. package/dist/runner/workflow-host.js +66 -0
  349. package/dist/runner/workflow-loop.d.ts +126 -0
  350. package/dist/runner/workflow-loop.js +372 -0
  351. package/dist/runner/workflow-spec.d.ts +157 -0
  352. package/dist/runner/workflow-spec.js +801 -0
  353. package/dist/runs-over-store.d.ts +203 -0
  354. package/dist/runs-over-store.js +396 -0
  355. package/dist/runs.d.ts +351 -220
  356. package/dist/runs.js +1570 -540
  357. package/dist/seal-key.d.ts +30 -0
  358. package/dist/seal-key.js +141 -0
  359. package/dist/sealed-settings-store.d.ts +71 -0
  360. package/dist/sealed-settings-store.js +205 -0
  361. package/dist/sealed-settings.d.ts +60 -0
  362. package/dist/sealed-settings.js +178 -0
  363. package/dist/secret-writes.d.ts +147 -0
  364. package/dist/secret-writes.js +144 -0
  365. package/dist/secrets.d.ts +7 -0
  366. package/dist/secrets.js +17 -2
  367. package/dist/served-only.d.ts +5 -0
  368. package/dist/served-only.js +12 -0
  369. package/dist/server-approvers.d.ts +8 -0
  370. package/dist/server-approvers.js +12 -0
  371. package/dist/server-fs.d.ts +40 -0
  372. package/dist/server-fs.js +138 -0
  373. package/dist/server-keys.d.ts +18 -0
  374. package/dist/server-keys.js +31 -0
  375. package/dist/server-lock.js +1 -1
  376. package/dist/server-secrets-store.d.ts +18 -0
  377. package/dist/server-secrets-store.js +54 -0
  378. package/dist/server-secrets.d.ts +23 -0
  379. package/dist/server-secrets.js +73 -0
  380. package/dist/server.d.ts +142 -73
  381. package/dist/server.js +1683 -596
  382. package/dist/sessions.d.ts +3 -1
  383. package/dist/sessions.js +8 -4
  384. package/dist/sign-ins-secrets.d.ts +35 -0
  385. package/dist/sign-ins-secrets.js +109 -0
  386. package/dist/sign-ins-store.d.ts +200 -0
  387. package/dist/sign-ins-store.js +373 -0
  388. package/dist/sign-ins.d.ts +43 -7
  389. package/dist/sign-ins.js +94 -18
  390. package/dist/skills.d.ts +6 -5
  391. package/dist/skills.js +18 -14
  392. package/dist/standard-webhooks.d.ts +30 -0
  393. package/dist/standard-webhooks.js +72 -0
  394. package/dist/stats.d.ts +5 -7
  395. package/dist/stats.js +8 -24
  396. package/dist/stop-signals.d.ts +22 -0
  397. package/dist/stop-signals.js +38 -0
  398. package/dist/store/agent-body.d.ts +103 -0
  399. package/dist/store/agent-body.js +126 -0
  400. package/dist/store/dialect.d.ts +59 -0
  401. package/dist/store/dialect.js +32 -0
  402. package/dist/store/fence.d.ts +22 -0
  403. package/dist/store/fence.js +15 -0
  404. package/dist/store/index.d.ts +17 -0
  405. package/dist/store/index.js +17 -0
  406. package/dist/store/journal/storage.d.ts +137 -0
  407. package/dist/store/journal/storage.js +1021 -0
  408. package/dist/store/open.d.ts +34 -0
  409. package/dist/store/open.js +30 -0
  410. package/dist/store/postgres/connection.d.ts +74 -0
  411. package/dist/store/postgres/connection.js +532 -0
  412. package/dist/store/postgres/dialect.d.ts +9 -0
  413. package/dist/store/postgres/dialect.js +39 -0
  414. package/dist/store/postgres/migrate.d.ts +21 -0
  415. package/dist/store/postgres/migrate.js +106 -0
  416. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  417. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  418. package/dist/store/postgres/store.d.ts +37 -0
  419. package/dist/store/postgres/store.js +48 -0
  420. package/dist/store/prompts.d.ts +11 -0
  421. package/dist/store/prompts.js +112 -0
  422. package/dist/store/schema.d.ts +26 -0
  423. package/dist/store/schema.js +522 -0
  424. package/dist/store/seal.d.ts +48 -0
  425. package/dist/store/seal.js +69 -0
  426. package/dist/store/sqlite/connection.d.ts +105 -0
  427. package/dist/store/sqlite/connection.js +309 -0
  428. package/dist/store/sqlite/memory.d.ts +2 -0
  429. package/dist/store/sqlite/memory.js +4 -0
  430. package/dist/store/sqlite/run-launch.d.ts +8 -0
  431. package/dist/store/sqlite/run-launch.js +20 -0
  432. package/dist/store/sqlite/run-patch.d.ts +54 -0
  433. package/dist/store/sqlite/run-patch.js +114 -0
  434. package/dist/store/sqlite/store.d.ts +33 -0
  435. package/dist/store/sqlite/store.js +1337 -0
  436. package/dist/store/sqlite/worker.d.ts +78 -0
  437. package/dist/store/sqlite/worker.js +242 -0
  438. package/dist/store/store.d.ts +1253 -0
  439. package/dist/store/store.js +190 -0
  440. package/dist/store-reads/analytics.d.ts +55 -0
  441. package/dist/store-reads/analytics.js +135 -0
  442. package/dist/store-reads/cap.d.ts +17 -0
  443. package/dist/store-reads/cap.js +17 -0
  444. package/dist/store-reads/decisions.d.ts +5 -0
  445. package/dist/store-reads/decisions.js +31 -0
  446. package/dist/store-reads/import-summary.d.ts +6 -0
  447. package/dist/store-reads/import-summary.js +14 -0
  448. package/dist/store-reads/journal.d.ts +30 -0
  449. package/dist/store-reads/journal.js +120 -0
  450. package/dist/store-reads/learning.d.ts +93 -0
  451. package/dist/store-reads/learning.js +202 -0
  452. package/dist/store-reads/runs.d.ts +42 -0
  453. package/dist/store-reads/runs.js +84 -0
  454. package/dist/store-reads/stats.d.ts +30 -0
  455. package/dist/store-reads/stats.js +59 -0
  456. package/dist/store-reads/workflow.d.ts +7 -0
  457. package/dist/store-reads/workflow.js +14 -0
  458. package/dist/store-view.d.ts +37 -0
  459. package/dist/store-view.js +305 -0
  460. package/dist/template-eval.d.ts +239 -0
  461. package/dist/template-eval.js +1020 -0
  462. package/dist/template-github-permissions.d.ts +18 -0
  463. package/dist/template-github-permissions.js +32 -0
  464. package/dist/templates.d.ts +199 -0
  465. package/dist/templates.js +637 -0
  466. package/dist/tool-blurbs.d.ts +4 -0
  467. package/dist/tool-blurbs.js +27 -0
  468. package/dist/tool-gate.d.ts +166 -35
  469. package/dist/tool-gate.js +411 -91
  470. package/dist/tool-keys-store.d.ts +110 -0
  471. package/dist/tool-keys-store.js +291 -0
  472. package/dist/tool-keys.d.ts +25 -12
  473. package/dist/tool-keys.js +20 -2
  474. package/dist/tool-plane.d.ts +113 -27
  475. package/dist/tool-plane.js +229 -76
  476. package/dist/tool-settings-store.d.ts +30 -0
  477. package/dist/tool-settings-store.js +53 -0
  478. package/dist/tools.d.ts +95 -24
  479. package/dist/tools.js +337 -61
  480. package/dist/trigger-accept.d.ts +36 -0
  481. package/dist/trigger-accept.js +152 -0
  482. package/dist/trigger-adapter.d.ts +143 -0
  483. package/dist/trigger-adapter.js +31 -0
  484. package/dist/trigger-adapters.d.ts +2 -0
  485. package/dist/trigger-adapters.js +4 -0
  486. package/dist/trigger-github.d.ts +2 -0
  487. package/dist/trigger-github.js +85 -0
  488. package/dist/trigger-schedule.d.ts +6 -0
  489. package/dist/trigger-schedule.js +115 -0
  490. package/dist/trigger-secrets-shown.d.ts +66 -0
  491. package/dist/trigger-secrets-shown.js +77 -0
  492. package/dist/trigger-signatures.d.ts +58 -0
  493. package/dist/trigger-signatures.js +79 -0
  494. package/dist/trigger-targets.d.ts +46 -0
  495. package/dist/trigger-targets.js +95 -0
  496. package/dist/trigger-webhook.d.ts +2 -0
  497. package/dist/trigger-webhook.js +92 -0
  498. package/dist/triggers.d.ts +282 -237
  499. package/dist/triggers.js +720 -608
  500. package/dist/turn-end.d.ts +3 -0
  501. package/dist/turn-end.js +3 -0
  502. package/dist/uploads.d.ts +10 -8
  503. package/dist/uploads.js +45 -45
  504. package/dist/usage.d.ts +33 -3
  505. package/dist/usage.js +38 -4
  506. package/dist/validate.d.ts +6 -0
  507. package/dist/validate.js +42 -12
  508. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  509. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  510. package/dist/web-fetch.d.ts +17 -9
  511. package/dist/web-fetch.js +53 -18
  512. package/dist/web-search.d.ts +1 -1
  513. package/dist/web-search.js +1 -1
  514. package/dist/webhooks.d.ts +33 -23
  515. package/dist/webhooks.js +69 -56
  516. package/dist/wires.d.ts +11 -0
  517. package/dist/wires.js +7 -0
  518. package/dist/workspace/archil-claim.d.ts +57 -0
  519. package/dist/workspace/archil-claim.js +154 -0
  520. package/dist/workspace/archil-disk.d.ts +104 -0
  521. package/dist/workspace/archil-disk.js +254 -0
  522. package/dist/workspace/archil-exec.d.ts +59 -0
  523. package/dist/workspace/archil-exec.js +218 -0
  524. package/dist/workspace/archil-key.d.ts +17 -0
  525. package/dist/workspace/archil-key.js +30 -0
  526. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  527. package/dist/workspace/archil-mount-credential.js +165 -0
  528. package/dist/workspace/archil.d.ts +59 -0
  529. package/dist/workspace/archil.js +676 -0
  530. package/dist/workspace/attach.d.ts +48 -0
  531. package/dist/workspace/attach.js +439 -0
  532. package/dist/workspace/computer-deps.d.ts +58 -0
  533. package/dist/workspace/computer-deps.js +113 -0
  534. package/dist/workspace/computer-for-claim.d.ts +115 -0
  535. package/dist/workspace/computer-for-claim.js +198 -0
  536. package/dist/workspace/computer-hold.d.ts +145 -0
  537. package/dist/workspace/computer-hold.js +258 -0
  538. package/dist/workspace/computer-ledger.d.ts +22 -0
  539. package/dist/workspace/computer-ledger.js +19 -0
  540. package/dist/workspace/computer-ports.d.ts +13 -0
  541. package/dist/workspace/computer-ports.js +108 -0
  542. package/dist/workspace/computer-providers.d.ts +12 -0
  543. package/dist/workspace/computer-providers.js +17 -0
  544. package/dist/workspace/computer-serves.d.ts +12 -0
  545. package/dist/workspace/computer-serves.js +15 -0
  546. package/dist/workspace/executors.d.ts +38 -0
  547. package/dist/workspace/executors.js +150 -0
  548. package/dist/workspace/glob.d.ts +2 -0
  549. package/dist/workspace/glob.js +25 -0
  550. package/dist/workspace/grep-worker.d.ts +11 -0
  551. package/dist/workspace/grep-worker.js +91 -0
  552. package/dist/workspace/hands.d.ts +25 -0
  553. package/dist/workspace/hands.js +121 -0
  554. package/dist/workspace/index.d.ts +23 -0
  555. package/dist/workspace/index.js +25 -0
  556. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  557. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  558. package/dist/workspace/kind-skills.d.ts +11 -0
  559. package/dist/workspace/kind-skills.js +16 -0
  560. package/dist/workspace/learning-workspace.d.ts +24 -0
  561. package/dist/workspace/learning-workspace.js +107 -0
  562. package/dist/workspace/local.d.ts +6 -0
  563. package/dist/workspace/local.js +632 -0
  564. package/dist/workspace/paths.d.ts +48 -0
  565. package/dist/workspace/paths.js +134 -0
  566. package/dist/workspace/pi-env.d.ts +39 -0
  567. package/dist/workspace/pi-env.js +397 -0
  568. package/dist/workspace/place.d.ts +7 -0
  569. package/dist/workspace/place.js +3 -0
  570. package/dist/workspace/resolve-computer.d.ts +106 -0
  571. package/dist/workspace/resolve-computer.js +188 -0
  572. package/dist/workspace/revision-skills.d.ts +15 -0
  573. package/dist/workspace/revision-skills.js +42 -0
  574. package/dist/workspace/run-tools.d.ts +173 -0
  575. package/dist/workspace/run-tools.js +172 -0
  576. package/dist/workspace/run-workspace.d.ts +25 -0
  577. package/dist/workspace/run-workspace.js +56 -0
  578. package/dist/workspace/server-run-workspace.d.ts +24 -0
  579. package/dist/workspace/server-run-workspace.js +84 -0
  580. package/dist/workspace/workspace.d.ts +169 -0
  581. package/dist/workspace/workspace.js +54 -0
  582. package/dist/workspace-paths.d.ts +1 -10
  583. package/dist/workspace-paths.js +3 -37
  584. package/dist/workspace.d.ts +3 -17
  585. package/dist/workspace.js +6 -74
  586. package/harnesses/claude-agent/package-lock.json +1533 -0
  587. package/harnesses/claude-agent/package.json +7 -0
  588. package/harnesses/codex/package-lock.json +135 -0
  589. package/harnesses/codex/package.json +7 -0
  590. package/launcher/agentrun-serve +13 -3
  591. package/package.json +36 -21
  592. package/skills/agentrun-serve/SKILL.md +2 -0
  593. package/templates/README.md +211 -0
  594. package/templates/code-review/agent.md +50 -0
  595. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  596. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  597. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  598. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  599. package/templates/code-review/evals/injection/case.yaml +3 -0
  600. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  601. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  602. package/templates/code-review/evals/injection/prompt.md +23 -0
  603. package/templates/code-review/evals/null-name/case.yaml +3 -0
  604. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  605. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  606. package/templates/code-review/evals/null-name/prompt.md +17 -0
  607. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  608. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  609. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  610. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  611. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  612. package/templates/code-review/evals/re-review/case.yaml +3 -0
  613. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  614. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  615. package/templates/code-review/evals/re-review/prompt.md +23 -0
  616. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  617. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  618. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  619. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  620. package/templates/code-review/findings.schema.json +125 -0
  621. package/templates/code-review/rules/REVIEW.md +41 -0
  622. package/templates/code-review/skills/review/SKILL.md +162 -0
  623. package/templates/inbound-lead/agent.md +76 -0
  624. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  626. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  627. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  629. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  630. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  631. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  632. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  633. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  634. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  635. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  636. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  637. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  638. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  639. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  640. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  641. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  644. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  645. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  646. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  647. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  648. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  649. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  650. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  652. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  654. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  656. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  657. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  658. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  659. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  660. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  661. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  662. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  663. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  664. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  665. package/templates/inbound-lead/lead.schema.json +587 -0
  666. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  667. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  668. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  669. package/templates/kyb/agent.md +44 -0
  670. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  671. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  672. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  673. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  674. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  675. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  676. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  677. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  678. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  679. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  680. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  681. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  682. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  683. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  684. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  685. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  686. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  687. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  688. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  689. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  690. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  691. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  692. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  693. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  694. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  695. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  696. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  697. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  698. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  699. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  700. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  701. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  702. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  703. package/templates/kyb/kyb.schema.json +274 -0
  704. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  705. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  706. package/templates/kyb/rules/SANCTIONS.md +140 -0
  707. package/templates/kyb/rules/SOURCES.md +92 -0
  708. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  709. package/templates/market-monitor/agent.md +58 -0
  710. package/templates/market-monitor/digest.schema.json +194 -0
  711. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  712. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  713. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  714. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  715. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  716. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  717. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  719. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  720. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  721. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  722. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  723. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  724. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  725. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  726. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  727. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  728. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  729. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  730. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  731. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  733. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  734. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  735. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  736. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  737. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  739. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  741. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  742. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  743. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  744. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  745. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  746. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  747. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  748. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  749. package/templates/market-monitor/rules/MONITOR.md +33 -0
  750. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  751. package/templates/release-notes/agent.md +47 -0
  752. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  753. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  754. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  755. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  756. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  757. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  758. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  759. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  760. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  761. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  762. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  763. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  764. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  765. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  766. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  767. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  768. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  769. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  770. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  771. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  772. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  773. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  774. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  775. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  776. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  777. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  778. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  779. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  780. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  781. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  782. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  783. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  784. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  785. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  786. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  787. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  788. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  789. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  790. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  791. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  792. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  793. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  794. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  795. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  796. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  797. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  798. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  799. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  800. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  801. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  802. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  803. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  804. package/templates/release-notes/notes.schema.json +145 -0
  805. package/templates/release-notes/rules/STYLE.md +47 -0
  806. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  807. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  808. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  809. package/dist/trigger-secrets.d.ts +0 -32
  810. package/dist/trigger-secrets.js +0 -143
package/dist/server.js CHANGED
@@ -1,78 +1,144 @@
1
1
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
2
2
  // token.
3
3
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
- import { chmod, lstat, mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
4
+ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
- import { dirname, join, resolve } from "node:path";
7
- import { pipeline } from "node:stream/promises";
6
+ import proxyaddr from "proxy-addr";
7
+ import { dirname, join, relative, resolve, sep } from "node:path";
8
8
  import { pathToFileURL } from "node:url";
9
9
  import { Worker } from "node:worker_threads";
10
10
  import { once } from "node:events";
11
- import { existsSync, readFileSync } from "node:fs";
11
+ import { existsSync } from "node:fs";
12
12
  import { rm } from "node:fs/promises";
13
13
  import { homedir } from "node:os";
14
- import { agentView, Agents, etagOf, homeBusy, revisionView, storeBusy } from "./agents.js";
14
+ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
15
15
  import { WORKFLOW_ADAPTERS } from "./app.js";
16
- import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV } from "./decisions.js";
17
- import { FAUX_WEB_ENV } from "./fetch-page.js";
16
+ import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
17
+ import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
18
18
  import { FAUX_MONID_ENV } from "./monid.js";
19
19
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
20
20
  import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolOf, toolsView } from "./tools.js";
21
21
  import { ApiError, invalid, unsupported } from "./errors.js";
22
- import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, SETUP_LOST, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
23
- import { checkedPath, decodedPath, homePath, hostOwnedOf, hostOwnedRefusal, ownedByIdentity } from "./home-path.js";
24
- import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, withoutFaux } from "./model.js";
25
- import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
22
+ import { deref, explain } from "./explain.js";
23
+ import { HOME_HOST_OWNED } from "./files.js";
24
+ import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
25
+ import { homePath, hostOwnedOf } from "./home-path.js";
26
+ import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
27
+ import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
28
+ import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
29
+ import { HarnessInstall, harnessesOf, installDirOf, NPM_STOP_GRACE_MS, npmInstall, removeFlatInstall } from "./harness-install.js";
26
30
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
27
31
  import { IMPORT_ASKED } from "./import.js";
28
- import { gradeModelOf, learningBudgetOf, learningOf } from "./learning.js";
29
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
32
+ import { answerStoreCall } from "./import-proxy.js";
33
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
34
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, writeNote } from "./learning-routes.js";
30
35
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
31
36
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
32
- import { boxesLine, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
37
+ import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
33
38
  import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
34
39
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
35
- import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
36
- import { HOST_FIX, hostName, loopbackNames } from "./host-check.js";
40
+ import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
41
+ import { hostFix, hostName, loopbackNames } from "./host-check.js";
42
+ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
43
+ import { browserHandBack, handBackTarget } from "./browser-commands.js";
44
+ import { computerView } from "./computer-view.js";
37
45
  import { durationMs, logLine } from "./print.js";
38
- import { knownToolCostOf, Runs, STATUSES, statusOf, toolCostOf, WAITS_ON_A_PERSON } from "./runs.js";
46
+ import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
47
+ import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
48
+ import { HELD_WAITS } from "./runner/journal-kinds.js";
49
+ import { servedTimelineRows } from "./run-timeline-served.js";
50
+ import { servedRunLearning } from "./run-learning-served.js";
51
+ import { runCutValues } from "./run-cut.js";
52
+ import { readLaunchBody } from "./run-launch.js";
53
+ import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
54
+ import { triggerTargets } from "./trigger-targets.js";
55
+ import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
56
+ import { runEntries } from "./store-reads/journal.js";
57
+ import { metersOverStore } from "./store-reads/cap.js";
58
+ import { watchRun } from "./live/stream.js";
59
+ import { stats as statsOverStore } from "./store-reads/stats.js";
60
+ import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
61
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
62
+ import { openStore, StoreBusy } from "./store/index.js";
63
+ import { FINAL_STATES } from "./store/store.js";
64
+ import { runModelRef } from "./model.js";
65
+ // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
66
+ const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
67
+ /** A busy store, and the home_busy answer it maps to (byte-identical to the old agents.ts words), for a read or write that
68
+ * meets the one store under load. */
69
+ const storeBusy = (error) => error instanceof StoreBusy;
70
+ const homeBusy = () => new ApiError("home_busy", "the agent store is busy with another write; try again", { retry_after_ms: 500 });
39
71
  import { runLines } from "./usage-lines.js";
40
- import { BOX_QUARANTINE, Quarantine } from "./box/sweep.js";
41
- import { boxesByDefault, boxesLog, boxRegistry, daytonaApi, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
42
- import { FAUX_EGRESS_ENV, sweepEgressDirs } from "./box-egress.js";
72
+ import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
73
+ import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
43
74
  import { startEgressContainer } from "./box-egress-vm.js";
75
+ import { dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV } from "./box-paths.js";
44
76
  import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
45
- import { startBoxRelay } from "./box-relay.js";
46
77
  import { vmRelay } from "./box-relay-vm.js";
47
78
  import { memoryMbOf } from "./run-box.js";
48
79
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
49
- import { meterFiguresIn } from "./cap.js";
50
- import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES } from "./runnable.js";
80
+ import { CAP_MODES } from "./cap.js";
81
+ import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
51
82
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
52
- import { redactedOutput } from "./key-refusal.js";
53
- import { analyticsFilter, analyticsView, pendingOf, statsView } from "./stats.js";
83
+ import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
84
+ import { bootSealKey } from "./seal-key.js";
85
+ import { analyticsFilter, analyticsView, statsView } from "./stats.js";
86
+ import { agentLearningOverStore, learningCountsOverStore } from "./store-reads/learning.js";
54
87
  import { outcomes } from "./usage.js";
55
- import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS, ToolKeys } from "./tool-keys.js";
56
- import { SIGN_INS_DIR, SignIns, vendorsOver } from "./sign-ins.js";
57
- import { MCP_AUTH_TYPES, McpServers } from "./mcp-servers.js";
88
+ import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS } from "./tool-keys.js";
89
+ import { toolKeysOverStore } from "./tool-keys-store.js";
90
+ import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
91
+ // E1b builds the store-backed sign-ins bridge (the old SignIns interface — peek/forgotten/view/forget — over store.signIns,
92
+ // byte-identical v2 shapes; "held"/held_by from a live run whose sign_in_handed holds the pointer, verified_at from the
93
+ // last holder's lease end). TODO(E1b): wire its sha; named import until then.
94
+ import { signInsOverStore } from "./sign-ins-store.js";
95
+ import { MCP_AUTH_TYPES } from "./mcp-probe.js";
96
+ import { mcpServersOverStore } from "./mcp-servers-store.js";
97
+ import { privateHostsRoute } from "./mcp-private-hosts.js";
58
98
  import { metaToolOf } from "./mcp-meta.js";
99
+ import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
59
100
  import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
60
- import { HOOK_TOLERANCE_S, hookHeadersRefusal, hookRefusal, TriggerSecrets } from "./trigger-secrets.js";
61
- import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, OVERLAP, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
62
- import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
63
- import { agentTools, browserKeyRow, settingsIssues, ToolSettings, withDefaults } from "./tool-plane.js";
101
+ import { appPermissionWarnings } from "./template-github-permissions.js";
102
+ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
103
+ import { openServerSecretsOverStore } from "./server-secrets-store.js";
104
+ import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
105
+ import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
106
+ import { GITHUB_API } from "./github.js";
107
+ import { HookCut, receivePush } from "./push-handler.js";
108
+ import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
109
+ import { webhook } from "./trigger-webhook.js";
110
+ import { SCHEME_NAMES } from "./trigger-signatures.js";
111
+ import { permissionFrom, pinWords } from "./tool-gate.js";
112
+ 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, GITHUB_TRIGGER_UNCONNECTED, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
114
+ 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";
116
+ import { toolSettingsOverStore } from "./tool-settings-store.js";
117
+ import { writeApprovers } from "./server-approvers.js";
64
118
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
65
- import { INLINE_TYPES, openWorkFile, removeWorkFile, typeOf, WALK_DEPTH, walkWork, WorkRefused, writesHeld, writeWorkFile } from "./workspace.js";
66
- import { markRunning, markStopping, takeServerLockAfterStop } from "./server-lock.js";
119
+ 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 { 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";
128
+ import { writesHeld } from "./workspace.js";
129
+ import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, isWorkspaceError, localWorkspace, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
+ import { keyReader } from "./key-meta.js";
131
+ // server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
67
132
  export const CONTRACT = "agentrun.v2/0";
68
133
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
69
134
  const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
70
135
  export const DEFAULT_PORT = 7340;
71
136
  const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
72
137
  const IDEMPOTENCY_FILE = ".idempotency.json";
138
+ /** A run's live viewer, under the run's path (browser-live.ts): its run id, the family's address (`computer`, one for every
139
+ * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
140
+ const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
73
141
  const MAX_BODY = 1 << 20;
74
- /** The largest body a webhook trigger takes (POST /v2/hooks/{id}). */
75
- const HOOK_MAX_BODY = 256 << 10;
76
142
  const MAX_MESSAGE = 20_000;
77
143
  const MAX_WAIT_MS = 25_000;
78
144
  const PAGE_ROWS = 500;
@@ -94,13 +160,15 @@ const noticeOf = (options) => (line) => {
94
160
  };
95
161
  /** Why a home's PUT or DELETE is 501 where `capabilities.home.writes` is false (workspace.ts writesHeld). */
96
162
  const HOME_WRITES_OFF = "This server can't write a home's files safely here: a write needs /proc/self/fd, as on Linux, which this platform lacks. Reads and the list still work.";
97
- const FILE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox; form-action 'none'";
163
+ /** Why a home's write or removal is refused when a link is on the way: the Workspace follows none. */
164
+ const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
98
165
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
99
166
  * harness's, which scripts the harnesses with or without it. */
100
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], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV]];
101
- /** The test switches a run's process gets, each module path resolved: empty outside tests. */
102
- function fauxEnvOf(options) {
103
- const env = options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {};
168
+ /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
169
+ * takes the same (test/support.mjs startInProcessRunner). */
170
+ export function fauxEnvOf(options) {
171
+ const env = options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {};
104
172
  if (!options.faux)
105
173
  return env;
106
174
  env[FAUX_ENV] = resolve(options.faux);
@@ -118,20 +186,20 @@ async function tokenIn(file) {
118
186
  return { token: known, made: false };
119
187
  }
120
188
  const token = `ar_local_${randomBytes(24).toString("base64url")}`;
121
- await writeFile(file, `${token}\n`, { mode: 0o600, flag: "w" });
122
- await chmod(file, 0o600);
189
+ // Whole or not there: a reader (the token file a server's record names, a script) never finds it made but empty.
190
+ await writeDurable(file, `${token}\n`, 0o600, undefined, true);
123
191
  return { token, made: true };
124
192
  }
125
193
  const digest = (text) => createHash("sha256").update(text).digest();
126
194
  /** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
127
195
  const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
128
- /** What an unknown trigger's request is checked against, so it is refused in a known trigger's time. */
129
- const NO_TRIGGER_SECRET = `whsec_${randomBytes(32).toString("base64")}`;
130
196
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
131
197
  const SESSION_S = SESSION_MS / 1000;
132
198
  export const ROUTES = [
133
199
  { method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
134
200
  { method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
201
+ // Answered here only with accounts off: with accounts on, the owner's routes answer it before any route (ownerRoute).
202
+ { method: "GET", pattern: /^\/auth\/session$/, name: "getAuthSession" },
135
203
  { method: "GET", pattern: /^\/health$/, name: "getHealth" },
136
204
  { method: "POST", pattern: /^\/agents$/, name: "createAgent" },
137
205
  { method: "GET", pattern: /^\/agents$/, name: "listAgents" },
@@ -151,6 +219,7 @@ export const ROUTES = [
151
219
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "writeHomeFile" },
152
220
  { method: "DELETE", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "deleteHomeFile" },
153
221
  { method: "GET", pattern: /^\/runs$/, name: "listAllRuns" },
222
+ { method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
154
223
  { method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
155
224
  { method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
156
225
  { method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
@@ -166,6 +235,22 @@ export const ROUTES = [
166
235
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
167
236
  { method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
168
237
  { method: "GET", pattern: /^\/runs\/([^/]+)\/files$/, name: "listRunFiles" },
238
+ { method: "GET", pattern: /^\/runs\/([^/]+)\/browser$/, name: "getRunBrowser" },
239
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/browser\/hand-back$/, name: "handBackRunBrowser" },
240
+ // The run's live computer view (GET: getRunComputer), and its owner's take-over and hand-back (the named 501 until the
241
+ // store-backed take-over lands). The run routes stay together.
242
+ { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
243
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
244
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
245
+ // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
246
+ // archilRoute): the server switch dispatches them, once the server opens its store.
247
+ { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
248
+ { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
249
+ { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
250
+ { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
251
+ { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
252
+ { method: "DELETE", pattern: /^\/workspace\/archil$/, name: "deleteWorkspaceArchil" },
253
+ { method: "POST", pattern: /^\/workspace\/archil\/test$/, name: "testWorkspaceArchil" },
169
254
  { method: "GET", pattern: /^\/runs\/([^/]+)\/files\/(.+)$/, name: "readRunFile" },
170
255
  { method: "POST", pattern: /^\/files$/, name: "createFile", raw: true },
171
256
  { method: "GET", pattern: /^\/files$/, name: "listFiles" },
@@ -184,6 +269,13 @@ export const ROUTES = [
184
269
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
185
270
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
186
271
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
272
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
273
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/callback$/, name: "mcpOAuthCallback" },
274
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/client\.json$/, name: "mcpOAuthClient" },
275
+ // Over the store-backed registry (mcp-private-hosts.ts privateHostsRoute); the PUT is a secret write as a whole, so the
276
+ // one secret-write check takes it from the owner's session alone.
277
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/private-hosts$/, name: "getMcpPrivateHosts" },
278
+ { method: "PUT", pattern: /^\/settings\/mcp-servers\/oauth\/private-hosts$/, name: "putMcpPrivateHosts" },
187
279
  { method: "GET", pattern: /^\/settings\/tools$/, name: "getToolSettings" },
188
280
  { method: "PUT", pattern: /^\/settings\/tools$/, name: "putToolSettings" },
189
281
  { method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
@@ -200,8 +292,15 @@ export const ROUTES = [
200
292
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/fire$/, name: "fireTrigger" },
201
293
  { method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
202
294
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
295
+ { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
296
+ { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
203
297
  // Answered before the bearer check: the request's signature is its credential.
204
298
  { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
299
+ { method: "GET", pattern: /^\/integrations\/github$/, name: "getGitHubConnection" },
300
+ { method: "DELETE", pattern: /^\/integrations\/github$/, name: "disconnectGitHub" },
301
+ { method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
302
+ { method: "GET", pattern: /^\/integrations\/github\/callback$/, name: "gitHubCallback" },
303
+ { method: "GET", pattern: /^\/integrations\/github\/installed$/, name: "gitHubInstalled" },
205
304
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
206
305
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
207
306
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
@@ -217,6 +316,31 @@ export const ROUTES = [
217
316
  ];
218
317
  /** Where agent `agentId`'s host-owned path is read on this server: its route, when ROUTES has one (the learning API, for
219
318
  * learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
319
+ /** A run's computer as GET /computer reads it with no viewer open: kind browser where its agent has the browser tool, its
320
+ * kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
321
+ * launch would be; off, saying why, where it has none or its browser resolves unavailable here.
322
+ * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
323
+ function computerOf(kept, env, family = "computer") {
324
+ const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
325
+ if (browser === undefined)
326
+ return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
327
+ return isUnavailable(browser) ? { off: whyUnavailable(browser) } : { kind: "browser" };
328
+ }
329
+ /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
330
+ * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
331
+ * a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
332
+ * the browser tool, else none. */
333
+ async function keptBrowserOf(store, runId) {
334
+ const row = await store.runs.launch(runId).catch(() => undefined);
335
+ const plane = row ? readLaunchBody(row.body)?.plane : undefined;
336
+ const kept = plane ? keptVendor(plane).browser : undefined;
337
+ if (kept !== undefined)
338
+ return kept;
339
+ const runRow = await store.runs.get(runId);
340
+ const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
341
+ const granted = (revision?.body?.tools ?? []).includes("browser");
342
+ return granted ? "browserbase" : undefined;
343
+ }
220
344
  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);
221
345
  /** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
222
346
  export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
@@ -248,11 +372,11 @@ export function offersEnvOf(env) {
248
372
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
249
373
  * the offers probed again, never shown. */
250
374
  const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
251
- /** What a revision that names no model needs here (capabilities' `models.needs`): null when one runs, else chooseModel's
252
- * `needs`, a provider's key or another model. Made from `env` alone, so it is remade only when env is. */
253
375
  async function needsOf(env) {
254
376
  const chosen = await chooseModel(env, undefined);
255
- return "why" in chosen ? chosen.needs : null;
377
+ if ("why" in chosen)
378
+ return { needs: chosen.needs, priced: null };
379
+ return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0 };
256
380
  }
257
381
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
258
382
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
@@ -285,8 +409,8 @@ export function forCaller(caps, ownerSession) {
285
409
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
286
410
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
287
411
  * needsOf says it for a revision that names no model (null when it runs). */
288
- function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel, refused = {}) {
289
- const models = { ...modelSource(env), ready: needs === null, needs };
412
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, gradeModel, refused = {}) {
413
+ const models = { ...modelSource(env), ready: needs === null, needs, priced };
290
414
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
291
415
  const memory = hostMemory();
292
416
  // The browser's key is its vendor's row: Kernel's where Kernel is picked or resolved (tool-plane.ts browserKeyRow).
@@ -317,7 +441,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
317
441
  secrets: {
318
442
  names: [...SECRET_NAMES],
319
443
  handoff: "pipe",
320
- condition: "Started by its launcher (the package's agentrun-serve, the image's entrypoint), the server takes each secret named here over a pipe and holds it in memory only, and a run's process gets, over a pipe of its own, a tool key only when its revision names a tool the key unlocks and a model key only when its model needs it: a pi run its model's provider's (per tier for a workflow), or the gateway's behind AGENT_MODEL_BASE_URL; a codex run OPENAI_API_KEY, or the gateway's; a claude-agent run ANTHROPIC_API_KEY. It never gets the server's own (its token, the seal key, the boxes' keys), and the decision keys a run's decision nodes need, and Parallel's where its web_fetch or web_search resolves to Parallel, and no other, go on a descriptor of their own: none of them is in any process's environment or command line. No run's environment holds any variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN segment, or a last PWD after another), on this list or not; one not on it stays in the server's own. The launcher runs before any run's process exists; the image starts it as PID 1. Started another way (node dist/cli.js), the server reads them from its environment, where a process of its user can read them.",
444
+ condition: "Started by its launcher (the package's agentrun-serve, the image's entrypoint), the server takes each secret named here over a pipe and holds it in memory only, and a run's process gets, over a pipe of its own, a tool key only when its revision names a tool the key unlocks and a model key only when its model needs it: a pi run its model's provider's (per tier for a workflow), or the gateway's behind AGENT_MODEL_BASE_URL; a codex run OPENAI_API_KEY, or the gateway's; a claude-agent run ANTHROPIC_API_KEY. It never gets the server's own (its token, the seal key, the store's URL, the boxes' keys), and the decision keys a run's decision nodes need, and Parallel's where its web_fetch or web_search resolves to Parallel, and no other, go on a descriptor of their own: none of them is in any process's environment or command line. No run's environment holds any variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN segment, or a last PWD after another), on this list or not; one not on it stays in the server's own. The launcher runs before any run's process exists; the image starts it as PID 1. Started another way (node dist/cli.js), the server reads them from its environment, where a process of its user can read them.",
321
445
  limit: "In memory is not out of reach: a process of the same user can read another's memory (/proc/<pid>/mem) where the kernel lets it attach. Linux's Yama ptrace_scope of 1 or more refuses that to all but a process's own ancestors; a host at 0 exposes the secrets to a run's own code. A run's process holds its model keys in memory, since it calls the model itself. A harness's CLI (codex, claude-agent) holds a key of its own for its session's model proxy in its environment: not a provider's key, but one a process of the same user could spend through that run's proxy while the session lives. Started as the package's bin on a host, until it execs, the launcher and any subshell it forks show the caller's environment, secrets included, to a process of the same user (/proc keeps a process's environment as it was at its exec). A run's process gets its secrets over a socket, read and closed as it starts; another process can take a socket only through pidfd_getfd, which the same ptrace rule refuses.",
322
446
  },
323
447
  /** What a workflow revision's run gets: each model node runs on the model of its tier (`models.fast`,
@@ -347,6 +471,10 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
347
471
  /** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
348
472
  * gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
349
473
  tool_permissions: true,
474
+ /** The owner watches a run's browser live (GET /runs/{id}/browser, and GET /runs/{id}/computer, browser-live.ts), takes
475
+ * it over from the viewer and hands it back, and answers the agent's ask for them (POST /runs/{id}/browser/hand-back,
476
+ * browser-person.ts). */
477
+ browser_live: { read_only: false, take_over: true, ask: true },
350
478
  /** An agent's browser stays signed in between its runs (sign-ins.ts): with a seal key to keep each pointer under, and a
351
479
  * browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
352
480
  sign_ins: sealKeyOf(env[SEAL_KEY_ENV]) !== undefined && tools.some((tool) => tool.name === "browser" && tool.available),
@@ -354,17 +482,18 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
354
482
  query: false,
355
483
  /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
356
484
  * (tool-keys.ts); with none handed over, nothing is kept, never in the clear. */
357
- tool_keys: { routes: true, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
358
- /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the same seal key
359
- * (mcp-servers.ts); with none, only servers that take no credential are kept. */
360
- mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable", harnesses: [...MCP_HARNESSES] },
485
+ tool_keys: { routes: true, at_rest: "sealed" },
486
+ /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
487
+ * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
488
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...MCP_HARNESSES] },
361
489
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
362
490
  learning,
363
491
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
364
492
  * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
365
- webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
493
+ // Always sealed: the server starts with its seal key (seal-key.ts ensureSealKey), so nothing is kept in the clear.
494
+ webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
366
495
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
367
- triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], overlap: [...OVERLAP], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: HOOK_MAX_BODY, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" } },
496
+ triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
368
497
  },
369
498
  regions: [{ id: "local", jurisdiction: null, state: "live" }],
370
499
  /** This server's own: where its OpenAPI document is, beside this one. */
@@ -408,28 +537,18 @@ function integerParam(value, name, max) {
408
537
  throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
409
538
  return Number(value);
410
539
  }
411
- /** The agent homes 0.1.0-beta.26 and earlier kept in the data directory (`<data>/<agent>/agent.sqlite`, an agent named
412
- * `runs` or a symlinked home included), which this version's store does not read: their agents and runs would not
413
- * show. This version keeps no `agent.sqlite` under the data directory. */
414
- async function oldHomes(data) {
415
- const found = [];
416
- for (const name of await readdir(data)) {
417
- const file = join(data, name, "agent.sqlite");
418
- if (await stat(file).then((info) => info.isFile(), () => false))
419
- found.push(file);
420
- }
421
- return found.sort();
422
- }
540
+ // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
541
+ // by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
423
542
  export async function startServe(options) {
543
+ // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
544
+ // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
545
+ delete process.env[HARNESS_TABLE_ENV];
546
+ // No start without a seal key (seal-key.ts): the one handed over, else the one kept under the config home, made at the
547
+ // first start with only its path printed. Every secret here is kept under it; there is no keeping one in the clear.
548
+ const seal = bootSealKey();
424
549
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
425
550
  // Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
426
551
  const data = await realpath(resolve(options.data));
427
- // What only reads and refuses comes first: a start refused for it creates nothing in the data root, server.lock included.
428
- const homes = await oldHomes(data);
429
- if (homes.length) {
430
- const named = homes.length > 5 ? [...homes.slice(0, 5), `and ${homes.length - 5} more`] : homes;
431
- throw new Error(`this data directory holds agent homes from AgentRun Server 0.1.0-beta.26 or earlier (${named.join(", ")}), which this version does not read: started here, it would show none of their agents or runs. Keep them with the earlier version, or move those directories out of ${data} to start this one; see "Upgrading from 0.1.0-beta.26" in the serve README.`);
432
- }
433
552
  if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
434
553
  throw new Error("the token must be 32 characters or more, with no whitespace");
435
554
  if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
@@ -444,30 +563,25 @@ export async function startServe(options) {
444
563
  if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
445
564
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
446
565
  const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
447
- // Then one server per data root, before anything writes it: a refused second server writes no token, opens no store,
448
- // adopts or sweeps no run, binds no port and prints no address (server-lock.ts). A failed start releases the lock and
449
- // leaves the file, which the next server reuses: unlinking it would race a server that opens it meanwhile. A server
450
- // that is stopping (its runs' processes still drain) is waited for, up to the time its mark gives, not refused.
451
- const lock = await takeServerLockAfterStop(data, {
452
- waiting: ({ pid, until }) => noticeOf(options)(`the server on this data root (pid ${pid}) is stopping; waiting for it, up to ${seconds(until - Date.now())}`),
453
- });
454
- // What a start that fails stops before the lock goes: the webhook deliveries it began, which would write the next
455
- // server's outbox.
566
+ // The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
567
+ const templates = readPackages(options.templates);
568
+ // One server per data root is the store's own EXCLUSIVE lock (StoreOwned), taken when startHolding opens the store; a
569
+ // data directory an earlier version wrote is refused there too (StoreFromEarlierVersion), in words, to start fresh. No
570
+ // server.lock, no oldHomes/oldLayout checks, no migration.
571
+ // What a start that fails stops: the webhook deliveries it began, which would write the next server's outbox, and the
572
+ // store handle it opened.
456
573
  const stops = [];
457
574
  try {
458
- // The server's record, which its stop rewrites in place (server-lock.ts): made now, so the stop makes nothing.
459
- markRunning(data);
460
- return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow }, stops);
575
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates, sealKey: seal.key }, stops);
461
576
  }
462
577
  catch (error) {
463
578
  for (const stop of stops)
464
579
  await stop().catch(() => undefined);
465
- lock.release();
466
580
  throw error;
467
581
  }
468
582
  }
469
- async function startHolding(options, data, lock, checked, stops) {
470
- const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow } = checked;
583
+ async function startHolding(options, data, checked, stops) {
584
+ const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
471
585
  /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
472
586
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
473
587
  * read (the view never fails for it). */
@@ -480,20 +594,35 @@ async function startHolding(options, data, lock, checked, stops) {
480
594
  const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
481
595
  const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
482
596
  const token = options.token ?? stored.token;
483
- const doorTokenFile = join(data, DOOR_TOKEN_FILE);
484
- const { token: doorToken } = await tokenIn(doorTokenFile);
597
+ // Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
598
+ // (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
599
+ // new file and token.
600
+ if (options.token !== undefined)
601
+ await rm(join(data, TOKEN_FILE), { force: true });
485
602
  const log = options.log;
486
603
  const quiet = process.env.AGENTRUN_LOG === "quiet";
487
604
  const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
488
- /** The host's secrets as a run's notes are checked against (learning-run.ts), and the keys a person saved on this
489
- * server (storedKeys, below), read at each call: a person's note, and every learning text read. */
490
- const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken, ...(triggerSecrets?.values() ?? [])];
491
- // Each webhook trigger's secret, made below once the environment is read; shown nowhere, as the server's own are not.
492
- let triggerSecrets;
493
- const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {}) };
605
+ /** Every secret this server never shows, read at each call, so one made, saved or rotated is cut at once: the host's,
606
+ * wherever its launcher put them, and the keys a person saved on it (read through `stored`, storedKeys below, by
607
+ * default), its tokens, and every one it holds (server-secrets.ts). What a run shows (runs.ts), what its learning
608
+ * keeps (learning-run.ts), a person's note, every learning text read, and the VM relay's errors are cut of it. */
609
+ const serverSecrets = (stored = storedKeys) => [...hostSecrets(process.env, stored), ...(secretStores?.values() ?? [])];
610
+ // The server's own secrets, and each trigger source's sealed settings, opened below once the environment is read;
611
+ // shown nowhere.
612
+ let secretStores;
613
+ let triggerSettings = new Map();
614
+ const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
615
+ // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
616
+ // EXCLUSIVE lock is the one-server lock (no server-lock.ts), and it refuses a data directory an earlier version wrote, in
617
+ // words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
618
+ // server writes and reads rows, and a runner (its own process, sharing only this store) runs every run.
619
+ // On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts), its owner lock the one-server lock.
620
+ const store = await openStore({ dataDir: data, role: "server" });
621
+ stops.push(() => store.close());
494
622
  // Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
495
- // call each the server's, and none could be deleted.
496
- const toolKeys = new ToolKeys(data, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
623
+ // call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
624
+ const toolKeys = toolKeysOverStore(store, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
625
+ await toolKeys.load();
497
626
  // A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
498
627
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
499
628
  const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
@@ -509,30 +638,36 @@ async function startHolding(options, data, lock, checked, stops) {
509
638
  const storedKeys = (name) => toolKeys.value(name);
510
639
  // A stored key that does not open is said once at the start, never a refusal to start.
511
640
  toolKeys.view();
512
- const mcpServers = new McpServers(data, withSecrets(base, "own"), VERSION);
513
- // What a run's grants are checked against, its pin made from and its credentials read from (runs.ts, runnable.ts).
514
- const mcpSource = {
515
- server: (name) => {
516
- try {
517
- const saved = mcpServers.get(name);
518
- return { url: saved.url, tools: saved.tools.map(({ name: tool, title, description, input_schema, annotations }) => ({ name: tool, ...(title ? { title } : {}), ...(description ? { description } : {}), inputSchema: input_schema, ...(annotations ? { annotations: annotations } : {}) })), ...(saved.prices ? { prices: saved.prices } : {}) };
519
- }
520
- catch {
521
- return undefined;
522
- }
523
- },
524
- headers: (name) => mcpServers.headers(name),
641
+ const mcpServers = mcpServersOverStore(store, withSecrets(base, "own"), VERSION);
642
+ if (options.githubMcpOrigin)
643
+ mcpServers.appOrigin = options.githubMcpOrigin;
644
+ // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
645
+ // step (blockersOf's `mcp`, and the template apply): the server is the one writer of these rows (a save, refresh, sign-in
646
+ // or delete), so the snapshot is refreshed after each of those and reads what is saved now. The runner reads the registry,
647
+ // pins and credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP source.
648
+ let mcpMeta = new Map();
649
+ const refreshMcpMeta = async () => {
650
+ mcpMeta = new Map((await store.mcp.servers()).map((row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [] }]));
525
651
  };
526
- // Each with whether it can be granted: a known meta tool can't (mcp-meta.ts).
652
+ await refreshMcpMeta();
653
+ // Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
654
+ // with whether each can be granted: a known meta tool can't (mcp-meta.ts).
527
655
  const mcpTools = (server) => {
528
- const saved = mcpSource.server(server);
656
+ const saved = mcpMeta.get(server);
529
657
  return saved?.tools.map((tool) => {
530
658
  const meta = metaToolOf(saved.url, tool.name);
531
- return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
659
+ const bound = { name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) };
660
+ return meta ? { ...bound, grantable: false, reason: meta.reason } : bound;
532
661
  });
533
662
  };
534
- // The server's tool settings, beside the agent store: capabilities say what they resolve to, again after a PUT.
535
- const settings = new ToolSettings(data);
663
+ // The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
664
+ // once here.
665
+ const settings = toolSettingsOverStore(store);
666
+ await settings.load();
667
+ // Whether anyone can answer an ask here (accounts on), for the runners, which read it from the store at each claim
668
+ // (server-approvers.ts): the one way a runner learns it.
669
+ await writeApprovers(store.settings, options.accounts === true);
670
+ mcpServers.toolSettings = () => settings.get();
536
671
  // The server's reading, in parts: `env`, its environment with its secrets, saved keys among them (storedKeys);
537
672
  // `offers`, what each harness offers, probed from env without the tool keys (offersEnvOf), the one slow part (each
538
673
  // CLI's package and pins, codex's binary hashed); and `caps`, the capabilities document made from both under the tool
@@ -569,8 +704,8 @@ async function startHolding(options, data, lock, checked, stops) {
569
704
  * finishes after it is dropped. */
570
705
  let needsAsked = 0;
571
706
  const keysChanged = async () => {
572
- // A run's learning, as its view, a list and its timeline row show it, is cut of the keys saved now (runs.ts).
573
- runs.keysChanged();
707
+ // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
708
+ // serverSecrets live, store-view), so a key change needs no cache invalidation here.
574
709
  env = withSecrets(base, "all", storedKeys);
575
710
  const mine = ++needsAsked;
576
711
  const next = await needsOf(env);
@@ -593,16 +728,34 @@ async function startHolding(options, data, lock, checked, stops) {
593
728
  let image;
594
729
  // What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
595
730
  // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
596
- const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : boxes.provider("docker") ? await boxNetworkOf(env, options.faux && options.fauxPlatform ? { platform: options.fauxPlatform } : {}) : { allow: "none", reason: "no Docker box on this server" };
597
- // The proxy directories runs that are gone left in /tmp (box-egress.ts): a live run's, any server's, stays.
731
+ // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
732
+ // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
733
+ // server is on a host.
734
+ const fauxMountinfo = options.faux ? (options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV]) : undefined;
735
+ // Where Docker has this server's files (box-paths.ts): its own, on a host; its container's mount of the data directory,
736
+ // for a server in a container given Docker's socket; or none, and docker is unavailable, saying why. Under --faux, a
737
+ // host's unless the test gives a container's mountinfo.
738
+ // 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
739
+ // (box-egress-vm.ts), never a volume's subpath of its data.
740
+ const platform = options.faux && options.fauxPlatform ? options.fauxPlatform : process.platform;
741
+ 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);
742
+ const boxPaths = "paths" in dockerPaths ? dockerPaths.paths : undefined;
743
+ const egressParent = boxPaths ? egressParentOf(data) : undefined;
744
+ if ("reason" in dockerPaths)
745
+ log?.(logLine("box_paths", { reason: dockerPaths.reason }));
746
+ 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 } : {}) });
747
+ // The proxy directories runs that are gone left in /tmp, or, in a container, on the data directory's mount
748
+ // (box-egress.ts): a live run's, any server's, stays.
598
749
  if (!fauxBox && boxes.provider("docker"))
599
- await sweepEgressDirs().catch(() => 0);
750
+ await sweepEgressDirs(undefined, undefined, egressParent).catch(() => 0);
600
751
  // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
601
752
  // (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.
602
753
  let egress;
603
754
  const dockerNetwork = (offer) => {
604
755
  if (!offer.available)
605
756
  return offer;
757
+ if ("reason" in dockerPaths)
758
+ return { id: offer.id, available: false, state: "unavailable", reason: dockerPaths.reason };
606
759
  if (boxNetwork.allow === "none")
607
760
  return { ...offer, network: "none", network_reason: boxNetwork.reason };
608
761
  const proxy = egress?.state();
@@ -647,7 +800,7 @@ async function startHolding(options, data, lock, checked, stops) {
647
800
  const vmClient = boxes.vmClient();
648
801
  // What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
649
802
  // process sees it.
650
- const vmSecrets = () => [...learningSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
803
+ const vmSecrets = () => [...serverSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
651
804
  const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
652
805
  const vmLimits = (() => {
653
806
  const limits = boxLimitsOf(env);
@@ -667,6 +820,7 @@ async function startHolding(options, data, lock, checked, stops) {
667
820
  const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
668
821
  egress = await startEgressContainer({
669
822
  env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
823
+ warn: (message) => (log ? log(logLine("box_egress", { runtime: boxNetwork.vm, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
670
824
  onChange: (state) => {
671
825
  egressLog(state);
672
826
  boxOffers = offersNow();
@@ -681,13 +835,87 @@ async function startHolding(options, data, lock, checked, stops) {
681
835
  log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
682
836
  if (image)
683
837
  imageLog(image.state());
684
- const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability);
685
- const agents = new Agents(data);
686
- triggerSecrets = new TriggerSecrets(data, env, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)));
687
- // Each agent's saved sign-ins (sign-ins.ts), under the seal key the tool keys are kept under: its vendor's calls on the
688
- // server's keys (under faux, the vendor's fake alone), and a lease held while the run it names has not ended.
689
- const signIns = new SignIns(data, sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]), vendorsOver(() => env, checkFetch), async (runId) => (await agents.request(() => agents.store.readRun(runId)))?.state === "running");
838
+ const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
839
+ const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
840
+ const sealKey = sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]);
841
+ // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
842
+ // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
843
+ // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
844
+ // faux-computers.ts's three providers stand in. The folder mode is read at each call (folderModeOf), so turning Archil
845
+ // on or off needs no rebuild; a key named in the server's environment wins over a saved one.
846
+ const browserToolNames = (await import("@parcha/pi-browser")).BROWSER_TOOLS.map((tool) => tool.name);
847
+ const localTools = new Set(hostToolDefs({ maxExecS: 600, shell: "local" }).map((def) => def.name));
848
+ const kindTools = (kind) => kind === "none" ? [] : kind === "sandbox" ? hostToolDefs({ maxExecS: 600, shell: "computer" }).map((def) => def.name).filter((name) => !localTools.has(name))
849
+ : kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
850
+ let faux;
851
+ const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
852
+ let computerRoutes;
853
+ const computersOf = () => (computerRoutes ??= createComputerRoutes({
854
+ store, sealKey: checked.sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
855
+ ...(options.faux
856
+ ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
857
+ : {
858
+ kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
859
+ // The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
860
+ factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
861
+ }),
862
+ }));
863
+ /** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
864
+ * computerReadiness): over the registry the claim reads (workspace/computer-deps.ts claimKinds, asked with what the
865
+ * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
866
+ * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
867
+ * runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
868
+ * a computer setting, in place of the box check. Whether Docker answers here is the boxes' own start-time probe
869
+ * (boxOffers, in memory: no new probe), with its reason, which says how to fix it. */
870
+ const dockerAnswers = (provider) => {
871
+ const box = boxAvailability(boxOffers).find((one) => one.id === provider);
872
+ return box?.available ? true : box?.reason ?? `${provider} is not a box this server has`;
873
+ };
874
+ const computerReady = async (setting) => computerReadiness(setting, (await folderModeOf(store)()) === "disk" ? 2 : 1, claimKinds({}), keyReader(store, checked.sealKey, withSecrets(process.env, "own")), dockerAnswers);
875
+ const archil = createArchilRoutes({ store, sealKey: checked.sealKey, env: process.env });
876
+ /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
877
+ const runComputerOf = async (runId, view) => {
878
+ const run = await store.runs.get(runId);
879
+ const body = run ? (await store.agents.revision(run.revisionId))?.body : undefined;
880
+ const setting = body?.computer ?? (body?.place ? computerOfPlace(body.place) : undefined);
881
+ if (!setting)
882
+ return {};
883
+ const error = view.error;
884
+ const field = runComputerField(setting, { id: runId, status: String(view.status), ...(error && typeof error.code === "string" ? { error: { code: error.code, message: String(error.message ?? "") } } : {}) });
885
+ return field ? { computer: field } : {};
886
+ };
887
+ // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
888
+ // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
889
+ // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
890
+ const ctx = BACKGROUND_CONTEXT;
891
+ const agents = {
892
+ get: (id) => getAgent(store, id),
893
+ list: (options = {}) => listAgents(store, options),
894
+ create: (body, check, fresh) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}) }),
895
+ commit: (entry, body, options = {}) => commitAgent(store, entry, body, options),
896
+ revisions: (id) => agentRevisions(store, id),
897
+ revision: (agentId, revisionId) => agentRevision(store, agentId, revisionId),
898
+ setCurrent: (entry, revisionId) => setCurrentRevision(store, entry, revisionId),
899
+ setArchived: (kind, id, archived) => (kind === "agent" ? setAgentArchived(store, id, archived) : archiveRun(store, id, archived)),
900
+ request: (fn) => Promise.resolve(fn()),
901
+ dir: data,
902
+ store: {
903
+ listRuns: (filter = {}) => listRunsOverStore(store, filter, ctx),
904
+ readRun: (id) => readRunOverStore(store, id, ctx),
905
+ runOfOrigin: (key) => runOfOriginOverStore(store, key),
906
+ readRevision: (id) => store.agents.revision(id),
907
+ },
908
+ close: () => store.close(),
909
+ };
910
+ ({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
911
+ secretStores.add("server", () => [token]);
912
+ // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
913
+ // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
914
+ // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
915
+ const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
690
916
  const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
917
+ // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
918
+ secretStores.add("webhook", () => webhooks.signingSecrets());
691
919
  stops.push(() => webhooks.close());
692
920
  const uploads = new Uploads(join(data, UPLOADS_DIR));
693
921
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
@@ -698,24 +926,126 @@ async function startHolding(options, data, lock, checked, stops) {
698
926
  const documents = options.documents ?? process.env[DOCUMENTS_ENV];
699
927
  if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
700
928
  throw new Error(`the documents directory ${documents} is not a directory`);
701
- const runs = new Runs({ dockerAllow: boxNetwork.allow, ...(egress?.volume ? { dockerVolume: egress.volume } : {}), agents, token, storedKeys, mcpServers: mcpSource, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(vmBoxes && vmRelayHalf ? { vmBoxes, vmLimits, vmRelay: vmRelayHalf } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(remoteBoxes ? { boxAllow, onNoBoxList } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker), ownSecrets: () => triggerSecrets?.values() ?? [], signIns, approvers: options.accounts === true });
702
- const daytona = daytonaApi(env);
703
- const relay = (remoteBoxes && daytona) || vmRelayHalf ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...(remoteBoxes && daytona ? daytona : {}), ...(vmRelayHalf ? { vm: vmRelayHalf } : {}), serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
704
- if (relay)
705
- stops.push(() => relay.close());
929
+ // The CLI harnesses, each installed on first use into the data's harnesses directory (harness-install.ts): one install
930
+ // of each at a time, which every run on that harness, and the save of an agent on it, waits for or starts; once one is
931
+ // in, the offers are probed again, so capabilities no longer say it installs on first use. Each is its table entry's
932
+ // `installs` (a test's stand-in has none).
933
+ // Claude Code as an earlier build installed it, at the top of the harnesses directory itself (read-only): removed once,
934
+ // before the first install, which then goes in beside nothing. Any other layout is left as it is.
935
+ let flat;
936
+ const flatRemoved = () => (flat ??= removeFlatInstall(harnessesOf(data)).then((removed) => void (removed && log?.(logLine("harness_install_removed", { dir: harnessesOf(data), said: `removed the earlier Claude Code install at ${harnessesOf(data)}: it installs again under harnesses/claude-agent` }))), (error) => ((flat = undefined), Promise.reject(error))));
937
+ const installed = HARNESSES.flatMap((id) => {
938
+ const harness = harnessOf(base, id);
939
+ return harness?.installs && harness.pins ? [{ entry: harness.installs, pins: harness.pins }] : [];
940
+ });
941
+ const installs = Object.fromEntries(installed.map(({ entry, pins }) => {
942
+ const lock = options.harnessLocks?.[entry.id];
943
+ // npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
944
+ const onKilled = () => log?.(logLine("harness_install_killed", { harness: entry.id, said: `npm did not stop within ${NPM_STOP_GRACE_MS / 1000} s of SIGTERM; killed` }));
945
+ return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, async (entry, dir, pins, signal) => (await flatRemoved(), npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) })), (ms) => {
946
+ log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
947
+ void probe(`${entry.id}_installed`).catch(() => undefined);
948
+ })];
949
+ }));
950
+ // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
951
+ // read once for this server (and again after a read that failed), through the faux one under --faux.
952
+ let pricing;
953
+ const decisionPrice = async (model) => {
954
+ const making = (pricing ??= (async () => {
955
+ const [{ openrouterProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(fauxEnvOf(options), FAUX_OPENROUTER_ENV)]);
956
+ return openrouterProvider(faux ? { fetch: faux } : {});
957
+ })());
958
+ // One that could not be made is made again next time: a rejection is never kept.
959
+ const provider = await making.catch((error) => { if (pricing === making)
960
+ pricing = undefined; throw error; });
961
+ return provider.priceOf(model);
962
+ };
963
+ // The run write half (runs-over-store): the server INSERTs a queued run and its launch (startRun), and writes command
964
+ // rows (message/stop/cancel/raise/approve/archive) a run's runner reads and applies. No per-run process, no HTTP door,
965
+ // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
966
+ // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
967
+ // reads launch.model alone).
968
+ const modelOf = (_entry, revision) => runModelRef(env, revision);
969
+ const startDeps = {
970
+ runBodyIssues,
971
+ pinnedOf,
972
+ inputIssuesOf,
973
+ explainRun,
974
+ // told and fallbackPlace are const arrows declared later in startHolding; wrap them so startDeps captures the binding
975
+ // (called at request time, after they are assigned) rather than reading them before their declaration.
976
+ told: (error) => told(error),
977
+ runnable,
978
+ readyFiles: (ids) => uploads.readyFiles(ids),
979
+ fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
980
+ workflowTitle,
981
+ serverSecrets,
982
+ toolSettings: () => settings.get(),
983
+ planeEnv: () => env,
984
+ approvers: options.accounts === true,
985
+ ...(documents ? { documents: resolve(documents) } : {}),
986
+ ...(boxAllow !== undefined ? { boxAllow } : {}),
987
+ modelOf,
988
+ // The run's learning start, decided at start as the old file-backed start decided it (learning-run.ts onStart/seedFor):
989
+ // the server's learning switch, the budget its # Learned section fits, the agent's seed read now from its learning folder
990
+ // (git), and the host's secrets as they are shown now to cut the notes a run is given. runs-over-store.learningStartFor
991
+ // pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed that cannot be read starts the run
992
+ // with nothing learned (a fault never refuses it). INERT until the runner installs learning-1's learningEndOfRun as its
993
+ // endOfRun (cutover-learning-end 283008bb05, E2r3's one-line spec-builder hookup); land this in that same round.
994
+ learning,
995
+ learningBudget,
996
+ seedFor: async (agentId) => {
997
+ // The switch runs no git in this process (learning.ts seedOf: the folder's own script and file API, which checks git
998
+ // itself); a git or folder fault surfaces here as a seedOf error, so the run starts with nothing learned, never refused.
999
+ return seedOf(data, agentId).then((seed) => ({ seed }), (error) => {
1000
+ process.stderr.write(`agentrun-serve: the agent ${agentId}'s learning folder could not be read, so its run starts with nothing learned: ${error.message}\n`);
1001
+ return { failed: error.message };
1002
+ });
1003
+ },
1004
+ shown: () => secretsShown(serverSecrets()),
1005
+ };
1006
+ // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1007
+ // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1008
+ // request) use the server's public address, else its own.
1009
+ // The run's key read from this server's environment with the keys a person saved, as its Timeline reads it (keyEnv below).
1010
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) });
1011
+ const ownOriginOf = () => options.publicUrl ?? url;
1012
+ // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1013
+ // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
1014
+ // and withheld verdict from store-view. The live browser viewer reads the runner's published handover from the store
1015
+ // (liveViewerLink, the one the runner's browser tool wrote under its claim), when this server has the seal key its token
1016
+ // is sealed under; with no seal key no live view is ever served, so the live branch is left off. The timeline route keeps
1017
+ // its own stub (store-reads journal + SSE) until E2c's timeline lands.
1018
+ const runReadsDeps = {
1019
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
1020
+ env,
1021
+ runView: (_store, runId) => viewOverStore(store, runId, viewDepsFor(ownOriginOf())),
1022
+ withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1023
+ cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1024
+ context: ctx,
1025
+ ...(sealKey ? { liveViewer: (runId) => liveViewerLink(store, sealKey, runId) } : {}),
1026
+ };
1027
+ // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1028
+ // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1029
+ // The route frames the SSE around its `page`, which long-polls the journal, byte-identical to the old live run's page.
1030
+ const timelines = runTimelines({
1031
+ context: ctx,
1032
+ // The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
1033
+ // or saved since is cut at once), the set its view's words, title and error are cut of: each secret this server never
1034
+ // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1035
+ // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1036
+ // from its journal, which keeps what the run said whole.
1037
+ timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) }, forStore, runId, context),
1038
+ runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1039
+ });
1040
+ const triggerDeps = {
1041
+ start: startDeps,
1042
+ getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1043
+ needAgent,
1044
+ momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1045
+ runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
1046
+ };
1047
+ const targets = triggerTargets(store, triggerDeps);
706
1048
  const expected = digest(`Bearer ${token}`);
707
- if (options.beforeAbort)
708
- runs.beforeAbort = options.beforeAbort;
709
- if (options.beforeReopenLaunch)
710
- runs.beforeReopenLaunch = options.beforeReopenLaunch;
711
- if (options.beforeSubmit)
712
- runs.beforeSubmit = options.beforeSubmit;
713
- if (options.beforeMetaSave)
714
- runs.beforeMetaSave = options.beforeMetaSave;
715
- if (options.onRunLoad)
716
- runs.onRunLoad = options.onRunLoad;
717
- if (options.messageOrigin)
718
- runs.messageOrigin = options.messageOrigin;
719
1049
  const keptFile = join(data, IDEMPOTENCY_FILE);
720
1050
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
721
1051
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
@@ -729,7 +1059,31 @@ async function startHolding(options, data, lock, checked, stops) {
729
1059
  await rename(`${keptFile}.partial`, keptFile);
730
1060
  }));
731
1061
  const host = options.host ?? "127.0.0.1";
732
- const owner = options.accounts ? new Owner(data, options.openSetup === true, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
1062
+ // Open setup (no code) only where no one else reaches the port: a loopback listener. Bound to any other address
1063
+ // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1064
+ const openSetup = options.openSetup === true && isLoopback(host);
1065
+ const owner = options.accounts ? new Owner(data, openSetup, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
1066
+ // Who a sign-in comes from, for its limit: the socket's peer, or, from a trusted proxy only, the client it forwards for.
1067
+ const trusted = (() => {
1068
+ if (!options.trustedProxies?.length)
1069
+ return undefined;
1070
+ try {
1071
+ return proxyaddr.compile([...options.trustedProxies]);
1072
+ }
1073
+ catch (error) {
1074
+ throw new Error(`trustedProxies: ${error.message}`);
1075
+ }
1076
+ })();
1077
+ const clientOf = (req) => (trusted ? proxyaddr(req, trusted) : req.socket.remoteAddress) ?? "unknown";
1078
+ /** Whether `req` may be shown a secret this server mints (trigger-secrets-shown.ts): the caller that may write one. */
1079
+ const mayHoldSecrets = (req) => writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) });
1080
+ /** A trigger's view with its minted secret's metadata, never the secret (trigger-secrets-shown.ts). */
1081
+ const withSecretOf = (view) => withTriggerSecret(view, adapters, (adapterId, scope, field) => {
1082
+ const settings = triggerSettings.get(adapterId);
1083
+ return settings?.get(scope, field) !== undefined ? "set" : settings?.unopenedAt(scope, field) ? "unopened" : "unset";
1084
+ });
1085
+ // The owner's open live views (browser-live.ts): each closes once no session that let it in holds.
1086
+ const viewers = new OpenViewers();
733
1087
  // A saved key is read by name from here, past the checks that refuse a start and before any run (a recovered one too)
734
1088
  // is launched: each launch hands over what is saved then. One server in a process reads them: the last started.
735
1089
  await probe("start");
@@ -745,112 +1099,64 @@ async function startHolding(options, data, lock, checked, stops) {
745
1099
  };
746
1100
  // Decided once, by the probe the confinement walks by: capabilities.home.writes says what PUT and DELETE do.
747
1101
  const homeWrites = caps.home.writes;
748
- // Runs an earlier server left: supervised again, carried back when they already ended, or opened again. Then, however
749
- // that went, the webhook's ledger against the agent store: waits of runs ended or gone dropped, and each end it lacks
750
- // queued. Each is its own step: a recovery that gives up (a store busy past its wait) still lets the catch-up run, and a
751
- // step that gives up is said, the next start trying it again.
752
- void runs
753
- .recover()
754
- .catch((error) => void process.stderr.write(`agentrun-serve: recovery: ${error.message}\n`))
755
- .then(async () => {
756
- const rows = (await agents.request(() => agents.store.listRuns())).filter((row) => !row.importedFrom);
757
- const byId = new Map(rows.map((row) => [row.id, row]));
758
- // An end's notice from its row and its serve.json alone, as the run list reads an ended run (summaryOfRow): never
759
- // its own store, whose read can fail, so a busy store loses no end. The same body a live end's notice has.
760
- await webhooks.catchUp(rows, async (id) => {
761
- const row = byId.get(id);
762
- if (!row)
763
- return null;
764
- const meta = await readJson(join(agents.dir, "runs", id, RUN_META));
765
- return { run_id: id, agent_id: row.agent, status: await runs.statusOfRow(row), title: isObject(meta) && typeof meta.title === "string" ? meta.title : "" };
766
- });
767
- })
768
- .catch((error) => void process.stderr.write(`agentrun-serve: the webhook's catch-up: ${error.message}\n`));
1102
+ // No server-side run recovery: a runner (its own process) claims every run an earlier runner left and resumes it from the
1103
+ // journal under the claim epoch — the server starts no run process and adopts none.
1104
+ // TODO(switch): rebuild the webhook catch-up over the store's run rows (listRuns + the run view's status) so an end a
1105
+ // stopped server never delivered is queued at the next start; deferred (webhooks stay until route-1's triggers8 merges).
769
1106
  // Schedules: each firing starts its run as POST /agents/{id}/runs does, capped, under the firing's key (triggers.ts).
770
1107
  // Firings an earlier server left due are driven again now, beside the recovery above.
771
- const triggers = new Triggers(data, {
1108
+ // Connect GitHub: the server's one GitHub App, in the store's trigger_settings (adapter github, scope server), where the
1109
+ // runner reads it per claim (runner/github-app.ts).
1110
+ const github = new GitHubConnection(triggerSettings.get("github"));
1111
+ const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
1112
+ /** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
1113
+ const githubConnection = () => github.view();
1114
+ /** What applying a template reads of the server (templates.ts TemplatesDeps). */
1115
+ const templateDeps = { githubConnection };
1116
+ // A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
1117
+ // with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
1118
+ // is a server secret while it may be in use.
1119
+ mcpServers.appToken = (signal) => githubConnect.tokenForListing(signal);
1120
+ secretStores.add("github-tokens", () => githubConnect.liveTokens());
1121
+ const triggers = new Triggers({
1122
+ // The server's own store (the one it opened) holds the triggers a person writes and reads; a test may inject another
1123
+ // (startServe's `store`).
1124
+ store: options.store ?? store,
772
1125
  clock: options.triggerClock,
1126
+ ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1127
+ adapters,
1128
+ unavailable: (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : undefined),
773
1129
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
774
- async targetIssues(target) {
775
- if (target.kind === "message_run") {
776
- const run = await runs.get(target.run_id);
777
- if (!run)
778
- return [{ field: "target.run_id", reason: "not_found", message: `no run ${target.run_id}` }];
779
- if (run.kind === "workflow")
780
- return [{ field: "target.run_id", reason: "not_allowed", message: "A workflow run takes no messages here." }];
781
- return run.meta.max_cost_usd === undefined ? [{ field: "target.run_id", reason: "not_allowed", message: NO_CAP }] : [];
782
- }
783
- const entry = await agents.get(target.agent_id);
784
- if (!entry)
785
- return [{ field: "target.agent_id", reason: "not_found", message: `no agent ${target.agent_id}` }];
786
- if (!entry.revision)
787
- return [{ field: "target.agent_id", reason: "invalid", message: `the agent ${target.agent_id} has no current revision` }];
788
- if (entry.revision.kind === "workflow")
789
- return [{ field: "target.agent_id", reason: "not_allowed", message: "A trigger's runs are capped, and a workflow run's spend is not capped here: name an agent that is not a workflow." }];
790
- const uncapped = target.max_cost_usd === undefined && entry.revision.body.maxCostUsd === undefined ? [{ field: "target.max_cost_usd", reason: "missing", message: `Every run a trigger starts is capped: give the target a max_cost_usd or set the agent's (the agent ${target.agent_id} has none).` }] : [];
791
- return [...uncapped, ...(await inputIssuesOf(entry.revision, target.input)).map((issue) => ({ ...issue, field: `target.${issue.field}` }))];
792
- },
793
- async start(target, input, trigger) {
794
- const entry = await needAgent(target.agent_id);
795
- // The target's cap, else the agent's default as it stands now: a run a trigger starts is never uncapped.
796
- const run = await startRunOf(entry, { input, ...(target.max_cost_usd !== undefined ? { max_cost_usd: target.max_cost_usd } : {}), ...(target.effort ? { effort: target.effort } : {}) }, { trigger, origin: { key: trigger.firing_key }, capped: true });
797
- return { run_id: run.id };
798
- },
799
- async message(target, input, key) {
800
- const run = await needRun(target.run_id);
801
- if (run.kind === "workflow")
802
- throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here.");
803
- // A store held past its retries is a busy store: the firing stays due and is tried again, never failed.
804
- if (await runs.tookMessage(run, key).catch((error) => { throw storeBusy(error) ? homeBusy() : error; }))
805
- return;
806
- // Never an uncapped turn, nor an answer to a person's question, an approval or a budget pause: a run that waits on
807
- // its person is told nothing by a trigger.
808
- if (run.meta.max_cost_usd === undefined)
809
- throw new ApiError("not_continuable", NO_CAP);
810
- const { status, state } = statusOf(run);
811
- if (status === "input_required" && state === "waiting")
812
- return { skipped: WAITS_ON_A_PERSON };
813
- try {
814
- await runs.message(run, String(input.content), key, { answers: false });
815
- }
816
- catch (error) {
817
- if (error instanceof ApiError && error.message === WAITS_ON_A_PERSON)
818
- return { skipped: WAITS_ON_A_PERSON };
819
- throw error;
820
- }
821
- },
822
- secrets: { mint: (id) => triggerSecrets.mint(id), remove: (id) => triggerSecrets.remove(id) },
1130
+ // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1131
+ // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
1132
+ // queue a firing takes — how many of a trigger's messages wait for a busy run — is route-1's store.triggers.
1133
+ ...targets,
1134
+ settings: (adapterId) => triggerSettings.get(adapterId),
823
1135
  notify: (failed, key) => webhooks.emitTrigger(failed, key),
824
- async runOf(key) {
825
- const started = await agents.request(() => agents.store.runOfOrigin(key));
826
- if (!started)
827
- return null;
828
- // Never set up as runs.ts load reads it (notSetUp: the store has it running and its serve.json holds no input), which
829
- // this start's recovery fails as server_lost_at_setup; or failed so already.
830
- const run = await runs.get(started.runId);
831
- return { run_id: started.runId, setup_lost: run?.notSetUp === true || run?.error?.details?.reason === SETUP_LOST };
832
- },
833
- async statusOf(runId) {
834
- const row = await agents.request(() => agents.store.readRun(runId));
835
- return row ? runs.statusOfRow(row) : null;
836
- },
837
1136
  });
1137
+ // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1138
+ stops.push(() => githubConnect.close());
838
1139
  stops.push(async () => triggers.close());
839
- triggers.start();
1140
+ // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1141
+ // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1142
+ void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1143
+ // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1144
+ // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
1145
+ void githubConnect.reconcile((detail) => triggers.turnOff("github", detail), { force: true });
840
1146
  // Setup's import of this machine's sessions: offered by a server on this machine only (no public address, listening
841
1147
  // on loopback), counted once (a listing, no transcript kept), run once, each on a worker thread (import-worker.ts) so
842
1148
  // a busy store's wait and the sessions' parsing never hold up a request.
843
- const offersImport = options.openSetup === true && options.publicUrl === undefined && isLoopback(host);
1149
+ const offersImport = openSetup && options.publicUrl === undefined;
844
1150
  let closing = false;
845
1151
  const workers = new Map();
846
1152
  // Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
847
1153
  const onWorker = (task) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
848
1154
  const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
849
- // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), and
850
- // the keys saved on its Tool keys page, opened now (each cut too, the same rule as the CLI's import: a saved key
851
- // and the server's own of the same name may differ), in the worker's memory alone: what the import cuts out of
852
- // everything it writes.
853
- workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })), stored: toolKeys.values() },
1155
+ // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
1156
+ // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1157
+ // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1158
+ // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1159
+ workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })) },
854
1160
  // Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
855
1161
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
856
1162
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
@@ -859,7 +1165,14 @@ async function startHolding(options, data, lock, checked, stops) {
859
1165
  });
860
1166
  workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
861
1167
  let answer;
862
- worker.on("message", (message) => void (answer = message));
1168
+ // The import worker opens no store of its own: a message carrying `req` is one of its calls to this server's open
1169
+ // store, answered against it and posted back; anything else is its one final answer.
1170
+ worker.on("message", (message) => {
1171
+ if (typeof message === "object" && message !== null && "req" in message)
1172
+ void answerStoreCall(store, ctx, message).then((reply) => worker.postMessage(reply));
1173
+ else
1174
+ answer = message;
1175
+ });
863
1176
  worker.once("error", failed);
864
1177
  worker.once("exit", (code) => {
865
1178
  workers.delete(worker);
@@ -935,33 +1248,11 @@ async function startHolding(options, data, lock, checked, stops) {
935
1248
  throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
936
1249
  return Buffer.concat(chunks);
937
1250
  }
938
- /** POST /v2/hooks/{trigger_id}: a webhook trigger's firing, signed by the Standard Webhooks spec under its secret
939
- * (trigger-secrets.ts), checked on the raw body before anything else. An unknown trigger, one that is off or not a
940
- * webhook's, and a check that fails are one answer, so no trigger id can be found by asking; an unknown one is
941
- * checked against a secret of no trigger's, so it takes the same time. A webhook-id already fired answers its firing. */
942
- async function hook(req, res, path) {
943
- const refuse = (reason) => {
944
- authFailed(`/v2${path}`, reason);
945
- return new ApiError("unauthenticated", "this route needs a request signed by the webhook trigger's secret");
946
- };
947
- // Headers that can never pass are refused before a byte of the body is read; they say nothing of the trigger.
948
- const early = hookHeadersRefusal(req.headers, Date.now());
949
- if (early)
950
- throw refuse(early);
951
- const body = await bytesOf(req, HOOK_MAX_BODY);
952
- let id = "";
953
- try {
954
- id = decodeURIComponent(/^\/hooks\/([^/]+)$/.exec(path)[1]);
955
- }
956
- catch { }
957
- const secret = ID.test(id) && triggers.hookable(id) ? triggerSecrets.value(id) : undefined;
958
- const refusal = hookRefusal(secret ?? NO_TRIGGER_SECRET, req.headers, body, Date.now());
959
- if (!secret || refusal)
960
- throw refuse(secret ? refusal : "no_webhook_trigger");
961
- const { created, firing } = triggers.receive(id, String(req.headers["webhook-id"]), body.toString("utf8"));
962
- return send(res, created ? 202 : 200, firing, created ? {} : { "idempotent-replayed": "true" });
963
- }
964
1251
  async function bodyOf(req) {
1252
+ // Read once: the secret-write check reads a registered operation's body before its route does (secret-writes.ts).
1253
+ const read = bodies.get(req);
1254
+ if (read !== undefined)
1255
+ return read;
965
1256
  const type = String(req.headers["content-type"] ?? "");
966
1257
  if (!type.startsWith("application/json"))
967
1258
  throw new ApiError("unsupported_media_type", "the body must be application/json");
@@ -975,23 +1266,62 @@ async function startHolding(options, data, lock, checked, stops) {
975
1266
  }
976
1267
  if (!isObject(value))
977
1268
  throw new ApiError("bad_request", "the body is not a JSON object");
1269
+ bodies.set(req, value);
978
1270
  return value;
979
1271
  }
1272
+ /** The tools a learned draft of agent `id` may name, as a run's merge reads them (learning-run.ts draftTools): its
1273
+ * current revision's, those the gate allows under the server's settings and the agent's own. */
1274
+ async function learnedDraftToolsOf(id) {
1275
+ const revision = (await needAgent(id)).revision;
1276
+ if (revision?.kind !== "agentic")
1277
+ return { tools: [], gated: {} };
1278
+ const [{ learnedDraftTools }, { permissionOf }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
1279
+ const server = settings.get();
1280
+ // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1281
+ const body = revision.body;
1282
+ return learnedDraftTools(body.tools ?? [], (name) => permissionOf(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask"));
1283
+ }
980
1284
  async function needAgent(id) {
981
1285
  const entry = ID.test(id) ? await agents.get(id) : null;
982
1286
  if (!entry)
983
1287
  throw new ApiError("not_found", `no agent ${id}`);
984
1288
  return entry;
985
1289
  }
1290
+ /** An agent view's extra fields (agents-store agentView): its saved sign-ins, its learning count, and its run counts.
1291
+ * The run counts read the store's runs (store-reads/runs.ts listRuns): `count` is every run the agent has, `live` those
1292
+ * still running (runReadState 'running': queued, running or parked), the same numbers the file-backed view showed. */
1293
+ const agentExtra = async (entry) => {
1294
+ const learning = await learningOfAgent(entry);
1295
+ const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1296
+ return { signIns: await signIns.view(entry.agent.id), ...(learning ? { learning } : {}), runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length } };
1297
+ };
1298
+ // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
1299
+ // routes read from the store + the run view now, not a live Run.
986
1300
  async function needRun(id) {
987
- const run = ID.test(id) ? await runs.get(id) : null;
1301
+ const run = ID.test(id) ? await momentOverStore(store, id, viewDepsFor(ownOriginOf())) : undefined;
988
1302
  if (!run)
989
1303
  throw new ApiError("not_found", `no run ${id}`);
990
1304
  return run;
991
1305
  }
1306
+ /** A run's v2 status and state now (the run view), for the answer an act reports once it has written its command row. */
1307
+ const runStatusState = async (runId) => {
1308
+ const v = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1309
+ return { status: v?.status ?? "queued", state: v?.state ?? "idle" };
1310
+ };
1311
+ /** The run read routes (timeline, files, graph, browser, live viewer) over the store are E2c's run-reads-over-store.ts
1312
+ * (watchRun + run-workspace + store-view), not committed yet. TODO(E2c): replace each call with its function on that sha. */
1313
+ 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"); };
992
1314
  const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
993
1315
  /** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
994
1316
  * origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
1317
+ /** A kept answer, replayed to `req`: its console page (a run's or an agent's console_url) at the address this request
1318
+ * reached (linkOrigin), not the first request's. */
1319
+ const pageFor = (req, body) => {
1320
+ if (!isObject(body) || typeof body.console_url !== "string")
1321
+ return body;
1322
+ const at = body.console_url.indexOf("/#/");
1323
+ return at < 0 ? body : { ...body, console_url: `${linkOrigin(req)}${body.console_url.slice(at)}` };
1324
+ };
995
1325
  async function idempotent(req, path, body, work) {
996
1326
  const key = req.headers["idempotency-key"];
997
1327
  if (key === undefined)
@@ -1010,7 +1340,7 @@ async function startHolding(options, data, lock, checked, stops) {
1010
1340
  throw mismatch();
1011
1341
  if (!known.answer)
1012
1342
  throw new ApiError("idempotency_in_progress", "the first request with this Idempotency-Key is still in flight", { retry_after_ms: 500 });
1013
- return { ...known.answer, headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
1343
+ return { ...known.answer, body: pageFor(req, known.answer.body), headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
1014
1344
  }
1015
1345
  idempotency.set(slot, { fingerprint, at: now });
1016
1346
  let answer;
@@ -1030,60 +1360,242 @@ async function startHolding(options, data, lock, checked, stops) {
1030
1360
  }
1031
1361
  // ---- runs -----------------------------------------------------------------------------------------------------------
1032
1362
  /** A workflow revision's shape as runnable.ts checks it: its workflow, tools, harness, place and tool settings. */
1033
- const workflowShape = ({ workflow, tools, harness, place, toolSettings }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}) });
1363
+ const workflowShape = ({ workflow, tools, harness, place, toolSettings, approvals }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}), ...(approvals === "never" ? { approvals } : {}) });
1034
1364
  const shapeOf = (revision) => (revision.kind === "agentic" ? { kind: "agentic", ...revision.body } : workflowShape(revision.body));
1035
1365
  /** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
1036
1366
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
1037
1367
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1038
1368
  async function runnable(revision, place, { capped = false } = {}) {
1039
- const shape = { ...shapeOf(revision), place };
1040
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers, mcp: mcpTools });
1369
+ const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1370
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
1041
1371
  if (!blockers.length)
1042
1372
  return;
1043
1373
  const message = blockers.map((b) => b.message).join(" ");
1374
+ // Each blocker as a 422 names its issue: its field, reason and message, and the fix when it has one.
1375
+ const fields = blockers.map(issueOf);
1044
1376
  const unbound = blockers.flatMap((b) => (b.tool ? [b.tool] : []));
1377
+ // A known MCP meta tool is no server or tool that is missing: it has a key of its own, with why it is not granted.
1378
+ const notGrantable = blockers.flatMap((b) => (b.notGrantable ? [b.notGrantable] : []));
1045
1379
  const missing = Object.fromEntries(blockers.flatMap((b) => (b.missing ? [[b.missing.tool, b.missing.vars]] : [])));
1046
1380
  const harness = blockers.find((b) => b.harness)?.harness;
1047
1381
  const box = blockers.find((b) => b.box)?.box;
1048
- const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}) };
1382
+ const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}), ...(notGrantable.length ? { not_grantable: notGrantable } : {}) };
1049
1383
  if (revision.kind === "agentic")
1050
- throw new ApiError("agent_not_runnable", message, { details: { unbound, missing, ...named } });
1384
+ throw new ApiError("agent_not_runnable", message, { fields, details: { unbound, missing, ...named } });
1051
1385
  const tier = blockers.find((b) => b.tier)?.tier;
1052
1386
  const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
1053
1387
  const denied = blockers.flatMap((b) => (b.denied ? [b.denied] : []));
1054
1388
  const asks = blockers.flatMap((b) => (b.asks ? [b.asks] : []));
1055
- throw new ApiError("agent_not_runnable", message, { details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
1389
+ throw new ApiError("agent_not_runnable", message, { fields, details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
1056
1390
  }
1057
- /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. */
1391
+ /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1392
+ const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
1393
+ /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. A
1394
+ * revision that names no place is checked where it would run (fallbackPlace). */
1058
1395
  async function saveable(revision) {
1059
- const shape = revision.kind === "agentic" ? revision : workflowShape(revision);
1060
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, offers, mcp: mcpTools });
1396
+ // The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
1397
+ // host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
1398
+ const body = revision.body;
1399
+ // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
1400
+ const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
1401
+ if (install) {
1402
+ void install.ensure().catch((error) => log?.(logLine("harness_install_failed", { harness: install.entry.id, message: error.message })));
1403
+ }
1404
+ const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1405
+ const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1406
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, offers, mcp: mcpTools });
1061
1407
  // An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
1062
1408
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1063
1409
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1064
- if (revision.kind === "agentic" && (revision.maxCostUsd ?? 0) > 0) {
1410
+ if ((body.maxCostUsd ?? 0) > 0) {
1065
1411
  const key = (b) => `${b.field}\n${b.message}`;
1066
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers, mcp: mcpTools })).map(key));
1067
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers, mcp: mcpTools });
1068
- blockers.push(...capped.filter((b) => !plain.has(key(b))).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1412
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, offers, mcp: mcpTools })).map(key));
1413
+ const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
1414
+ // A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
1415
+ // agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
1416
+ const added = capped.filter((b) => !plain.has(key(b)));
1417
+ blockers.push(...added.filter((b) => b.unpriced));
1418
+ blockers.push(...added.filter((b) => !b.unpriced).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1069
1419
  }
1070
1420
  const never = blockers.filter((b) => !b.host);
1071
1421
  if (never.length)
1072
1422
  throw invalid(never.map(issueOf));
1073
1423
  return blockers.map(issueOf);
1074
1424
  }
1425
+ /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
1426
+ * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
1427
+ * tool the box refuses (browser) keeps the runner. */
1428
+ async function createAgentOf(body) {
1429
+ let warnings = [];
1430
+ const definition = checkDefinitionBody(body);
1431
+ const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1432
+ const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1433
+ const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1434
+ return { entry, warnings };
1435
+ }
1436
+ /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1437
+ * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
1438
+ * agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
1439
+ * deny the owner set on this server stays, with a warning), its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
1440
+ * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
1441
+ * before it are deleted and the agent is archived (an agent store keeps every agent), and the refusal is the answer, a 422's fields under `triggers.<i>`; a
1442
+ * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
1443
+ * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
1444
+ async function applyTemplate(pkg, body) {
1445
+ const { parameters, grants, model: override, approvals } = applyBodyOf(pkg, body);
1446
+ const missing = pkg.secrets.filter((name) => !secret(name, storedKeys));
1447
+ const saved = pkg.mcp.filter((need) => mcpMeta.has(need.server));
1448
+ const unsaved = pkg.mcp.filter((need) => !saved.includes(need));
1449
+ const needed = unsaved.filter((need) => need.required);
1450
+ // A webhook trigger's secret is kept sealed, never in the clear: with no seal key, its create would be refused after
1451
+ // the agent is made, so the apply is refused first, naming each one.
1452
+ const unsealed = sealKeyOf(env[SEAL_KEY_ENV]) ? [] : pkg.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [i] : []));
1453
+ if (missing.length || needed.length || unsealed.length) {
1454
+ const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
1455
+ const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1456
+ const sealing = `Start the server with its launcher, agentrun-serve, which makes and keeps a seal key, or set ${SEAL_KEY_ENV} (32 random bytes in base64) where AgentRun starts, then apply the template again.`;
1457
+ throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`), ...(unsealed.length ? ["a seal key for its webhook trigger's secret"] : [])].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 })), ...unsealed.map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: `This server has no seal key (${SEAL_KEY_ENV}), so it cannot keep the webhook trigger's secret.`, fix: sealing }))] });
1458
+ }
1459
+ // An MCP server the package can do without is skipped, and said: its tools are not granted.
1460
+ 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.` }));
1461
+ const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
1462
+ const picked = override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
1463
+ const model = picked.model;
1464
+ // Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
1465
+ // choice was not an option here (not_set_up_here would read as a run refused until the host has something).
1466
+ const modelWarnings = "warning" in picked && picked.warning ? [{ field: "model", reason: "not_an_option", message: picked.warning }] : [];
1467
+ const defaultTools = "place" in newAgentPlace(boxOffers) ? NEW_AGENT_TOOLS : [];
1468
+ // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1469
+ const server = settings.get();
1470
+ const denied = grants.filter((tool) => { const set = permissionFrom(tool, server); return set.from === "server" && set.permission === "deny"; });
1471
+ const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent was not allowed it: its runs are refused it until the owner changes that setting.` }));
1472
+ // The tools this server's own settings pin (or hold refused for a pin that does not read): a package's pin the agent
1473
+ // store can't keep yet is covered there, so its grant stands; any other such tool is made deny (compiled).
1474
+ // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1475
+ // never), else ask. Deny and pins hold either way.
1476
+ const chosenApprovals = approvals ?? pkg.approvals;
1477
+ const serverPinned = new Set(Object.entries(settings.get()).filter(([, one]) => one?.pin || one?.brokenPin).map(([name]) => name));
1478
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), serverPinned, ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
1479
+ // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1480
+ // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1481
+ const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
1482
+ if (refusedTriggers.length)
1483
+ throw invalid(refusedTriggers);
1484
+ // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
1485
+ for (const one of [made.agent, ...made.triggers])
1486
+ if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
1487
+ throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
1488
+ const { entry, warnings } = await createAgentOf(made.agent);
1489
+ const ids = [];
1490
+ // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
1491
+ // /triggers hands back its own, so the owner can give it to the sender.
1492
+ const secrets = [];
1493
+ // A github trigger on a server GitHub is not connected to is skipped, never the apply: the agent stands, and the
1494
+ // answer says to connect GitHub and apply again (a warning under triggers.<i>).
1495
+ const unconnected = new Set();
1496
+ try {
1497
+ for (const [i, trigger] of made.triggers.entries()) {
1498
+ try {
1499
+ const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
1500
+ ids.push(madeId);
1501
+ if (secret)
1502
+ secrets.push({ trigger_id: madeId, secret });
1503
+ }
1504
+ catch (error) {
1505
+ if (error instanceof ApiError && error.code === "github_not_connected" && isObject(trigger.source) && trigger.source.kind === "github") {
1506
+ unconnected.add(i);
1507
+ continue;
1508
+ }
1509
+ if (error instanceof ApiError && error.code === "input_invalid" && error.extra.fields)
1510
+ throw told(new ApiError("input_invalid", error.message, { ...error.extra, fields: error.extra.fields.map((f) => ({ ...f, field: `triggers.${i}.${f.field}` })) }));
1511
+ throw error;
1512
+ }
1513
+ }
1514
+ }
1515
+ catch (error) {
1516
+ for (const id of ids.reverse()) {
1517
+ try {
1518
+ await triggers.remove(id);
1519
+ }
1520
+ catch (undo) {
1521
+ log?.(logLine("template_undo_failed", { template: pkg.name, trigger: id, message: undo.message }));
1522
+ }
1523
+ }
1524
+ // Archived through the trigger engine, as POST /agents/{id}/archive is: a trigger the undo could not remove is turned
1525
+ // off in that same store transaction with the reason agent_archived, never with none, and unarchive answers it.
1526
+ await triggers.agentArchived(entry.agent.id).catch((undo) => log?.(logLine("template_undo_failed", { template: pkg.name, agent: entry.agent.id, message: undo.message })));
1527
+ throw error;
1528
+ }
1529
+ // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1530
+ 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.` }));
1531
+ // A pin this server's agent store does not keep yet (tool-plane.ts AGENT_LAYER_PINS): said, with the setting that holds
1532
+ // the send to its destination meanwhile, the server's.
1533
+ const unkept = made.unkept.map(({ tool, pin }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: serverPinned.has(tool) ? `${tool} is not pinned to ${pinWords(pin)} for this agent yet (this server's agent store keeps an agent's own pin from the store cutover on); this server's own pin of ${tool} holds its calls meanwhile.` : `${tool} is not pinned to ${pinWords(pin)} for this agent yet: this server's agent store keeps an agent's own pin from the store cutover on. Until then the agent was made with ${tool} set to deny, so nothing it reads can send it elsewhere. Pin it on this server, which holds every agent's calls of ${tool}, and apply again to let it.`, ...(serverPinned.has(tool) ? {} : { fix: `Add ${JSON.stringify({ [tool]: { pin } })} to this server's tool settings (Settings → Tools; PUT /v2/settings/tools replaces the whole map, so send it with the rest).` }) }));
1534
+ // A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
1535
+ // MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
1536
+ const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
1537
+ // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
1538
+ const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1539
+ // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
1540
+ const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
1541
+ ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: GITHUB_TRIGGER_UNCONNECTED } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
1542
+ : []));
1543
+ // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1544
+ // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1545
+ const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
1546
+ 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, ...unkept, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1547
+ return { applied, minted };
1548
+ }
1549
+ /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
1550
+ * with the documented run bodies; a workflow run's its workflow's input schema, never the agentic example. Each value
1551
+ * suggested must pass this route's own checks of the body, the workflow's input check among them. */
1552
+ async function explainRun(issues, body, revision) {
1553
+ const dsl = revision?.kind === "workflow" ? await import("@parcha/agentrun-dsl") : undefined;
1554
+ const workflow = dsl && revision?.kind === "workflow" ? revision.body.workflow : undefined;
1555
+ const declared = workflow?.input?.schemaId === undefined ? undefined : workflow.schemas[workflow.input.schemaId];
1556
+ const input = !dsl ? DEFAULT_INPUT_SCHEMA : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
1557
+ const base = deref(openapi, { $ref: "#/components/schemas/RunCreate" }) ?? {};
1558
+ const schema = { ...base, properties: { ...base.properties, input } };
1559
+ const check = (sent) => {
1560
+ const value = isObject(sent) ? sent : {};
1561
+ const issues = runBodyIssues(value);
1562
+ if (!revision || !isObject(value.input))
1563
+ return issues;
1564
+ return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, DEFAULT_INPUT_SCHEMA))];
1565
+ };
1566
+ return explain(issues, openapi, schema, { examples: dsl ? [] : examplesOf("createRun"), body, check });
1567
+ }
1075
1568
  /** A run's input: an agentic run's `{content: string}`, a workflow run's what its workflow's input schema takes. */
1076
1569
  async function inputIssuesOf(revision, input) {
1077
1570
  if (revision.kind === "agentic")
1078
1571
  return inputIssues(input, DEFAULT_INPUT_SCHEMA);
1079
1572
  const { validateWorkflow } = await import("@parcha/agentrun-dsl");
1573
+ return workflowInputIssues(validateWorkflow, revision, input);
1574
+ }
1575
+ /** A workflow run's input against its workflow's input schema, as the DSL checks it before the first node. */
1576
+ function workflowInputIssues(validateWorkflow, revision, input) {
1577
+ if (revision.kind !== "workflow")
1578
+ return [];
1080
1579
  const checked = validateWorkflow(revision.body.workflow, { executeCode: false, input });
1081
- return checked.ok ? [] : checked.issues.map((i) => ({ field: `input${i.path ? ` at ${i.path}` : ""}`, reason: "invalid", message: `the workflow does not take this input: ${i.code}${i.path ? ` at ${i.path}` : ""}` }));
1580
+ if (checked.ok)
1581
+ return [];
1582
+ return checked.issues.map((i) => {
1583
+ // An input problem has no path of its own; its message names the schema's path and why (the DSL's schemaProblems
1584
+ // reports schema paths, never the input's data), so it is said as it is, and the field carries that path (#1926).
1585
+ const said = !i.path && i.code === "INPUT_INVALID" && i.message ? i.message.replace(/^input:\s*/, "") : `${i.code}${i.path ? ` at ${i.path}` : ""}`;
1586
+ const at = i.path || /^(#\/\S*?):\s/.exec(said)?.[1];
1587
+ return { field: `input${at ? ` at ${at}` : ""}`, reason: "invalid", message: `the workflow does not take this input: ${said}` };
1588
+ });
1082
1589
  }
1590
+ /** Where a person opens a page an answer to `req` names (a run's or an agent's console_url, console-links.ts): the
1591
+ * server's public URL when it has one; else the address the request reached it at, which passed the Host check (a
1592
+ * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
1593
+ * at the public URL or the server's own address. */
1594
+ const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
1083
1595
  async function createRun(req, agentId) {
1084
1596
  const entry = await needAgent(agentId);
1085
1597
  if (entry.agent.archivedAt)
1086
- throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: entry.agent.archivedAt } });
1598
+ 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() } });
1087
1599
  const body = await bodyOf(req);
1088
1600
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
1089
1601
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -1092,20 +1604,108 @@ async function startHolding(options, data, lock, checked, stops) {
1092
1604
  if (first.existing?.fingerprint !== origin.fingerprint)
1093
1605
  throw mismatch();
1094
1606
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1095
- return { status: 202, body: await runs.view(await needRun(first.runId)), headers };
1607
+ return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1096
1608
  }
1097
1609
  const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
1098
- // Its view from the run itself: it is written, with its first message, so an answer read from the store, which a
1099
- // busy store would turn into home_busy, would refuse a run that runs, and a retry would start a second one.
1100
- return { status: 202, body: await runs.view(run, { stored: null }), headers: { location: `/v2/runs/${run.id}` } };
1610
+ // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
1611
+ return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
1101
1612
  });
1102
1613
  }
1614
+ /** POST /runs: a run of an agent another system owns, given inline. The body is POST /agents/{agent_id}/runs' own, but
1615
+ * `revision` (the run's revision is its external version's), with the agent's reference in its source (`external`) and
1616
+ * the agent as POST /agents takes one (`definition`, `skills`, `note`), checked as that route checks it, in its words.
1617
+ * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
1618
+ * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
1619
+ async function createInlineRun(req) {
1620
+ const body = await bodyOf(req);
1621
+ const { external, definition, skills, note, revision: pinned, ...run } = body;
1622
+ const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
1623
+ const issues = [
1624
+ ...externalIssues(external),
1625
+ ...(pinned !== undefined ? [{ field: "revision", reason: "not_allowed", message: "An inline run pins no revision: it runs the revision of its external version.", fix: "Remove revision." }] : []),
1626
+ ...runBodyIssues(run),
1627
+ ...definitionBodyIssues(given),
1628
+ // The agent's id is this server's, one per external reference, and its version is the reference's.
1629
+ ...["id", "version"].flatMap((key) => (isObject(definition) && definition[key] !== undefined ? [{ field: `definition.${key}`, reason: "not_allowed", message: `An inline agent's ${key} is its external reference's: the definition names none.`, fix: `Remove definition.${key}.` }] : [])),
1630
+ ];
1631
+ if (issues.length)
1632
+ throw invalid(issues);
1633
+ const checked = checkDefinitionBody(given);
1634
+ const revision = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
1635
+ // Refused where POST /agents refuses the definition (one this host can never run); what this host still lacks for it
1636
+ // is the run's own refusal (prepareLaunch's runnable), as for a run of a stored agent.
1637
+ await saveable(revision);
1638
+ const ref = external;
1639
+ const inline = {
1640
+ external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
1641
+ name: checked.definition.name,
1642
+ description: typeof checked.definition.description === "string" ? checked.definition.description : null,
1643
+ revision,
1644
+ };
1645
+ return idempotent(req, "/runs", body, async (origin) => {
1646
+ // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
1647
+ const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
1648
+ if (first) {
1649
+ if (first.existing?.fingerprint !== origin.fingerprint)
1650
+ throw mismatch();
1651
+ const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1652
+ return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
1653
+ }
1654
+ const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}) });
1655
+ return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
1656
+ });
1657
+ }
1658
+ /** An inline run's `external`, field by field: its source and kind (no colon, which the reference's key splits on), its
1659
+ * id in its source (text), and its version there (text or a whole number). */
1660
+ function externalIssues(external) {
1661
+ if (external === undefined)
1662
+ return [{ field: "external", reason: "missing", message: "external is the agent's reference in the system that owns it: {source, kind, id, version}" }];
1663
+ if (!isObject(external))
1664
+ return [{ field: "external", reason: "wrong_type", message: "external is an object: {source, kind, id, version}" }];
1665
+ const issues = unknownFields(external, ["source", "kind", "id", "version"]).map((issue) => ({ ...issue, field: `external.${issue.field}`, message: `external keeps no field ${issue.field}.` }));
1666
+ for (const key of ["source", "kind"]) {
1667
+ const value = external[key];
1668
+ if (value === undefined)
1669
+ issues.push({ field: `external.${key}`, reason: "missing", message: `external.${key} is required` });
1670
+ else if (typeof value !== "string")
1671
+ issues.push({ field: `external.${key}`, reason: "wrong_type", message: `external.${key} is text` });
1672
+ else if (!EXTERNAL_NAME.test(value))
1673
+ issues.push({ field: `external.${key}`, reason: "bad_format", message: `external.${key} does not match ${EXTERNAL_NAME.source}` });
1674
+ }
1675
+ if (external.id === undefined)
1676
+ issues.push({ field: "external.id", reason: "missing", message: "external.id is required" });
1677
+ else if (typeof external.id !== "string" || external.id.length < 1 || external.id.length > 255)
1678
+ issues.push({ field: "external.id", reason: "wrong_type", message: "external.id is the agent's id in its source: text of 1 to 255 characters" });
1679
+ const { version } = external;
1680
+ if (version === undefined)
1681
+ issues.push({ field: "external.version", reason: "missing", message: "external.version is required" });
1682
+ else if (!((typeof version === "string" && version.length >= 1 && version.length <= 128) || (Number.isSafeInteger(version) && version >= 0)))
1683
+ issues.push({ field: "external.version", reason: "wrong_type", message: "external.version is the agent's version in its source: text of 1 to 128 characters, or a whole number" });
1684
+ return issues;
1685
+ }
1103
1686
  /** A run of `entry`'s agent from a create's body, checked as POST /agents/{id}/runs checks it: that route's, and a
1104
1687
  * trigger's firing's, which names itself as the run's `trigger`. Under `origin`, a key that already started a run
1105
1688
  * gets that run (the agent store's run_origins). */
1106
1689
  /** `capped`: the run must have a cap (a trigger's), its own or else its agent's default. */
1107
- async function startRunOf(entry, body, { trigger, origin, capped = false } = {}) {
1108
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id"]);
1690
+ /** `from`: who the run's first message is from when the person did not write it (a trigger's firing). */
1691
+ async function startRunOf(entry, body, options = {}) {
1692
+ // Every check the old start made, in the same order and words, now lives in the run write half (runs-over-store.startRun,
1693
+ // over StartDeps): the body's fields, the revision it pins, the input against its schema, the cap rules, the plane this
1694
+ // host resolves, whether the revision can run here — then an INSERT of a queued run and its launch in one transaction,
1695
+ // which a runner reads at its claim. No process, no door, no setup file.
1696
+ return startRun(store, startDeps, entry, body, options);
1697
+ }
1698
+ /** The revision a run of `entry` starts on: the one `body.revision` pins, else the agent's current; undefined when the
1699
+ * pin names none, or the agent has no revision. */
1700
+ async function pinnedOf(entry, body) {
1701
+ const found = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
1702
+ // A store RevisionRow is the same revision the run path reads as a pi Revision (its body is the revision body JSON); the
1703
+ // run write half (StartDeps) types it as Revision, so the row is handed across as one.
1704
+ return found ? { revision: found.revision, version: found.version } : undefined;
1705
+ }
1706
+ /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
1707
+ function runBodyIssues(body) {
1708
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id"]);
1109
1709
  if (!isObject(body.input))
1110
1710
  issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
1111
1711
  if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
@@ -1114,35 +1714,11 @@ async function startHolding(options, data, lock, checked, stops) {
1114
1714
  issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
1115
1715
  if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
1116
1716
  issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
1717
+ if (body.cap_mode !== undefined && !CAP_MODES.includes(body.cap_mode))
1718
+ issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
1117
1719
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
1118
1720
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
1119
- if (issues.length)
1120
- throw invalid(issues);
1121
- if (body.quote_id !== undefined)
1122
- throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
1123
- // Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
1124
- const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
1125
- const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
1126
- if (!pinned)
1127
- throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
1128
- const { revision, version } = pinned;
1129
- if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
1130
- throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
1131
- const input = body.input;
1132
- const wrong = await inputIssuesOf(revision, input);
1133
- if (wrong.length)
1134
- throw invalid(wrong);
1135
- // The run's own cap, else the agent's default (an agentic revision's): the caller chose its own.
1136
- const cap = typeof body.max_cost_usd === "number" ? body.max_cost_usd : revision.kind === "agentic" ? revision.body.maxCostUsd : undefined;
1137
- if (capped && cap === undefined)
1138
- throw invalid([{ field: "max_cost_usd", reason: "missing", message: "Every run a trigger starts is capped: give the trigger's target a max_cost_usd or set the agent's." }]);
1139
- const place = resolvePlace(revision.body.place);
1140
- await runnable(revision, place, { capped: cap !== undefined });
1141
- // The title shows on the run's page, the runs list and Mission Control: built from its input as shown, each held
1142
- // value redacted before a long one is cut (a cut key could no longer be found), and the run gets its input as given.
1143
- const shown = redactedOutput(input, learningSecrets());
1144
- const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, isObject(shown) ? shown : {}) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
1145
- return runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(cap !== undefined ? { maxCostUsd: cap } : {}), ...(trigger ? { trigger } : {}), ...(origin ? { origin } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
1721
+ return issues;
1146
1722
  }
1147
1723
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
1148
1724
  /** A list's `archived`: true lists only what is archived, false (the default) only what is not. */
@@ -1152,7 +1728,7 @@ async function startHolding(options, data, lock, checked, stops) {
1152
1728
  throw new ApiError("bad_request", "archived is true or false");
1153
1729
  return value === "true";
1154
1730
  }
1155
- async function runsPage(url, filter) {
1731
+ async function runsPage(url, filter, origin) {
1156
1732
  const limit = limitOf(url.searchParams.get("limit"));
1157
1733
  const offset = cursorOf(url.searchParams.get("cursor"));
1158
1734
  const status = url.searchParams.get("status");
@@ -1162,19 +1738,18 @@ async function startHolding(options, data, lock, checked, stops) {
1162
1738
  if (value !== undefined && !ID.test(value))
1163
1739
  throw new ApiError("bad_request", `${key} is an id`);
1164
1740
  const archived = archivedParam(url);
1165
- let rows = (await agents.request(() => agents.store.listRuns(filter))).filter((row) => Boolean(row.archivedAt) === archived);
1741
+ const vd = viewDepsFor(origin);
1742
+ let rows = (await listRunsOverStore(store, filter, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
1166
1743
  if (status !== null) {
1167
- const statuses = await Promise.all(rows.map((row) => runs.statusOfRow(row)));
1744
+ // The v2 status is the run view's (store-view over the journal), per row.
1745
+ const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
1168
1746
  rows = rows.filter((_, i) => statuses[i] === status);
1169
1747
  }
1170
- const versions = new Map();
1171
- for (const agent of new Set(rows.slice(offset, offset + limit).map((row) => row.agent)))
1172
- for (const r of await agents.revisions(agent))
1173
- versions.set(r.id, r.version);
1174
- const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => runs.summaryOfRow(row, versions)));
1748
+ // summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
1749
+ const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => summaryOverStore(store, row.id, vd)));
1175
1750
  return { runs: page, next_cursor: nextCursor(offset + limit, rows.length) };
1176
1751
  }
1177
- async function timeline(req, res, url, run) {
1752
+ async function timeline(req, res, url, runId) {
1178
1753
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
1179
1754
  const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
1180
1755
  // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
@@ -1182,12 +1757,11 @@ async function startHolding(options, data, lock, checked, stops) {
1182
1757
  if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
1183
1758
  throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
1184
1759
  const limit = asked === null ? PAGE_ROWS : Number(asked);
1185
- const pageOf = async (from, wait) => {
1186
- const page = await runs.page(run, from, wait, limit);
1187
- return { run_id: run.id, status: page.status, state: page.state, reset: page.reset, rows: page.rows, drop: page.drop, next_after: page.next_after, unchanged: page.unchanged, has_more: page.has_more, final: page.final, cost: runs.cost(run) };
1188
- };
1760
+ // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
1761
+ // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
1762
+ // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
1189
1763
  if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
1190
- const page = await pageOf(after, waitMs);
1764
+ const page = await timelines.page(store, runId, after, waitMs, limit);
1191
1765
  return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
1192
1766
  }
1193
1767
  const last = req.headers["last-event-id"];
@@ -1198,9 +1772,20 @@ async function startHolding(options, data, lock, checked, stops) {
1198
1772
  const beat = setInterval(() => res.write(": keepalive\n\n"), 15_000);
1199
1773
  let open = true;
1200
1774
  res.once("close", () => void (open = false));
1775
+ // The live wake: watchRun (live/stream.ts) signals a new journal commit or the run's end, so the page is re-read at
1776
+ // once instead of only on a poll. A run with no watch (gone, or a store with no live) falls back to a 1s re-read; the
1777
+ // page it serves is byte-identical either way.
1778
+ const stream = await watchRun(store, runId).catch(() => undefined);
1779
+ let notify;
1780
+ stream?.start(() => notify?.());
1781
+ const nextChange = (ms) => new Promise((resolve) => {
1782
+ const t = setTimeout(() => ((notify = undefined), resolve()), ms);
1783
+ t.unref?.();
1784
+ notify = () => (clearTimeout(t), (notify = undefined), resolve());
1785
+ });
1201
1786
  try {
1202
1787
  for (let first = true; open; first = false) {
1203
- const page = await pageOf(cursor, first ? 0 : 15_000);
1788
+ const page = await timelines.page(store, runId, cursor, 0, limit);
1204
1789
  if (!open)
1205
1790
  break;
1206
1791
  if (first || !page.unchanged || page.final)
@@ -1210,117 +1795,57 @@ async function startHolding(options, data, lock, checked, stops) {
1210
1795
  res.write(`event: end\ndata: ${JSON.stringify({ reason: "terminal" })}\n\n`);
1211
1796
  break;
1212
1797
  }
1798
+ // Until the next commit, the run's end, or 15s (the keepalive cadence; a run with no watch re-reads every 1s).
1799
+ await Promise.race([nextChange(stream ? 15_000 : 1_000), ...(stream ? [stream.closed] : [])]);
1213
1800
  }
1214
1801
  }
1215
1802
  finally {
1216
1803
  clearInterval(beat);
1804
+ await stream?.stop().catch(() => { });
1217
1805
  res.end();
1218
1806
  }
1219
1807
  }
1220
- const fileView = (path, st) => ({ path, size_bytes: st.size, modified_at: new Date(st.mtimeMs).toISOString(), content_type: typeOf(path) ?? null });
1221
- /** The files under `base` (a run's work/, an agent's home), through no link (workspace.ts): each regular file's own size
1222
- * and time, a dot-name left out. `deep` when a directory below WALK_DEPTH was there and not entered. In a `home`, a
1223
- * host-owned name at its top is the host's: named in `owned`, and nothing below it walked. */
1224
- async function walk(base, home = false) {
1225
- const out = [];
1226
- const owned = [];
1227
- let deep = false;
1228
- if (!(await lstat(base).catch(() => null))?.isDirectory())
1229
- return { files: out, deep, owned };
1230
- // The directory unreadable as a whole lists nothing; what the walk could not read in it is left out.
1231
- await walkWork(base, (path, st, readable) => {
1232
- if (st.isFile())
1233
- out.push({ ...fileView(path, st), ...(readable ? {} : { unreadable: true }) });
1234
- else if (st.isDirectory() && path.split("/").length > WALK_DEPTH)
1235
- deep = true;
1236
- return out.length <= FILE_LIST_CAP;
1237
- }, {
1238
- skip: (name, path) => {
1239
- if (name.startsWith("."))
1240
- return true;
1241
- if (!home || path !== name || !hostOwnedOf(name))
1242
- return false;
1243
- owned.push(name);
1244
- return true;
1245
- },
1246
- }).catch((error) => {
1247
- if (!(error instanceof WorkRefused))
1248
- throw error;
1249
- });
1250
- return { files: out, deep, owned };
1251
- }
1252
- /** The file `rel` under `root`, raw; `unreadable` says why one this server cannot read is private. */
1253
- async function sendFile(req, res, url, root, rel, unreadable) {
1254
- if (!(await lstat(root).catch(() => null))?.isDirectory())
1255
- throw new ApiError("not_found", "no such file");
1256
- // Through no link, held from the open to the last byte (workspace.ts): a name swapped for one is refused, not followed.
1257
- const opened = await openWorkFile(root, rel).catch((error) => {
1258
- if (error instanceof WorkRefused && error.reason === "unreadable")
1259
- throw new ApiError("system_file_forbidden", `This file was created private by ${unreadable}: this server cannot read it.`, { details: { reason: "unreadable" } });
1260
- return null;
1261
- });
1262
- if (!opened)
1263
- throw new ApiError("not_found", "no such file");
1264
- const { handle, stats: st } = opened;
1265
- const type = typeOf(rel) ?? "application/octet-stream";
1266
- const download = url.searchParams.get("download") === "1" || !INLINE_TYPES.has(type);
1267
- const name = rel.split("/").at(-1).replace(/[^\w.-]/g, "_");
1268
- res.writeHead(200, {
1269
- "content-type": type,
1270
- "content-length": st.size,
1271
- "x-content-type-options": "nosniff",
1272
- "cache-control": "no-store",
1273
- ...(type.startsWith("text/html") ? { "content-security-policy": FILE_CSP } : {}),
1274
- ...(download ? { "content-disposition": `attachment; filename="${name}"` } : {}),
1275
- });
1276
- if (req.method === "HEAD" || st.size === 0) {
1277
- await handle.close();
1278
- return void res.end();
1279
- }
1280
- await pipeline(handle.createReadStream(), res).catch(() => undefined);
1281
- await handle.close().catch(() => undefined);
1282
- }
1808
+ // ---- files ----------------------------------------------------------------------------------------------------------
1809
+ // A run's Workspace (its files' list and reads) is the store-backed run reads' now (run-reads-over-store, E2c, over the
1810
+ // run's launch place with run-workspace.ts), not a local folder off the data directory. Removed with the file routes.
1283
1811
  // ---- an agent's home --------------------------------------------------------------------------------------------------
1284
- /** The agent's home, `homes/<its home key>/`: null while nothing was ever written to it, made with homes/ (0700) when
1285
- * `make`. Neither is ever a link: a read finds no home there, and a write is refused. */
1286
- async function homeDir(agentId, make) {
1287
- const home = homeOf(data, agentId);
1288
- for (const dir of [join(data, HOMES_DIR), home]) {
1289
- // One made is synced into its parent, so a write in it that is answered survives a crash of the machine.
1290
- if (make && (await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => (error.code === "EEXIST" ? false : Promise.reject(error)))))
1291
- await syncDir(dirname(dir));
1292
- if ((await lstat(dir).catch(() => null))?.isDirectory())
1293
- continue;
1294
- if (make)
1295
- throw new WorkRefused(dir, "link");
1296
- return null;
1812
+ /** Agent `agentId`'s home as its Workspace (paths.ts agentHomeFolder): null while nothing was ever written to it. With
1813
+ * `make`, its folder and each above it under the data directory are made (0700) where absent, each one made synced
1814
+ * into its parent, so a write in it that is answered survives a crash of the machine. Never a link: a read finds no
1815
+ * home there, and a write is refused. */
1816
+ async function homeWorkspace(agentId, make) {
1817
+ const root = agentHomeFolder(data, agentId);
1818
+ if (make) {
1819
+ let dir = data;
1820
+ for (const part of relative(data, root).split(sep)) {
1821
+ dir = join(dir, part);
1822
+ if (await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => (error.code === "EEXIST" ? false : Promise.reject(error))))
1823
+ await syncDir(dirname(dir));
1824
+ }
1297
1825
  }
1298
- return home;
1299
- }
1300
- /** Refused when `rel`'s first segment is, on this disk, the same entry as a host-owned path of the home (home-path.ts):
1301
- * the name check holds for the spellings it knows, and this for any other a disk takes. */
1302
- async function notHostOwned(home, rel, agentId, write) {
1303
- const owned = await ownedByIdentity(home, rel);
1304
- if (owned)
1305
- throw hostOwnedRefusal(owned, agentId, write, ownedReadAt(agentId));
1826
+ if ((await lstat(root).catch(() => null))?.isDirectory())
1827
+ return localWorkspace(root);
1828
+ if (make)
1829
+ throw new ApiError("system_file_forbidden", LINK_REFUSED, { details: { reason: "link" } });
1830
+ return null;
1306
1831
  }
1307
- /** A write to the home or a removal from it refused (workspace.ts), as its answer. */
1832
+ /** A write to the home or a removal from it the Workspace refused, as its answer. */
1308
1833
  function homeRefusal(error) {
1309
- if (!(error instanceof WorkRefused))
1834
+ if (!isWorkspaceError(error))
1310
1835
  throw error;
1311
- if (error.reason === "link")
1312
- throw new ApiError("system_file_forbidden", "A link is on the way to this path, or is the file: this server follows none.", { details: { reason: "link" } });
1313
- if (error.reason === "unreadable")
1836
+ if (error.code === "ESCAPE")
1837
+ throw new ApiError("system_file_forbidden", LINK_REFUSED, { details: { reason: "link" } });
1838
+ const denied = ["EACCES", "EPERM"].includes(error.cause?.code ?? "");
1839
+ if (denied)
1314
1840
  throw new ApiError("system_file_forbidden", "This server may not enter a directory on the way to this path.", { details: { reason: "unreadable" } });
1315
- if (error.reason === "not_regular")
1841
+ if (error.code === "REFUSED" || error.code === "EXISTS" || error.code === "NOT_FOUND")
1316
1842
  throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
1317
- if (error.reason === "unheld")
1318
- throw new ApiError("unsupported_here", HOME_WRITES_OFF);
1319
- throw new ApiError("not_found", "no such file");
1843
+ throw error;
1320
1844
  }
1321
1845
  // ---- usage ----------------------------------------------------------------------------------------------------------
1322
- // Each ended run's meters, from its store (meterFiguresIn): kept, as its store no longer changes, keyed by its end, so a run
1323
- // opened again and ended again is read again. A store that cannot be read leaves it all tokens.
1846
+ // Each ended run's meters, over the one store (store-reads/cap metersOverStore, cap.ts meterFiguresFrom over A's journal):
1847
+ // kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
1848
+ // again. A run whose journal cannot be read leaves it all tokens.
1324
1849
  const endedMeters = new Map();
1325
1850
  // 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
1326
1851
  // its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
@@ -1329,28 +1854,24 @@ async function startHolding(options, data, lock, checked, stops) {
1329
1854
  const savedSoFarOf = (row) => {
1330
1855
  const key = `${row.id} ${row.endedAt}`;
1331
1856
  if (!endedSoFar.has(key)) {
1857
+ // 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
1858
+ // (runStorePath is gone). Undefined until the usage route reads it over the store.
1332
1859
  let usd;
1333
- try {
1334
- const kept = JSON.parse(readFileSync(join(dirname(dirname(agents.store.runStorePath(row.id))), RUN_META), "utf8")).cost_so_far?.so_far_usd;
1335
- usd = typeof kept === "number" && Number.isFinite(kept) ? kept : undefined;
1336
- }
1337
- catch {
1860
+ {
1338
1861
  usd = undefined;
1339
1862
  }
1340
1863
  endedSoFar.set(key, usd);
1341
1864
  }
1342
1865
  return endedSoFar.get(key);
1343
1866
  };
1344
- const metersOf = (row) => {
1867
+ const metersOf = async (row) => {
1345
1868
  const key = `${row.id} ${row.endedAt}`;
1346
1869
  let meters = endedMeters.get(key);
1347
1870
  if (!meters) {
1348
- try {
1349
- meters = meterFiguresIn(agents.store.runStorePath(row.id));
1350
- }
1351
- catch {
1352
- meters = { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
1353
- }
1871
+ // An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
1872
+ // folded back from the paid-tools session (store-reads/journal withPaidCosts), as meterFiguresIn read a file-backed
1873
+ // run's own database — the same figures (the money-parity rule).
1874
+ meters = await metersOverStore(store, row.id, ctx);
1354
1875
  endedMeters.set(key, meters);
1355
1876
  }
1356
1877
  return meters;
@@ -1389,26 +1910,29 @@ async function startHolding(options, data, lock, checked, stops) {
1389
1910
  const at = Date.parse(row.startedAt);
1390
1911
  if (!(at >= from && at < to))
1391
1912
  continue;
1392
- const live = row.state === "running" ? await runs.get(row.id) : null;
1393
- const usd = live ? runs.cost(live).usd : (row.costUsd ?? null);
1913
+ // A running run's cost is its booked-so-far spend (store-reads/runs listRuns reads it over the store with
1914
+ // spentOverStore); an ended run's is its stored cost. A null cost (a running run with none yet) counts unpriced.
1915
+ const usd = row.costUsd ?? null;
1394
1916
  const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
1395
1917
  // By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
1396
1918
  // `tokens`, all from the same records: a live run's rows (a call still marked is no charge), else its store as it
1397
1919
  // ended (a call a crash cut makes `tools` unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
1398
1920
  // An ended run's are its store's figures (metersOf keeps them, never its timeline), read for its lines by meter and,
1399
- // by any group, for what a run of unknown cost is known to have spent.
1400
- const read = (group === "meter" && usd !== 0) || usd === null ? (live ? { tools: toolCostOf(live.rows), tokens: null, browser: { usd: toolCostOf(live.rows, "browser"), seconds: null }, others: toolCostOf(live.rows, "browser", true), known: { tokens: 0, browser: knownToolCostOf(live.rows, "browser"), others: knownToolCostOf(live.rows, "browser", true) } } : metersOf(row)) : undefined;
1921
+ // by any group, for what a run of unknown cost is known to have spent. Read once per run (the store read is async): by
1922
+ // meter (its lines and its not-metered calls), and for any group of a run of unknown cost (its known so-far).
1923
+ const all = group === "meter" || usd === null ? await metersOf(row) : undefined;
1924
+ const read = (group === "meter" && usd !== 0) || usd === null ? all : undefined;
1401
1925
  // A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
1402
1926
  // total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
1403
1927
  // the lower bound unpriced_runs says it is.
1404
- const soFar = usd !== null || !read ? 0 : live ? (runs.cost(live).so_far_usd ?? 0) : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
1928
+ const soFar = usd !== null || !read ? 0 : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
1405
1929
  const meters = group === "meter" && usd !== 0 ? read : undefined;
1406
1930
  if (meters && meters.browser.usd !== 0)
1407
1931
  browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
1408
1932
  // Its parts of the lines (usage-lines.ts): an unknown one counts the run unpriced there and adds what is known of it.
1409
1933
  // An unpriced MCP call is in none of them: counted apart as not metered on the tools line, which a $0 run shows only
1410
1934
  // when it made one.
1411
- const unmetered = group !== "meter" ? 0 : ((live ? live.rows.find((one) => one.kind === "usage")?.usage?.not_metered : metersOf(row).notMetered) ?? 0);
1935
+ const unmetered = group !== "meter" ? 0 : (all?.notMetered ?? 0);
1412
1936
  notMetered += unmetered;
1413
1937
  if (unmetered && !lines.has("tools"))
1414
1938
  lines.set("tools", { usd: 0, unpriced: 0 });
@@ -1461,8 +1985,9 @@ async function startHolding(options, data, lock, checked, stops) {
1461
1985
  throw invalid(issues);
1462
1986
  return { password: body.password, body };
1463
1987
  }
1464
- /** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out and GET /v2/auth/session, answered before any
1465
- * credential: their own checks are the setup code (or the token), the password, and the session. */
1988
+ /** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
1989
+ * /v2/auth/session, answered before any credential: their own checks are the setup code (or the token), the password,
1990
+ * and the session. */
1466
1991
  async function ownerRoute(req, res, path, me) {
1467
1992
  const method = path === "/auth/session" || path === "/setup/import" ? "GET" : "POST";
1468
1993
  if (req.method !== method)
@@ -1482,11 +2007,20 @@ async function startHolding(options, data, lock, checked, stops) {
1482
2007
  // The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
1483
2008
  // cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
1484
2009
  const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
1485
- const made = await me.setFirst(password, body.code, byToken, along);
2010
+ // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
2011
+ // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2012
+ const tokenAsCode = typeof body.code === "string" && body.code !== "" && timingSafeEqual(digest(`Bearer ${body.code}`), expected);
2013
+ const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
1486
2014
  if (made === "exists")
1487
2015
  throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
1488
- if (made === "code")
1489
- throw new ApiError("forbidden", "that is not the setup code in the server's log, or it has expired");
2016
+ if (made === "missing")
2017
+ throw new ApiError("forbidden", "this server's setup takes the setup code in its log: send it as code");
2018
+ if (made === "wrong")
2019
+ throw new ApiError("forbidden", "that is not the setup code in the server's log");
2020
+ if (made === "new")
2021
+ throw new ApiError("forbidden", "that setup code expired, or five wrong tries voided it: a new one is in the server's log");
2022
+ // A new password ends every session from before (a reset in another process cleared the old one).
2023
+ viewers.recheck();
1490
2024
  // The count is for the offer, now answered: it stops.
1491
2025
  stopCount();
1492
2026
  // Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
@@ -1517,34 +2051,122 @@ async function startHolding(options, data, lock, checked, stops) {
1517
2051
  }
1518
2052
  case "/auth/sign-in": {
1519
2053
  fromPage(req);
1520
- const allowed = me.allow(req.socket.remoteAddress ?? "unknown");
1521
- if (allowed === "full")
1522
- authFailed("/v2/auth/sign-in", "sign_in_table_full");
1523
- if (allowed !== "ok")
1524
- throw new ApiError("rate_limited", "too many sign-ins; try again later", { retry_after_ms: 900_000 }, { "retry-after": "900" });
2054
+ // The body first: the limit's place is taken only for the password's check, so a body sent slowly holds nothing
2055
+ // of the limit (the request's own timeout bounds it, as on any route).
1525
2056
  const { password } = await passwordIn(req, ["password"], false);
1526
2057
  if (!me.hasPassword())
1527
2058
  throw new ApiError("forbidden", "this server has no password yet: set it on the setup page");
1528
- if (!(await me.check(password))) {
2059
+ // Never refused for good (owner.ts SignInLimit): a try past the limit is told how long to wait, a minute at most.
2060
+ const allowed = me.signIns.allow(clientOf(req));
2061
+ if (!allowed.ok) {
2062
+ const seconds = Math.ceil(allowed.retryAfterMs / 1000);
2063
+ throw new ApiError("rate_limited", `too many sign-ins ${allowed.by === "address" ? "from this address" : "on this server"}; try again in ${seconds} s`, { retry_after_ms: allowed.retryAfterMs }, { "retry-after": String(seconds) });
2064
+ }
2065
+ if (allowed.untracked)
2066
+ authFailed("/v2/auth/sign-in", "sign_in_table_full");
2067
+ // The try holds its place in the server's count while the password is checked: a wrong one is charged.
2068
+ let wrong = false;
2069
+ try {
2070
+ wrong = !(await me.check(password));
2071
+ }
2072
+ finally {
2073
+ allowed.done(wrong);
2074
+ }
2075
+ if (wrong) {
1529
2076
  authFailed("/v2/auth/sign-in", "wrong_password");
1530
2077
  throw new ApiError("unauthenticated", "that is not the password");
1531
2078
  }
1532
2079
  return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
1533
2080
  }
2081
+ // This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
2082
+ // cleared; every other browser's session left as it is. A viewer watching with it is cut off.
1534
2083
  case "/auth/sign-out": {
2084
+ fromPage(req);
2085
+ if (!signedIn(req, me))
2086
+ throw new ApiError("unauthenticated", "this browser is not signed in");
2087
+ for (const value of heldSessions(req))
2088
+ if (me.valid(value))
2089
+ me.revoke(value);
2090
+ viewers.recheck();
2091
+ return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
2092
+ }
2093
+ // Every browser and phone: the sessions' epoch moves on, so every cookie made before is none, this one's too.
2094
+ case "/auth/sign-out-everywhere": {
1535
2095
  fromPage(req);
1536
2096
  if (!signedIn(req, me))
1537
2097
  throw new ApiError("unauthenticated", "this browser is not signed in");
1538
2098
  me.signOutEverywhere();
2099
+ viewers.recheck();
1539
2100
  return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
1540
2101
  }
1541
- case "/auth/session":
1542
- return send(res, 200, { password_set: me.hasPassword(), signed_in: signedIn(req, me) });
2102
+ case "/auth/session": {
2103
+ // Before the owner's password is set: whether setup takes the printed code (a server at a public address, or on a non-loopback listener), so
2104
+ // the page asks for it when opened with no link. Never the code itself.
2105
+ const set = me.hasPassword();
2106
+ // secrets_writable: whether this browser may save a secret (secret-writes.ts mayWriteSecrets, the dispatch check's
2107
+ // own rule), so the console offers a paste only where it would be taken. Answered before the page marks the
2108
+ // request, so its facts are read here: accounts are on, and its session is its password's.
2109
+ const writable = secretsWritableFields({ accounts: true, passwordSession: signedIn(req, me), consoleSession: false, token: req.headers.authorization !== undefined && !signedIn(req, me), loopbackBound: isLoopback(host) });
2110
+ return send(res, 200, { accounts: true, password_set: set, signed_in: signedIn(req, me), ...writable, ...(set ? {} : { setup_code: !me.openSetup }) });
2111
+ }
1543
2112
  }
1544
2113
  throw new ApiError("not_found", `no route /v2${path}`);
1545
2114
  }
1546
2115
  // ---- routing --------------------------------------------------------------------------------------------------------
2116
+ /** A route's answer; a 422's field issues told from the operation's request body schema (explain.ts). */
1547
2117
  async function route(req, res, url, path) {
2118
+ try {
2119
+ return await routeOf(req, res, url, path);
2120
+ }
2121
+ catch (error) {
2122
+ const name = ROUTES.find((r) => r.pattern.test(path) && r.method === req.method)?.name;
2123
+ if (!(error instanceof ApiError) || error.code !== "input_invalid" || !error.extra.fields?.length || !name || explained.has(error))
2124
+ throw error;
2125
+ const body = bodies.get(req);
2126
+ const fields = explain(error.extra.fields, openapi, bodySchemaOf(name), { examples: examplesOf(name), body, check: body && BODY_CHECKS[name]?.(body) });
2127
+ throw new ApiError(error.code, error.message === error.extra.fields[0].message ? fields[0].message : error.message, { ...error.extra, fields }, error.headers);
2128
+ }
2129
+ }
2130
+ /** The 422s already told where they were thrown, with the checks only that place has (a run's, its agent's input). */
2131
+ const explained = new WeakSet();
2132
+ const told = (error) => (explained.add(error), error);
2133
+ /** Each request's body as bodyOf read it, for the 422's suggestions to be checked against. */
2134
+ const bodies = new WeakMap();
2135
+ /** The check of a whole body a route makes before anything else, by operation, for the body sent: what a suggested
2136
+ * value must pass. PUT .../definition's contract body (the definition itself) has none here. */
2137
+ const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating });
2138
+ const BODY_CHECKS = {
2139
+ createAgent: () => definitionCheck(true),
2140
+ updateDefinition: (sent) => ("definition" in sent ? definitionCheck(false) : undefined),
2141
+ // POST /runs' agent, given inline, is POST /agents' body inside its own: checked as that one is.
2142
+ createInlineRun: () => (body) => {
2143
+ const { definition, skills, note } = isObject(body) ? body : {};
2144
+ return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) });
2145
+ },
2146
+ };
2147
+ /** An operation's documented request bodies (its JSON media type's examples), each its value. */
2148
+ function examplesOf(operationId) {
2149
+ for (const item of Object.values(openapi.paths)) {
2150
+ for (const op of Object.values(item)) {
2151
+ if (op.operationId !== operationId)
2152
+ continue;
2153
+ const media = op.requestBody?.content?.["application/json"] ?? {};
2154
+ return Object.values(media.examples ?? {}).map((example) => example.value);
2155
+ }
2156
+ }
2157
+ return [];
2158
+ }
2159
+ /** An operation's JSON request body schema in the served document, if it has one. */
2160
+ function bodySchemaOf(operationId) {
2161
+ for (const item of Object.values(openapi.paths)) {
2162
+ for (const op of Object.values(item)) {
2163
+ if (op.operationId === operationId)
2164
+ return deref(openapi, op.requestBody?.content?.["application/json"]?.schema);
2165
+ }
2166
+ }
2167
+ return undefined;
2168
+ }
2169
+ async function routeOf(req, res, url, path) {
1548
2170
  const matching = ROUTES.filter((r) => r.pattern.test(path));
1549
2171
  // `/v2` twice: a path an answer gives (upload.url, a Location) appended to the /v2 base, where it starts at the root.
1550
2172
  if (!matching.length)
@@ -1552,15 +2174,65 @@ async function startHolding(options, data, lock, checked, stops) {
1552
2174
  const found = matching.find((r) => r.method === req.method || (req.method === "HEAD" && r.method === "GET"));
1553
2175
  if (!found)
1554
2176
  throw new ApiError("method_not_allowed", `${req.method} is not a method of ${path}`, {}, { allow: [...new Set(matching.map((r) => r.method))].join(", ") });
1555
- if (found.name === "getCapabilities")
1556
- return send(res, 200, forCaller(caps, byOwnerSession(req)));
2177
+ if (found.name === "getCapabilities") {
2178
+ // features.computers: the computer kinds this server offers now (computers.ts), read at each answer, since turning
2179
+ // Archil on or off, or saving a key, changes them.
2180
+ const answer = forCaller(caps, byOwnerSession(req));
2181
+ return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
2182
+ }
1557
2183
  if (found.name === "getOpenapi")
1558
2184
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
1559
- // The one route with no token: a webhook trigger's request, checked by its signature before anything else is read.
1560
- if (found.name === "receiveHook")
1561
- return hook(req, res, path);
2185
+ // With accounts off there is no owner, and the console still asks whether it may save a secret: secret-writes.ts'
2186
+ // verdict over the request the page just marked, never a signed-in user it doesn't have.
2187
+ if (found.name === "getAuthSession")
2188
+ return send(res, 200, { accounts: false, ...secretsWritableFields(secretWriterFacts(req, { accounts: false, loopbackBound: isLoopback(host) })) });
2189
+ // The one route with no token: a pushed trigger source's request, checked by its source before anything else is
2190
+ // read (push-handler.ts).
2191
+ if (found.name === "receiveHook") {
2192
+ // A body cut at its cap or its time is answered, then its socket closed: never read to its end.
2193
+ 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]);
2194
+ return send(res, answer.status, answer.body, answer.headers ?? {});
2195
+ }
2196
+ // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2197
+ // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2198
+ if (found.name === "mcpOAuthCallback") {
2199
+ // Its state's start set a cookie in the browser that started it: no other browser finishes that sign-in.
2200
+ const state = url.searchParams.get("state");
2201
+ if (!startedHere(req.headers.cookie, req.socket.localPort, state))
2202
+ throw new ApiError("forbidden", "This sign-in was started in another browser, or its 10 minutes are over: start it again in Settings → MCP servers, in this browser.");
2203
+ const location = await mcpServers.oauthCallback(url.searchParams, stopping.signal);
2204
+ // A sign-in that finished kept the server's tools again: the grant-check snapshot reads them.
2205
+ await refreshMcpMeta();
2206
+ // Its sign-in is over: its cookie goes.
2207
+ return void res.writeHead(302, { location, "cache-control": "no-store", "set-cookie": signInCookie(req.socket.localPort, state, overHttps(req), 0) }).end();
2208
+ }
2209
+ if (found.name === "mcpOAuthClient")
2210
+ return send(res, 200, mcpServers.clientDocument(), { "cache-control": "public, max-age=3600" });
2211
+ // Connect GitHub's two steps back from GitHub: the owner's browser, which carries no token. The callback's state is
2212
+ // its check, with the cookie its start set in that browser; an installation is kept only as GitHub, asked with the
2213
+ // App's own JWT, says it is the App's.
2214
+ // Both answer the browser with where to go, never an error body: on to install the App, or to the console's GitHub
2215
+ // settings, connected or with why not.
2216
+ if (found.name === "gitHubCallback") {
2217
+ const state = url.searchParams.get("state") ?? "";
2218
+ // Another browser's (no cookie for this state) leaves the state as it is, for the browser that started it.
2219
+ if (!state || !gitHubStartedHere(req.headers.cookie, req.socket.localPort, state))
2220
+ return void res.writeHead(302, { location: githubConnect.failed("state_invalid", "the browser brought no cookie for this state"), "cache-control": "no-store" }).end();
2221
+ const { location, installState } = await githubConnect.callback(url.searchParams.get("code"), state, stopping.signal);
2222
+ // Its state's cookie goes; the install state's is set, for the installed redirect GitHub sends this browser to.
2223
+ const cookies = [stateCookie(req.socket.localPort, state, overHttps(req), 0), ...(installState ? [stateCookie(req.socket.localPort, installState, overHttps(req), undefined, INSTALLED_PATH)] : [])];
2224
+ return void res.writeHead(302, { location, "cache-control": "no-store", "set-cookie": cookies }).end();
2225
+ }
2226
+ if (found.name === "gitHubInstalled") {
2227
+ // Bound only by the install state the callback sent GitHub and the cookie it set in this browser.
2228
+ const state = url.searchParams.get("state");
2229
+ const bound = state && gitHubStartedHere(req.headers.cookie, req.socket.localPort, state) ? state : null;
2230
+ const location = await githubConnect.installed(url.searchParams.get("installation_id"), bound, stopping.signal);
2231
+ return void res.writeHead(302, { location, "cache-control": "no-store", ...(bound ? { "set-cookie": stateCookie(req.socket.localPort, bound, overHttps(req), 0, INSTALLED_PATH) } : {}) }).end();
2232
+ }
1562
2233
  if (found.name === "getHealth") {
1563
- const health = await healthOf(data, minFreeBytes);
2234
+ // The store this server opened (SQLite or Postgres), never a second open of the data directory's file.
2235
+ const health = await healthOf(store, data, minFreeBytes);
1564
2236
  return send(res, health.status === "ok" ? 200 : 503, health);
1565
2237
  }
1566
2238
  // Approving a note the grader held for its owner's OK (a risky rule a run's user asked for) takes the owner's
@@ -1577,12 +2249,46 @@ async function startHolding(options, data, lock, checked, stops) {
1577
2249
  authFailed(`/v2${path}`, "approve_without_session");
1578
2250
  throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1579
2251
  }
2252
+ // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
2253
+ // approving a note is (never a token a run, an MCP client or a script may hold).
2254
+ if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
2255
+ const what = found.name.endsWith("Browser") ? "browser" : "computer";
2256
+ authFailed(`/v2${path}`, `${what}_without_session`);
2257
+ throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
2258
+ }
2259
+ // A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
2260
+ if (COMPUTER_ROUTES.has(found.name) && !byOwnerSession(req) && req.headers.authorization !== undefined)
2261
+ authFailed(`/v2${path}`, "computer_without_session");
1580
2262
  // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
1581
2263
  // token, which the run's own process, an agent's MCP client or a script may hold.
1582
2264
  if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1583
2265
  authFailed(`/v2${path}`, "approve_without_session");
1584
2266
  throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1585
2267
  }
2268
+ // Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
2269
+ // owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
2270
+ // non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
2271
+ // What a stored predicate read to let the request through (SecretRequest.seen): the operation's write is refused if
2272
+ // that changed before it lands, so a write allowed against one stored credential never lands over another.
2273
+ let secretSeen;
2274
+ if (isSecretWriteOperation(found.name) && req.headers.authorization !== undefined && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
2275
+ const body = req.method === "DELETE" || req.method === "GET" ? undefined : await bodyOf(req).catch(() => undefined);
2276
+ // A segment that is not valid percent-encoding is taken as it came: the request goes on to the token's own check.
2277
+ const params = (found.pattern.exec(path) ?? []).slice(1).map((part) => {
2278
+ try {
2279
+ return part === undefined ? "" : decodeURIComponent(part);
2280
+ }
2281
+ catch {
2282
+ return part;
2283
+ }
2284
+ });
2285
+ const checked = { params, store };
2286
+ if (await writesSecretFor(found.name, body, checked)) {
2287
+ authFailed(`/v2${path}`, "secret_without_session");
2288
+ throw new ApiError("forbidden", SECRET_WRITE_REFUSAL);
2289
+ }
2290
+ secretSeen = checked.seen;
2291
+ }
1586
2292
  if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
1587
2293
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
1588
2294
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
@@ -1595,14 +2301,8 @@ async function startHolding(options, data, lock, checked, stops) {
1595
2301
  case "createAgent": {
1596
2302
  const body = await bodyOf(req);
1597
2303
  const answer = await idempotent(req, "/agents", body, async () => {
1598
- let warnings = [];
1599
- // A new agent that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision;
1600
- // one that names a tool the box refuses (browser) keeps the runner, as before.
1601
- const definition = checkDefinitionBody(body);
1602
- const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1603
- const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1604
- const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1605
- return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
2304
+ const { entry, warnings } = await createAgentOf(body);
2305
+ return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
1606
2306
  });
1607
2307
  return send(res, answer.status, answer.body, answer.headers);
1608
2308
  }
@@ -1610,14 +2310,14 @@ async function startHolding(options, data, lock, checked, stops) {
1610
2310
  const limit = limitOf(url.searchParams.get("limit"));
1611
2311
  const offset = cursorOf(url.searchParams.get("cursor"));
1612
2312
  const archived = archivedParam(url);
1613
- const all = (await agents.list()).filter((entry) => Boolean(entry.agent.archivedAt) === archived);
1614
- return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)))), next_cursor: nextCursor(offset + limit, all.length) });
2313
+ const all = await agents.list({ archived });
2314
+ return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, linkOrigin(req), await agentExtra(entry)))), next_cursor: nextCursor(offset + limit, all.length) });
1615
2315
  }
1616
2316
  case "getAgent": {
1617
2317
  const entry = await needAgent(id);
1618
2318
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
1619
2319
  const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
1620
- return send(res, 200, { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), tools }, { etag: etagOf(entry) });
2320
+ return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
1621
2321
  }
1622
2322
  case "updateDefinition": {
1623
2323
  const entry = await needAgent(id);
@@ -1640,14 +2340,15 @@ async function startHolding(options, data, lock, checked, stops) {
1640
2340
  let warnings = [];
1641
2341
  const check = async (revision) => void (warnings = await saveable(revision));
1642
2342
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
1643
- return send(res, 200, { ...agentView(edited, await signIns.view(edited.agent.id), await learningOfAgent(edited)), warnings }, { etag: etagOf(edited) });
2343
+ return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
1644
2344
  }
1645
2345
  case "listRevisions": {
1646
2346
  const entry = await needAgent(id);
1647
2347
  const limit = limitOf(url.searchParams.get("limit"));
1648
2348
  const offset = cursorOf(url.searchParams.get("cursor"));
1649
2349
  const all = await agents.revisions(id);
1650
- const page = await agents.request(() => all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row, agents.store.readRevision(row.id))));
2350
+ // agentRevisions already carries each row's version and current flag; revisionView builds the v2 shape from it.
2351
+ const page = all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row));
1651
2352
  return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
1652
2353
  }
1653
2354
  case "setCurrent": {
@@ -1662,16 +2363,20 @@ async function startHolding(options, data, lock, checked, stops) {
1662
2363
  if (!(await agents.revision(id, revision)))
1663
2364
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
1664
2365
  const moved = await agents.setCurrent(entry, revision);
1665
- return send(res, 200, agentView(moved, await signIns.view(moved.agent.id), await learningOfAgent(moved)), { etag: etagOf(moved) });
2366
+ return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
1666
2367
  }
1667
2368
  case "archiveAgent":
1668
2369
  case "unarchiveAgent": {
1669
- await needAgent(id);
1670
- await agents.setArchived("agent", id, found.name === "archiveAgent");
1671
- if (found.name === "archiveAgent")
1672
- await runs.archived();
2370
+ // An agent another system owns is that system's to keep or drop: archiving it here is refused, as an edit is.
2371
+ refuseExternal((await needAgent(id)).agent);
2372
+ // No run sweep on archive: a runner reads an archived agent's run rows directly, nothing to sweep.
2373
+ // The engine archives (or unarchives) the agent itself: archived, every trigger that runs as it turns off with
2374
+ // agent_archived in that same store transaction; unarchived, none turns on. Never archived first by another path,
2375
+ // which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
2376
+ // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
2377
+ const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
1673
2378
  const entry = await needAgent(id);
1674
- return send(res, 200, agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), { etag: etagOf(entry) });
2379
+ return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), triggers_off: triggersOff }, { etag: etagOf(entry) });
1675
2380
  }
1676
2381
  case "forgetSignIn": {
1677
2382
  await needAgent(id);
@@ -1688,18 +2393,29 @@ async function startHolding(options, data, lock, checked, stops) {
1688
2393
  const answer = await createRun(req, id);
1689
2394
  return send(res, answer.status, answer.body, answer.headers);
1690
2395
  }
2396
+ case "createInlineRun": {
2397
+ const answer = await createInlineRun(req);
2398
+ return send(res, answer.status, answer.body, answer.headers);
2399
+ }
1691
2400
  case "listRuns":
1692
2401
  await needAgent(id);
1693
- return send(res, 200, await runsPage(url, { agent: id }));
2402
+ return send(res, 200, await runsPage(url, { agent: id }, linkOrigin(req)));
1694
2403
  case "listAllRuns": {
1695
2404
  const agent = url.searchParams.get("agent") ?? undefined;
1696
2405
  const revision = url.searchParams.get("revision") ?? undefined;
1697
- return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }));
2406
+ return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
2407
+ }
2408
+ case "getRun": {
2409
+ const view = await viewOverStore(store, id, viewDepsFor(linkOrigin(req)));
2410
+ if (!view)
2411
+ throw new ApiError("not_found", `no run ${id}`);
2412
+ return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
1698
2413
  }
1699
- case "getRun":
1700
- return send(res, 200, await runs.view(await needRun(id)));
1701
2414
  case "getTimeline":
1702
- return timeline(req, res, url, await needRun(id));
2415
+ await needRun(id);
2416
+ // Awaited, not dropped: a throw from the timeline (a run gone mid-stream, a bad page) reaches the router's catch,
2417
+ // which answers; a floated rejection would hang the request with no answer.
2418
+ return await timeline(req, res, url, id);
1703
2419
  case "sendMessage": {
1704
2420
  const run = await needRun(id);
1705
2421
  if (run.kind === "workflow")
@@ -1714,10 +2430,9 @@ async function startHolding(options, data, lock, checked, stops) {
1714
2430
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
1715
2431
  if (content.length > MAX_MESSAGE)
1716
2432
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
1717
- const { mode, messageId } = await runs.message(run, content);
1718
- // The run's state as the message left it, from the run itself: the stored row (its view's) would make a
1719
- // message already taken answer home_busy while another connection holds the agent store.
1720
- const { status, state } = statusOf(run);
2433
+ const { mode, messageId } = await message(store, run, content);
2434
+ // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
2435
+ const { status, state } = await runStatusState(run.id);
1721
2436
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
1722
2437
  });
1723
2438
  return send(res, answer.status, answer.body, answer.headers);
@@ -1731,26 +2446,23 @@ async function startHolding(options, data, lock, checked, stops) {
1731
2446
  const cap = body.max_cost_usd;
1732
2447
  if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
1733
2448
  throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
1734
- if (run.kind === "workflow")
1735
- throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here, so it has no cap to raise." }]);
1736
- const now = run.meta.max_cost_usd;
2449
+ const now = run.maxCostUsd;
1737
2450
  if (now === undefined)
1738
2451
  throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
1739
- const { resumed, messageId, note } = await runs.raiseCap(run, cap);
1740
- const { status, state } = statusOf(run);
2452
+ const { resumed, messageId, note } = await raiseCap(store, run, cap);
2453
+ const { status, state } = await runStatusState(run.id);
1741
2454
  return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
1742
2455
  }
1743
2456
  case "stopRun": {
1744
2457
  const run = await needRun(id);
1745
- const stopped = await runs.stop(run);
1746
- // From the run itself, as a message's answer: a stop that happened is never answered home_busy.
1747
- const { status, state } = statusOf(run);
2458
+ const stopped = await stopRunOverStore(store, run.id);
2459
+ const { status, state } = await runStatusState(run.id);
1748
2460
  return send(res, 200, { run_id: run.id, stopped, status, state });
1749
2461
  }
1750
2462
  case "cancelRun": {
1751
2463
  const run = await needRun(id);
1752
- const requested = await runs.cancel(run);
1753
- return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: statusOf(run).status });
2464
+ const requested = await cancel(store, run);
2465
+ return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: (await runStatusState(run.id)).status });
1754
2466
  }
1755
2467
  case "answerApproval": {
1756
2468
  // The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
@@ -1763,31 +2475,104 @@ async function startHolding(options, data, lock, checked, stops) {
1763
2475
  issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
1764
2476
  if (issues.length)
1765
2477
  throw invalid(issues);
1766
- await runs.approve(run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
2478
+ await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
1767
2479
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
1768
2480
  return void res.end();
1769
2481
  }
1770
2482
  case "archiveRun":
1771
2483
  case "unarchiveRun": {
1772
2484
  const run = await needRun(id);
1773
- await agents.setArchived("run", run.id, found.name === "archiveRun");
1774
- if (found.name === "archiveRun")
1775
- await runs.archived();
1776
- return send(res, 200, await runs.view(run));
2485
+ await archiveRun(store, run.id, found.name === "archiveRun");
2486
+ return send(res, 200, await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))));
1777
2487
  }
1778
- case "listRunFiles": {
2488
+ case "getRunBrowser":
2489
+ case "getRunComputer": {
2490
+ // One read for both families, over the one store: the computer family's answer, and the browser's own in its base
2491
+ // shape (its link under /browser/live, no kind or hold, off's why as `reason`).
1779
2492
  const run = await needRun(id);
1780
- // A remote box's turn just ended: its pull lands first, so the list shows what the box wrote.
1781
- await runs.pulled(run.id);
1782
- const { files, deep } = await walk(join(run.dir, "work"));
1783
- files.sort((a, b) => a.path.localeCompare(b.path));
1784
- return send(res, 200, { run_id: run.id, files: files.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || files.length > FILE_LIST_CAP });
2493
+ const family = found.name === "getRunBrowser" ? "browser" : "computer";
2494
+ // The run's open viewer, from the store's sealed viewer rows the runner publishes its hand-over into (browser-live.ts
2495
+ // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store.
2496
+ const hold = await computerHoldOf(store, run.id);
2497
+ const kept = await keptBrowserOf(store, run.id);
2498
+ const view = await computerView({
2499
+ viewer: async () => {
2500
+ if (sealKey === undefined)
2501
+ return undefined;
2502
+ if (family === "browser") {
2503
+ const link = await liveViewerLink(store, sealKey, run.id);
2504
+ return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
2505
+ }
2506
+ return computerViewerLink(store, sealKey, run.id);
2507
+ },
2508
+ computer: () => computerOf(kept, env, family),
2509
+ hold: () => hold,
2510
+ });
2511
+ if (family === "browser")
2512
+ 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" });
2513
+ return send(res, 200, view, { "cache-control": "no-store" });
2514
+ }
2515
+ case "handBackRunBrowser": {
2516
+ // The owner's answer to the agent's ask for them in its browser (browser-commands.ts): the first answer wins, the same
2517
+ // one again is that answer, a different one is 409; an ask past its expiry has `expired`. A hand-over command row the
2518
+ // runner reads and applies.
2519
+ const run = await needRun(id);
2520
+ const body = await bodyOf(req);
2521
+ const issues = unknownFields(body, ["outcome"]);
2522
+ if (body.outcome !== "done" && body.outcome !== "cancelled")
2523
+ issues.push({ field: "outcome", reason: body.outcome === undefined ? "missing" : "not_an_option", message: "outcome is done or cancelled" });
2524
+ if (issues.length)
2525
+ throw invalid(issues);
2526
+ // The ask this answer targets, read over the run's hand-over entries and the hand-back commands before this write;
2527
+ // browserHandBack writes the answer (its not_found and handoff_answered words, with details.outcome, as the console
2528
+ // and tests read them), then lets the lowest-id command win, re-reading the journal for a live view's own give.
2529
+ const entries = (await runEntries(store, run.id, ctx));
2530
+ const target = handBackTarget(entries, await store.commands(run.id, 0));
2531
+ const answered = await browserHandBack(store, run.id, body.outcome, target, Date.now(), async () => (await runEntries(store, run.id, ctx)));
2532
+ return send(res, 200, { outcome: answered.outcome }, { "cache-control": "no-store" });
2533
+ }
2534
+ case "takeOverRunComputer":
2535
+ case "handBackRunComputer": {
2536
+ // The owner's take-over of a run's desktop or phone, and the hand-back for every kind (computer-routes.ts), over the
2537
+ // store: the hold is the run's journal, a take-over and a hand-back are command rows its runner applies; a browser's
2538
+ // hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
2539
+ const run = await needRun(id);
2540
+ const answer = await computerRoute(found.name, run.id, {
2541
+ ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, accounts: owner !== undefined, body: await bodyOf(req),
2542
+ }, store, { context: ctx });
2543
+ return send(res, 200, answer, { "cache-control": "no-store" });
2544
+ }
2545
+ case "listComputers":
2546
+ case "saveComputerKeys":
2547
+ case "testComputer": {
2548
+ // Settings → Computers (computers.ts): the rules are the handler's; this sends its answer.
2549
+ const provider = found.name === "listComputers" ? undefined : id;
2550
+ const body = found.name === "saveComputerKeys" ? await bodyOf(req) : undefined;
2551
+ const controller = new AbortController();
2552
+ req.once("close", () => controller.abort());
2553
+ return send(res, 200, await settingsComputerRoute(computersOf(), found.name, { ...(provider !== undefined ? { provider } : {}), ...(body !== undefined ? { body } : {}), signal: controller.signal }), { "cache-control": "no-store" });
2554
+ }
2555
+ case "getWorkspaceArchil":
2556
+ case "putWorkspaceArchil":
2557
+ case "deleteWorkspaceArchil":
2558
+ case "testWorkspaceArchil": {
2559
+ // The owner's Archil settings, Mode 2 on and off (archil-routes.ts): the rules are the handler's.
2560
+ const body = found.name === "putWorkspaceArchil" ? await bodyOf(req) : undefined;
2561
+ const controller = new AbortController();
2562
+ req.once("close", () => controller.abort());
2563
+ return send(res, 200, await archilRoute(archil, found.name, { ...(body !== undefined ? { body } : {}), signal: controller.signal }), { "cache-control": "no-store" });
2564
+ }
2565
+ case "listRunFiles": {
2566
+ await needRun(id);
2567
+ // A run's files through the server's read-only Workspace of its folder (serverRunWorkspace); a run with no folder
2568
+ // lists none, a withheld run refuses (403), as the base did (filesShown). Same shape and cap the file route answered.
2569
+ return send(res, 200, await listRunFilesOverStore(store, id, runReadsDeps));
1785
2570
  }
1786
2571
  // An archived agent's home is read and written as any other's: as its definition is.
1787
2572
  case "listHomeFiles": {
1788
2573
  await needAgent(id);
1789
- const home = await homeDir(id, false);
1790
- const { files, deep, owned } = home ? await walk(home, true) : { files: [], deep: false, owned: [] };
2574
+ const home = await homeWorkspace(id, false);
2575
+ const { files, deep, owned } = home ? await listFiles(home, FILE_LIST_CAP, { owned: (name) => hostOwnedOf(name) !== undefined }) : { files: [], deep: false, owned: [] };
1791
2576
  // A host-owned path there is one entry by its name, and none of what is in it.
1792
2577
  const listed = [...files, ...owned.map((path) => ({ path, host_owned: true }))].sort((a, b) => a.path.localeCompare(b.path));
1793
2578
  return send(res, 200, { agent_id: id, files: listed.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || listed.length > FILE_LIST_CAP });
@@ -1795,11 +2580,10 @@ async function startHolding(options, data, lock, checked, stops) {
1795
2580
  case "readHomeFile": {
1796
2581
  await needAgent(id);
1797
2582
  const rel = homePath(second, id, false, ownedReadAt(id));
1798
- const home = await homeDir(id, false);
2583
+ const home = await homeWorkspace(id, false);
1799
2584
  if (!home)
1800
2585
  throw new ApiError("not_found", "no such file");
1801
- await notHostOwned(home, rel, id, false);
1802
- return sendFile(req, res, url, home, rel, "another user");
2586
+ return sendWorkspaceFile(req, res, url, home, rel, "another user");
1803
2587
  }
1804
2588
  case "writeHomeFile": {
1805
2589
  await needAgent(id);
@@ -1807,25 +2591,30 @@ async function startHolding(options, data, lock, checked, stops) {
1807
2591
  throw new ApiError("unsupported_here", HOME_WRITES_OFF);
1808
2592
  const rel = homePath(second, id, true);
1809
2593
  const bytes = await bytesOf(req);
1810
- // Each write lands whole (a temporary file renamed over the old one); of two at once, the last rename wins.
1811
- const st = await homeDir(id, true)
1812
- .then(async (home) => {
1813
- await notHostOwned(home, rel, id, true);
1814
- return writeWorkFile(home, rel, bytes);
1815
- })
1816
- .catch(homeRefusal);
1817
- return send(res, 200, fileView(rel, st));
2594
+ // Each write lands whole (the Workspace's write is atomic); of two at once, the last one wins.
2595
+ const home = await homeWorkspace(id, true);
2596
+ await home.write(rel, bytes).catch(homeRefusal);
2597
+ const written = await entryAt(home, rel);
2598
+ if (written?.kind !== "file")
2599
+ throw new ApiError("not_found", "no such file");
2600
+ return send(res, 200, viewOf(rel, written));
1818
2601
  }
1819
2602
  case "deleteHomeFile": {
1820
2603
  await needAgent(id);
1821
2604
  if (!homeWrites)
1822
2605
  throw new ApiError("unsupported_here", HOME_WRITES_OFF);
1823
2606
  const rel = homePath(second, id, true);
1824
- const home = await homeDir(id, false);
2607
+ const home = await homeWorkspace(id, false);
1825
2608
  if (!home)
1826
2609
  throw new ApiError("not_found", "no such file");
1827
- await notHostOwned(home, rel, id, true);
1828
- await removeWorkFile(home, rel).catch(homeRefusal);
2610
+ // A file alone: a folder is refused by the listing; a link (never listed) by the Workspace's remove (ESCAPE).
2611
+ if ((await entryAt(home, rel))?.kind === "dir")
2612
+ throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
2613
+ await home.remove(rel).catch((error) => {
2614
+ if (isWorkspaceError(error, "NOT_FOUND"))
2615
+ throw new ApiError("not_found", "no such file");
2616
+ homeRefusal(error);
2617
+ });
1829
2618
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
1830
2619
  return void res.end();
1831
2620
  }
@@ -1852,14 +2641,25 @@ async function startHolding(options, data, lock, checked, stops) {
1852
2641
  return send(res, 200, { ok: issues.length === 0, issues, warnings });
1853
2642
  }
1854
2643
  case "getRunGraph":
1855
- return send(res, 200, await runs.graph(await needRun(id)));
2644
+ await needRun(id);
2645
+ // The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
2646
+ // a run whose output is withheld is refused (403), as the route refused it.
2647
+ return send(res, 200, await runGraphView(store, id, runReadsDeps));
1856
2648
  case "pauseRun":
1857
- case "resumeRun":
1858
- return send(res, 200, await runs.pause(await needRun(id), found.name === "pauseRun"));
1859
- case "readRunFile": {
2649
+ case "resumeRun": {
2650
+ // A workflow run's pause or resume is a command its runner reads and applies (runs-over-store.pauseOrResume): an
2651
+ // agentic run has none (501, its turn is stopped instead), an ended or cancelling one takes none (409). The route
2652
+ // adds the run's status from its view.
1860
2653
  const run = await needRun(id);
1861
- await runs.pulled(run.id);
1862
- return sendFile(req, res, url, join(run.dir, "work"), checkedPath(decodedPath(second), "the run's own, not a file it wrote"), "a tool in the run's box");
2654
+ const { paused } = await (found.name === "pauseRun" ? pauseRunOverStore : resumeRunOverStore)(store, run);
2655
+ const { status } = await runStatusState(run.id);
2656
+ return send(res, 200, { run_id: run.id, paused, status });
2657
+ }
2658
+ case "readRunFile": {
2659
+ await needRun(id);
2660
+ // One of a run's files through the server's read-only Workspace, streamed as the file route streams it; a withheld
2661
+ // run refuses (403, as filesShown did), the path check and 404 words are the reader's own.
2662
+ return readRunFileOverStore(store, id, second, req, res, url, runReadsDeps);
1863
2663
  }
1864
2664
  case "createFile": {
1865
2665
  // A `path` in the query, or a body that is not JSON: the file sent in one call, its bytes the body. Else the
@@ -1901,15 +2701,19 @@ async function startHolding(options, data, lock, checked, stops) {
1901
2701
  return send(res, 200, await usage(url));
1902
2702
  case "getStats": {
1903
2703
  const filter = analyticsFilter(url);
1904
- // A run this server holds as ended whose end the store does not have yet is pending: counted as it ended, its
1905
- // metrics left out until the store has them (stats.ts pendingOf).
1906
- const [stats, analytics, rows, pending] = await agents.request(() => {
1907
- const stats = agents.store.stats();
1908
- const pending = pendingOf(stats.running, runs);
1909
- return [stats, agents.store.analytics({ ...filter, pending }), agents.store.listRuns(), pending];
1910
- });
1911
- // How the runs that tried to learn fared: a held run's learning from memory, any other's end from the ledger.
1912
- return send(res, 200, { ...statsView(stats, runs, pending), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
2704
+ // The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
2705
+ // runs over the store for the learning counts. No in-process pending set and no held Runs: the runner writes a
2706
+ // run's end to the store before it lets it go.
2707
+ const [s, a] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter })]);
2708
+ // Each running row's status over the store (viewOverStore), for the active/needs_input/unknown buckets.
2709
+ const vd = viewDepsFor(ownOriginOf());
2710
+ const runningStatus = new Map();
2711
+ await Promise.all(s.running.map(async (id) => { const v = await viewOverStore(store, id, vd); if (v?.status)
2712
+ runningStatus.set(id, v.status); }));
2713
+ // How the runs that tried to learn fared, over the store (learning-1's learningCountsOverStore): the same figures the
2714
+ // ledger gave, run for run; no held run's learning from memory.
2715
+ const learning = await learningCountsOverStore(store, filter);
2716
+ return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: analyticsView(a, filter), learning });
1913
2717
  }
1914
2718
  case "listToolKeys":
1915
2719
  // The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
@@ -1923,27 +2727,73 @@ async function startHolding(options, data, lock, checked, stops) {
1923
2727
  // directory and its keys by now.
1924
2728
  if (stopping.signal.aborted)
1925
2729
  throw new ApiError("unavailable", "The server is shutting down: the key was not saved.");
1926
- toolKeys.save(id, body, check);
2730
+ await toolKeys.save(id, body, check);
1927
2731
  await keysChanged();
1928
2732
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
1929
2733
  }
1930
2734
  case "deleteToolKey":
1931
- toolKeys.remove(id);
2735
+ await toolKeys.remove(id);
1932
2736
  await keysChanged();
1933
2737
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
1934
2738
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
1935
2739
  case "listMcpServers":
1936
- return send(res, 200, mcpServers.list());
2740
+ return send(res, 200, await mcpServers.list());
1937
2741
  case "getMcpServer":
1938
- return send(res, 200, mcpServers.get(id));
2742
+ return send(res, 200, await mcpServers.get(id));
1939
2743
  case "previewMcpServer":
1940
2744
  return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
1941
- case "saveMcpServer":
1942
- return send(res, 200, await mcpServers.save(id, await bodyOf(req), stopping.signal));
1943
- case "refreshMcpServer":
1944
- return send(res, 200, await mcpServers.refresh(id, stopping.signal));
2745
+ case "saveMcpServer": {
2746
+ const saved = await mcpServers.save(id, await bodyOf(req), stopping.signal, secretSeen);
2747
+ await refreshMcpMeta();
2748
+ return send(res, 200, saved);
2749
+ }
2750
+ case "refreshMcpServer": {
2751
+ const refreshed = await mcpServers.refresh(id, stopping.signal);
2752
+ await refreshMcpMeta();
2753
+ return send(res, 200, refreshed);
2754
+ }
2755
+ case "startMcpOAuth": {
2756
+ // The cookie is set on the address the request came to, and the authorization server sends the browser back
2757
+ // to the callback's: they must be the one origin, or the callback never sees the cookie. The redirect URI
2758
+ // stays that one address (a registered client names it), and a start from another answers where to go.
2759
+ const origin = mcpServers.callbackOrigin;
2760
+ if (ownOrigin(req) !== origin)
2761
+ throw new ApiError("wrong_origin", `This server's sign-in comes back to ${origin}, and finishes only in a browser that started it there: open the console at ${origin}${MCP_SETTINGS_PAGE} and sign in from it.`, { details: { open: `${origin}${MCP_SETTINGS_PAGE}` } });
2762
+ const started = await mcpServers.oauthStart(id, await bodyOf(req));
2763
+ const state = new URL(started.authorization_url).searchParams.get("state") ?? "";
2764
+ return send(res, 200, started, { "set-cookie": signInCookie(req.socket.localPort, state, overHttps(req)) });
2765
+ }
2766
+ case "connectGitHub": {
2767
+ const started = githubConnect.start(await bodyOf(req), ownOrigin(req));
2768
+ // The callback finishes only in this browser: the cookie it brings back names this state.
2769
+ return send(res, 200, started, { "set-cookie": stateCookie(req.socket.localPort, started.state, overHttps(req)) });
2770
+ }
2771
+ case "getGitHubConnection": {
2772
+ // Repaired from GitHub's own first, at most once a minute: a missed installation event is put right here.
2773
+ await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
2774
+ // Always a 200: not connected is an answer, never an error a browser logs as one.
2775
+ const view = githubConnection();
2776
+ return send(res, 200, view ? { connected: true, ...view } : { connected: false });
2777
+ }
2778
+ case "disconnectGitHub": {
2779
+ const view = githubConnection();
2780
+ if (!view)
2781
+ throw new ApiError("not_found", "No GitHub App is connected to this server.");
2782
+ const settingsUrl = github.settingsUrl();
2783
+ // Awaited: the App's rows go before the answer, so a Connect right after never races their removal.
2784
+ await github.remove();
2785
+ // Kept, and off: an agent keeps its triggers, which go on again once GitHub is connected again.
2786
+ const off = await triggers.turnOff("github", "GitHub was disconnected from this server: connect it again in Settings, then turn the trigger on.");
2787
+ log?.(logLine("github", { condition: "github_disconnected", app_id: view.app_id, triggers_off: off }));
2788
+ return send(res, 200, { disconnected: true, triggers_off: off, note: `Delete the App itself on GitHub: ${settingsUrl}` });
2789
+ }
2790
+ case "getMcpPrivateHosts":
2791
+ return send(res, 200, await privateHostsRoute(mcpServers, { method: "GET" }), { "cache-control": "no-store" });
2792
+ case "putMcpPrivateHosts":
2793
+ return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
1945
2794
  case "deleteMcpServer":
1946
- mcpServers.remove(id);
2795
+ await mcpServers.remove(id, secretSeen);
2796
+ await refreshMcpMeta();
1947
2797
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
1948
2798
  case "getToolSettings":
1949
2799
  return send(res, 200, withDefaults(settings.get()));
@@ -1954,7 +2804,7 @@ async function startHolding(options, data, lock, checked, stops) {
1954
2804
  const issues = settingsIssues(body);
1955
2805
  if (issues.length)
1956
2806
  throw invalid(issues);
1957
- settings.put(body);
2807
+ await settings.put(body);
1958
2808
  // A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
1959
2809
  recompose();
1960
2810
  return send(res, 200, withDefaults(settings.get()));
@@ -1963,19 +2813,24 @@ async function startHolding(options, data, lock, checked, stops) {
1963
2813
  // they are now; a write as the definition's: an archived agent's too.
1964
2814
  case "getAgentLearning": {
1965
2815
  await needAgent(id);
1966
- const rows = await agents.request(() => agents.store.listRuns({ agent: id }));
1967
- // Counted as GET /stats counts (learning-run.ts counts): a held run from memory, any other's end from the ledger;
1968
- // what learning changed, from the same rows and ledger (learningImpact).
1969
- const { counts, impact } = await runs.learning.ofAgent(rows, id);
1970
- return send(res, 200, await agentLearning(data, id, secretsShown(learningSecrets()), counts, impact));
2816
+ // The agent's learning view: its notes, skills, workflows and log from its learning folder; its run-fared counts, each
2817
+ // note's runs (given it and that read it) and its impact over the one store (agentLearningOverStore), from each run's
2818
+ // launch, journal and learning end.
2819
+ const { counts, impact, notes } = await agentLearningOverStore(store, id);
2820
+ return send(res, 200, await agentLearning(data, id, secretsShown(serverSecrets()), counts, impact, notes));
1971
2821
  }
1972
2822
  case "listLearningNotes":
1973
2823
  case "listLearningLog":
1974
2824
  await needAgent(id);
1975
- return send(res, 200, await (found.name === "listLearningNotes" ? learningNotes : learningLog)(data, id, url.searchParams, secretsShown(learningSecrets())));
2825
+ if (found.name === "listLearningNotes") {
2826
+ // The notes from the agent's learning folder, each with its runs over the one store (agentLearningOverStore's noteRuns).
2827
+ const { notes } = await agentLearningOverStore(store, id);
2828
+ return send(res, 200, await learningNotes(data, id, url.searchParams, secretsShown(serverSecrets()), notes));
2829
+ }
2830
+ return send(res, 200, await learningLog(data, id, url.searchParams, secretsShown(serverSecrets())));
1976
2831
  case "readLearningFile":
1977
2832
  await needAgent(id);
1978
- return sendNote(res, 200, await readNote(data, id, second, secretsShown(learningSecrets())));
2833
+ return sendNote(res, 200, await readNote(data, id, second, secretsShown(serverSecrets())));
1979
2834
  case "writeLearningFile":
1980
2835
  case "retireLearningFile":
1981
2836
  case "approveLearningFile":
@@ -1983,22 +2838,31 @@ async function startHolding(options, data, lock, checked, stops) {
1983
2838
  await needAgent(id);
1984
2839
  const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
1985
2840
  const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
1986
- const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile" });
2841
+ const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: serverSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile", draftTools: () => learnedDraftToolsOf(id) });
1987
2842
  // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
1988
- const shown = secretsShown(learningSecrets());
2843
+ const shown = secretsShown(serverSecrets());
1989
2844
  const located = written.status === 201 && shown.name(written.file) === written.file;
1990
2845
  return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
1991
2846
  }
1992
- case "getRunLearning":
1993
- return send(res, 200, await runLearning(await needRun(id), secretsShown(learningSecrets()), learningSecrets()));
2847
+ case "getRunLearning": {
2848
+ const run = await needRun(id);
2849
+ // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
2850
+ // from its launch, what it holds for the owner's OK as the store's run view reads it (no folder), byte-identical to main.
2851
+ // Cut by the run's one cut, and refused for a withheld run (run-learning-served.ts).
2852
+ return send(res, 200, await servedRunLearning({ serverSecrets, signIns }, store, run.id));
2853
+ }
1994
2854
  case "getRunLearningDiff":
1995
- return send(res, 200, await runDiff(data, await needRun(id), secretsShown(learningSecrets())));
2855
+ await needRun(id);
2856
+ // TODO(learning-1): the run's learning diff over the store — learning-1's diff read on untangle/cutover-switch-learn, not the run's
2857
+ // .learning/diffs files. Wire when its head lands.
2858
+ return runReadsTodo();
1996
2859
  case "getWebhook":
1997
2860
  return send(res, 200, webhooks.view());
1998
2861
  case "saveWebhook": {
1999
2862
  // Never through `idempotent`: its record would keep the answer, and the first one holds the secret.
2863
+ // Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets its metadata and the words.
2000
2864
  const saved = webhooks.save(await bodyOf(req));
2001
- return send(res, saved.created ? 201 : 200, { ...saved.view, ...(saved.secret ? { secret: saved.secret } : {}) });
2865
+ return send(res, saved.created ? 201 : 200, webhookSaved(saved.view, saved.secret, mayHoldSecrets(req)));
2002
2866
  }
2003
2867
  case "deleteWebhook":
2004
2868
  webhooks.remove();
@@ -2010,7 +2874,7 @@ async function startHolding(options, data, lock, checked, stops) {
2010
2874
  case "redeliverWebhook":
2011
2875
  return send(res, 200, await webhooks.redeliver(id));
2012
2876
  case "listTriggers":
2013
- return send(res, 200, triggers.list());
2877
+ return send(res, 200, { triggers: (await triggers.list()).triggers.map(withSecretOf) });
2014
2878
  case "createTrigger": {
2015
2879
  const body = await bodyOf(req);
2016
2880
  // A webhook trigger's secret is in its first answer alone: the Idempotency-Key's record keeps the trigger and a
@@ -2023,16 +2887,39 @@ async function startHolding(options, data, lock, checked, stops) {
2023
2887
  });
2024
2888
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
2025
2889
  const { note: _, ...first } = answer.body;
2026
- return send(res, answer.status, secret && !replayed ? { ...first, secret } : answer.body, answer.headers);
2890
+ // Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets secret_set and the words.
2891
+ return send(res, answer.status, secret && !replayed ? triggerMade(first, secret, mayHoldSecrets(req), new Date().toISOString()) : answer.body, answer.headers);
2892
+ }
2893
+ case "listTemplates":
2894
+ return send(res, 200, { templates: templates.map(packageView) });
2895
+ case "applyTemplate": {
2896
+ const pkg = templates.find((t) => t.name === id);
2897
+ if (!pkg)
2898
+ throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
2899
+ const body = await bodyOf(req);
2900
+ // The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
2901
+ // keeps a webhook trigger's secret (below).
2902
+ let minted = new Map();
2903
+ const answer = await idempotent(req, `/templates/${pkg.name}/apply`, body, async () => {
2904
+ const made = await applyTemplate(pkg, body);
2905
+ minted = made.minted;
2906
+ return { status: 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
2907
+ });
2908
+ // Each webhook trigger's secret, to the owner's session in this first answer alone (trigger-secrets-shown.ts
2909
+ // templateApplied): the record above never held it, so a replay under the key shows none.
2910
+ const replayed = answer.headers?.["idempotent-replayed"] === "true";
2911
+ const shown = replayed ? "replay" : mayHoldSecrets(req) ? "first" : "token";
2912
+ return send(res, answer.status, answer.status === 201 ? templateApplied(answer.body, minted, shown) : answer.body, answer.headers);
2027
2913
  }
2028
2914
  case "rotateTriggerSecret":
2029
- return send(res, 200, triggers.rotate(id));
2915
+ // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
2916
+ return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
2030
2917
  case "getTrigger":
2031
- return send(res, 200, triggers.get(id));
2918
+ return send(res, 200, withSecretOf(await triggers.get(id)));
2032
2919
  case "updateTrigger":
2033
2920
  return send(res, 200, await triggers.update(id, await bodyOf(req)));
2034
2921
  case "deleteTrigger":
2035
- triggers.remove(id);
2922
+ await triggers.remove(id);
2036
2923
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
2037
2924
  case "fireTrigger": {
2038
2925
  const key = req.headers["idempotency-key"];
@@ -2042,7 +2929,7 @@ async function startHolding(options, data, lock, checked, stops) {
2042
2929
  return send(res, fired.created ? 202 : 200, fired.firing, fired.created ? {} : { "idempotent-replayed": "true" });
2043
2930
  }
2044
2931
  case "listTriggerFirings":
2045
- return send(res, 200, triggers.firings(id));
2932
+ return send(res, 200, await triggers.firings(id));
2046
2933
  }
2047
2934
  throw new ApiError("not_found", `no route ${path}`);
2048
2935
  }
@@ -2053,6 +2940,35 @@ async function startHolding(options, data, lock, checked, stops) {
2053
2940
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
2054
2941
  res.end(text);
2055
2942
  }
2943
+ /** A run's live viewer's page and files (browser-live.ts, /v2/runs/{id}/computer/live/*): the owner's signed-in page
2944
+ * alone, GET or HEAD, for a viewer the run's live process has handed over. The bytes are this server's own copy of pi-browser's viewer, never the run's port's:
2945
+ * only the viewer's WebSocket reaches the run. */
2946
+ async function liveRoute(req, res, runId, family, rest) {
2947
+ if (req.method !== "GET" && req.method !== "HEAD")
2948
+ throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
2949
+ if (!byOwnerSession(req)) {
2950
+ authFailed(`/v2/runs/${runId}/${family}/live`, req.headers.authorization === undefined ? "no_credential" : `${family}_without_session`);
2951
+ throw req.headers.authorization === undefined ? new ApiError("unauthenticated", `a run's live ${family} view takes the owner's password sign-in in the console`) : new ApiError("forbidden", `a run's live ${family} view takes the owner's password sign-in in the console, never a token`);
2952
+ }
2953
+ await needRun(runId);
2954
+ // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim; liveViewerFor picks
2955
+ // a named viewer's handover or the run's open one). None for a run no runner holds; with no seal key this server serves
2956
+ // no live view. A /computer/live path reaches a viewer of every kind (the link GET /computer gives, a browser's among
2957
+ // them), a /browser/live path a browser's alone (familyReaches).
2958
+ const handover = sealKey ? await liveViewerFor(store, sealKey, runId, rest) : undefined;
2959
+ if (handover === undefined || !familyReaches(family, handover))
2960
+ throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
2961
+ await serveViewerFile(req, res, rest);
2962
+ }
2963
+ /** The origin of the address people open (`publicUrl`, AGENTRUN_PUBLIC_URL), lowercased; none, undefined. */
2964
+ const publicOrigin = (() => {
2965
+ try {
2966
+ return options.publicUrl ? new URL(options.publicUrl).origin.toLowerCase() : undefined;
2967
+ }
2968
+ catch {
2969
+ return undefined;
2970
+ }
2971
+ })();
2056
2972
  let names;
2057
2973
  const server = createServer((req, res) => {
2058
2974
  const requestId = `req_${randomBytes(8).toString("hex")}`;
@@ -2066,6 +2982,9 @@ async function startHolding(options, data, lock, checked, stops) {
2066
2982
  const fail = (error) => {
2067
2983
  if (res.headersSent)
2068
2984
  return void res.end();
2985
+ // A request cut before its body was read (push-handler.ts readCapped): its socket goes once the answer is out.
2986
+ if (error instanceof HookCut)
2987
+ res.once("finish", () => req.socket.destroy());
2069
2988
  // A store still busy past a request's wait is home_busy, whichever read or write met it.
2070
2989
  const known = error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : new ApiError("internal", error?.message ?? String(error));
2071
2990
  if (!(error instanceof ApiError) && !storeBusy(error))
@@ -2084,7 +3003,7 @@ async function startHolding(options, data, lock, checked, stops) {
2084
3003
  if (names && !names.has(hostName(req.headers.host) ?? "")) {
2085
3004
  if (/\btext\/html\b/i.test(String(req.headers.accept ?? "")))
2086
3005
  return sendHostRefused(req, res);
2087
- return fail(new ApiError("forbidden", `unexpected Host header: ${HOST_FIX}`));
3006
+ return fail(new ApiError("forbidden", `unexpected Host header: ${hostFix(req.socket.localPort ?? 0)}`));
2088
3007
  }
2089
3008
  // Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
2090
3009
  const raw = (req.url ?? "/").split("?")[0];
@@ -2095,12 +3014,74 @@ async function startHolding(options, data, lock, checked, stops) {
2095
3014
  return void mcp(req, res).catch(fail);
2096
3015
  if (raw === "/llms.txt")
2097
3016
  return void answerLlms(req, res).catch(fail);
2098
- if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}) }))
3017
+ if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
2099
3018
  return;
3019
+ // Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
3020
+ // a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
3021
+ if (options.faux && raw.startsWith(`${FAUX_VIEW_PATH}/`)) {
3022
+ const page = fauxOf().viewPage(raw);
3023
+ if (page === undefined)
3024
+ return fail(new ApiError("not_found", `no faux desktop at ${raw}`));
3025
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(req.method === "HEAD" ? undefined : page);
3026
+ return;
3027
+ }
2100
3028
  if (!raw.startsWith("/v2/"))
2101
3029
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3030
+ // 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
3031
+ // decoded here, where a throw would leave the request listener.
3032
+ const viewing = LIVE_PATH.exec(raw);
3033
+ if (viewing)
3034
+ return ID.test(viewing[1]) ? void liveRoute(req, res, viewing[1], viewing[2], viewing[3]).catch(fail) : fail(new ApiError("not_found", "no run's live view at that address"));
2102
3035
  route(req, res, url, raw.slice(3)).catch(fail);
2103
3036
  });
3037
+ // A request's headers come within 10 s, whatever its route: nothing sends more than a few kilobytes of them. Its body
3038
+ // keeps Node's 5-minute request timeout, which an upload of a large file needs; the token-less hook route has its own
3039
+ // 30 s for its body (push-handler.ts HOOK_BODY_MS), so dribbling senders hold no socket for long.
3040
+ server.headersTimeout = 10_000;
3041
+ // The one upgrade this server takes: a run's live computer viewer's WebSocket (browser-live.ts). Every other is refused.
3042
+ server.on("upgrade", (req, socket, head) => {
3043
+ socket.on("error", () => socket.destroy());
3044
+ const raw = (req.url ?? "/").split("?")[0];
3045
+ const viewing = LIVE_PATH.exec(raw);
3046
+ const deny = (status) => void socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
3047
+ // On loopback, the Host check every route gets (host-check.ts), first: a page that rebound a name of its own to this
3048
+ // address sends its own name as Origin too, which the Origin check below would take, so its Host is what gives it
3049
+ // away. Its name alone, on any port, as the HTTP routes check it.
3050
+ if (names && !names.has(hostName(req.headers.host) ?? ""))
3051
+ return deny("403 Forbidden");
3052
+ if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3053
+ return deny("404 Not Found");
3054
+ // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
3055
+ // (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
3056
+ // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing.
3057
+ const sent = String(req.headers.origin ?? "").toLowerCase();
3058
+ if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
3059
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
3060
+ if (!owner || !signedIn(req, owner))
3061
+ return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
3062
+ // Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
3063
+ let piping = false;
3064
+ void (async () => {
3065
+ const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
3066
+ // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
3067
+ // runner holds; with no seal key no live view is served. A /computer/live socket reaches a viewer of every kind, a
3068
+ // /browser/live socket a browser's alone (familyReaches), as the page does.
3069
+ const viewerHandover = run && sealKey ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
3070
+ const handover = viewerHandover !== undefined && familyReaches(viewing[2], viewerHandover) ? viewerHandover : undefined;
3071
+ if (!handover)
3072
+ return deny("404 Not Found");
3073
+ // Gone during the lookup, or the server is closing and has ended its viewers, or is about to.
3074
+ if (socket.destroyed || closing)
3075
+ return void socket.destroy();
3076
+ // Checked again after the lookup, then for as long as the socket is open: the sessions that let it in, and no other.
3077
+ const held = heldSessions(req);
3078
+ const admitted = () => held.some((value) => owner.valid(value));
3079
+ if (!admitted())
3080
+ return deny("401 Unauthorized");
3081
+ viewers.watch(socket, admitted);
3082
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; });
3083
+ })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
3084
+ });
2104
3085
  const first = options.port ?? DEFAULT_PORT;
2105
3086
  const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
2106
3087
  for (let port = first;; port++) {
@@ -2141,27 +3122,127 @@ async function startHolding(options, data, lock, checked, stops) {
2141
3122
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
2142
3123
  owner?.attach(options.publicUrl ?? url);
2143
3124
  webhooks.attach(options.publicUrl ?? url);
3125
+ mcpServers.attach(options.publicUrl ?? url, url);
3126
+ // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
3127
+ // to the store and this server runs no run, so it follows the store: each read takes the runs not final yet and the
3128
+ // newest runs (one that started and ended between two reads is among them). It tells each end it has not told once the
3129
+ // run reads final, and each wait of a run a runner left parked (or let go of) once it reads input_required. The markers
3130
+ // 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
3131
+ // once across restarts; a start first catches up the ends the ledger lacks, which no server was up to see. A store read
3132
+ // of the runs ended (or parked) since a mark would be the cleaner seam than this read of the open runs every 250 ms.
3133
+ const RUN_ENDS_POLL_MS = 250;
3134
+ const RUN_ENDS_NEWEST = 50;
3135
+ const final = (row) => FINAL_STATES.includes(row.state);
3136
+ const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
3137
+ /** 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. */
3138
+ const endNotice = async (id) => {
3139
+ const row = await store.runs.get(id);
3140
+ const summary = row && (await summaryOverStore(store, id, viewDepsFor(ownOriginOf())));
3141
+ if (!row || !summary)
3142
+ return null;
3143
+ return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
3144
+ };
3145
+ const toldEnds = new Map();
3146
+ /** 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
3147
+ * is not read again, and a new wait comes with a new claim, so a new epoch. */
3148
+ const readWaits = new Map();
3149
+ /** When each held wait (a run waiting on its person with its claim held) was last read again. */
3150
+ const heldReadAt = new Map();
3151
+ const HELD_WAIT_REREAD_MS = 1_000;
3152
+ const waitKinds = new Set(["question", "approval", "budget", "browser"]);
3153
+ /** The wait of a run its runner left parked (or let go of), told once as main told it: its marker the run's last row
3154
+ * that shows (not usage, a phase or learning's), its kind the pending card's (a stop's when it waits on no card). */
3155
+ const tellWait = async (row) => {
3156
+ const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
3157
+ if (readWaits.get(row.id) === seen)
3158
+ return;
3159
+ const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
3160
+ if (view?.status !== "input_required")
3161
+ return void readWaits.set(row.id, seen);
3162
+ const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3163
+ const marker = rows.findLast((r) => r.kind !== "usage" && r.kind !== "phase" && r.agent_label !== LEARNING_LABEL)?.id;
3164
+ if (!marker)
3165
+ return void readWaits.set(row.id, seen);
3166
+ const card = view.pending?.kind;
3167
+ const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3168
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
3169
+ if (webhooks.emit("run.needs_input", notice, marker) !== "unsaved")
3170
+ readWaits.set(row.id, seen);
3171
+ };
3172
+ let openRuns = new Set();
3173
+ let endsTimer;
3174
+ let endsRead = Promise.resolve();
3175
+ const readEnds = async () => {
3176
+ const open = new Set();
3177
+ for (const state of ["queued", "running", "parked"]) {
3178
+ for (const row of await store.runs.list({ state })) {
3179
+ open.add(row.id);
3180
+ // A run waits on its person once its runner has let it go: parked, or running with no runner. Or held in its claim
3181
+ // waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its browser hand-over,
3182
+ // tools.ts), which its row's summary says (HELD_WAITS); a new ask sets it anew, so each is read and told once.
3183
+ const waitsInClaim = row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3184
+ // A held run's next ask in the same claim reads the same row as its last (state, epoch, runner, summary), and the
3185
+ // answer between may come and go within one read: so a held wait is read again now and then (HELD_WAIT_REREAD_MS),
3186
+ // and told once per ask all the same, since each ask's notice is keyed to its own last row (webhooks.ts emit).
3187
+ if (waitsInClaim && Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3188
+ heldReadAt.set(row.id, Date.now());
3189
+ readWaits.delete(row.id);
3190
+ }
3191
+ if (!closing && (row.state === "parked" || (row.state === "running" && row.runner === null) || waitsInClaim))
3192
+ await tellWait(row).catch(() => undefined);
3193
+ }
3194
+ }
3195
+ const newest = await store.runs.list({ limit: RUN_ENDS_NEWEST });
3196
+ for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
3197
+ if (open.has(id) || closing)
3198
+ continue;
3199
+ const now = await endNotice(id).catch(() => undefined);
3200
+ // Unread (a busy store): read again at the next turn, never lost.
3201
+ if (now === undefined) {
3202
+ open.add(id);
3203
+ continue;
3204
+ }
3205
+ readWaits.delete(id);
3206
+ heldReadAt.delete(id);
3207
+ if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3208
+ continue;
3209
+ if (webhooks.emit("run.ended", now.notice, now.endedAt) !== "unsaved")
3210
+ toldEnds.set(id, now.endedAt);
3211
+ }
3212
+ openRuns = open;
3213
+ };
3214
+ const followEnds = () => {
3215
+ if (closing)
3216
+ return;
3217
+ endsRead = readEnds()
3218
+ .catch((error) => log?.(logLine("webhook", { condition: "run_ends_unread", error: error.message })))
3219
+ .finally(() => {
3220
+ if (!closing)
3221
+ (endsTimer = setTimeout(followEnds, RUN_ENDS_POLL_MS)).unref();
3222
+ });
3223
+ };
3224
+ void store.runs
3225
+ .list({})
3226
+ .then((rows) => webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), endNotice))
3227
+ .catch((error) => log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))
3228
+ .finally(followEnds);
2144
3229
  const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
2145
3230
  /** The server's stop: once (`close` keeps its promise). */
2146
3231
  let stopped;
2147
3232
  async function stop() {
2148
- // First, the record a start on this data root waits on while the runs' processes drain and exit (server-lock.ts),
2149
- // rewritten in place: this close's bound, with time for the deliveries and the listener after them. One not
2150
- // written leaves a start refused.
2151
- const { runs: busy, boundMs } = runs.stopping();
2152
- try {
2153
- markStopping(data, Date.now() + boundMs + STOP_MARGIN_MS);
2154
- }
2155
- catch (error) {
2156
- const fields = { reason: error.code ?? error.message };
2157
- void (log ? log(logLine("stopping_mark_unwritten", fields)) : process.stderr.write(`agentrun-serve: ${logLine("stopping_mark_unwritten", fields)}\n`));
2158
- }
2159
- if (busy > 0)
2160
- noticeOf(options)(`stopping: waiting up to ${seconds(boundMs)} for ${busy === 1 ? "1 run to finish its turn" : `${busy} runs to finish their turn`}`);
2161
- // An import under way stops between two session files and is waited for: nothing writes the store after close. A
2162
- // count writes nothing (it lists and reads), so it is ended at once: its listing of a big home checks for no stop.
3233
+ // The server writes rows and a runner (its own process) runs every run, so this stop drains no run process and writes
3234
+ // no "stopping" mark for a start to wait on: the store's EXCLUSIVE lock is this server's one-server lock, released as
3235
+ // the store closes, and the next server takes it. The deliveries, the import, the installs and the listener stop first;
3236
+ // the store closes last.
2163
3237
  closing = true;
2164
3238
  stopping.abort();
3239
+ // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
3240
+ const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
3241
+ // Aborted now, so nothing it writes races the next server on the same refresh token; drained before the store closes.
3242
+ const mcpStopped = mcpServers.close();
3243
+ // A repair of the GitHub installations under way stops waiting on GitHub and writes nothing from here: before the
3244
+ // triggers close, so it never turns one off into a closed file.
3245
+ const githubStopped = githubConnect.close();
2165
3246
  triggers.close();
2166
3247
  for (const [worker, { task }] of workers) {
2167
3248
  if (task === "plan")
@@ -2171,18 +3252,22 @@ async function startHolding(options, data, lock, checked, stops) {
2171
3252
  }
2172
3253
  await Promise.all([...workers.values()].map((w) => w.exit));
2173
3254
  await importing;
2174
- // Runs that end while their processes stop still give their notices; then the deliveries stop, before the lock goes.
2175
- await runs.close();
2176
- await relay?.close();
2177
- // Before the lock goes: the image's last record lands first (box-image.ts), never after the next server's start.
3255
+ await installStopped;
3256
+ // Before the store closes: the image's last record lands first (box-image.ts), never after the next server's start.
2178
3257
  await image?.close();
2179
3258
  // The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
2180
3259
  await egress?.close();
3260
+ // The ends' follower stops before the webhooks it feeds and the store it reads.
3261
+ clearTimeout(endsTimer);
3262
+ await endsRead;
2181
3263
  await webhooks.close();
3264
+ // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
3265
+ viewers.close();
2182
3266
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
2183
- agents.close();
2184
- // The record stays: the next server rewrites it as it starts, and a stopped one whose time has passed is no stop.
2185
- lock.release();
3267
+ await mcpStopped;
3268
+ await githubStopped;
3269
+ // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
3270
+ await store.close();
2186
3271
  }
2187
3272
  return {
2188
3273
  url,
@@ -2191,10 +3276,12 @@ async function startHolding(options, data, lock, checked, stops) {
2191
3276
  token,
2192
3277
  tokenFile,
2193
3278
  tokenMade: stored?.made ?? false,
2194
- ...(setupUrl ? { setupUrl } : {}),
3279
+ ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
2195
3280
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
2196
3281
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
2197
3282
  // never writes this data root's record again (the next server's, by then).
2198
3283
  close: () => (stopped ??= stop()),
3284
+ // No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
3285
+ stopping: () => ({ runs: 0, boundMs: 0 }),
2199
3286
  };
2200
3287
  }