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

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