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

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 (444) hide show
  1. package/CHANGELOG.md +270 -0
  2. package/README.md +343 -246
  3. package/dist/adapters.d.ts +0 -7
  4. package/dist/adapters.js +11 -22
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +14 -0
  14. package/dist/api-only.js +33 -0
  15. package/dist/archil-routes.d.ts +1 -1
  16. package/dist/bash-read-only.d.ts +22 -0
  17. package/dist/bash-read-only.js +701 -0
  18. package/dist/box-egress-vm.d.ts +0 -8
  19. package/dist/box-egress-vm.js +0 -10
  20. package/dist/box-egress.d.ts +0 -4
  21. package/dist/box-egress.js +1 -16
  22. package/dist/box-paths.d.ts +25 -2
  23. package/dist/box-paths.js +79 -11
  24. package/dist/box-relay.d.ts +0 -11
  25. package/dist/box-relay.js +0 -20
  26. package/dist/box-settings.d.ts +26 -0
  27. package/dist/box-settings.js +63 -0
  28. package/dist/boxes.d.ts +21 -1
  29. package/dist/boxes.js +27 -20
  30. package/dist/browser-commands.d.ts +5 -2
  31. package/dist/browser-commands.js +4 -4
  32. package/dist/browser-computer.d.ts +5 -0
  33. package/dist/browser-computer.js +21 -0
  34. package/dist/browser-cost.d.ts +9 -6
  35. package/dist/browser-cost.js +94 -51
  36. package/dist/browser-live.d.ts +7 -20
  37. package/dist/browser-live.js +15 -93
  38. package/dist/browser-person.d.ts +18 -53
  39. package/dist/browser-person.js +94 -279
  40. package/dist/budget.d.ts +0 -4
  41. package/dist/budget.js +0 -7
  42. package/dist/cap.d.ts +8 -12
  43. package/dist/cap.js +12 -27
  44. package/dist/cli.js +61 -20
  45. package/dist/closed-pipes.d.ts +2 -0
  46. package/dist/closed-pipes.js +13 -0
  47. package/dist/computer-commands.d.ts +2 -0
  48. package/dist/computer-commands.js +2 -0
  49. package/dist/computer-keys.js +5 -2
  50. package/dist/computer-setting.d.ts +20 -4
  51. package/dist/computer-setting.js +25 -5
  52. package/dist/computers.d.ts +31 -3
  53. package/dist/computers.js +70 -11
  54. package/dist/confine.d.ts +120 -0
  55. package/dist/confine.js +436 -0
  56. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  57. package/dist/console/assets/index-opTN5Naq.css +1 -0
  58. package/dist/console/index.html +2 -2
  59. package/dist/daytona-api.d.ts +0 -11
  60. package/dist/daytona-api.js +1 -82
  61. package/dist/decision-rows.d.ts +1 -1
  62. package/dist/decision-rows.js +1 -1
  63. package/dist/docker-daemon.d.ts +31 -0
  64. package/dist/docker-daemon.js +56 -0
  65. package/dist/docker-host-addresses.d.ts +37 -0
  66. package/dist/docker-host-addresses.js +110 -0
  67. package/dist/effort-guidance.js +4 -3
  68. package/dist/environment.d.ts +0 -3
  69. package/dist/environment.js +3 -5
  70. package/dist/errors.d.ts +0 -2
  71. package/dist/errors.js +6 -9
  72. package/dist/filed-answer.d.ts +32 -0
  73. package/dist/filed-answer.js +160 -0
  74. package/dist/files.d.ts +1 -11
  75. package/dist/files.js +2 -21
  76. package/dist/github-connection.d.ts +2 -2
  77. package/dist/github-connection.js +1 -1
  78. package/dist/graph-view.d.ts +3 -5
  79. package/dist/graph-view.js +4 -14
  80. package/dist/handed-values.d.ts +9 -0
  81. package/dist/handed-values.js +26 -0
  82. package/dist/harness-install.d.ts +22 -5
  83. package/dist/harness-install.js +98 -20
  84. package/dist/harness-opencode/adapter.d.ts +7 -0
  85. package/dist/harness-opencode/adapter.js +23 -6
  86. package/dist/harness-opencode/index.d.ts +1 -1
  87. package/dist/harness-opencode/index.js +1 -1
  88. package/dist/harness-opencode/verify.d.ts +17 -0
  89. package/dist/harness-opencode/verify.js +30 -10
  90. package/dist/harness-table.js +6 -1
  91. package/dist/harness.d.ts +4 -3
  92. package/dist/harness.js +16 -1
  93. package/dist/heard.js +1 -1
  94. package/dist/held-fd.d.ts +5 -0
  95. package/dist/held-fd.js +14 -0
  96. package/dist/host-calls.d.ts +20 -0
  97. package/dist/host-calls.js +12 -0
  98. package/dist/host-tools.d.ts +4 -21
  99. package/dist/host-tools.js +4 -61
  100. package/dist/host.d.ts +2 -4
  101. package/dist/host.js +2 -7
  102. package/dist/import-summary.d.ts +1 -5
  103. package/dist/import-summary.js +0 -21
  104. package/dist/import.d.ts +6 -6
  105. package/dist/import.js +62 -24
  106. package/dist/key-refusal.d.ts +5 -1
  107. package/dist/key-refusal.js +19 -4
  108. package/dist/learn/check.d.ts +6 -2
  109. package/dist/learn/check.js +83 -29
  110. package/dist/learn/folder.d.ts +5 -1
  111. package/dist/learn/folder.js +10 -3
  112. package/dist/learn/grade.d.ts +14 -0
  113. package/dist/learn/grade.js +68 -12
  114. package/dist/learn/index.d.ts +4 -4
  115. package/dist/learn/index.js +4 -4
  116. package/dist/learn/reflect.d.ts +31 -2
  117. package/dist/learn/reflect.js +79 -4
  118. package/dist/learn/relevance.d.ts +24 -0
  119. package/dist/learn/relevance.js +91 -0
  120. package/dist/learn/secrets.d.ts +8 -1
  121. package/dist/learn/secrets.js +95 -15
  122. package/dist/learn/skills.d.ts +112 -14
  123. package/dist/learn/skills.js +556 -52
  124. package/dist/learned-workflow.d.ts +37 -5
  125. package/dist/learned-workflow.js +106 -12
  126. package/dist/learning-routes.d.ts +16 -49
  127. package/dist/learning-routes.js +46 -36
  128. package/dist/learning-run.d.ts +6 -250
  129. package/dist/learning-run.js +11 -665
  130. package/dist/learning-words.d.ts +12 -5
  131. package/dist/learning-words.js +18 -9
  132. package/dist/learning.d.ts +93 -77
  133. package/dist/learning.js +176 -304
  134. package/dist/live/stream.js +1 -1
  135. package/dist/live/translate.js +13 -3
  136. package/dist/local-models.d.ts +11 -5
  137. package/dist/local-models.js +13 -8
  138. package/dist/mcp-gateway.d.ts +11 -52
  139. package/dist/mcp-gateway.js +44 -148
  140. package/dist/mcp-oauth.d.ts +10 -14
  141. package/dist/mcp-oauth.js +14 -32
  142. package/dist/mcp-probe.d.ts +0 -7
  143. package/dist/mcp-probe.js +4 -10
  144. package/dist/mcp-servers-store.d.ts +6 -6
  145. package/dist/mcp-servers-store.js +13 -15
  146. package/dist/mcp-store.js +3 -4
  147. package/dist/mcp.js +4 -3
  148. package/dist/model.d.ts +6 -7
  149. package/dist/model.js +43 -27
  150. package/dist/monid.d.ts +0 -2
  151. package/dist/monid.js +3 -6
  152. package/dist/openapi.d.ts +8 -1
  153. package/dist/openapi.js +124 -50
  154. package/dist/page.d.ts +1 -3
  155. package/dist/page.js +9 -19
  156. package/dist/paid-calls.d.ts +21 -27
  157. package/dist/paid-calls.js +28 -62
  158. package/dist/pause.d.ts +0 -2
  159. package/dist/pause.js +1 -8
  160. package/dist/place.d.ts +0 -5
  161. package/dist/place.js +0 -10
  162. package/dist/print.d.ts +2 -1
  163. package/dist/print.js +4 -2
  164. package/dist/propose.js +83 -39
  165. package/dist/push-handler.d.ts +1 -1
  166. package/dist/reflect-range.d.ts +25 -0
  167. package/dist/reflect-range.js +30 -0
  168. package/dist/refusal-words.d.ts +5 -1
  169. package/dist/refusal-words.js +5 -1
  170. package/dist/rows.d.ts +1 -1
  171. package/dist/run-cut.d.ts +0 -6
  172. package/dist/run-cut.js +0 -6
  173. package/dist/run-db.d.ts +2 -13
  174. package/dist/run-db.js +2 -41
  175. package/dist/run-launch.d.ts +19 -2
  176. package/dist/run-launch.js +13 -5
  177. package/dist/run-learning-served.d.ts +46 -2
  178. package/dist/run-learning-served.js +26 -7
  179. package/dist/run-reads-over-store.d.ts +1 -1
  180. package/dist/run-reads-over-store.js +15 -6
  181. package/dist/run-secrets.d.ts +33 -0
  182. package/dist/run-secrets.js +53 -0
  183. package/dist/run-timeline-served.d.ts +5 -1
  184. package/dist/run-timeline-served.js +19 -5
  185. package/dist/run-view.d.ts +12 -17
  186. package/dist/run-view.js +29 -28
  187. package/dist/runnable.d.ts +18 -10
  188. package/dist/runnable.js +21 -10
  189. package/dist/runner/adapter-loop.d.ts +14 -3
  190. package/dist/runner/adapter-loop.js +464 -62
  191. package/dist/runner/adapter-run-spec.d.ts +29 -8
  192. package/dist/runner/adapter-run-spec.js +96 -37
  193. package/dist/runner/adapters/index.js +11 -1
  194. package/dist/runner/adapters/pi.d.ts +15 -1
  195. package/dist/runner/adapters/pi.js +19 -5
  196. package/dist/runner/beside.d.ts +30 -3
  197. package/dist/runner/beside.js +54 -12
  198. package/dist/runner/claim-secrets.d.ts +10 -1
  199. package/dist/runner/claim-secrets.js +49 -15
  200. package/dist/runner/cli-run-spec.d.ts +2 -0
  201. package/dist/runner/cli-run-spec.js +60 -17
  202. package/dist/runner/commands.js +1 -1
  203. package/dist/runner/computer-journal.d.ts +15 -2
  204. package/dist/runner/computer-journal.js +41 -5
  205. package/dist/runner/conformance/harness.js +118 -8
  206. package/dist/runner/conformance/subject.d.ts +4 -1
  207. package/dist/runner/dispatch.d.ts +8 -1
  208. package/dist/runner/dispatch.js +81 -7
  209. package/dist/runner/end-of-run.d.ts +8 -2
  210. package/dist/runner/end-of-run.js +10 -4
  211. package/dist/runner/github-app.js +1 -1
  212. package/dist/runner/harness-loops.d.ts +9 -1
  213. package/dist/runner/harness-loops.js +15 -2
  214. package/dist/runner/journal-kinds.d.ts +30 -6
  215. package/dist/runner/journal-kinds.js +20 -5
  216. package/dist/runner/journal-reader.d.ts +1 -1
  217. package/dist/runner/journal-reader.js +2 -2
  218. package/dist/runner/learning-ask.d.ts +4 -0
  219. package/dist/runner/learning-ask.js +15 -1
  220. package/dist/runner/learning-end.d.ts +18 -3
  221. package/dist/runner/learning-end.js +113 -11
  222. package/dist/runner/learning-loop.d.ts +5 -0
  223. package/dist/runner/learning-loop.js +26 -6
  224. package/dist/runner/live-ticker.d.ts +1 -1
  225. package/dist/runner/live-ticker.js +28 -4
  226. package/dist/runner/loop-contract.d.ts +3 -2
  227. package/dist/runner/main.d.ts +64 -10
  228. package/dist/runner/main.js +165 -27
  229. package/dist/runner/mcp-claim.d.ts +1 -1
  230. package/dist/runner/mcp-claim.js +2 -3
  231. package/dist/runner/mcp-run.d.ts +2 -0
  232. package/dist/runner/mcp-run.js +15 -5
  233. package/dist/runner/memory-claim.d.ts +9 -0
  234. package/dist/runner/memory-claim.js +25 -0
  235. package/dist/runner/metrics.d.ts +33 -1
  236. package/dist/runner/metrics.js +85 -1
  237. package/dist/runner/model-route.d.ts +13 -0
  238. package/dist/runner/model-route.js +154 -11
  239. package/dist/runner/redact.d.ts +8 -2
  240. package/dist/runner/redact.js +11 -2
  241. package/dist/runner/reflect-hook.d.ts +12 -1
  242. package/dist/runner/reflect-hook.js +33 -3
  243. package/dist/runner/runner.d.ts +20 -0
  244. package/dist/runner/runner.js +56 -10
  245. package/dist/runner/store-port.d.ts +1 -1
  246. package/dist/runner/store-secrets.d.ts +3 -3
  247. package/dist/runner/store-secrets.js +8 -12
  248. package/dist/runner/text-tools.d.ts +44 -0
  249. package/dist/runner/text-tools.js +237 -0
  250. package/dist/runner/workflow-loop.d.ts +6 -0
  251. package/dist/runner/workflow-loop.js +6 -4
  252. package/dist/runner/workflow-spec.d.ts +18 -0
  253. package/dist/runner/workflow-spec.js +68 -26
  254. package/dist/runs-over-store.d.ts +8 -3
  255. package/dist/runs-over-store.js +76 -19
  256. package/dist/seal-key.d.ts +54 -15
  257. package/dist/seal-key.js +232 -82
  258. package/dist/sealed-settings-store.d.ts +19 -4
  259. package/dist/sealed-settings-store.js +9 -9
  260. package/dist/sealing.d.ts +4 -0
  261. package/dist/sealing.js +20 -0
  262. package/dist/secret-cut.d.ts +1 -1
  263. package/dist/secret-cut.js +1 -1
  264. package/dist/secret-name.d.ts +9 -0
  265. package/dist/secret-name.js +15 -0
  266. package/dist/secret-writes.d.ts +0 -1
  267. package/dist/secret-writes.js +0 -1
  268. package/dist/secrets.d.ts +2 -10
  269. package/dist/secrets.js +21 -17
  270. package/dist/server-fs.d.ts +4 -0
  271. package/dist/server-fs.js +8 -2
  272. package/dist/server-lock.d.ts +0 -24
  273. package/dist/server-lock.js +1 -80
  274. package/dist/server-secrets-store.d.ts +4 -4
  275. package/dist/server-secrets-store.js +10 -32
  276. package/dist/server-secrets.d.ts +4 -9
  277. package/dist/server-secrets.js +12 -33
  278. package/dist/server.d.ts +26 -44
  279. package/dist/server.js +229 -142
  280. package/dist/sign-ins-store.d.ts +34 -36
  281. package/dist/sign-ins-store.js +27 -38
  282. package/dist/sign-ins.d.ts +2 -119
  283. package/dist/sign-ins.js +5 -311
  284. package/dist/standard-webhooks.d.ts +1 -1
  285. package/dist/standard-webhooks.js +1 -1
  286. package/dist/stats.d.ts +3 -2
  287. package/dist/stats.js +1 -1
  288. package/dist/store/agent-body.d.ts +8 -2
  289. package/dist/store/agent-body.js +16 -4
  290. package/dist/store/index.d.ts +3 -3
  291. package/dist/store/index.js +3 -3
  292. package/dist/store/open.d.ts +18 -5
  293. package/dist/store/open.js +23 -3
  294. package/dist/store/postgres/connection.d.ts +18 -2
  295. package/dist/store/postgres/connection.js +156 -32
  296. package/dist/store/postgres/migrate.d.ts +4 -0
  297. package/dist/store/postgres/migrate.js +27 -3
  298. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  299. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  300. package/dist/store/postgres/store.d.ts +9 -2
  301. package/dist/store/postgres/store.js +9 -0
  302. package/dist/store/schema.js +1 -1
  303. package/dist/store/seal.js +2 -2
  304. package/dist/store/sqlite/connection.js +49 -5
  305. package/dist/store/sqlite/run-patch.d.ts +3 -0
  306. package/dist/store/sqlite/run-patch.js +3 -0
  307. package/dist/store/sqlite/store.js +64 -20
  308. package/dist/store/store.d.ts +38 -6
  309. package/dist/store/store.js +12 -2
  310. package/dist/store-reads/cap.d.ts +1 -1
  311. package/dist/store-reads/cap.js +22 -4
  312. package/dist/store-reads/journal.d.ts +25 -6
  313. package/dist/store-reads/journal.js +173 -21
  314. package/dist/store-reads/learning.d.ts +26 -8
  315. package/dist/store-reads/learning.js +12 -4
  316. package/dist/store-reads/workflow.d.ts +1 -1
  317. package/dist/store-reads/workflow.js +1 -1
  318. package/dist/store-view.d.ts +5 -1
  319. package/dist/store-view.js +91 -23
  320. package/dist/template-eval.d.ts +60 -4
  321. package/dist/template-eval.js +120 -54
  322. package/dist/templates.d.ts +24 -10
  323. package/dist/templates.js +69 -38
  324. package/dist/timeline/group.d.ts +33 -0
  325. package/dist/timeline/group.js +77 -0
  326. package/dist/timeline/index.d.ts +7 -0
  327. package/dist/timeline/index.js +7 -0
  328. package/dist/timeline/labels.d.ts +79 -0
  329. package/dist/timeline/labels.js +150 -0
  330. package/dist/timeline/origin.d.ts +56 -0
  331. package/dist/timeline/origin.js +92 -0
  332. package/dist/timeline/render-text.d.ts +11 -0
  333. package/dist/timeline/render-text.js +62 -0
  334. package/dist/timeline/timeline.d.ts +274 -0
  335. package/dist/timeline/timeline.js +1308 -0
  336. package/dist/timeline/util.d.ts +17 -0
  337. package/dist/timeline/util.js +49 -0
  338. package/dist/tool-gate.d.ts +41 -216
  339. package/dist/tool-gate.js +79 -540
  340. package/dist/tool-keys-store.d.ts +11 -12
  341. package/dist/tool-keys-store.js +24 -31
  342. package/dist/tool-keys.d.ts +9 -104
  343. package/dist/tool-keys.js +15 -271
  344. package/dist/tool-plane.d.ts +14 -42
  345. package/dist/tool-plane.js +23 -81
  346. package/dist/tool-settings-store.d.ts +1 -2
  347. package/dist/tool-settings-store.js +5 -8
  348. package/dist/tools.d.ts +31 -19
  349. package/dist/tools.js +101 -108
  350. package/dist/trigger-adapter.d.ts +2 -2
  351. package/dist/trigger-schedule.js +2 -1
  352. package/dist/trigger-secrets-shown.js +5 -1
  353. package/dist/trigger-targets.d.ts +13 -1
  354. package/dist/trigger-targets.js +31 -1
  355. package/dist/triggers.d.ts +2 -2
  356. package/dist/triggers.js +3 -3
  357. package/dist/turn-end.d.ts +1 -1
  358. package/dist/turn-end.js +1 -1
  359. package/dist/turns.d.ts +0 -6
  360. package/dist/turns.js +0 -19
  361. package/dist/uploads.js +1 -1
  362. package/dist/usage.d.ts +0 -2
  363. package/dist/usage.js +0 -2
  364. package/dist/validate.d.ts +2 -0
  365. package/dist/validate.js +23 -14
  366. package/dist/webhooks.d.ts +102 -76
  367. package/dist/webhooks.js +266 -233
  368. package/dist/workflow-run.d.ts +114 -0
  369. package/dist/workflow-run.js +144 -0
  370. package/dist/workspace/beneath.d.ts +19 -0
  371. package/dist/workspace/beneath.js +106 -0
  372. package/dist/workspace/computer-deps.d.ts +52 -5
  373. package/dist/workspace/computer-deps.js +154 -19
  374. package/dist/workspace/computer-for-claim.d.ts +19 -14
  375. package/dist/workspace/computer-for-claim.js +77 -16
  376. package/dist/workspace/computer-hold.d.ts +6 -1
  377. package/dist/workspace/computer-hold.js +6 -1
  378. package/dist/workspace/computer-janitor.d.ts +47 -0
  379. package/dist/workspace/computer-janitor.js +182 -0
  380. package/dist/workspace/computer-providers.d.ts +6 -2
  381. package/dist/workspace/computer-providers.js +1 -1
  382. package/dist/workspace/grep-worker.d.ts +5 -0
  383. package/dist/workspace/grep-worker.js +9 -6
  384. package/dist/workspace/index.d.ts +4 -3
  385. package/dist/workspace/index.js +4 -4
  386. package/dist/workspace/local.d.ts +11 -2
  387. package/dist/workspace/local.js +161 -43
  388. package/dist/workspace/resolve-computer.d.ts +50 -10
  389. package/dist/workspace/resolve-computer.js +46 -11
  390. package/dist/workspace/run-tools.d.ts +13 -31
  391. package/dist/workspace/run-tools.js +10 -27
  392. package/dist/workspace-paths.d.ts +0 -17
  393. package/dist/workspace-paths.js +1 -41
  394. package/dist/workspace.d.ts +0 -17
  395. package/dist/workspace.js +3 -99
  396. package/launcher/agentrun-serve +6 -33
  397. package/package.json +14 -14
  398. package/templates/README.md +9 -3
  399. package/templates/inbound-lead/agent.md +1 -1
  400. package/templates/kyb/agent.md +1 -1
  401. package/templates/market-monitor/agent.md +2 -2
  402. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  403. package/dist/app.d.ts +0 -5
  404. package/dist/app.js +0 -514
  405. package/dist/bound-files.d.ts +0 -4
  406. package/dist/bound-files.js +0 -164
  407. package/dist/bounds.d.ts +0 -26
  408. package/dist/bounds.js +0 -137
  409. package/dist/coding-tools.d.ts +0 -47
  410. package/dist/coding-tools.js +0 -189
  411. package/dist/computer-adb.d.ts +0 -12
  412. package/dist/computer-adb.js +0 -14
  413. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  414. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  415. package/dist/content-filter.d.ts +0 -7
  416. package/dist/content-filter.js +0 -23
  417. package/dist/disk.d.ts +0 -33
  418. package/dist/disk.js +0 -85
  419. package/dist/door-line.d.ts +0 -23
  420. package/dist/door-line.js +0 -83
  421. package/dist/grade.d.ts +0 -63
  422. package/dist/grade.js +0 -150
  423. package/dist/harness-app.d.ts +0 -69
  424. package/dist/harness-app.js +0 -1162
  425. package/dist/mcp-servers.d.ts +0 -269
  426. package/dist/mcp-servers.js +0 -456
  427. package/dist/packs.d.ts +0 -71
  428. package/dist/packs.js +0 -180
  429. package/dist/request-start.d.ts +0 -27
  430. package/dist/request-start.js +0 -381
  431. package/dist/run-box.d.ts +0 -205
  432. package/dist/run-box.js +0 -661
  433. package/dist/run-holder.d.ts +0 -52
  434. package/dist/run-holder.js +0 -139
  435. package/dist/runs.d.ts +0 -1200
  436. package/dist/runs.js +0 -4103
  437. package/dist/sealed-settings.d.ts +0 -60
  438. package/dist/sealed-settings.js +0 -178
  439. package/dist/served-only.d.ts +0 -5
  440. package/dist/served-only.js +0 -12
  441. package/dist/sessions.d.ts +0 -6
  442. package/dist/sessions.js +0 -109
  443. package/dist/workspace/computer-serves.d.ts +0 -12
  444. package/dist/workspace/computer-serves.js +0 -15
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import proxyaddr from "proxy-addr";
7
+ import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
7
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";
@@ -12,12 +13,12 @@ import { existsSync } from "node:fs";
12
13
  import { rm } from "node:fs/promises";
13
14
  import { homedir } from "node:os";
14
15
  import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
15
- import { WORKFLOW_ADAPTERS } from "./app.js";
16
+ import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
16
17
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
17
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
- import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolOf, toolsView } from "./tools.js";
21
+ import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
21
22
  import { ApiError, invalid, unsupported } from "./errors.js";
22
23
  import { deref, explain } from "./explain.js";
23
24
  import { HOME_HOST_OWNED } from "./files.js";
@@ -26,16 +27,17 @@ import { homePath, hostOwnedOf } from "./home-path.js";
26
27
  import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
27
28
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
28
29
  import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
29
- import { HarnessInstall, harnessesOf, installDirOf, NPM_STOP_GRACE_MS, npmInstall, removeFlatInstall } from "./harness-install.js";
30
+ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
30
31
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
31
32
  import { IMPORT_ASKED } from "./import.js";
32
33
  import { answerStoreCall } from "./import-proxy.js";
33
34
  import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
34
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, writeNote } from "./learning-routes.js";
35
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
35
36
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
36
37
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
37
38
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
38
- import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
39
+ import { BOX_ALLOW_ENV, boxAllowOf, boxAllowSetIn, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./box-settings.js";
40
+ import { dockerLimitsOf } from "./workspace/computer-deps.js";
39
41
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
40
42
  import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
41
43
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
@@ -47,7 +49,8 @@ import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raise
47
49
  import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
48
50
  import { HELD_WAITS } from "./runner/journal-kinds.js";
49
51
  import { servedTimelineRows } from "./run-timeline-served.js";
50
- import { servedRunLearning } from "./run-learning-served.js";
52
+ import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
53
+ import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
51
54
  import { runCutValues } from "./run-cut.js";
52
55
  import { readLaunchBody } from "./run-launch.js";
53
56
  import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
@@ -59,45 +62,39 @@ import { watchRun } from "./live/stream.js";
59
62
  import { stats as statsOverStore } from "./store-reads/stats.js";
60
63
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
61
64
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
62
- import { openStore, StoreBusy } from "./store/index.js";
65
+ import { openStore } from "./store/index.js";
66
+ import { answerOf, logged } from "./agents.js";
63
67
  import { FINAL_STATES } from "./store/store.js";
64
68
  import { runModelRef } from "./model.js";
65
69
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
66
70
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
67
- /** A busy store, and the home_busy answer it maps to (byte-identical to the old agents.ts words), for a read or write that
68
- * meets the one store under load. */
69
- const storeBusy = (error) => error instanceof StoreBusy;
70
- const homeBusy = () => new ApiError("home_busy", "the agent store is busy with another write; try again", { retry_after_ms: 500 });
71
71
  import { runLines } from "./usage-lines.js";
72
72
  import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
73
+ import { dockerDaemonCheck } from "./docker-daemon.js";
73
74
  import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
74
75
  import { startEgressContainer } from "./box-egress-vm.js";
75
- import { dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV } from "./box-paths.js";
76
+ import { dockerComputerRefusal, dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
77
+ import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
76
78
  import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
77
79
  import { vmRelay } from "./box-relay-vm.js";
78
- import { memoryMbOf } from "./run-box.js";
79
80
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
80
81
  import { CAP_MODES } from "./cap.js";
81
82
  import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
82
83
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
83
84
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
84
- import { bootSealKey } from "./seal-key.js";
85
+ import { bootSealKey, withSealKey } from "./seal-key.js";
85
86
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
86
- import { agentLearningOverStore, learningCountsOverStore } from "./store-reads/learning.js";
87
- import { outcomes } from "./usage.js";
88
- import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS } from "./tool-keys.js";
87
+ import { agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
88
+ import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
89
89
  import { toolKeysOverStore } from "./tool-keys-store.js";
90
90
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
91
- // E1b builds the store-backed sign-ins bridge (the old SignIns interface — peek/forgotten/view/forget — over store.signIns,
92
- // byte-identical v2 shapes; "held"/held_by from a live run whose sign_in_handed holds the pointer, verified_at from the
93
- // last holder's lease end). TODO(E1b): wire its sha; named import until then.
94
91
  import { signInsOverStore } from "./sign-ins-store.js";
95
92
  import { MCP_AUTH_TYPES } from "./mcp-probe.js";
96
93
  import { mcpServersOverStore } from "./mcp-servers-store.js";
97
94
  import { privateHostsRoute } from "./mcp-private-hosts.js";
98
95
  import { metaToolOf } from "./mcp-meta.js";
99
96
  import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
100
- import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
97
+ import { OUTBOUND_WEBHOOK, WEBHOOK_EVENTS, waitMarkerOf, Webhooks } from "./webhooks.js";
101
98
  import { appPermissionWarnings } from "./template-github-permissions.js";
102
99
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
103
100
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
@@ -108,7 +105,7 @@ import { HookCut, receivePush } from "./push-handler.js";
108
105
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
109
106
  import { webhook } from "./trigger-webhook.js";
110
107
  import { SCHEME_NAMES } from "./trigger-signatures.js";
111
- import { permissionFrom, pinWords } from "./tool-gate.js";
108
+ import { permissionFrom } from "./tool-gate.js";
112
109
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
113
110
  import { applyBodyOf, compiled, GITHUB_TRIGGER_UNCONNECTED, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
114
111
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
@@ -126,7 +123,7 @@ import { computerCapabilities, createComputerRoutes, folderModeOf, settingsCompu
126
123
  import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
127
124
  import { runComputerField } from "./run-computer.js";
128
125
  import { writesHeld } from "./workspace.js";
129
- import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, isWorkspaceError, localWorkspace, serverRunWorkspace, storeLedger } from "./workspace/index.js";
126
+ import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
127
  import { keyReader } from "./key-meta.js";
131
128
  // server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
132
129
  export const CONTRACT = "agentrun.v2/0";
@@ -164,7 +161,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
164
161
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
165
162
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
166
163
  * harness's, which scripts the harnesses with or without it. */
167
- const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV]];
164
+ 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]];
168
165
  /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
169
166
  * takes the same (test/support.mjs startInProcessRunner). */
170
167
  export function fauxEnvOf(options) {
@@ -212,8 +209,6 @@ export const ROUTES = [
212
209
  { method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
213
210
  { method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
214
211
  { method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
215
- { method: "GET", pattern: /^\/agents\/([^/]+)\/home$/, name: "exportHome", capability: "home.export" },
216
- { method: "PUT", pattern: /^\/agents\/([^/]+)\/home$/, name: "importHome", capability: "home.import" },
217
212
  { method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files$/, name: "listHomeFiles" },
218
213
  { method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "readHomeFile" },
219
214
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "writeHomeFile" },
@@ -229,7 +224,6 @@ export const ROUTES = [
229
224
  { method: "POST", pattern: /^\/runs\/([^/]+)\/approvals\/([^/]+)$/, name: "answerApproval" },
230
225
  { method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
231
226
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
232
- { method: "POST", pattern: /^\/runs\/([^/]+)\/kill$/, name: "killRun", capability: "runs.kill" },
233
227
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
234
228
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
235
229
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
@@ -408,14 +402,15 @@ export function forCaller(caps, ownerSession) {
408
402
  }
409
403
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
410
404
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
411
- * needsOf says it for a revision that names no model (null when it runs). */
412
- function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, gradeModel, refused = {}) {
405
+ * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
406
+ * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. */
407
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, gradeModel, refused = {}, runnerShell) {
413
408
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
414
409
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
415
410
  const memory = hostMemory();
416
411
  // The browser's key is its vendor's row: Kernel's where Kernel is picked or resolved (tool-plane.ts browserKeyRow).
417
412
  const keyFor = (tool) => (tool.name === "browser" ? browserKeyRow(tool.provider, tool.resolves?.[DEFAULT_HARNESS]) : keyOf(tool.name));
418
- const tools = toolsView(env, toolSettings, noBoxReason(boxes), refused).map((tool) => (keyFor(tool) ? { ...tool, key: keyFor(tool) } : tool));
413
+ const tools = toolsView(env, toolSettings, noBoxReason(boxes), refused, runnerShell).map((tool) => (keyFor(tool) ? { ...tool, key: keyFor(tool) } : tool));
419
414
  const browser = tools.find((tool) => tool.name === "browser");
420
415
  return {
421
416
  backend: "local",
@@ -475,13 +470,13 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
475
470
  * it over from the viewer and hands it back, and answers the agent's ask for them (POST /runs/{id}/browser/hand-back,
476
471
  * browser-person.ts). */
477
472
  browser_live: { read_only: false, take_over: true, ask: true },
478
- /** An agent's browser stays signed in between its runs (sign-ins.ts): with a seal key to keep each pointer under, and a
479
- * browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
480
- sign_ins: sealKeyOf(env[SEAL_KEY_ENV]) !== undefined && tools.some((tool) => tool.name === "browser" && tool.available),
473
+ /** An agent's browser stays signed in between its runs (sign-ins-store.ts), each pointer sealed under the server's seal
474
+ * key: with a browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
475
+ sign_ins: tools.some((tool) => tool.name === "browser" && tool.available),
481
476
  vault: false,
482
477
  query: false,
483
- /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
484
- * (tool-keys.ts); with none handed over, nothing is kept, never in the clear. */
478
+ /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the server's seal key
479
+ * (tool-keys-store.ts), never in the clear. */
485
480
  tool_keys: { routes: true, at_rest: "sealed" },
486
481
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
487
482
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
@@ -489,8 +484,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
489
484
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
490
485
  learning,
491
486
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
492
- * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
493
- // Always sealed: the server starts with its seal key (seal-key.ts ensureSealKey), so nothing is kept in the clear.
487
+ * ends (webhooks.ts); its secret kept sealed under the same seal key. */
488
+ // Always sealed: the server starts with its seal key (seal-key.ts bootSealKey), so nothing is kept in the clear.
494
489
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
495
490
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
496
491
  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" } },
@@ -540,12 +535,12 @@ function integerParam(value, name, max) {
540
535
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
541
536
  // by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
542
537
  export async function startServe(options) {
538
+ // API-only: no console, so no owner to sign in to it (and no setup code printed for a page that is refused).
539
+ if (options.apiOnly)
540
+ options = { ...options, accounts: false, openSetup: false };
543
541
  // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
544
542
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
545
543
  delete process.env[HARNESS_TABLE_ENV];
546
- // No start without a seal key (seal-key.ts): the one handed over, else the one kept under the config home, made at the
547
- // first start with only its path printed. Every secret here is kept under it; there is no keeping one in the clear.
548
- const seal = bootSealKey();
549
544
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
550
545
  // Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
551
546
  const data = await realpath(resolve(options.data));
@@ -554,7 +549,11 @@ export async function startServe(options) {
554
549
  if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
555
550
  throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
556
551
  enabledBoxes(process.env);
557
- boxLimitsOf(process.env);
552
+ // A Docker computer's size an operator sets (workspace/computer-deps.ts): a value the Docker provider refuses stops the
553
+ // start, in its words.
554
+ dockerLimitsOf(process.env);
555
+ // The Docker host's addresses an operator names (workspace/computer-deps.ts): a bad entry stops the start, in words.
556
+ dockerHostAddressesOf(process.env);
558
557
  const boxAllow = boxAllowOf(process.env);
559
558
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
560
559
  const learning = learningOf(process.env, options.learning);
@@ -572,7 +571,7 @@ export async function startServe(options) {
572
571
  // store handle it opened.
573
572
  const stops = [];
574
573
  try {
575
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates, sealKey: seal.key }, stops);
574
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates }, stops);
576
575
  }
577
576
  catch (error) {
578
577
  for (const stop of stops)
@@ -617,11 +616,25 @@ async function startHolding(options, data, checked, stops) {
617
616
  // words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
618
617
  // server writes and reads rows, and a runner (its own process, sharing only this store) runs every run.
619
618
  // On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts), its owner lock the one-server lock.
620
- const store = await openStore({ dataDir: data, role: "server" });
619
+ // A server deploying while the old one still holds the schema waits for it (said once), never exits at once.
620
+ const store = await openStore({
621
+ dataDir: data, role: "server",
622
+ warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
623
+ ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
624
+ });
621
625
  stops.push(() => store.close());
622
- // Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
626
+ // No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
627
+ // else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
628
+ // secrets another key sealed is refused, in words, and no key is made over them. Every secret here is kept under it;
629
+ // there is no keeping one in the clear.
630
+ const seal = await bootSealKey(store, data);
631
+ stops.push(async () => seal.release());
632
+ // This server's own key on every environment it reads its secrets from, so a reader opens what this store holds with the
633
+ // key checked against it, never another data directory's that this process booted too (secrets.ts holds one made key).
634
+ const own = (env) => withSealKey(env, seal.text);
635
+ // Which fields are the server's is read from what it is started with alone: handed the saved keys too, the tool keys would
623
636
  // call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
624
- const toolKeys = toolKeysOverStore(store, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
637
+ 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`)));
625
638
  await toolKeys.load();
626
639
  // 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,
627
640
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
@@ -638,7 +651,7 @@ async function startHolding(options, data, checked, stops) {
638
651
  const storedKeys = (name) => toolKeys.value(name);
639
652
  // A stored key that does not open is said once at the start, never a refusal to start.
640
653
  toolKeys.view();
641
- const mcpServers = mcpServersOverStore(store, withSecrets(base, "own"), VERSION);
654
+ const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
642
655
  if (options.githubMcpOrigin)
643
656
  mcpServers.appOrigin = options.githubMcpOrigin;
644
657
  // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
@@ -675,7 +688,7 @@ async function startHolding(options, data, checked, stops) {
675
688
  // settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
676
689
  // which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
677
690
  // no restart and no request opening the file. The offers are probed once saved keys are read (below), at the start.
678
- let env = withSecrets(base, "all", storedKeys);
691
+ let env = own(withSecrets(base, "all", storedKeys));
679
692
  let offers;
680
693
  let caps;
681
694
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -684,7 +697,8 @@ async function startHolding(options, data, checked, stops) {
684
697
  // With accounts off no one can answer an ask (the answer route takes the owner's session alone): each tool ask is
685
698
  // offered for says it needs the password sign-in, as learning's approve does.
686
699
  const askNeeds = (made) => (options.accounts ? made : { ...made, tools: made.tools.map((tool) => (tool.permissions.includes("ask") ? { ...tool, ask_needs: "password" } : tool)) });
687
- const recompose = () => void (caps = askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel, toolKeys.refused())));
700
+ const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel, toolKeys.refused(), runnerShell));
701
+ const recompose = () => void (caps = compose());
688
702
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
689
703
  let offersFrom;
690
704
  let probes = 0;
@@ -706,7 +720,7 @@ async function startHolding(options, data, checked, stops) {
706
720
  const keysChanged = async () => {
707
721
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
708
722
  // serverSecrets live, store-view), so a key change needs no cache invalidation here.
709
- env = withSecrets(base, "all", storedKeys);
723
+ env = own(withSecrets(base, "all", storedKeys));
710
724
  const mine = ++needsAsked;
711
725
  const next = await needsOf(env);
712
726
  if (mine === needsAsked)
@@ -726,7 +740,7 @@ async function startHolding(options, data, checked, stops) {
726
740
  // is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
727
741
  // box here there is none, so no run waits on one an earlier start left.
728
742
  let image;
729
- // What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
743
+ // What a Docker box's programs reach, resolved once here (box-settings.ts boxNetworkOf): the setting's list, on a Docker
730
744
  // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
731
745
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
732
746
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
@@ -751,15 +765,30 @@ async function startHolding(options, data, checked, stops) {
751
765
  // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
752
766
  // (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.
753
767
  let egress;
768
+ // A run's Docker computer mounts the run's folder, and the computer's daemon, by this server's paths: as they are on
769
+ // its Docker's own host, or as its named data volume's subpaths from a container of that Docker's (compose.yaml).
770
+ // Any other layout, or a daemon of another machine (DOCKER_HOST, or the current context's endpoint: box-paths.ts
771
+ // remoteDockerOnce), can't run one, and says so here (dockerComputerRefusal), where capabilities, the run's start
772
+ // (dockerAnswers) and a place's box check all read it: no run starts only to fail at its create.
773
+ const dockerElsewhere = fauxBox || !boxes.provider("docker") ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
774
+ // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
775
+ // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
776
+ // runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
777
+ const hostAddresses = dockerElsewhere === undefined && boxPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
778
+ if (hostAddresses)
779
+ log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
780
+ const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
781
+ // The addresses found, where an operator looks: capabilities' Docker entry.
782
+ const hostShown = hostAddresses && hostAddresses.addresses.length > 0 ? { host_addresses: hostAddresses.addresses } : {};
754
783
  const dockerNetwork = (offer) => {
755
784
  if (!offer.available)
756
785
  return offer;
757
- if ("reason" in dockerPaths)
758
- return { id: offer.id, available: false, state: "unavailable", reason: dockerPaths.reason };
786
+ if (dockerRefused !== undefined)
787
+ return { id: offer.id, available: false, state: "unavailable", reason: dockerRefused };
759
788
  if (boxNetwork.allow === "none")
760
789
  return { ...offer, network: "none", network_reason: boxNetwork.reason };
761
790
  const proxy = egress?.state();
762
- return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist" };
791
+ return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist", ...hostShown };
763
792
  };
764
793
  // A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
765
794
  // one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
@@ -802,10 +831,6 @@ async function startHolding(options, data, checked, stops) {
802
831
  // process sees it.
803
832
  const vmSecrets = () => [...serverSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
804
833
  const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
805
- const vmLimits = (() => {
806
- const limits = boxLimitsOf(env);
807
- return { cpus: limits.cpus, memoryMb: memoryMbOf(limits.memory) };
808
- })();
809
834
  // Daytona could not keep a run's box's domain list: said in the log and in capabilities, which recompose now.
810
835
  // Daytona's own words go to the log, so a refusal for another cause is not taken silently for a tier that takes no list.
811
836
  const onNoBoxList = (code, message) => {
@@ -837,7 +862,7 @@ async function startHolding(options, data, checked, stops) {
837
862
  imageLog(image.state());
838
863
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
839
864
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
840
- const sealKey = sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]);
865
+ const sealKey = seal.key;
841
866
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
842
867
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
843
868
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -849,15 +874,37 @@ async function startHolding(options, data, checked, stops) {
849
874
  : kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
850
875
  let faux;
851
876
  const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
877
+ /** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
878
+ * Computers' view and a run's start check (below) both ask it. Where AGENTRUN_BOXES lists Docker and it is no faux
879
+ * box, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
880
+ * daemon that stops after the start is seen, and one that is gone says so in noDockerWords); once it answers, the
881
+ * box's start-time answer stands. A box the start did not make keeps its reason ("start Docker, then restart
882
+ * AgentRun"): the start's checks of Docker (Docker elsewhere, this server's paths, host addresses, its network) ran
883
+ * without it, so a daemon that answers later is not taken. Else the box's start-time answer (boxOffers), with its
884
+ * reason, which says how to fix it. */
885
+ const dockerDaemon = dockerDaemonCheck({ env });
886
+ const dockerAnswers = async (provider) => {
887
+ const box = boxAvailability(boxOffers).find((one) => one.id === provider);
888
+ if (provider === "docker" && !fauxBox && enabledBoxes(env).has("docker")) {
889
+ const daemon = await dockerDaemon();
890
+ if (!daemon.up || box?.available)
891
+ return daemon;
892
+ }
893
+ else if (box?.available)
894
+ return { up: true };
895
+ return { up: false, absent: false, reason: box?.reason ?? `${provider} is not a box this server has` };
896
+ };
852
897
  let computerRoutes;
853
898
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
854
- store, sealKey: checked.sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
899
+ store, sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
855
900
  ...(options.faux
901
+ // --faux's providers stand in for every vendor's, a local one's daemon included.
856
902
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
857
903
  : {
858
904
  kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
859
905
  // The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
860
906
  factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
907
+ answers: dockerAnswers,
861
908
  }),
862
909
  }));
863
910
  /** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
@@ -865,14 +912,15 @@ async function startHolding(options, data, checked, stops) {
865
912
  * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
866
913
  * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
867
914
  * runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
868
- * a computer setting, in place of the box check. Whether Docker answers here is the boxes' own start-time probe
869
- * (boxOffers, in memory: no new probe), with its reason, which says how to fix it. */
870
- const dockerAnswers = (provider) => {
871
- const box = boxAvailability(boxOffers).find((one) => one.id === provider);
872
- return box?.available ? true : box?.reason ?? `${provider} is not a box this server has`;
873
- };
874
- const computerReady = async (setting) => computerReadiness(setting, (await folderModeOf(store)()) === "disk" ? 2 : 1, claimKinds({}), keyReader(store, checked.sealKey, withSecrets(process.env, "own")), dockerAnswers);
875
- const archil = createArchilRoutes({ store, sealKey: checked.sealKey, env: process.env });
915
+ * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers'. */
916
+ /** The server's folder mode now: 2 when the owner's Archil settings are saved (the run's folder on the disk), else 1. */
917
+ const modeNow = async () => ((await folderModeOf(store)()) === "disk" ? 2 : 1);
918
+ const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow);
919
+ /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
920
+ * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
921
+ * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
922
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
923
+ const archil = createArchilRoutes({ store, sealKey, env: process.env });
876
924
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
877
925
  const runComputerOf = async (runId, view) => {
878
926
  const run = await store.runs.get(runId);
@@ -913,9 +961,10 @@ async function startHolding(options, data, checked, stops) {
913
961
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
914
962
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
915
963
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
916
- const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
917
- // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
918
- secretStores.add("webhook", () => webhooks.signingSecrets());
964
+ // The outbound webhook and its outbox, in the store; its signing secret among the server's sealed settings, which list it
965
+ // (and each one it held before) with the server's own secrets.
966
+ const webhooks = new Webhooks(store, triggerSettings.get(OUTBOUND_WEBHOOK.id), (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
967
+ await webhooks.load();
919
968
  stops.push(() => webhooks.close());
920
969
  const uploads = new Uploads(join(data, UPLOADS_DIR));
921
970
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
@@ -930,10 +979,6 @@ async function startHolding(options, data, checked, stops) {
930
979
  // of each at a time, which every run on that harness, and the save of an agent on it, waits for or starts; once one is
931
980
  // in, the offers are probed again, so capabilities no longer say it installs on first use. Each is its table entry's
932
981
  // `installs` (a test's stand-in has none).
933
- // Claude Code as an earlier build installed it, at the top of the harnesses directory itself (read-only): removed once,
934
- // before the first install, which then goes in beside nothing. Any other layout is left as it is.
935
- let flat;
936
- const flatRemoved = () => (flat ??= removeFlatInstall(harnessesOf(data)).then((removed) => void (removed && log?.(logLine("harness_install_removed", { dir: harnessesOf(data), said: `removed the earlier Claude Code install at ${harnessesOf(data)}: it installs again under harnesses/claude-agent` }))), (error) => ((flat = undefined), Promise.reject(error))));
937
982
  const installed = HARNESSES.flatMap((id) => {
938
983
  const harness = harnessOf(base, id);
939
984
  return harness?.installs && harness.pins ? [{ entry: harness.installs, pins: harness.pins }] : [];
@@ -942,7 +987,7 @@ async function startHolding(options, data, checked, stops) {
942
987
  const lock = options.harnessLocks?.[entry.id];
943
988
  // npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
944
989
  const onKilled = () => log?.(logLine("harness_install_killed", { harness: entry.id, said: `npm did not stop within ${NPM_STOP_GRACE_MS / 1000} s of SIGTERM; killed` }));
945
- return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, async (entry, dir, pins, signal) => (await flatRemoved(), npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) })), (ms) => {
990
+ return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, (entry, dir, pins, signal) => npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) }), (ms) => {
946
991
  log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
947
992
  void probe(`${entry.id}_installed`).catch(() => undefined);
948
993
  })];
@@ -984,15 +1029,22 @@ async function startHolding(options, data, checked, stops) {
984
1029
  approvers: options.accounts === true,
985
1030
  ...(documents ? { documents: resolve(documents) } : {}),
986
1031
  ...(boxAllow !== undefined ? { boxAllow } : {}),
1032
+ // Whether that is the operator's own setting, not the default: a browser is held to an operator's list alone.
1033
+ ...(boxAllowSetIn(process.env) ? { boxAllowSet: true } : {}),
987
1034
  modelOf,
988
1035
  // The run's learning start, decided at start as the old file-backed start decided it (learning-run.ts onStart/seedFor):
989
1036
  // the server's learning switch, the budget its # Learned section fits, the agent's seed read now from its learning folder
990
- // (git), and the host's secrets as they are shown now to cut the notes a run is given. runs-over-store.learningStartFor
991
- // pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed that cannot be read starts the run
992
- // with nothing learned (a fault never refuses it). INERT until the runner installs learning-1's learningEndOfRun as its
993
- // endOfRun (cutover-learning-end 283008bb05, E2r3's one-line spec-builder hookup); land this in that same round.
1037
+ // (git), and the host's secrets as they are shown now to cut the notes a run is given, a loopback address kept (local),
1038
+ // as the run's .learning/ files keep it: the run's own machine, which an agent with no read tool learns of only here.
1039
+ // runs-over-store.learningStartFor pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed
1040
+ // that cannot be read starts the run with nothing learned (a fault never refuses it). The runner's spec builders read
1041
+ // it back as the run's end-of-run step (runner/learning-end.ts learningEndOfRun, in adapter-run-spec.ts and
1042
+ // cli-run-spec.ts).
994
1043
  learning,
995
1044
  learningBudget,
1045
+ // The model the server names to grade what a run proposes (capabilities' learning.grade_model), carried on each learning
1046
+ // start for the runner's learning run to grade on: none, the agent's own.
1047
+ ...(gradeModelOf(env, options.gradeModel) ? { gradeModel: gradeModelOf(env, options.gradeModel) } : {}),
996
1048
  seedFor: async (agentId) => {
997
1049
  // The switch runs no git in this process (learning.ts seedOf: the folder's own script and file API, which checks git
998
1050
  // itself); a git or folder fault surfaces here as a seedOf error, so the run starts with nothing learned, never refused.
@@ -1001,20 +1053,30 @@ async function startHolding(options, data, checked, stops) {
1001
1053
  return { failed: error.message };
1002
1054
  });
1003
1055
  },
1004
- shown: () => secretsShown(serverSecrets()),
1056
+ shown: () => secretsShown(serverSecrets(), { local: true }),
1005
1057
  };
1006
1058
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1007
1059
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1008
1060
  // request) use the server's public address, else its own.
1009
1061
  // The run's key read from this server's environment with the keys a person saved, as its Timeline reads it (keyEnv below).
1010
- const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) });
1062
+ // The learning routes' cut: the server's secrets and agent `agentId`'s own sign-in pointers, live and forgotten; 403 when
1063
+ // one of them can't be read here (agentPointers), never a shorter cut.
1064
+ const learningValues = async (agentId) => {
1065
+ const pointers = await agentPointers(signIns, agentId);
1066
+ if (pointers === "unreadable")
1067
+ throw new ApiError("forbidden", WITHHELD_LEARNING);
1068
+ return [...serverSecrets(), ...pointers];
1069
+ };
1070
+ const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1071
+ // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1072
+ const statuses = (agentId) => statusesOf(data, agentId);
1073
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
1011
1074
  const ownOriginOf = () => options.publicUrl ?? url;
1012
1075
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1013
1076
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
1014
1077
  // and withheld verdict from store-view. The live browser viewer reads the runner's published handover from the store
1015
- // (liveViewerLink, the one the runner's browser tool wrote under its claim), when this server has the seal key its token
1016
- // is sealed under; with no seal key no live view is ever served, so the live branch is left off. The timeline route keeps
1017
- // its own stub (store-reads journal + SSE) until E2c's timeline lands.
1078
+ // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1079
+ // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1018
1080
  const runReadsDeps = {
1019
1081
  runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
1020
1082
  env,
@@ -1022,7 +1084,7 @@ async function startHolding(options, data, checked, stops) {
1022
1084
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1023
1085
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1024
1086
  context: ctx,
1025
- ...(sealKey ? { liveViewer: (runId) => liveViewerLink(store, sealKey, runId) } : {}),
1087
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId),
1026
1088
  };
1027
1089
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1028
1090
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
@@ -1034,7 +1096,7 @@ async function startHolding(options, data, checked, stops) {
1034
1096
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1035
1097
  // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1036
1098
  // from its journal, which keeps what the run said whole.
1037
- timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) }, forStore, runId, context),
1099
+ timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context),
1038
1100
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1039
1101
  });
1040
1102
  const triggerDeps = {
@@ -1043,6 +1105,12 @@ async function startHolding(options, data, checked, stops) {
1043
1105
  needAgent,
1044
1106
  momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1045
1107
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
1108
+ completedOutput: async (runId) => {
1109
+ const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1110
+ if (view?.status !== "completed")
1111
+ return undefined;
1112
+ return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null };
1113
+ },
1046
1114
  };
1047
1115
  const targets = triggerTargets(store, triggerDeps);
1048
1116
  const expected = digest(`Bearer ${token}`);
@@ -1075,6 +1143,19 @@ async function startHolding(options, data, checked, stops) {
1075
1143
  }
1076
1144
  })();
1077
1145
  const clientOf = (req) => (trusted ? proxyaddr(req, trusted) : req.socket.remoteAddress) ?? "unknown";
1146
+ // The owner's own sign-in (the right password) that came with X-Forwarded-For from an address not trusted as a proxy is
1147
+ // said once a start, with that address (`event=forwarded_untrusted peer=<it>`): behind a proxy that publishes no
1148
+ // address (Render's), the proxy that carried the owner's request, the one to name in AGENTRUN_TRUSTED_PROXIES. Only a
1149
+ // right password says it, so a peer that can reach the server without the password can't put its own address there;
1150
+ // once, so the log says it one time.
1151
+ let forwardedSaid = false;
1152
+ const sayForwarded = (req) => {
1153
+ const peer = req.socket.remoteAddress ?? "unknown";
1154
+ if (forwardedSaid || req.headers["x-forwarded-for"] === undefined || (trusted?.(peer, 0) ?? false))
1155
+ return;
1156
+ forwardedSaid = true;
1157
+ log?.(logLine("forwarded_untrusted", { peer }));
1158
+ };
1078
1159
  /** Whether `req` may be shown a secret this server mints (trigger-secrets-shown.ts): the caller that may write one. */
1079
1160
  const mayHoldSecrets = (req) => writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) });
1080
1161
  /** A trigger's view with its minted secret's metadata, never the secret (trigger-secrets-shown.ts). */
@@ -1156,7 +1237,7 @@ async function startHolding(options, data, checked, stops) {
1156
1237
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1157
1238
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1158
1239
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1159
- workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })) },
1240
+ 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]]; })) },
1160
1241
  // Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
1161
1242
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1162
1243
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
@@ -1367,7 +1448,7 @@ async function startHolding(options, data, checked, stops) {
1367
1448
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1368
1449
  async function runnable(revision, place, { capped = false } = {}) {
1369
1450
  const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1370
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
1451
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1371
1452
  if (!blockers.length)
1372
1453
  return;
1373
1454
  const message = blockers.map((b) => b.message).join(" ");
@@ -1403,14 +1484,14 @@ async function startHolding(options, data, checked, stops) {
1403
1484
  }
1404
1485
  const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1405
1486
  const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1406
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, offers, mcp: mcpTools });
1487
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools });
1407
1488
  // 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
1408
1489
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1409
1490
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1410
1491
  if ((body.maxCostUsd ?? 0) > 0) {
1411
1492
  const key = (b) => `${b.field}\n${b.message}`;
1412
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, offers, mcp: mcpTools })).map(key));
1413
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
1493
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools })).map(key));
1494
+ const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1414
1495
  // A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
1415
1496
  // agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
1416
1497
  const added = capped.filter((b) => !plain.has(key(b)));
@@ -1447,14 +1528,10 @@ async function startHolding(options, data, checked, stops) {
1447
1528
  const saved = pkg.mcp.filter((need) => mcpMeta.has(need.server));
1448
1529
  const unsaved = pkg.mcp.filter((need) => !saved.includes(need));
1449
1530
  const needed = unsaved.filter((need) => need.required);
1450
- // A webhook trigger's secret is kept sealed, never in the clear: with no seal key, its create would be refused after
1451
- // the agent is made, so the apply is refused first, naming each one.
1452
- const unsealed = sealKeyOf(env[SEAL_KEY_ENV]) ? [] : pkg.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [i] : []));
1453
- if (missing.length || needed.length || unsealed.length) {
1531
+ if (missing.length || needed.length) {
1454
1532
  const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
1455
1533
  const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1456
- const sealing = `Start the server with its launcher, agentrun-serve, which makes and keeps a seal key, or set ${SEAL_KEY_ENV} (32 random bytes in base64) where AgentRun starts, then apply the template again.`;
1457
- throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`), ...(unsealed.length ? ["a seal key for its webhook trigger's secret"] : [])].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server })), ...unsealed.map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: `This server has no seal key (${SEAL_KEY_ENV}), so it cannot keep the webhook trigger's secret.`, fix: sealing }))] });
1534
+ throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server }))] });
1458
1535
  }
1459
1536
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1460
1537
  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.` }));
@@ -1469,13 +1546,10 @@ async function startHolding(options, data, checked, stops) {
1469
1546
  const server = settings.get();
1470
1547
  const denied = grants.filter((tool) => { const set = permissionFrom(tool, server); return set.from === "server" && set.permission === "deny"; });
1471
1548
  const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent was not allowed it: its runs are refused it until the owner changes that setting.` }));
1472
- // The tools this server's own settings pin (or hold refused for a pin that does not read): a package's pin the agent
1473
- // store can't keep yet is covered there, so its grant stands; any other such tool is made deny (compiled).
1474
1549
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1475
1550
  // never), else ask. Deny and pins hold either way.
1476
1551
  const chosenApprovals = approvals ?? pkg.approvals;
1477
- const serverPinned = new Set(Object.entries(settings.get()).filter(([, one]) => one?.pin || one?.brokenPin).map(([name]) => name));
1478
- const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), serverPinned, ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
1552
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
1479
1553
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1480
1554
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1481
1555
  const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
@@ -1528,9 +1602,6 @@ async function startHolding(options, data, checked, stops) {
1528
1602
  }
1529
1603
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1530
1604
  const unpinned = made.unpinned.map(({ tool, parameters: named }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: `${tool}'s arguments are fixed by ${named.map((one) => `the ${one} parameter`).join(" and ")}, which was not given, so the agent was made with ${tool} set to deny: it can't call it at all. Apply again with ${named.join(" and ")} set to let it.` }));
1531
- // A pin this server's agent store does not keep yet (tool-plane.ts AGENT_LAYER_PINS): said, with the setting that holds
1532
- // the send to its destination meanwhile, the server's.
1533
- const unkept = made.unkept.map(({ tool, pin }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: serverPinned.has(tool) ? `${tool} is not pinned to ${pinWords(pin)} for this agent yet (this server's agent store keeps an agent's own pin from the store cutover on); this server's own pin of ${tool} holds its calls meanwhile.` : `${tool} is not pinned to ${pinWords(pin)} for this agent yet: this server's agent store keeps an agent's own pin from the store cutover on. Until then the agent was made with ${tool} set to deny, so nothing it reads can send it elsewhere. Pin it on this server, which holds every agent's calls of ${tool}, and apply again to let it.`, ...(serverPinned.has(tool) ? {} : { fix: `Add ${JSON.stringify({ [tool]: { pin } })} to this server's tool settings (Settings → Tools; PUT /v2/settings/tools replaces the whole map, so send it with the rest).` }) }));
1534
1605
  // A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
1535
1606
  // MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
1536
1607
  const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
@@ -1543,7 +1614,7 @@ async function startHolding(options, data, checked, stops) {
1543
1614
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1544
1615
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1545
1616
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
1546
- const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...unpinned, ...unkept, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1617
+ const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1547
1618
  return { applied, minted };
1548
1619
  }
1549
1620
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
@@ -1946,8 +2017,9 @@ async function startHolding(options, data, checked, stops) {
1946
2017
  total.unpriced++;
1947
2018
  total.usd += usd ?? soFar;
1948
2019
  }
1949
- // What learning spent on this server, outside any run (usage.ts): each run's grade, on the day its learning ended.
1950
- for (const entry of (await outcomes(data)).values()) {
2020
+ // What learning spent on this server, outside any run (store-reads/learning.ts learningSpendOverStore): each run's grade, on
2021
+ // the day its learning ended.
2022
+ for (const entry of await learningSpendOverStore(store, { from, to })) {
1951
2023
  const at = Date.parse(entry.at);
1952
2024
  if (at >= from && at < to)
1953
2025
  add(lineKey(entry.agent, entry.at, "learning"), entry.cost);
@@ -2076,6 +2148,7 @@ async function startHolding(options, data, checked, stops) {
2076
2148
  authFailed("/v2/auth/sign-in", "wrong_password");
2077
2149
  throw new ApiError("unauthenticated", "that is not the password");
2078
2150
  }
2151
+ sayForwarded(req);
2079
2152
  return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
2080
2153
  }
2081
2154
  // This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
@@ -2176,8 +2249,10 @@ async function startHolding(options, data, checked, stops) {
2176
2249
  throw new ApiError("method_not_allowed", `${req.method} is not a method of ${path}`, {}, { allow: [...new Set(matching.map((r) => r.method))].join(", ") });
2177
2250
  if (found.name === "getCapabilities") {
2178
2251
  // features.computers: the computer kinds this server offers now (computers.ts), read at each answer, since turning
2179
- // Archil on or off, or saving a key, changes them.
2180
- const answer = forCaller(caps, byOwnerSession(req));
2252
+ // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
2253
+ // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
2254
+ const runnerShell = shellTools(await shellOf({ kind: "none" }));
2255
+ const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
2181
2256
  return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
2182
2257
  }
2183
2258
  if (found.name === "getOpenapi")
@@ -2497,8 +2572,6 @@ async function startHolding(options, data, checked, stops) {
2497
2572
  const kept = await keptBrowserOf(store, run.id);
2498
2573
  const view = await computerView({
2499
2574
  viewer: async () => {
2500
- if (sealKey === undefined)
2501
- return undefined;
2502
2575
  if (family === "browser") {
2503
2576
  const link = await liveViewerLink(store, sealKey, run.id);
2504
2577
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
@@ -2627,7 +2700,7 @@ async function startHolding(options, data, checked, stops) {
2627
2700
  throw invalid([{ field: "workflow", reason: body.workflow === undefined ? "missing" : "wrong_type", message: "workflow is the workflow definition, an object" }]);
2628
2701
  if (body.tools !== undefined && !(Array.isArray(body.tools) && body.tools.every((t) => typeof t === "string")))
2629
2702
  throw invalid([{ field: "tools", reason: "wrong_type", message: "tools is a list of tool names" }]);
2630
- const { workflowIssues } = await import("@parcha/pi-durable-agent/workflow");
2703
+ const { workflowIssues } = await import("./workflow-run.js");
2631
2704
  const { issues, warnings } = await workflowIssues(body.workflow, body.tools);
2632
2705
  // What a save refuses on this host (a model node's tool, a code node where none runs), and what it lacks yet.
2633
2706
  if (!issues.length) {
@@ -2810,14 +2883,15 @@ async function startHolding(options, data, checked, stops) {
2810
2883
  return send(res, 200, withDefaults(settings.get()));
2811
2884
  }
2812
2885
  // A person's view and control of what an agent learned (learning-routes.ts). Every text cut of the host's secrets as
2813
- // they are now; a write as the definition's: an archived agent's too.
2886
+ // they are now and of the agent's own sign-in pointers, live and forgotten (agentPointers); a write as the
2887
+ // definition's: an archived agent's too.
2814
2888
  case "getAgentLearning": {
2815
2889
  await needAgent(id);
2816
2890
  // The agent's learning view: its notes, skills, workflows and log from its learning folder; its run-fared counts, each
2817
2891
  // note's runs (given it and that read it) and its impact over the one store (agentLearningOverStore), from each run's
2818
2892
  // launch, journal and learning end.
2819
2893
  const { counts, impact, notes } = await agentLearningOverStore(store, id);
2820
- return send(res, 200, await agentLearning(data, id, secretsShown(serverSecrets()), counts, impact, notes));
2894
+ return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, notes));
2821
2895
  }
2822
2896
  case "listLearningNotes":
2823
2897
  case "listLearningLog":
@@ -2825,12 +2899,12 @@ async function startHolding(options, data, checked, stops) {
2825
2899
  if (found.name === "listLearningNotes") {
2826
2900
  // The notes from the agent's learning folder, each with its runs over the one store (agentLearningOverStore's noteRuns).
2827
2901
  const { notes } = await agentLearningOverStore(store, id);
2828
- return send(res, 200, await learningNotes(data, id, url.searchParams, secretsShown(serverSecrets()), notes));
2902
+ return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
2829
2903
  }
2830
- return send(res, 200, await learningLog(data, id, url.searchParams, secretsShown(serverSecrets())));
2904
+ return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
2831
2905
  case "readLearningFile":
2832
2906
  await needAgent(id);
2833
- return sendNote(res, 200, await readNote(data, id, second, secretsShown(serverSecrets())));
2907
+ return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
2834
2908
  case "writeLearningFile":
2835
2909
  case "retireLearningFile":
2836
2910
  case "approveLearningFile":
@@ -2838,34 +2912,38 @@ async function startHolding(options, data, checked, stops) {
2838
2912
  await needAgent(id);
2839
2913
  const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
2840
2914
  const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
2841
- const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: serverSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile", draftTools: () => learnedDraftToolsOf(id) });
2915
+ // What it refuses is what the reads cut: a note shown cut is never saved over the hidden text.
2916
+ const refuse = await learningValues(id);
2917
+ const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse, approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile", draftTools: () => learnedDraftToolsOf(id) });
2842
2918
  // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
2843
- const shown = secretsShown(serverSecrets());
2919
+ const shown = secretsShown(refuse);
2844
2920
  const located = written.status === 201 && shown.name(written.file) === written.file;
2845
2921
  return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
2846
2922
  }
2847
2923
  case "getRunLearning": {
2848
2924
  const run = await needRun(id);
2849
2925
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
2850
- // from its launch, what it holds for the owner's OK as the store's run view reads it (no folder), byte-identical to main.
2926
+ // from its launch, what it holds for the owner's OK as the store's run view reads it (on its folder's main), as main.
2851
2927
  // Cut by the run's one cut, and refused for a withheld run (run-learning-served.ts).
2852
- return send(res, 200, await servedRunLearning({ serverSecrets, signIns }, store, run.id));
2928
+ return send(res, 200, await servedRunLearning({ serverSecrets, signIns, statuses }, store, run.id));
2929
+ }
2930
+ case "getRunLearningDiff": {
2931
+ const run = await needRun(id);
2932
+ // The run's learning diff over the store (learning-routes.ts runDiffOverStore): its merge from its agent's learning
2933
+ // folder, else its kept proposal's notes against its seed, else no file against the seed its launch names. Cut by the
2934
+ // run's one cut, and refused for a withheld run, as its learning is (run-learning-served.ts).
2935
+ return send(res, 200, await servedRunDiff({ serverSecrets, signIns }, store, data, run.id));
2853
2936
  }
2854
- case "getRunLearningDiff":
2855
- await needRun(id);
2856
- // TODO(learning-1): the run's learning diff over the store — learning-1's diff read on untangle/cutover-switch-learn, not the run's
2857
- // .learning/diffs files. Wire when its head lands.
2858
- return runReadsTodo();
2859
2937
  case "getWebhook":
2860
2938
  return send(res, 200, webhooks.view());
2861
2939
  case "saveWebhook": {
2862
2940
  // Never through `idempotent`: its record would keep the answer, and the first one holds the secret.
2863
2941
  // Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets its metadata and the words.
2864
- const saved = webhooks.save(await bodyOf(req));
2942
+ const saved = await webhooks.save(await bodyOf(req));
2865
2943
  return send(res, saved.created ? 201 : 200, webhookSaved(saved.view, saved.secret, mayHoldSecrets(req)));
2866
2944
  }
2867
2945
  case "deleteWebhook":
2868
- webhooks.remove();
2946
+ await webhooks.remove();
2869
2947
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
2870
2948
  case "testWebhook":
2871
2949
  return send(res, 200, await webhooks.test());
@@ -2952,10 +3030,9 @@ async function startHolding(options, data, checked, stops) {
2952
3030
  }
2953
3031
  await needRun(runId);
2954
3032
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim; liveViewerFor picks
2955
- // a named viewer's handover or the run's open one). None for a run no runner holds; with no seal key this server serves
2956
- // no live view. A /computer/live path reaches a viewer of every kind (the link GET /computer gives, a browser's among
3033
+ // 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
2957
3034
  // them), a /browser/live path a browser's alone (familyReaches).
2958
- const handover = sealKey ? await liveViewerFor(store, sealKey, runId, rest) : undefined;
3035
+ const handover = await liveViewerFor(store, sealKey, runId, rest);
2959
3036
  if (handover === undefined || !familyReaches(family, handover))
2960
3037
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
2961
3038
  await serveViewerFile(req, res, rest);
@@ -2985,9 +3062,10 @@ async function startHolding(options, data, checked, stops) {
2985
3062
  // A request cut before its body was read (push-handler.ts readCapped): its socket goes once the answer is out.
2986
3063
  if (error instanceof HookCut)
2987
3064
  res.once("finish", () => req.socket.destroy());
2988
- // A store still busy past a request's wait is home_busy, whichever read or write met it.
2989
- const known = error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : new ApiError("internal", error?.message ?? String(error));
2990
- if (!(error instanceof ApiError) && !storeBusy(error))
3065
+ // A store still busy past a request's wait, or a write still open at its deadline, is home_busy, whichever read or
3066
+ // write met it: the request may be sent again, never a 500 (agents.ts answerOf, as an MCP tool's call answers).
3067
+ const known = answerOf(error);
3068
+ if (logged(error))
2991
3069
  process.stderr.write(`agentrun-serve: ${error?.stack ?? String(error)}\n`);
2992
3070
  send(res, known.status, known.body(requestId), known.headers);
2993
3071
  };
@@ -3007,6 +3085,10 @@ async function startHolding(options, data, checked, stops) {
3007
3085
  }
3008
3086
  // Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
3009
3087
  const raw = (req.url ?? "/").split("?")[0];
3088
+ // API-only (api-only.ts): any address but the run routes is refused here, before the page, the owner's routes, the
3089
+ // MCP endpoint, the token-less hooks or the token check read anything of the request.
3090
+ if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
3091
+ return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
3010
3092
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
3011
3093
  if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw.startsWith("/v2/auth/")))
3012
3094
  return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
@@ -3014,7 +3096,7 @@ async function startHolding(options, data, checked, stops) {
3014
3096
  return void mcp(req, res).catch(fail);
3015
3097
  if (raw === "/llms.txt")
3016
3098
  return void answerLlms(req, res).catch(fail);
3017
- if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3099
+ if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3018
3100
  return;
3019
3101
  // Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
3020
3102
  // a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
@@ -3049,6 +3131,9 @@ async function startHolding(options, data, checked, stops) {
3049
3131
  // away. Its name alone, on any port, as the HTTP routes check it.
3050
3132
  if (names && !names.has(hostName(req.headers.host) ?? ""))
3051
3133
  return deny("403 Forbidden");
3134
+ // API-only: a run's live view is the console's, and refused with it.
3135
+ if (options.apiOnly)
3136
+ return deny("404 Not Found");
3052
3137
  if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3053
3138
  return deny("404 Not Found");
3054
3139
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
@@ -3064,9 +3149,9 @@ async function startHolding(options, data, checked, stops) {
3064
3149
  void (async () => {
3065
3150
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
3066
3151
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
3067
- // runner holds; with no seal key no live view is served. A /computer/live socket reaches a viewer of every kind, a
3152
+ // runner holds. A /computer/live socket reaches a viewer of every kind, a
3068
3153
  // /browser/live socket a browser's alone (familyReaches), as the page does.
3069
- const viewerHandover = run && sealKey ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
3154
+ const viewerHandover = run ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
3070
3155
  const handover = viewerHandover !== undefined && familyReaches(viewing[2], viewerHandover) ? viewerHandover : undefined;
3071
3156
  if (!handover)
3072
3157
  return deny("404 Not Found");
@@ -3150,8 +3235,8 @@ async function startHolding(options, data, checked, stops) {
3150
3235
  const heldReadAt = new Map();
3151
3236
  const HELD_WAIT_REREAD_MS = 1_000;
3152
3237
  const waitKinds = new Set(["question", "approval", "budget", "browser"]);
3153
- /** The wait of a run its runner left parked (or let go of), told once as main told it: its marker the run's last row
3154
- * that shows (not usage, a phase or learning's), its kind the pending card's (a stop's when it waits on no card). */
3238
+ /** The wait of a run its runner left parked (or let go of), or holds in its claim, told once per ask: its marker the
3239
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). */
3155
3240
  const tellWait = async (row) => {
3156
3241
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
3157
3242
  if (readWaits.get(row.id) === seen)
@@ -3160,13 +3245,14 @@ async function startHolding(options, data, checked, stops) {
3160
3245
  if (view?.status !== "input_required")
3161
3246
  return void readWaits.set(row.id, seen);
3162
3247
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3163
- const marker = rows.findLast((r) => r.kind !== "usage" && r.kind !== "phase" && r.agent_label !== LEARNING_LABEL)?.id;
3248
+ // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3249
+ const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3164
3250
  if (!marker)
3165
3251
  return void readWaits.set(row.id, seen);
3166
3252
  const card = view.pending?.kind;
3167
3253
  const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3168
3254
  const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
3169
- if (webhooks.emit("run.needs_input", notice, marker) !== "unsaved")
3255
+ if ((await webhooks.emit("run.needs_input", notice, marker)) !== "unsaved")
3170
3256
  readWaits.set(row.id, seen);
3171
3257
  };
3172
3258
  let openRuns = new Set();
@@ -3206,7 +3292,7 @@ async function startHolding(options, data, checked, stops) {
3206
3292
  heldReadAt.delete(id);
3207
3293
  if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3208
3294
  continue;
3209
- if (webhooks.emit("run.ended", now.notice, now.endedAt) !== "unsaved")
3295
+ if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
3210
3296
  toldEnds.set(id, now.endedAt);
3211
3297
  }
3212
3298
  openRuns = open;
@@ -3268,6 +3354,7 @@ async function startHolding(options, data, checked, stops) {
3268
3354
  await githubStopped;
3269
3355
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
3270
3356
  await store.close();
3357
+ seal.release();
3271
3358
  }
3272
3359
  return {
3273
3360
  url,