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

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 (568) hide show
  1. package/CHANGELOG.md +452 -0
  2. package/README.md +311 -142
  3. package/dist/agent-rows.d.ts +1 -1
  4. package/dist/agents-store.d.ts +35 -3
  5. package/dist/agents-store.js +39 -14
  6. package/dist/answer-json.d.ts +34 -1
  7. package/dist/answer-json.js +91 -9
  8. package/dist/api-only.d.ts +1 -1
  9. package/dist/api-only.js +2 -2
  10. package/dist/attach-conformance-cli.d.ts +1 -0
  11. package/dist/attach-conformance-cli.js +18 -0
  12. package/dist/attach-conformance.d.ts +25 -0
  13. package/dist/attach-conformance.js +343 -0
  14. package/dist/browser-cost.d.ts +1 -1
  15. package/dist/browser-cost.js +52 -93
  16. package/dist/browser-live.d.ts +20 -8
  17. package/dist/browser-live.js +50 -27
  18. package/dist/cap.d.ts +0 -407
  19. package/dist/cap.js +4 -1028
  20. package/dist/catalog.d.ts +1 -12
  21. package/dist/catalog.js +4 -34
  22. package/dist/cli.js +13 -4
  23. package/dist/composio-preset.d.ts +53 -0
  24. package/dist/composio-preset.js +221 -0
  25. package/dist/computer-attach.d.ts +125 -0
  26. package/dist/computer-attach.js +330 -0
  27. package/dist/computer-calls.d.ts +60 -0
  28. package/dist/computer-calls.js +209 -0
  29. package/dist/computer-channel.d.ts +57 -0
  30. package/dist/computer-channel.js +115 -0
  31. package/dist/computer-commands.d.ts +1 -1
  32. package/dist/computer-held-routes.d.ts +35 -0
  33. package/dist/computer-held-routes.js +106 -0
  34. package/dist/computer-held.d.ts +48 -0
  35. package/dist/computer-held.js +87 -0
  36. package/dist/computer-keys.d.ts +21 -1
  37. package/dist/computer-keys.js +53 -11
  38. package/dist/computer-live.d.ts +165 -0
  39. package/dist/computer-live.js +655 -0
  40. package/dist/computer-setting.d.ts +15 -2
  41. package/dist/computer-setting.js +20 -4
  42. package/dist/computer-view.d.ts +14 -0
  43. package/dist/computer-view.js +51 -3
  44. package/dist/computer-viewer.d.ts +6 -0
  45. package/dist/computer-viewer.js +311 -0
  46. package/dist/computers.d.ts +37 -8
  47. package/dist/computers.js +62 -14
  48. package/dist/console/assets/index-CjqQirbo.css +1 -0
  49. package/dist/console/assets/index-b6-XY5A9.js +576 -0
  50. package/dist/console/index.html +2 -2
  51. package/dist/console-links.d.ts +2 -0
  52. package/dist/console-links.js +3 -0
  53. package/dist/decisions.js +4 -0
  54. package/dist/faux-computers.d.ts +9 -20
  55. package/dist/faux-computers.js +56 -26
  56. package/dist/github-connection.d.ts +10 -2
  57. package/dist/github-connection.js +65 -2
  58. package/dist/github-faux.js +1 -1
  59. package/dist/graph-view.d.ts +1 -1
  60. package/dist/harness-opencode/adapter.js +7 -3
  61. package/dist/harness-opencode/facts.js +0 -2
  62. package/dist/harness-opencode/host/policy.d.ts +2 -5
  63. package/dist/harness-opencode/host/policy.js +8 -32
  64. package/dist/harness-table.d.ts +0 -2
  65. package/dist/harness-table.js +0 -2
  66. package/dist/harness.d.ts +1 -0
  67. package/dist/harness.js +35 -1
  68. package/dist/host-tools.d.ts +2 -6
  69. package/dist/host-tools.js +7 -10
  70. package/dist/hosted-search.d.ts +5 -6
  71. package/dist/hosted-search.js +2 -28
  72. package/dist/import-sources.d.ts +10 -0
  73. package/dist/import-sources.js +44 -2
  74. package/dist/import.d.ts +3 -3
  75. package/dist/import.js +37 -6
  76. package/dist/key-words.d.ts +3 -2
  77. package/dist/key-words.js +4 -2
  78. package/dist/learn/check.d.ts +10 -2
  79. package/dist/learn/check.js +13 -5
  80. package/dist/learn/commit.d.ts +14 -2
  81. package/dist/learn/commit.js +23 -9
  82. package/dist/learn/compile.d.ts +243 -0
  83. package/dist/learn/compile.js +471 -0
  84. package/dist/learn/folder.d.ts +6 -0
  85. package/dist/learn/folder.js +4 -1
  86. package/dist/learn/general.d.ts +69 -0
  87. package/dist/learn/general.js +75 -0
  88. package/dist/learn/grade.d.ts +5 -1
  89. package/dist/learn/grade.js +29 -7
  90. package/dist/learn/notes.d.ts +8 -0
  91. package/dist/learn/notes.js +18 -0
  92. package/dist/learn/promote.d.ts +253 -0
  93. package/dist/learn/promote.js +428 -0
  94. package/dist/learn/refit.d.ts +39 -0
  95. package/dist/learn/refit.js +236 -0
  96. package/dist/learn/reflect.d.ts +9 -20
  97. package/dist/learn/reflect.js +18 -125
  98. package/dist/learn/replay-calls.d.ts +63 -0
  99. package/dist/learn/replay-calls.js +158 -0
  100. package/dist/learn/skills.d.ts +50 -14
  101. package/dist/learn/skills.js +183 -47
  102. package/dist/learn/workflow-nodes.d.ts +15 -0
  103. package/dist/learn/workflow-nodes.js +44 -0
  104. package/dist/learned-nodes.d.ts +50 -2
  105. package/dist/learned-nodes.js +41 -2
  106. package/dist/learned-workflow.d.ts +43 -3
  107. package/dist/learned-workflow.js +170 -28
  108. package/dist/learning-batch.d.ts +283 -0
  109. package/dist/learning-batch.js +574 -0
  110. package/dist/learning-cost.d.ts +18 -6
  111. package/dist/learning-cost.js +15 -7
  112. package/dist/learning-evals.d.ts +33 -0
  113. package/dist/learning-evals.js +98 -0
  114. package/dist/learning-routes.d.ts +37 -2
  115. package/dist/learning-routes.js +52 -8
  116. package/dist/learning-words.d.ts +13 -0
  117. package/dist/learning-words.js +13 -0
  118. package/dist/learning.d.ts +55 -17
  119. package/dist/learning.js +91 -48
  120. package/dist/live/stream.js +6 -3
  121. package/dist/live/translate.d.ts +4 -3
  122. package/dist/live/translate.js +8 -4
  123. package/dist/live-reach.d.ts +37 -0
  124. package/dist/live-reach.js +62 -0
  125. package/dist/llm.js +0 -3
  126. package/dist/mcp-gateway.d.ts +21 -20
  127. package/dist/mcp-gateway.js +76 -55
  128. package/dist/mcp-oauth.d.ts +62 -7
  129. package/dist/mcp-oauth.js +134 -19
  130. package/dist/mcp-pin-first.d.ts +37 -0
  131. package/dist/mcp-pin-first.js +107 -0
  132. package/dist/mcp-private-hosts.d.ts +4 -4
  133. package/dist/mcp-private-hosts.js +20 -12
  134. package/dist/mcp-probe.d.ts +27 -11
  135. package/dist/mcp-probe.js +60 -42
  136. package/dist/mcp-secret-writes.js +4 -0
  137. package/dist/mcp-servers-store.d.ts +115 -25
  138. package/dist/mcp-servers-store.js +241 -43
  139. package/dist/mcp-sources.d.ts +39 -0
  140. package/dist/mcp-sources.js +74 -0
  141. package/dist/mcp-store.d.ts +21 -4
  142. package/dist/mcp-store.js +33 -8
  143. package/dist/mcp-wire.d.ts +22 -0
  144. package/dist/mcp-wire.js +36 -0
  145. package/dist/mcp.js +3 -3
  146. package/dist/meta-tool-names.d.ts +1 -0
  147. package/dist/meta-tool-names.js +3 -0
  148. package/dist/model-form.d.ts +26 -0
  149. package/dist/model-form.js +80 -0
  150. package/dist/model.d.ts +13 -0
  151. package/dist/model.js +69 -25
  152. package/dist/monid.d.ts +51 -25
  153. package/dist/monid.js +226 -140
  154. package/dist/openapi.js +694 -59
  155. package/dist/page.d.ts +18 -0
  156. package/dist/page.js +48 -20
  157. package/dist/paid-calls.d.ts +26 -29
  158. package/dist/paid-calls.js +46 -102
  159. package/dist/place-offers.d.ts +2 -3
  160. package/dist/place-offers.js +3 -7
  161. package/dist/place.js +1 -2
  162. package/dist/print.d.ts +15 -1
  163. package/dist/print.js +14 -3
  164. package/dist/propose.d.ts +10 -1
  165. package/dist/propose.js +30 -10
  166. package/dist/provider.js +12 -4
  167. package/dist/reflect-range.d.ts +8 -1
  168. package/dist/reflect-range.js +3 -2
  169. package/dist/rows.d.ts +5 -3
  170. package/dist/rows.js +15 -4
  171. package/dist/run-launch.d.ts +27 -2
  172. package/dist/run-launch.js +15 -4
  173. package/dist/run-learning-served.d.ts +13 -2
  174. package/dist/run-manifest.d.ts +5 -0
  175. package/dist/run-manifest.js +20 -0
  176. package/dist/run-reads-over-store.d.ts +1 -1
  177. package/dist/run-repo.d.ts +20 -0
  178. package/dist/run-repo.js +63 -0
  179. package/dist/run-secrets.js +2 -3
  180. package/dist/run-timeline-served.d.ts +1 -1
  181. package/dist/run-timeline-served.js +5 -2
  182. package/dist/run-view.d.ts +19 -8
  183. package/dist/run-view.js +62 -26
  184. package/dist/runnable.d.ts +0 -3
  185. package/dist/runnable.js +37 -29
  186. package/dist/runner/adapter-loop.d.ts +47 -17
  187. package/dist/runner/adapter-loop.js +1427 -303
  188. package/dist/runner/adapter-run-spec.d.ts +23 -9
  189. package/dist/runner/adapter-run-spec.js +162 -56
  190. package/dist/runner/adapters/pi-computer.d.ts +9 -0
  191. package/dist/runner/adapters/pi-computer.js +51 -0
  192. package/dist/runner/adapters/pi.d.ts +25 -11
  193. package/dist/runner/adapters/pi.js +168 -45
  194. package/dist/runner/beside.d.ts +7 -3
  195. package/dist/runner/beside.js +21 -11
  196. package/dist/runner/claim-secrets.d.ts +4 -0
  197. package/dist/runner/claim-secrets.js +6 -1
  198. package/dist/runner/cli-run-spec.d.ts +20 -3
  199. package/dist/runner/cli-run-spec.js +174 -64
  200. package/dist/runner/commands.d.ts +3 -1
  201. package/dist/runner/commands.js +28 -3
  202. package/dist/runner/computer-channel.d.ts +34 -0
  203. package/dist/runner/computer-channel.js +62 -0
  204. package/dist/runner/conformance/harness.d.ts +3 -0
  205. package/dist/runner/conformance/harness.js +224 -17
  206. package/dist/runner/conformance/subject.d.ts +12 -5
  207. package/dist/runner/dispatch.js +3 -0
  208. package/dist/runner/end-of-run.d.ts +23 -12
  209. package/dist/runner/end-of-run.js +41 -16
  210. package/dist/runner/feedback-round.d.ts +52 -0
  211. package/dist/runner/feedback-round.js +79 -0
  212. package/dist/runner/github-app.d.ts +2 -1
  213. package/dist/runner/github-app.js +4 -2
  214. package/dist/runner/harness-loops.js +15 -1
  215. package/dist/runner/held-run.d.ts +65 -0
  216. package/dist/runner/held-run.js +158 -0
  217. package/dist/runner/journal-kinds.d.ts +44 -7
  218. package/dist/runner/journal-kinds.js +29 -0
  219. package/dist/runner/journal-reader.d.ts +5 -4
  220. package/dist/runner/journal-reader.js +12 -10
  221. package/dist/runner/learning-ask.d.ts +7 -1
  222. package/dist/runner/learning-ask.js +21 -6
  223. package/dist/runner/learning-dispatch.d.ts +22 -0
  224. package/dist/runner/learning-dispatch.js +77 -10
  225. package/dist/runner/learning-end.d.ts +69 -13
  226. package/dist/runner/learning-end.js +340 -87
  227. package/dist/runner/learning-factory.d.ts +1 -1
  228. package/dist/runner/learning-factory.js +11 -5
  229. package/dist/runner/learning-loop.d.ts +86 -8
  230. package/dist/runner/learning-loop.js +178 -23
  231. package/dist/runner/learning-seed.d.ts +11 -0
  232. package/dist/runner/learning-seed.js +27 -0
  233. package/dist/runner/live-ticker.js +1 -0
  234. package/dist/runner/loop-contract.d.ts +26 -3
  235. package/dist/runner/loop.d.ts +21 -2
  236. package/dist/runner/loop.js +23 -2
  237. package/dist/runner/main.d.ts +13 -1
  238. package/dist/runner/main.js +27 -5
  239. package/dist/runner/mcp-claim.d.ts +15 -8
  240. package/dist/runner/mcp-claim.js +176 -71
  241. package/dist/runner/mcp-github.js +1 -1
  242. package/dist/runner/mcp-run.d.ts +21 -57
  243. package/dist/runner/mcp-run.js +25 -85
  244. package/dist/runner/meta-tools.d.ts +37 -0
  245. package/dist/runner/meta-tools.js +268 -0
  246. package/dist/runner/metrics.d.ts +11 -2
  247. package/dist/runner/metrics.js +26 -5
  248. package/dist/runner/model-route.js +12 -3
  249. package/dist/runner/monid-run.d.ts +16 -0
  250. package/dist/runner/monid-run.js +96 -0
  251. package/dist/runner/pr-checkout.d.ts +1 -0
  252. package/dist/runner/pr-checkout.js +1 -1
  253. package/dist/runner/promotion.d.ts +80 -0
  254. package/dist/runner/promotion.js +562 -0
  255. package/dist/runner/reflect-hook.d.ts +46 -13
  256. package/dist/runner/reflect-hook.js +149 -48
  257. package/dist/runner/runner.d.ts +26 -0
  258. package/dist/runner/runner.js +208 -17
  259. package/dist/runner/scratch-sweep.d.ts +13 -0
  260. package/dist/runner/scratch-sweep.js +62 -0
  261. package/dist/runner/sessions.d.ts +9 -4
  262. package/dist/runner/sessions.js +5 -1
  263. package/dist/runner/step-guard.d.ts +62 -0
  264. package/dist/runner/step-guard.js +93 -0
  265. package/dist/runner/store-port.d.ts +4 -2
  266. package/dist/runner/store-secrets.js +4 -3
  267. package/dist/runner/subagent.d.ts +0 -3
  268. package/dist/runner/subagent.js +10 -13
  269. package/dist/runner/workflow-first.d.ts +216 -0
  270. package/dist/runner/workflow-first.js +303 -0
  271. package/dist/runner/workflow-host.d.ts +6 -1
  272. package/dist/runner/workflow-host.js +1 -1
  273. package/dist/runner/workflow-loop.d.ts +1 -1
  274. package/dist/runner/workflow-loop.js +17 -10
  275. package/dist/runner/workflow-spec.d.ts +15 -2
  276. package/dist/runner/workflow-spec.js +63 -23
  277. package/dist/runs-over-store.d.ts +17 -3
  278. package/dist/runs-over-store.js +59 -20
  279. package/dist/seal-key.js +3 -3
  280. package/dist/sealed-settings-store.d.ts +5 -2
  281. package/dist/sealed-settings-store.js +10 -4
  282. package/dist/secret-writes.d.ts +5 -4
  283. package/dist/secret-writes.js +5 -4
  284. package/dist/server-secrets-store.d.ts +4 -3
  285. package/dist/server-secrets-store.js +15 -9
  286. package/dist/server-secrets.js +3 -2
  287. package/dist/server.d.ts +119 -18
  288. package/dist/server.js +841 -202
  289. package/dist/settings-wake.d.ts +23 -0
  290. package/dist/settings-wake.js +65 -0
  291. package/dist/standard-webhooks.d.ts +4 -1
  292. package/dist/standard-webhooks.js +8 -4
  293. package/dist/store/agent-body.d.ts +14 -3
  294. package/dist/store/agent-body.js +14 -10
  295. package/dist/store/command-wake.d.ts +13 -0
  296. package/dist/store/command-wake.js +37 -0
  297. package/dist/store/dialect.d.ts +6 -0
  298. package/dist/store/dialect.js +5 -0
  299. package/dist/store/index.d.ts +1 -1
  300. package/dist/store/journal/storage.d.ts +3 -2
  301. package/dist/store/journal/storage.js +13 -5
  302. package/dist/store/postgres/connection.js +3 -1
  303. package/dist/store/postgres/dialect.js +4 -0
  304. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  305. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  306. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  307. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  308. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  309. package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
  310. package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
  311. package/dist/store/schema.d.ts +10 -1
  312. package/dist/store/schema.js +104 -15
  313. package/dist/store/sqlite/connection.d.ts +2 -2
  314. package/dist/store/sqlite/connection.js +2 -2
  315. package/dist/store/sqlite/run-patch.d.ts +7 -5
  316. package/dist/store/sqlite/run-patch.js +45 -18
  317. package/dist/store/sqlite/store.js +331 -72
  318. package/dist/store/store.d.ts +312 -21
  319. package/dist/store/store.js +12 -1
  320. package/dist/store-reads/cap.d.ts +1 -1
  321. package/dist/store-reads/cap.js +8 -1
  322. package/dist/store-reads/decisions.d.ts +2 -2
  323. package/dist/store-reads/decisions.js +1 -1
  324. package/dist/store-reads/import-summary.d.ts +1 -1
  325. package/dist/store-reads/journal.d.ts +30 -5
  326. package/dist/store-reads/journal.js +128 -56
  327. package/dist/store-reads/learning.d.ts +114 -12
  328. package/dist/store-reads/learning.js +238 -48
  329. package/dist/store-reads/loop.d.ts +61 -0
  330. package/dist/store-reads/loop.js +111 -0
  331. package/dist/store-reads/runs.d.ts +1 -1
  332. package/dist/store-reads/workflow.d.ts +1 -1
  333. package/dist/store-view.d.ts +6 -0
  334. package/dist/store-view.js +59 -26
  335. package/dist/template-eval.d.ts +18 -9
  336. package/dist/template-eval.js +95 -68
  337. package/dist/template-github-permissions.d.ts +24 -10
  338. package/dist/template-github-permissions.js +36 -15
  339. package/dist/template-import.d.ts +31 -0
  340. package/dist/template-import.js +121 -0
  341. package/dist/template-source.d.ts +51 -0
  342. package/dist/template-source.js +371 -0
  343. package/dist/templates.d.ts +218 -46
  344. package/dist/templates.js +493 -181
  345. package/dist/timeline/computer.d.ts +48 -0
  346. package/dist/timeline/computer.js +169 -0
  347. package/dist/timeline/index.d.ts +4 -3
  348. package/dist/timeline/index.js +4 -3
  349. package/dist/timeline/labels.d.ts +6 -2
  350. package/dist/timeline/labels.js +93 -2
  351. package/dist/timeline/origin.d.ts +19 -5
  352. package/dist/timeline/origin.js +11 -4
  353. package/dist/timeline/timeline.d.ts +22 -1
  354. package/dist/timeline/timeline.js +34 -18
  355. package/dist/timeline/util.d.ts +4 -0
  356. package/dist/timeline/util.js +14 -0
  357. package/dist/tool-gate.d.ts +84 -50
  358. package/dist/tool-gate.js +179 -101
  359. package/dist/tool-keys.d.ts +4 -1
  360. package/dist/tool-keys.js +8 -3
  361. package/dist/tool-list.d.ts +26 -0
  362. package/dist/tool-list.js +43 -0
  363. package/dist/tool-names.d.ts +71 -0
  364. package/dist/tool-names.js +99 -0
  365. package/dist/tool-plane.d.ts +33 -27
  366. package/dist/tool-plane.js +72 -39
  367. package/dist/tools.d.ts +32 -7
  368. package/dist/tools.js +37 -24
  369. package/dist/trigger-adapter.d.ts +4 -0
  370. package/dist/trigger-secrets-shown.d.ts +2 -2
  371. package/dist/trigger-secrets-shown.js +1 -1
  372. package/dist/trigger-signatures.d.ts +25 -6
  373. package/dist/trigger-signatures.js +41 -7
  374. package/dist/trigger-targets.d.ts +2 -0
  375. package/dist/trigger-targets.js +1 -0
  376. package/dist/trigger-webhook.js +5 -2
  377. package/dist/triggers.d.ts +7 -3
  378. package/dist/triggers.js +35 -5
  379. package/dist/turns.js +16 -1
  380. package/dist/validate.d.ts +15 -7
  381. package/dist/validate.js +102 -45
  382. package/dist/web-fetch.d.ts +2 -8
  383. package/dist/web-fetch.js +2 -22
  384. package/dist/web-search.d.ts +10 -5
  385. package/dist/web-search.js +7 -6
  386. package/dist/webhooks.d.ts +145 -102
  387. package/dist/webhooks.js +559 -322
  388. package/dist/workflow/decisions.d.ts +1 -1
  389. package/dist/workflow/node-runner.d.ts +2 -1
  390. package/dist/workflow/node.d.ts +2 -1
  391. package/dist/workflow/node.js +3 -1
  392. package/dist/workflow/pi-versions.d.ts +23 -0
  393. package/dist/workflow/pi-versions.js +57 -0
  394. package/dist/workflow/record-tool.d.ts +2 -1
  395. package/dist/workflow/store.d.ts +1 -1
  396. package/dist/workflow/task.js +3 -2
  397. package/dist/workflow-run.d.ts +1 -1
  398. package/dist/workspace/attached-computers.d.ts +41 -0
  399. package/dist/workspace/attached-computers.js +114 -0
  400. package/dist/workspace/computer-deps.d.ts +19 -9
  401. package/dist/workspace/computer-deps.js +24 -9
  402. package/dist/workspace/computer-for-claim.d.ts +23 -8
  403. package/dist/workspace/computer-for-claim.js +92 -33
  404. package/dist/workspace/computer-hold.d.ts +11 -27
  405. package/dist/workspace/computer-hold.js +41 -55
  406. package/dist/workspace/computer-ledger.d.ts +3 -1
  407. package/dist/workspace/computer-ledger.js +4 -0
  408. package/dist/workspace/computer-mcp.d.ts +25 -0
  409. package/dist/workspace/computer-mcp.js +41 -0
  410. package/dist/workspace/computer-ports.d.ts +4 -13
  411. package/dist/workspace/computer-ports.js +4 -107
  412. package/dist/workspace/computer-script.d.ts +53 -0
  413. package/dist/workspace/computer-script.js +172 -0
  414. package/dist/workspace/executors.d.ts +1 -1
  415. package/dist/workspace/index.d.ts +4 -2
  416. package/dist/workspace/index.js +3 -1
  417. package/dist/workspace/kind-skills/desktop/SKILL.md +132 -84
  418. package/dist/workspace/kind-skills/phone/SKILL.md +104 -85
  419. package/dist/workspace/local.js +2 -2
  420. package/dist/workspace/resolve-computer.d.ts +24 -1
  421. package/dist/workspace/resolve-computer.js +40 -16
  422. package/dist/workspace/run-tools.d.ts +56 -21
  423. package/dist/workspace/run-tools.js +55 -34
  424. package/dist/wrap-up.d.ts +21 -0
  425. package/dist/wrap-up.js +21 -0
  426. package/launcher/agentrun-serve +4 -2
  427. package/package.json +19 -16
  428. package/templates/README.md +111 -45
  429. package/templates/code-review/agent.md +30 -14
  430. package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
  431. package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
  432. package/templates/code-review/evals/injection/case.yaml +2 -1
  433. package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
  434. package/templates/code-review/evals/mentions-defused/case.yaml +2 -2
  435. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
  436. package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
  437. package/templates/code-review/evals/never-flag/case.yaml +2 -1
  438. package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
  439. package/templates/code-review/evals/null-name/case.yaml +2 -1
  440. package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
  441. package/templates/code-review/evals/off-by-one/case.yaml +2 -1
  442. package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
  443. package/templates/code-review/evals/other-repo/case.yaml +16 -0
  444. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
  445. package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
  446. package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
  447. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
  448. package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
  449. package/templates/code-review/evals/other-repo/prompt.md +10 -0
  450. package/templates/code-review/evals/re-review/case.yaml +2 -1
  451. package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
  452. package/templates/code-review/evals/re-review-open/case.yaml +2 -1
  453. package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
  454. package/templates/code-review/evals/repo-rule/case.yaml +2 -1
  455. package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
  456. package/templates/code-review/evals/two-defects/case.yaml +2 -1
  457. package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
  458. package/templates/code-review/rules/CODEREVIEW.md +1 -1
  459. package/templates/code-review/skills/review/DEEP.md +3 -2
  460. package/templates/code-review/skills/review/REVIEWER.md +3 -2
  461. package/templates/code-review/skills/review/SKILL.md +4 -3
  462. package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
  463. package/templates/inbound-lead/agent.md +26 -16
  464. package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
  465. package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
  466. package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
  467. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
  468. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
  469. package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
  470. package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
  471. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
  472. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
  473. package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
  474. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
  475. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
  476. package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
  477. package/templates/kyb/agent.md +15 -5
  478. package/templates/kyb/evals/adverse-media/prompt.md +2 -7
  479. package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
  480. package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
  481. package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
  482. package/templates/kyb/evals/name-collision/prompt.md +2 -6
  483. package/templates/kyb/evals/no-invention/prompt.md +2 -6
  484. package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
  485. package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
  486. package/templates/kyb/kyb.schema.json +8 -7
  487. package/templates/kyb/skills/kyb/SKILL.md +9 -6
  488. package/templates/market-monitor/agent.md +19 -12
  489. package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
  490. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
  491. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
  492. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
  493. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  494. package/templates/release-notes/agent.md +32 -10
  495. package/templates/release-notes/evals/draft-not-publish/case.yaml +4 -3
  496. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
  497. package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
  498. package/templates/release-notes/evals/issue-write-refused/case.yaml +4 -3
  499. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
  500. package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
  501. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
  502. package/templates/release-notes/evals/learned-style/case.yaml +2 -1
  503. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
  504. package/templates/release-notes/evals/other-repo/case.yaml +24 -0
  505. package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
  506. package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
  507. package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
  508. package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
  509. package/templates/release-notes/evals/other-repo/prompt.md +32 -0
  510. package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
  511. package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
  512. package/templates/release-notes/notes.schema.json +1 -1
  513. package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
  514. package/dist/console/assets/index-BI4Byidu.js +0 -550
  515. package/dist/console/assets/index-C19gUF2n.css +0 -1
  516. package/dist/run-db.d.ts +0 -53
  517. package/dist/run-db.js +0 -116
  518. package/dist/tool-blurbs.d.ts +0 -4
  519. package/dist/tool-blurbs.js +0 -28
  520. package/dist/tool-budget.d.ts +0 -26
  521. package/dist/tool-budget.js +0 -56
  522. package/dist/workflow/readers.d.ts +0 -36
  523. package/dist/workflow/readers.js +0 -145
  524. package/dist/workflow/wal.d.ts +0 -11
  525. package/dist/workflow/wal.js +0 -106
  526. package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
  527. package/templates/code-review/evals/injection/graders/schema.md +0 -5
  528. package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
  529. package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
  530. package/templates/code-review/evals/null-name/graders/schema.md +0 -5
  531. package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
  532. package/templates/code-review/evals/re-review/graders/schema.md +0 -5
  533. package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
  534. package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
  535. package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
  536. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
  537. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
  538. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
  539. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
  540. package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
  541. package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
  542. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
  543. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
  544. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
  545. package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
  546. package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
  547. package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
  548. package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
  549. package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
  550. package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
  551. package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
  552. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
  553. package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
  554. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
  555. package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
  556. package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
  557. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
  558. package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
  559. package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
  560. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
  561. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
  562. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
  563. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
  564. package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
  565. package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
  566. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
  567. package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
  568. package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
package/dist/server.js CHANGED
@@ -12,14 +12,15 @@ import { once } from "node:events";
12
12
  import { existsSync } from "node:fs";
13
13
  import { rm } from "node:fs/promises";
14
14
  import { homedir } from "node:os";
15
- import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
15
+ import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
16
+ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
16
17
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
17
18
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
18
19
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
19
- import { FAUX_MONID_ENV } from "./monid.js";
20
+ import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid } from "./monid.js";
20
21
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
21
22
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
22
- import { ApiError, invalid, unsupported } from "./errors.js";
23
+ import { ApiError, invalid, sentence, unsupported } from "./errors.js";
23
24
  import { deref, explain } from "./explain.js";
24
25
  import { HOME_HOST_OWNED } from "./files.js";
25
26
  import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
@@ -31,19 +32,20 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
31
32
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
32
33
  import { IMPORT_ASKED } from "./import.js";
33
34
  import { answerStoreCall } from "./import-proxy.js";
34
- import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, seedOf } from "./learning.js";
35
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
35
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
36
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
36
37
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
37
38
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
38
39
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
39
40
  import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
40
41
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
41
42
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
42
- import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
43
+ import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
43
44
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
44
- import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
45
+ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
45
46
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
- import { computerView } from "./computer-view.js";
47
+ import { computerView, sessionIn } from "./computer-view.js";
48
+ import { liveReachOf } from "./live-reach.js";
47
49
  import { screenWaitEnded } from "./browser-wait-ended.js";
48
50
  import { durationMs, logLine } from "./print.js";
49
51
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
@@ -65,7 +67,9 @@ import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
65
67
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
66
68
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
67
69
  import { answerOf, logged } from "./agents.js";
68
- import { FINAL_STATES } from "./store/store.js";
70
+ import { LABEL_MAX, openFeedbackRound } from "./runner/feedback-round.js";
71
+ import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
72
+ import { GRADE_SOURCES, gradeView, promotionsOf, promotionsShown, putGrade } from "./learn/promote.js";
69
73
  import { runModelRef } from "./model.js";
70
74
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
71
75
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
@@ -76,25 +80,32 @@ import { dockerDaemonCheck } from "./docker-daemon.js";
76
80
  import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
77
81
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
78
82
  import { CAP_MODES } from "./cap.js";
79
- import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
83
+ import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
80
84
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
81
85
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
82
86
  import { bootSealKey, withSealKey } from "./seal-key.js";
83
87
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
84
88
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
85
89
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
86
- import { agentCostOverStore, agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
87
- import { costCsv, learningCostQuery } from "./learning-cost.js";
90
+ import { agentLoopOverStore } from "./store-reads/loop.js";
91
+ import { printable } from "./learn/index.js";
92
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
93
+ import { figuresOf, LearningBatches } from "./learning-batch.js";
94
+ import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
95
+ import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
88
96
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
89
97
  import { toolKeysOverStore } from "./tool-keys-store.js";
90
98
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
91
99
  import { signInsOverStore } from "./sign-ins-store.js";
92
- import { MCP_AUTH_TYPES, mcpAuthOf } from "./mcp-probe.js";
100
+ import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
101
+ import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
93
102
  import { mcpServersOverStore } from "./mcp-servers-store.js";
103
+ import { getMcpServer, listMcpServers } from "./mcp-store.js";
94
104
  import { privateHostsRoute } from "./mcp-private-hosts.js";
95
105
  import { metaToolOf } from "./mcp-meta.js";
106
+ import { mcpPinOf } from "./mcp-gateway.js";
96
107
  import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
97
- import { OUTBOUND_WEBHOOK, WEBHOOK_EVENTS, waitMarkerOf, Webhooks } from "./webhooks.js";
108
+ import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
98
109
  import { appPermissionWarnings } from "./template-github-permissions.js";
99
110
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
100
111
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
@@ -102,28 +113,37 @@ import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
102
113
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
103
114
  import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
104
115
  import { GITHUB_API } from "./github.js";
116
+ import { bindingOf, REPO_NAME } from "./run-repo.js";
105
117
  import { HookCut, receivePush } from "./push-handler.js";
106
118
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
107
119
  import { webhook } from "./trigger-webhook.js";
108
120
  import { SCHEME_NAMES } from "./trigger-signatures.js";
109
- import { permissionFrom } from "./tool-gate.js";
121
+ import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
122
+ import { isMcpWildcard, mcpNameOf as mcpToolOf, mcpToolName, monidDroppedWords, monidNameOf } from "./tool-names.js";
123
+ import { wireName } from "./catalog.js";
110
124
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
111
- import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
112
- import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
113
- import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
125
+ import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
126
+ import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
127
+ import { templateInstallLink, templateLink } from "./console-links.js";
128
+ import { GITHUB_HOSTS } from "./template-source.js";
129
+ import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
130
+ import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
131
+ import { wakeAnsweredBySetting } from "./settings-wake.js";
114
132
  import { toolSettingsOverStore } from "./tool-settings-store.js";
115
133
  import { readApprovers, writeApprovers } from "./server-approvers.js";
116
134
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
117
135
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
118
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
119
- import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
120
- import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
136
+ import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
137
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
138
+ import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
139
+ import { createAttachRoutes, pairedView } from "./computer-attach.js";
140
+ import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
141
+ import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
121
142
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
122
143
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
123
144
  import { computerOfPlace } from "./computer-setting.js";
124
145
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
125
- import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
126
- import { runComputerField } from "./run-computer.js";
146
+ import { fauxComputers } from "./faux-computers.js";
127
147
  import { writesHeld } from "./workspace.js";
128
148
  import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
129
149
  import { keyReader } from "./key-meta.js";
@@ -219,6 +239,8 @@ export const ROUTES = [
219
239
  { method: "POST", pattern: /^\/runs\/([^/]+)\/cancel$/, name: "cancelRun" },
220
240
  { method: "POST", pattern: /^\/runs\/([^/]+)\/approvals\/([^/]+)$/, name: "answerApproval" },
221
241
  { method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
242
+ // A person's or an eval's grade of an ended run (learn/promote.ts): what promotion by replay reads.
243
+ { method: "PUT", pattern: /^\/runs\/([^/]+)\/grade$/, name: "gradeRun" },
222
244
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
223
245
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
224
246
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
@@ -232,11 +254,24 @@ export const ROUTES = [
232
254
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
233
255
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
234
256
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
257
+ // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
258
+ // protocol calls, and keeps its computer after its agent's end until released.
259
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/start$/, name: "startRun" },
260
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/call$/, name: "callRunComputer" },
261
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/release$/, name: "releaseRunComputer" },
235
262
  // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
236
263
  // archilRoute): the server switch dispatches them, once the server opens its store.
237
264
  { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
238
265
  { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
239
266
  { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
267
+ { method: "GET", pattern: /^\/computers\/([^/]+)\/choices$/, name: "listComputerChoices" },
268
+ // A person's own computer paired with this server (computer-attach.ts): the owner's code, the driver's trade of it for
269
+ // its token (no token of the server's: the code is the credential), the attach socket (a WebSocket: the server's
270
+ // upgrade takes it; a plain GET is told so), and a computer's removal.
271
+ { method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
272
+ { method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
273
+ { method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
274
+ { method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
240
275
  { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
241
276
  { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
242
277
  { method: "DELETE", pattern: /^\/workspace\/archil$/, name: "deleteWorkspaceArchil" },
@@ -255,8 +290,10 @@ export const ROUTES = [
255
290
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
256
291
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
257
292
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
293
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
258
294
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
259
295
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
296
+ { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
260
297
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
261
298
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
262
299
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -283,6 +320,8 @@ export const ROUTES = [
283
320
  { method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
284
321
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
285
322
  { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
323
+ { method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
324
+ { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
286
325
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
287
326
  // Answered before the bearer check: the request's signature is its credential.
288
327
  { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
@@ -295,6 +334,14 @@ export const ROUTES = [
295
334
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
296
335
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
297
336
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
337
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
338
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
339
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
340
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
341
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
342
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
343
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
344
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/loop$/, name: "getLearningLoop" },
298
345
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
299
346
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
300
347
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
@@ -302,6 +349,7 @@ export const ROUTES = [
302
349
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
303
350
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
304
351
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
352
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
305
353
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
306
354
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
307
355
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
@@ -486,7 +534,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
486
534
  tool_keys: { routes: true, at_rest: "sealed" },
487
535
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
488
536
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
489
- mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...MCP_HARNESSES] },
537
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...HARNESSES] },
490
538
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
491
539
  learning,
492
540
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -660,6 +708,15 @@ async function startHolding(options, data, checked, stops) {
660
708
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
661
709
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
662
710
  stops.push(() => store.close());
711
+ // The packages served: the bundled ones, read and checked before the start, and those imported here, which the store
712
+ // keeps and are checked again as they load (template-import.ts). One that no longer checks is left out, said in the log.
713
+ const registry = new TemplateRegistry(templates);
714
+ await loadImported({ registry, store }, (id, why) => log?.(logLine("template_import_skipped", { template: id, why })));
715
+ // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
716
+ // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
717
+ // store is refused above (its owner lock).
718
+ const attachHub = new AttachHub();
719
+ const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
663
720
  // The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
664
721
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
665
722
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -708,24 +765,23 @@ async function startHolding(options, data, checked, stops) {
708
765
  const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
709
766
  if (options.githubMcpOrigin)
710
767
  mcpServers.appOrigin = options.githubMcpOrigin;
711
- // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
712
- // step (blockersOf's `mcp`, and the template apply): the server is the one writer of these rows (a save, refresh, sign-in
713
- // or delete), so the snapshot is refreshed after each of those and reads what is saved now. The runner reads the registry,
714
- // pins and credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP source.
768
+ mcpServers.standIns = options.mcpStandIns === true;
769
+ // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the checks read in step (which
770
+ // servers are saved, a workflow's grants, the template apply): the server is the one writer of these rows (a save,
771
+ // refresh, sign-in or delete), so the snapshot is refreshed after each of those and reads what is saved now. An agent's
772
+ // save lists its granted servers live and pins their tools on its revision (saveable, mcpListingOf); the runner reads
773
+ // that pin and the credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP
774
+ // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on.
715
775
  let mcpMeta = new Map();
716
776
  const refreshMcpMeta = async () => {
717
- mcpMeta = new Map((await store.mcp.servers()).map((row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [] }]));
777
+ mcpMeta = new Map(await Promise.all((await listMcpServers(store)).map(async (row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [], source: await mcpServers.sourceOf(row) }])));
718
778
  };
719
779
  await refreshMcpMeta();
720
780
  // Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
721
781
  // with whether each can be granted: a known meta tool can't (mcp-meta.ts).
722
782
  const mcpTools = (server) => {
723
783
  const saved = mcpMeta.get(server);
724
- return saved?.tools.map((tool) => {
725
- const meta = metaToolOf(saved.url, tool.name);
726
- const bound = { name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) };
727
- return meta ? { ...bound, grantable: false, reason: meta.reason } : bound;
728
- });
784
+ return saved && marked(saved.url, { tools: saved.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) })) }).tools;
729
785
  };
730
786
  // The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
731
787
  // once here.
@@ -820,6 +876,10 @@ async function startHolding(options, data, checked, stops) {
820
876
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
821
877
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
822
878
  const sealKey = seal.key;
879
+ // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
880
+ // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
881
+ const reach = liveReachOf(env, sealKey);
882
+ const answers = (handover) => viewerAnswers(handover, reach);
823
883
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
824
884
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
825
885
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -828,9 +888,9 @@ async function startHolding(options, data, checked, stops) {
828
888
  const browserToolNames = (await import("@parcha/pi-browser")).BROWSER_TOOLS.map((tool) => tool.name);
829
889
  const localTools = new Set(hostToolDefs({ maxExecS: 600, shell: "local" }).map((def) => def.name));
830
890
  const kindTools = (kind) => kind === "none" ? [] : kind === "sandbox" ? hostToolDefs({ maxExecS: 600, shell: "computer" }).map((def) => def.name).filter((name) => !localTools.has(name))
831
- : kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
891
+ : kind === "browser" ? browserToolNames : [...COMPUTER_TOOLS];
832
892
  let faux;
833
- const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
893
+ const fauxOf = () => (faux ??= fauxComputers());
834
894
  /** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
835
895
  * Computers' view and a run's start check (below) both ask it. Where AGENTRUN_BOXES lists Docker and it is no faux
836
896
  * Docker, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
@@ -859,6 +919,7 @@ async function startHolding(options, data, checked, stops) {
859
919
  const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
860
920
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
861
921
  store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
922
+ paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
862
923
  ...(options.faux
863
924
  // --faux's providers stand in for every vendor's, a local one's daemon included.
864
925
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -872,18 +933,29 @@ async function startHolding(options, data, checked, stops) {
872
933
  }));
873
934
  /** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
874
935
  * computerReadiness): over the registry the claim reads (workspace/computer-deps.ts claimKinds, asked with what the
875
- * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
876
- * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
936
+ * runner composes with: under --faux, faux's, as runner/main.ts runnerComputers gives its runs' faux; else the
937
+ * package's), in the folder mode of now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
877
938
  * runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
878
939
  * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers', and whether a
879
940
  * provider's program is on this machine is hostWhy's, read at the start. */
880
941
  /** The server's folder mode now: 2 when the owner's Archil settings are saved (the run's folder on the disk), else 1. */
881
942
  const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
882
- const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
943
+ /** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
944
+ const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
945
+ // A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
946
+ // attached to this process's hub.
947
+ const computerReady = async (setting) => {
948
+ const paired = await store.pairedComputers.list();
949
+ const row = paired.find((one) => one.id === setting.provider);
950
+ const offline = row ? pairedRefusal(row, attachHub) : undefined;
951
+ if (offline)
952
+ return { refused: offline };
953
+ return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
954
+ };
883
955
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
884
956
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
885
957
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
886
- const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
958
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
887
959
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
888
960
  * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
889
961
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
@@ -903,6 +975,19 @@ async function startHolding(options, data, checked, stops) {
903
975
  }
904
976
  return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
905
977
  };
978
+ /** Each package's computer list read against this server now, as a listing shows it (`computer_here`): what an apply
979
+ * here would pick (pickComputer), the shell asked for once for them all. */
980
+ const computerHere = async (packages) => {
981
+ const here = packages.some((one) => one.computer) ? await shellHere() : undefined;
982
+ return (pkg) => {
983
+ const pick = here && pickComputer(pkg, here);
984
+ if (!pick)
985
+ return null;
986
+ if ("refused" in pick)
987
+ return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
988
+ return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
989
+ };
990
+ };
906
991
  const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
907
992
  /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
908
993
  * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
@@ -912,16 +997,7 @@ async function startHolding(options, data, checked, stops) {
912
997
  return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
913
998
  };
914
999
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
915
- const runComputerOf = async (runId, view) => {
916
- const run = await store.runs.get(runId);
917
- const body = run ? (await store.agents.revision(run.revisionId))?.body : undefined;
918
- const setting = body?.computer ?? (body?.place ? computerOfPlace(body.place) : undefined);
919
- if (!setting)
920
- return {};
921
- const error = view.error;
922
- const field = runComputerField(setting, { id: runId, status: String(view.status), ...(error && typeof error.code === "string" ? { error: { code: error.code, message: String(error.message ?? "") } } : {}) });
923
- return field ? { computer: field } : {};
924
- };
1000
+ const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
925
1001
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
926
1002
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
927
1003
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -929,7 +1005,7 @@ async function startHolding(options, data, checked, stops) {
929
1005
  const agents = {
930
1006
  get: (id) => getAgent(store, id),
931
1007
  list: (options = {}) => listAgents(store, options),
932
- create: (body, check, fresh) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}) }),
1008
+ create: (body, check, fresh, template) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}), ...(template ? { template } : {}) }),
933
1009
  commit: (entry, body, options = {}) => commitAgent(store, entry, body, options),
934
1010
  revisions: (id) => agentRevisions(store, id),
935
1011
  revision: (agentId, revisionId) => agentRevision(store, agentId, revisionId),
@@ -951,11 +1027,17 @@ async function startHolding(options, data, checked, stops) {
951
1027
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
952
1028
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
953
1029
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
954
- // The outbound webhook and its outbox, in the store; its signing secret among the server's sealed settings, which list it
955
- // (and each one it held before) with the server's own secrets.
956
- 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);
957
- await webhooks.load();
1030
+ const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
1031
+ ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1032
+ privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1033
+ });
1034
+ // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
958
1035
  stops.push(() => webhooks.close());
1036
+ await webhooks.load();
1037
+ // Where an earlier version kept the webhook: no longer read.
1038
+ if (existsSync(join(data, WEBHOOK_FILE)))
1039
+ log?.(logLine("webhook", { condition: "webhook_left_over", file: join(data, WEBHOOK_FILE), effect: "not read: the webhook is kept in the store now; set it again with PUT /v2/settings/webhook" }));
1040
+ secretStores.add("webhook", () => webhooks.signingSecrets());
959
1041
  const uploads = new Uploads(join(data, UPLOADS_DIR));
960
1042
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
961
1043
  // temp file found now is a crashed one's.
@@ -1010,6 +1092,7 @@ async function startHolding(options, data, checked, stops) {
1010
1092
  const modelOf = (_entry, revision) => runModelRef(env, revision);
1011
1093
  const startDeps = {
1012
1094
  runBodyIssues,
1095
+ boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
1013
1096
  pinnedOf,
1014
1097
  inputIssuesOf,
1015
1098
  explainRun,
@@ -1017,6 +1100,7 @@ async function startHolding(options, data, checked, stops) {
1017
1100
  // (called at request time, after they are assigned) rather than reading them before their declaration.
1018
1101
  told: (error) => told(error),
1019
1102
  runnable,
1103
+ pinFirst: (revision) => pinFirst(revision),
1020
1104
  readyFiles: (ids) => uploads.readyFiles(ids),
1021
1105
  files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1022
1106
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
@@ -1069,6 +1153,60 @@ async function startHolding(options, data, checked, stops) {
1069
1153
  },
1070
1154
  shown: () => secretsShown(serverSecrets(), { local: true }),
1071
1155
  };
1156
+ /** What a learning batch's loop reads of a run, from its view. */
1157
+ const batchRunView = async (runId) => {
1158
+ const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1159
+ if (!v)
1160
+ return undefined;
1161
+ return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1162
+ };
1163
+ // Learn from a CSV (learning-batch.ts): a batch's loop runs in this process over the run write half and the run view; its
1164
+ // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
1165
+ // (create's answer, read, list, cancel) cut its text as the learning routes do (learningShown, below).
1166
+ const batches = new LearningBatches({
1167
+ settings: store.settings,
1168
+ learning: async (agentId) => {
1169
+ const entry = await needAgent(agentId);
1170
+ if (entry.agent.archivedAt)
1171
+ return { learns: false, why: "it is archived." };
1172
+ if (learning === "off")
1173
+ return { learns: false, why: "this server's learning is off (--learning)." };
1174
+ if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1175
+ return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1176
+ return { learns: true };
1177
+ },
1178
+ // A row's run starts under the row's key (the store's run origin, as an Idempotency-Key's run does), so a start the
1179
+ // server stopped before its row kept the id is found again, never started twice.
1180
+ find: async (key) => (await agents.request(() => agents.store.runOfOrigin(key)))?.runId,
1181
+ start: async (agentId, body, key) => (await startRunOf(await needAgent(agentId), body, { origin: { key } })).id,
1182
+ view: (runId) => batchRunView(runId),
1183
+ // Sent already: a steer the run's commands hold with these words, not refused (a follow-up to an ended run is one too,
1184
+ // its reopen's).
1185
+ sent: async (runId, content) => (await store.commands(runId, 0)).some((c) => c.kind === "steer" && c.refused === null && c.body?.text === content),
1186
+ message: async (runId, content) => void (await message(store, await needRun(runId), content)),
1187
+ // A run that is not there has nothing to stop; any other failure is the loop's (the row stays live and owned).
1188
+ cancel: async (runId) => {
1189
+ const moment = ID.test(runId) ? await momentOverStore(store, runId, viewDepsFor(ownOriginOf())) : undefined;
1190
+ if (moment)
1191
+ await cancel(store, moment);
1192
+ },
1193
+ figures: async (runId) => {
1194
+ const stored = await store.runs.get(runId);
1195
+ if (!stored)
1196
+ return undefined;
1197
+ // A run still going has no stored cost yet (its column is written at its end): its live cost, from its view, stands in,
1198
+ // so a batch's cost now and the cost it books are costRunOf both.
1199
+ const run = FINAL_STATES.includes(stored.state) ? stored : { ...stored, costUsd: (await batchRunView(runId))?.cost_usd ?? null };
1200
+ // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1201
+ const newest = await store.learning.proposal(runId);
1202
+ const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1203
+ // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then.
1204
+ return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends);
1205
+ },
1206
+ // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1207
+ shown: (agentId) => learningShown(agentId),
1208
+ ...(options.batchPollMs ? { pollMs: options.batchPollMs } : {}),
1209
+ });
1072
1210
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1073
1211
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1074
1212
  // request) use the server's public address, else its own.
@@ -1098,7 +1236,7 @@ async function startHolding(options, data, checked, stops) {
1098
1236
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1099
1237
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1100
1238
  context: ctx,
1101
- liveViewer: (runId) => liveViewerLink(store, sealKey, runId),
1239
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers),
1102
1240
  };
1103
1241
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1104
1242
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
@@ -1114,6 +1252,7 @@ async function startHolding(options, data, checked, stops) {
1114
1252
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1115
1253
  });
1116
1254
  const triggerDeps = {
1255
+ ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}),
1117
1256
  start: startDeps,
1118
1257
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1119
1258
  needAgent,
@@ -1145,6 +1284,8 @@ async function startHolding(options, data, checked, stops) {
1145
1284
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1146
1285
  const openSetup = options.openSetup === true && isLoopback(host);
1147
1286
  const owner = options.accounts ? new Owner(data, openSetup, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
1287
+ // With no accounts, the console's sessions: made by the link this start prints, never from the token (page.ts).
1288
+ const consoleSessions = owner ? undefined : new ConsoleSessions();
1148
1289
  // Who a sign-in comes from, for its limit: the socket's peer, or, from a trusted proxy only, the client it forwards for.
1149
1290
  const trusted = (() => {
1150
1291
  if (!options.trustedProxies?.length)
@@ -1221,6 +1362,17 @@ async function startHolding(options, data, checked, stops) {
1221
1362
  const githubConnection = () => github.view();
1222
1363
  /** What applying a template reads of the server (templates.ts TemplatesDeps). */
1223
1364
  const templateDeps = { githubConnection };
1365
+ // A template import reads GitHub's own hosts alone (a test's faux GitHub in their place), with an installation token of
1366
+ // the App when GitHub is connected (tokenForListing: metadata read, the least there is), else anonymously, and says why.
1367
+ const importDeps = {
1368
+ registry, store,
1369
+ reach: async (signal) => {
1370
+ const api = options.templateImportApi ?? GITHUB_API;
1371
+ const hosts = options.templateImportApi ? [new URL(options.templateImportApi).host] : GITHUB_HOSTS;
1372
+ const minted = options.templateImportApi ? { unusable: "it reads a test's GitHub" } : await githubConnect.tokenForListing(signal).catch((error) => ({ unusable: error.message }));
1373
+ return "token" in minted ? { api, hosts, token: minted.token } : { api, hosts, anonymous: "unusable" in minted ? minted.unusable : minted.failed };
1374
+ },
1375
+ };
1224
1376
  // A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
1225
1377
  // with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
1226
1378
  // is a server secret while it may be in use.
@@ -1247,6 +1399,7 @@ async function startHolding(options, data, checked, stops) {
1247
1399
  stops.push(async () => triggers.close());
1248
1400
  // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1249
1401
  // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1402
+ void batches.resume().catch((error) => void process.stderr.write(`agentrun-serve: the learning batches' resume: ${error.message}\n`));
1250
1403
  void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1251
1404
  // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1252
1405
  // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
@@ -1265,7 +1418,7 @@ async function startHolding(options, data, checked, stops) {
1265
1418
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1266
1419
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1267
1420
  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]]; })) },
1268
- // Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
1421
+ // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
1269
1422
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1270
1423
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
1271
1424
  // runner's child holds many).
@@ -1389,13 +1542,30 @@ async function startHolding(options, data, checked, stops) {
1389
1542
  // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1390
1543
  const body = revision.body;
1391
1544
  // A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
1392
- const rows = (body.tools ?? []).some((name) => /^mcp:[^/]+\/\*$/.test(name)) ? await store.mcp.servers().catch(() => []) : [];
1545
+ const rows = (body.tools ?? []).some(isMcpWildcard) ? await listMcpServers(store).catch(() => []) : [];
1393
1546
  const listed = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
1394
1547
  const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
1395
1548
  // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1396
1549
  const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1397
1550
  // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1398
- return { tools, gated, deniedBy, ask: { asked, fits: learnedAskFits } };
1551
+ const ask = { asked, fits: learnedAskFits };
1552
+ // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1553
+ // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1554
+ const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1555
+ const providers = await decisionProvidersIn(env);
1556
+ if (!providers)
1557
+ return { tools, gated, deniedBy, ask };
1558
+ const decided = {};
1559
+ const decisionDeniedBy = {};
1560
+ for (const provider of DECISION_PROVIDER_KEYS) {
1561
+ const { permission, from } = gate(provider);
1562
+ if (permission === "allow")
1563
+ continue;
1564
+ decided[provider] = permission;
1565
+ if (permission === "deny")
1566
+ decisionDeniedBy[provider] = from;
1567
+ }
1568
+ return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1399
1569
  }
1400
1570
  async function needAgent(id) {
1401
1571
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1494,7 +1664,31 @@ async function startHolding(options, data, checked, stops) {
1494
1664
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1495
1665
  async function runnable(revision, place, { capped = false } = {}) {
1496
1666
  const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1497
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1667
+ // An agentic revision's MCP tools are checked as its save pinned them (its pin, never the server's listing now), for
1668
+ // a server still saved here; a granted tool its pin does not hold is said first, with how to pin it.
1669
+ const pin = (revision.mcpPin ?? {});
1670
+ if (revision.kind === "agentic") {
1671
+ const unpinned = (revision.body.tools ?? []).flatMap((tool, index) => {
1672
+ const named = mcpToolOf(tool);
1673
+ if (!named || !mcpMeta.has(named.server))
1674
+ return [];
1675
+ const pinned = Object.hasOwn(pin, named.server) && pin[named.server].tools.some((one) => one.name === named.tool);
1676
+ return pinned ? [] : [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: save the agent again to pin it.`, tool }];
1677
+ });
1678
+ if (unpinned.length)
1679
+ throw new ApiError("agent_not_runnable", unpinned.map((one) => one.message).join(" "), { fields: unpinned.map(({ tool: _tool, ...issue }) => issue), details: { unbound: unpinned.map((one) => one.tool), missing: {} } });
1680
+ }
1681
+ const pinnedTools = (server) => {
1682
+ const saved = mcpMeta.get(server);
1683
+ if (!saved || !Object.hasOwn(pin, server))
1684
+ return undefined;
1685
+ // A meta tool at the URL it was pinned on or at the server's URL now (a server moved to a provider's host since).
1686
+ return pin[server].tools.map((tool) => {
1687
+ const meta = metaToolOf(pin[server].url, tool.name) ?? metaToolOf(saved.url, tool.name);
1688
+ return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
1689
+ });
1690
+ };
1691
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, decisionPrice });
1498
1692
  if (!blockers.length)
1499
1693
  return;
1500
1694
  const message = blockers.map((b) => b.message).join(" ");
@@ -1517,9 +1711,80 @@ async function startHolding(options, data, checked, stops) {
1517
1711
  }
1518
1712
  /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1519
1713
  const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
1520
- /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. A
1521
- * revision that names no place is checked where it would run (fallbackPlace). */
1522
- async function saveable(revision) {
1714
+ /** What a save of `revision` pins of the MCP tools it grants (an agentic revision's: a workflow's nodes bind none): each
1715
+ * granted server listed once, now, with its saved credential (McpServersOverStore.pinListing), as `tools` each server's
1716
+ * listing in the harnesses' shape for the save's checks (blockersOf's `mcp`), and `pin` making the pin from them. A server
1717
+ * that cannot be listed keeps the agent's `previous` pin for it when every tool the save grants from it is already
1718
+ * there (an edit that grants nothing new from it, its instructions say); else the save is refused (422) in words naming
1719
+ * it: nothing is saved, and saving again once it answers pins it. */
1720
+ async function mcpListingOf(revision, previous) {
1721
+ const tools = revision.kind === "agentic" ? (revision.body.tools ?? []) : [];
1722
+ const granted = tools.filter((tool) => mcpToolOf(tool) !== undefined);
1723
+ const listings = new Map();
1724
+ // A server carried from the previous pin, as that pin holds it (its tools already in the harnesses' shape).
1725
+ const carried = new Map();
1726
+ const before = (previous && typeof previous === "object" ? previous : {});
1727
+ const carry = (server) => {
1728
+ const kept = Object.hasOwn(before, server) ? before[server] : undefined;
1729
+ const all = kept && granted.every((tool) => { const named = mcpToolOf(tool); return named.server !== server || kept.tools.some((one) => one.name === named.tool); });
1730
+ if (all)
1731
+ carried.set(server, kept);
1732
+ return all;
1733
+ };
1734
+ const refused = [];
1735
+ await Promise.all([...new Set(granted.map((tool) => mcpToolOf(tool).server))].map(async (server) => {
1736
+ try {
1737
+ const listing = await mcpServers.pinListing(server, stopping.signal);
1738
+ if (listing)
1739
+ listings.set(server, listing);
1740
+ }
1741
+ catch (error) {
1742
+ if (!(error instanceof ApiError))
1743
+ throw error;
1744
+ if (carry(server))
1745
+ return;
1746
+ const why = error.extra.fields?.[0]?.message ?? error.message;
1747
+ refused.push({ field: `definition.tools[${tools.findIndex((tool) => mcpToolOf(tool)?.server === server)}]`, reason: "unavailable", message: `${sentence(`The MCP server ${server} could not be listed to pin its tools: ${why}`)} Nothing was saved: save again once it answers.` });
1748
+ }
1749
+ }));
1750
+ if (refused.length)
1751
+ throw invalid(refused.sort((a, b) => a.field.localeCompare(b.field)));
1752
+ const bound = (server) => {
1753
+ const kept = carried.get(server);
1754
+ // A carried server's tools are checked as pinned, a meta tool marked at its URL then or now (as runnable does).
1755
+ if (kept)
1756
+ return kept.tools.map((tool) => { const meta = metaToolOf(kept.url, tool.name) ?? (mcpMeta.has(server) ? metaToolOf(mcpMeta.get(server).url, tool.name) : undefined); return meta ? { ...tool, grantable: false, reason: meta.reason } : tool; });
1757
+ return listings.get(server)?.tools.map((tool) => ({ ...boundTool(tool), ...(tool.grantable === false ? { grantable: false, reason: tool.reason } : {}) }));
1758
+ };
1759
+ return {
1760
+ // A workflow's grants are checked on the registry's listing, as before: its nodes bind no MCP tool, so the save refuses them.
1761
+ tools: revision.kind === "agentic" ? bound : mcpTools,
1762
+ pin: () => {
1763
+ if (!granted.length)
1764
+ return undefined;
1765
+ try {
1766
+ return mcpPinOf(granted, { server: (name) => { const kept = carried.get(name); if (kept)
1767
+ return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices }; } });
1768
+ }
1769
+ catch (error) {
1770
+ throw invalid([{ field: "definition.tools", reason: "not_an_option", message: error.message }]);
1771
+ }
1772
+ },
1773
+ };
1774
+ }
1775
+ /** The revision a run starts on, its MCP tools pinned: one saved with no pin that grants a tool of a server saved here is
1776
+ * pinned at this, its first run (mcp-pin-first.ts pinFirst, the claim's path too). One that can't be (a server that
1777
+ * can't be listed, or no longer lists a granted tool) is left unpinned, and runnable refuses it (409) as before. */
1778
+ async function pinFirst(revision) {
1779
+ if ((revision.mcpPin ?? null) !== null)
1780
+ return revision;
1781
+ const pin = await pinFirstOf(revision, { saved: (server) => mcpMeta.has(server), pinListing: (server) => mcpServers.pinListing(server, stopping.signal), pinOnce: (id, made) => store.agents.pinOnce(id, made) });
1782
+ return pin ? { ...revision, mcpPin: pin } : revision;
1783
+ }
1784
+ /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks, and
1785
+ * what the save stamps on it (its MCP pin, mcpListingOf; its monid pin, on its body). A revision that names no place is
1786
+ * checked where it would run (fallbackPlace). */
1787
+ async function saveable(revision, previous) {
1523
1788
  // The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
1524
1789
  // host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
1525
1790
  const body = revision.body;
@@ -1530,14 +1795,16 @@ async function startHolding(options, data, checked, stops) {
1530
1795
  }
1531
1796
  const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1532
1797
  const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1533
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools });
1798
+ const listing = await mcpListingOf(revision, previous);
1799
+ const mcp = listing.tools;
1800
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp });
1534
1801
  // 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
1535
1802
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1536
1803
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1537
1804
  if ((body.maxCostUsd ?? 0) > 0) {
1538
1805
  const key = (b) => `${b.field}\n${b.message}`;
1539
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools })).map(key));
1540
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1806
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp })).map(key));
1807
+ const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, shellOf, offers, mcp, decisionPrice });
1541
1808
  // A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
1542
1809
  // agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
1543
1810
  const added = capped.filter((b) => !plain.has(key(b)));
@@ -1547,17 +1814,46 @@ async function startHolding(options, data, checked, stops) {
1547
1814
  const never = blockers.filter((b) => !b.host);
1548
1815
  if (never.length)
1549
1816
  throw invalid(never.map(issueOf));
1550
- return blockers.map(issueOf);
1817
+ // Its monid grants pinned against what monid lists now, on this server's monid key (monid.ts pinMonid): the pin is
1818
+ // stamped on the revision's body, and its runs read it, never monid's listing. A grant monid does not list is refused
1819
+ // here. An endpoint a wildcard left out (priced by usage: monid.ts unboundedWords) is a warning at the wildcard's grant.
1820
+ const leftOut = [];
1821
+ if (revision.kind === "agentic") {
1822
+ const send = await checkFetch("monid");
1823
+ // The key as the server reads it (env: what it was started with, its handed secrets and its saved keys).
1824
+ const pinned = await pinMonid(body.tools ?? [], { key: env[MONID_KEY_ENV]?.trim(), fetch: send ?? (async () => { throw new Error("no fake of monid's API under faux"); }), signal: stopping.signal });
1825
+ if (pinned && "refused" in pinned)
1826
+ throw invalid(pinned.refused.map(({ tool, message }) => ({ field: (body.tools ?? []).includes(tool) ? `definition.tools[${body.tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
1827
+ if (pinned) {
1828
+ // Each pinned endpoint's input held to the harness's own measured refusals, as an MCP grant is (runnable.ts
1829
+ // mcpGrant): one it would drop or retype refuses the save at the grant that named it, never every run.
1830
+ const harness = body.harness ?? DEFAULT_HARNESS;
1831
+ const problems = harnessOf(env, harness)?.facts?.schemaProblems;
1832
+ const tools = body.tools ?? [];
1833
+ const grantOf = (tool) => (tools.includes(tool) ? tools.indexOf(tool) : tools.indexOf(`monid:${monidNameOf(tool)?.provider}/*`));
1834
+ const dropped = problems ? Object.entries(pinned.pin).flatMap(([tool, { input }]) => problems(wireName(tool), input).slice(0, 1).map((first) => ({ tool, first }))) : [];
1835
+ if (dropped.length)
1836
+ throw invalid(dropped.map(({ tool, first }) => ({ field: `definition.tools[${grantOf(tool)}]`, reason: "not_an_option", message: monidDroppedWords(tool, harness, first) })));
1837
+ revision.body.monidPin = pinned.pin;
1838
+ leftOut.push(...pinned.leftOut.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: "not_an_option", message })));
1839
+ }
1840
+ }
1841
+ const mcpPin = listing.pin();
1842
+ return { warnings: [...blockers.map(issueOf), ...leftOut], stamp: mcpPin ? { mcpPin } : {} };
1551
1843
  }
1552
1844
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
1553
1845
  * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
1554
1846
  * tool the box refuses (browser) keeps the runner. */
1555
- async function createAgentOf(body) {
1847
+ async function createAgentOf(body, template) {
1556
1848
  let warnings = [];
1557
1849
  const definition = checkDefinitionBody(body);
1558
1850
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1559
1851
  const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1560
- const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1852
+ const entry = await agents.create(definition, async (revision) => {
1853
+ const saved = await saveable(revision);
1854
+ warnings = saved.warnings;
1855
+ return saved.stamp;
1856
+ }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
1561
1857
  return { entry, warnings };
1562
1858
  }
1563
1859
  /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
@@ -1608,22 +1904,30 @@ async function startHolding(options, data, checked, stops) {
1608
1904
  }
1609
1905
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1610
1906
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
1611
- * agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
1612
- * deny the owner set on this server stays, with a warning), its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
1907
+ * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, each set to allow (a
1908
+ * deny the owner set on this server stays, with a warning): a tool left unticked is not the agent's, under any approvals, its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
1613
1909
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
1614
1910
  * before it are deleted and the agent is archived (an agent store keeps every agent), and the refusal is the answer, a 422's fields under `triggers.<i>`; a
1615
1911
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
1616
1912
  * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
1617
- async function applyTemplate(pkg, body) {
1618
- const { parameters, grants, model: override, approvals } = applyBodyOf(pkg, body);
1619
- const missing = pkg.secrets.filter((name) => !secret(name, storedKeys));
1620
- const saved = pkg.mcp.filter((need) => mcpMeta.has(need.server));
1621
- const unsaved = pkg.mcp.filter((need) => !saved.includes(need));
1913
+ async function applyTemplate(template, body) {
1914
+ const { parameters, grants: asked, servers: picks, model: override, approvals } = applyBodyOf(template, body);
1915
+ const missing = template.secrets.filter((name) => !secret(name, storedKeys));
1916
+ // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
1917
+ // one: several and no pick is a 422); the package's
1918
+ // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
1919
+ const mapped = serversFor(template, [...mcpMeta].map(([name, meta]) => ({ name, ...meta.source })), picks);
1920
+ const servers = Object.fromEntries(mapped.flatMap(({ need, server }) => (server ? [[need.toolkit, server]] : [])));
1921
+ const pkg = onServers(template, servers);
1922
+ const saved = mapped.flatMap(({ need, server }) => (server ? [{ ...need, server }] : []));
1923
+ const unsaved = mapped.filter(({ server }) => !server).map(({ need }) => need);
1924
+ // A grant of a need with no server here grants nothing: dropped before the names move, so it never reads as a tool
1925
+ // of a saved server that happens to be named as its toolkit.
1926
+ const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
1622
1927
  const needed = unsaved.filter((need) => need.required);
1623
1928
  if (missing.length || needed.length) {
1624
1929
  const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
1625
- const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1626
- throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server }))] });
1930
+ throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].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.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
1627
1931
  }
1628
1932
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
1629
1933
  // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
@@ -1633,7 +1937,7 @@ async function startHolding(options, data, checked, stops) {
1633
1937
  throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
1634
1938
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1635
1939
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1636
- const skipped = unsaved.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server, so the agent was made without its tools (${need.tools.join(", ")}). Save it in Settings → MCP servers and apply again to grant them.` }));
1940
+ const skipped = unsaved.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}, so the agent was made without its tools (${need.tools.join(", ")}).`, fix: mcpSetUp(need) }));
1637
1941
  const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
1638
1942
  const picked = override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
1639
1943
  const model = picked.model;
@@ -1650,17 +1954,18 @@ async function startHolding(options, data, checked, stops) {
1650
1954
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1651
1955
  // never), else ask. Deny and pins hold either way.
1652
1956
  const chosenApprovals = approvals ?? pkg.approvals;
1653
- const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
1957
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants, held: denied, ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
1654
1958
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1655
1959
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1656
- const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
1960
+ const refusedTriggers = madeTriggerIssues(made.triggers, Date.now(), pkg.inputSchema);
1657
1961
  if (refusedTriggers.length)
1658
1962
  throw invalid(refusedTriggers);
1659
1963
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
1660
1964
  for (const one of [made.agent, ...made.triggers])
1661
1965
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
1662
1966
  throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
1663
- const { entry, warnings } = await createAgentOf(made.agent);
1967
+ // The agent keeps where it came from (its first revision's package): the package's id, version and, imported, its SHA.
1968
+ const { entry, warnings } = await createAgentOf(made.agent, { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null });
1664
1969
  const ids = [];
1665
1970
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
1666
1971
  // /triggers hands back its own, so the owner can give it to the sender.
@@ -1703,9 +2008,12 @@ async function startHolding(options, data, checked, stops) {
1703
2008
  }
1704
2009
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1705
2010
  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.` }));
1706
- // A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
1707
- // MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
1708
- const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
2011
+ // A GitHub tool the owner granted (ticked) that an installation of Connect GitHub's App does not hold the permission
2012
+ // for (read from GitHub, never assumed), where the github MCP server runs on the App's tokens: said now, before a run's
2013
+ // first call is refused; or that the check could not be made (template-github-permissions.ts). An unticked tool is
2014
+ // not the agent's, so nothing is said of it.
2015
+ const ticked = saved.map((need) => ({ ...need, tools: need.tools.filter((tool) => grants.includes(mcpToolName(need.server, tool))) }));
2016
+ const appShort = await appPermissionWarnings({ name: pkg.name, mcp: ticked }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
1709
2017
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
1710
2018
  const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1711
2019
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
@@ -1715,17 +2023,20 @@ async function startHolding(options, data, checked, stops) {
1715
2023
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1716
2024
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1717
2025
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
1718
- const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
2026
+ // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2027
+ const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2028
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1719
2029
  return { applied, minted };
1720
2030
  }
1721
- /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
1722
- * with the documented run bodies; a workflow run's its workflow's input schema, never the agentic example. Each value
2031
+ /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
2032
+ * (`{content: string}` with none), with the documented run bodies;a workflow run's its workflow's input schema, never the agentic example. Each value
1723
2033
  * suggested must pass this route's own checks of the body, the workflow's input check among them. */
1724
2034
  async function explainRun(issues, body, revision) {
1725
2035
  const dsl = revision?.kind === "workflow" ? await import("@parcha/agentrun-dsl") : undefined;
1726
2036
  const workflow = dsl && revision?.kind === "workflow" ? revision.body.workflow : undefined;
1727
2037
  const declared = workflow?.input?.schemaId === undefined ? undefined : workflow.schemas[workflow.input.schemaId];
1728
- const input = !dsl ? DEFAULT_INPUT_SCHEMA : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
2038
+ const typed = revision?.kind === "agentic" ? inputSchemaOf(revision.body.inputSchema) : DEFAULT_INPUT_SCHEMA;
2039
+ const input = !dsl ? typed : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
1729
2040
  const base = deref(openapi, { $ref: "#/components/schemas/RunCreate" }) ?? {};
1730
2041
  const schema = { ...base, properties: { ...base.properties, input } };
1731
2042
  const check = (sent) => {
@@ -1733,14 +2044,15 @@ async function startHolding(options, data, checked, stops) {
1733
2044
  const issues = runBodyIssues(value);
1734
2045
  if (!revision || !isObject(value.input))
1735
2046
  return issues;
1736
- return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, DEFAULT_INPUT_SCHEMA))];
2047
+ return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, typed))];
1737
2048
  };
1738
2049
  return explain(issues, openapi, schema, { examples: dsl ? [] : examplesOf("createRun"), body, check });
1739
2050
  }
1740
- /** A run's input: an agentic run's `{content: string}`, a workflow run's what its workflow's input schema takes. */
2051
+ /** A run's input: an agentic run's what its revision's input schema in force takes (`{content: string}` with none), a
2052
+ * workflow run's what its workflow's input schema takes. */
1741
2053
  async function inputIssuesOf(revision, input) {
1742
2054
  if (revision.kind === "agentic")
1743
- return inputIssues(input, DEFAULT_INPUT_SCHEMA);
2055
+ return inputIssues(input, inputSchemaOf(revision.body.inputSchema));
1744
2056
  const { validateWorkflow } = await import("@parcha/agentrun-dsl");
1745
2057
  return workflowInputIssues(validateWorkflow, revision, input);
1746
2058
  }
@@ -1780,7 +2092,7 @@ async function startHolding(options, data, checked, stops) {
1780
2092
  const handed = mcpAuthOf(mcp_auth, issues);
1781
2093
  const auth = {};
1782
2094
  for (const [server, headers] of Object.entries(handed ?? {})) {
1783
- const row = await store.mcp.server(server);
2095
+ const row = await getMcpServer(store, server);
1784
2096
  if (row?.auth !== "per_run")
1785
2097
  issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
1786
2098
  else
@@ -1832,16 +2144,26 @@ async function startHolding(options, data, checked, stops) {
1832
2144
  if (issues.length)
1833
2145
  throw invalid(issues);
1834
2146
  const checked = checkDefinitionBody(given);
1835
- const revision = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
1836
- // Refused where POST /agents refuses the definition (one this host can never run); what this host still lacks for it
1837
- // is the run's own refusal (prepareLaunch's runnable), as for a run of a stored agent.
1838
- await saveable(revision);
2147
+ const made = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
2148
+ // A version's first run is its save: refused where POST /agents refuses the definition (one this host can never run),
2149
+ // its MCP tools pinned as a save pins them (a server down keeps the agent's current pin when this version grants nothing
2150
+ // new from it). A version already stored is a run of its revision, as a run of a stored agent is: no save, nothing
2151
+ // listed here, its pin as stored (one stored with no pin is pinned at this run, StartDeps.pinFirst). What this host
2152
+ // still lacks for either is the run's own refusal (prepareLaunch's runnable).
1839
2153
  const ref = external;
2154
+ const mapped = await store.agents.byExternal(externalKey(ref));
2155
+ const stored = mapped ? await store.agents.externalRevision(mapped.id, String(ref.version)) : undefined;
2156
+ const current = !stored && mapped?.currentRevision ? await store.agents.revision(mapped.currentRevision) : undefined;
2157
+ // A version already stored keeps its revision's monid pin, not what monid lists now: its definition never changes
2158
+ // here, so it compares equal to the stored one (startInline), and monid's listing is not read again.
2159
+ const keptMonid = stored?.kind === "agentic" ? stored.body.monidPin : undefined;
2160
+ const revision = stored ? (keptMonid ? { ...made, body: { ...made.body, monidPin: keptMonid } } : made) : { ...made, ...(await saveable(made, current?.mcpPin)).stamp };
1840
2161
  const inline = {
1841
2162
  external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
1842
2163
  name: checked.definition.name,
1843
2164
  description: typeof checked.definition.description === "string" ? checked.definition.description : null,
1844
2165
  revision,
2166
+ ...(stored ? { stored } : {}),
1845
2167
  };
1846
2168
  return idempotent(req, "/runs", body, async (origin) => {
1847
2169
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -1907,7 +2229,10 @@ async function startHolding(options, data, checked, stops) {
1907
2229
  }
1908
2230
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
1909
2231
  function runBodyIssues(body) {
1910
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "archil_disk"]);
2232
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2233
+ issues.push(...holdIssues(body));
2234
+ if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2235
+ issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
1911
2236
  if (body.archil_disk !== undefined) {
1912
2237
  const disk = body.archil_disk;
1913
2238
  const extra = isObject(disk) ? Object.keys(disk).filter((key) => key !== "disk_id") : [];
@@ -1928,6 +2253,10 @@ async function startHolding(options, data, checked, stops) {
1928
2253
  issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
1929
2254
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
1930
2255
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2256
+ if (body.workflow_first !== undefined && typeof body.workflow_first !== "boolean")
2257
+ issues.push({ field: "workflow_first", reason: "wrong_type", message: "workflow_first is true or false" });
2258
+ if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2259
+ issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
1931
2260
  return issues;
1932
2261
  }
1933
2262
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
@@ -2389,6 +2718,10 @@ async function startHolding(options, data, checked, stops) {
2389
2718
  const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, /^\/hooks\/([^/]+)$/.exec(path)[1]);
2390
2719
  return send(res, answer.status, answer.body, answer.headers ?? {});
2391
2720
  }
2721
+ // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
2722
+ // limited by source address before anything in the body is checked.
2723
+ if (found.name === "pairComputer")
2724
+ return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
2392
2725
  // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2393
2726
  // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2394
2727
  if (found.name === "mcpOAuthCallback") {
@@ -2520,7 +2853,20 @@ async function startHolding(options, data, checked, stops) {
2520
2853
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
2521
2854
  // A tool of bash's family the agent's computer gives no shell for reads unavailable (runShellOf).
2522
2855
  const revision = entry.revision;
2523
- const tools = revision ? agentTools(env, settings.get(), await toolingOf(revision), caps.tools.map((tool) => tool.name), await shellOfRevision(revision)) : [];
2856
+ const tooling = revision ? await toolingOf(revision) : undefined;
2857
+ // An MCP tool's effect, what "allow reads" reads: as the revision's pin marks it (pinnedEffect), the marks its runs
2858
+ // read. A revision saved before pins were made at save holds none until its first run, which pins its saved
2859
+ // server's listing then (pinFirst): so until then, that listing now (mcp-servers-store.ts).
2860
+ const pin = revision?.mcpPin ?? undefined;
2861
+ const listed = !pin && tooling?.tools.some((name) => mcpToolOf(name)) ? new Map((await store.mcp.servers()).map((row) => [row.name, (row.tools ?? [])])) : undefined;
2862
+ const effectOf = (name) => {
2863
+ if (pin)
2864
+ return pinnedEffect(pin, name);
2865
+ const parsed = mcpToolOf(name);
2866
+ const tool = parsed && listed?.get(parsed.server)?.find((one) => one.name === parsed.tool);
2867
+ return tool ? toolEffect(tool.annotations) : undefined;
2868
+ };
2869
+ const tools = revision && tooling ? agentTools(env, settings.get(), tooling, caps.tools.map((tool) => tool.name), await shellOfRevision(revision), effectOf) : [];
2524
2870
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
2525
2871
  }
2526
2872
  case "updateDefinition": {
@@ -2542,7 +2888,13 @@ async function startHolding(options, data, checked, stops) {
2542
2888
  // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
2543
2889
  // the same revision exactly one lands.
2544
2890
  let warnings = [];
2545
- const check = async (revision) => void (warnings = await saveable(revision));
2891
+ const check = async (revision, on) => {
2892
+ // The pin of the revision this try builds on (commitAgent's read, a retry's newer one): a server down now keeps
2893
+ // it when the edit grants nothing new from it.
2894
+ const saved = await saveable(revision, on?.mcpPin);
2895
+ warnings = saved.warnings;
2896
+ return saved.stamp;
2897
+ };
2546
2898
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
2547
2899
  reconcileComputer(id);
2548
2900
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
@@ -2651,7 +3003,7 @@ async function startHolding(options, data, checked, stops) {
2651
3003
  if (content.length > MAX_MESSAGE)
2652
3004
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
2653
3005
  // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
2654
- const { mode, messageId } = await message(store, run, content, seal ? { launchSealed: seal(run.id) } : {});
3006
+ const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal(run.id) } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
2655
3007
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
2656
3008
  const { status, state } = await runStatusState(run.id);
2657
3009
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -2694,17 +3046,50 @@ async function startHolding(options, data, checked, stops) {
2694
3046
  // The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
2695
3047
  const run = await needRun(id);
2696
3048
  const body = await bodyOf(req);
2697
- const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
3049
+ const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note" && k !== "confirm_destructive").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
3050
+ if (body.confirm_destructive !== undefined && body.confirm_destructive !== true)
3051
+ issues.push({ field: "confirm_destructive", reason: "wrong_type", message: "confirm_destructive is true when sent: the second confirm of a destructive call's allow" });
2698
3052
  if (body.decision !== "allow" && body.decision !== "deny")
2699
3053
  issues.push({ field: "decision", reason: body.decision === undefined ? "missing" : "not_an_option", message: "decision is allow or deny" });
2700
3054
  if (body.note !== undefined && (typeof body.note !== "string" || body.note.length > 2000))
2701
3055
  issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
2702
3056
  if (issues.length)
2703
3057
  throw invalid(issues);
2704
- await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
3058
+ await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined, body.confirm_destructive === true);
2705
3059
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
2706
3060
  return void res.end();
2707
3061
  }
3062
+ case "gradeRun": {
3063
+ const row = ID.test(id) ? await store.runs.get(id) : undefined;
3064
+ if (!row)
3065
+ throw new ApiError("not_found", `no run ${id}`);
3066
+ const body = await bodyOf(req);
3067
+ const extra = unknownFields(body, ["correct", "expected", "source", "label"]);
3068
+ if (extra.length)
3069
+ throw invalid(extra);
3070
+ if (typeof body.correct !== "boolean")
3071
+ throw invalid([{ field: "correct", reason: body.correct === undefined ? "missing" : "wrong_type", message: "correct is true or false: whether the run's answer was right" }]);
3072
+ if (body.expected !== undefined && !isObject(body.expected))
3073
+ throw invalid([{ field: "expected", reason: "wrong_type", message: "expected is an object: the fields a right answer's JSON holds" }]);
3074
+ if (body.source !== undefined && !GRADE_SOURCES.includes(body.source))
3075
+ throw invalid([{ field: "source", reason: "not_an_option", message: `source is one of ${GRADE_SOURCES.join(", ")}` }]);
3076
+ if (body.label !== undefined && (typeof body.label !== "string" || body.label.length > LABEL_MAX))
3077
+ throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
3078
+ if (!FINAL_STATES.includes(row.state))
3079
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
3080
+ const m = (isObject(row.metrics) ? row.metrics : {});
3081
+ if (m.path === "replay")
3082
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "A replay run is never graded: its answer is scored against the run it replays." }]);
3083
+ const path = RUN_PATHS.includes(m.path) ? m.path : "agent";
3084
+ const grade = {
3085
+ run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
3086
+ ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3087
+ };
3088
+ await putGrade(store.settings, row.agentId, grade);
3089
+ // What the grade asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3090
+ const feedback = await openFeedbackRound(store, grade, typeof body.label === "string" ? body.label : undefined);
3091
+ return send(res, 200, { ...gradeView(grade), feedback });
3092
+ }
2708
3093
  case "archiveRun":
2709
3094
  case "unarchiveRun": {
2710
3095
  const run = await needRun(id);
@@ -2718,18 +3103,24 @@ async function startHolding(options, data, checked, stops) {
2718
3103
  const run = await needRun(id);
2719
3104
  const family = found.name === "getRunBrowser" ? "browser" : "computer";
2720
3105
  // The run's open viewer, from the store's sealed viewer rows the runner publishes its hand-over into (browser-live.ts
2721
- // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store.
2722
- const hold = await computerHoldOf(store, run.id);
3106
+ // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store,
3107
+ // and where a computer with no viewer is (sessionIn), both over one read of the run's journal.
3108
+ const entries = (await runEntries(store, run.id, ctx));
3109
+ const hold = await computerHoldOf(store, run.id, { entries: async () => entries });
2723
3110
  const kept = await keptBrowserOf(store, run.id);
3111
+ // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
3112
+ // none with its kind, never off as if the agent had none (#2170).
3113
+ const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
2724
3114
  const view = await computerView({
2725
3115
  viewer: async () => {
2726
3116
  if (family === "browser") {
2727
- const link = await liveViewerLink(store, sealKey, run.id);
3117
+ const link = await liveViewerLink(store, sealKey, run.id, answers);
2728
3118
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
2729
3119
  }
2730
- return computerViewerLink(store, sealKey, run.id);
3120
+ return computerViewerLink(store, sealKey, run.id, answers);
2731
3121
  },
2732
- computer: () => computerOf(kept, env, family),
3122
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
3123
+ session: (kind) => sessionIn(kind, entries, run.terminal),
2733
3124
  hold: () => hold,
2734
3125
  // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
2735
3126
  // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
@@ -2770,9 +3161,25 @@ async function startHolding(options, data, checked, stops) {
2770
3161
  }, store, { context: ctx });
2771
3162
  return send(res, 200, answer, { "cache-control": "no-store" });
2772
3163
  }
3164
+ case "startRun":
3165
+ case "callRunComputer":
3166
+ case "releaseRunComputer": {
3167
+ // A call on a run's computer (the computer call channel) and a held computer's start and release
3168
+ // (computer-held-routes.ts), over the store: each a command row the run's runner applies.
3169
+ const run = await needRun(id);
3170
+ return send(res, 200, await heldRoute(found.name, run.id, await bodyOf(req), store, { context: ctx }), { "cache-control": "no-store" });
3171
+ }
3172
+ case "createPairing":
3173
+ return send(res, 201, await attach.createPairing(), { "cache-control": "no-store" });
3174
+ case "attachComputer":
3175
+ throw new ApiError("bad_request", `${ATTACH_PATH} is the attach WebSocket: a paired computer's driver dials it with Upgrade: websocket and its own token`);
3176
+ case "deleteComputer":
3177
+ await attach.remove(id);
3178
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
2773
3179
  case "listComputers":
2774
3180
  case "saveComputerKeys":
2775
- case "testComputer": {
3181
+ case "testComputer":
3182
+ case "listComputerChoices": {
2776
3183
  // Settings → Computers (computers.ts): the rules are the handler's; this sends its answer.
2777
3184
  const provider = found.name === "listComputers" ? undefined : id;
2778
3185
  const body = found.name === "saveComputerKeys" ? await bodyOf(req) : undefined;
@@ -2975,6 +3382,17 @@ async function startHolding(options, data, checked, stops) {
2975
3382
  await refreshMcpMeta();
2976
3383
  return send(res, 200, saved);
2977
3384
  }
3385
+ // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
3386
+ case "listComposioTools":
3387
+ return send(res, 200, await composioTools(await bodyOf(req), options.composioControl ?? {}, stopping.signal), { "cache-control": "no-store" });
3388
+ case "saveComposioServer": {
3389
+ // The name is checked before Composio is called: a refused name leaves nothing made there.
3390
+ mcpNameOf(id);
3391
+ const body = await bodyOf(req);
3392
+ const answer = await composioSave(body, options.composioControl ?? {}, (mcp, made) => mcpServers.save(id, mcp, stopping.signal, undefined, made), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3393
+ await refreshMcpMeta();
3394
+ return send(res, 200, answer, { "cache-control": "no-store" });
3395
+ }
2978
3396
  case "refreshMcpServer": {
2979
3397
  const refreshed = await mcpServers.refresh(id, stopping.signal);
2980
3398
  await refreshMcpMeta();
@@ -3019,10 +3437,18 @@ async function startHolding(options, data, checked, stops) {
3019
3437
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "GET" }), { "cache-control": "no-store" });
3020
3438
  case "putMcpPrivateHosts":
3021
3439
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
3022
- case "deleteMcpServer":
3023
- await mcpServers.remove(id, secretSeen);
3440
+ case "deleteMcpServer": {
3441
+ // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3442
+ // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3443
+ // Composio refusing or not answering, or a key that does not open, never keeps our row: the answer says what to
3444
+ // remove there by hand.
3445
+ const { composio: made } = await mcpServers.remove(id, secretSeen);
3024
3446
  await refreshMcpMeta();
3447
+ const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3448
+ if (forgotten && !forgotten.removed)
3449
+ return send(res, 200, { deleted: true, composio: forgotten }, { "cache-control": "no-store" });
3025
3450
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3451
+ }
3026
3452
  case "getToolSettings":
3027
3453
  return send(res, 200, withDefaults(settings.get()));
3028
3454
  case "putToolSettings": {
@@ -3032,9 +3458,15 @@ async function startHolding(options, data, checked, stops) {
3032
3458
  const issues = settingsIssues(body);
3033
3459
  if (issues.length)
3034
3460
  throw invalid(issues);
3461
+ const before = settings.get();
3035
3462
  await settings.put(body);
3036
3463
  // A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
3037
3464
  recompose();
3465
+ // A run parked on a call whose tool reads allow now, on its pinned revision: woken, so its next claim's gate answers
3466
+ // the ask by the setting (settings-wake.ts), before this answer. The settings as the runner's gate reads them.
3467
+ const woken = await wakeAnsweredBySetting(store, await loadToolSettings(store), before);
3468
+ if (woken.length)
3469
+ log?.(logLine("tool_settings", { condition: "runs_woken", runs: woken.join(",") }));
3038
3470
  return send(res, 200, withDefaults(settings.get()));
3039
3471
  }
3040
3472
  // A person's view and control of what an agent learned (learning-routes.ts). Every text cut of the host's secrets as
@@ -3055,13 +3487,70 @@ async function startHolding(options, data, checked, stops) {
3055
3487
  const read = await agentCostOverStore(store, id, limit);
3056
3488
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
3057
3489
  const shown = await learningShown(id);
3058
- const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })) };
3490
+ const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })), workflows: read.workflows.map((one) => ({ ...one, workflow: shown.name(one.workflow) })) };
3059
3491
  if (csv) {
3060
3492
  res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-disposition": `attachment; filename="${id}-cost-per-run.csv"` });
3061
3493
  return void res.end(costCsv(cost.runs));
3062
3494
  }
3063
3495
  return send(res, 200, { agent: id, ...cost });
3064
3496
  }
3497
+ case "listLearningPromotions": {
3498
+ await needAgent(id);
3499
+ // Each learned workflow's promotion records, oldest first (learn/promote.ts): its replays' numbers and decisions,
3500
+ // its refits, its holds. Aggregates only; every text in them cut as the other learning reads cut theirs
3501
+ // (promotionsShown: a reason and a refit guard's label as well as each workflow's name).
3502
+ return send(res, 200, { agent: id, ...promotionsShown(await promotionsOf(store.settings, id), await learningShown(id)) });
3503
+ }
3504
+ case "createLearningBatch": {
3505
+ await needAgent(id);
3506
+ const made = await batches.create(id, await bodyOf(req));
3507
+ return send(res, 202, await batches.read(id, made.id), { location: `/v2/agents/${encodeURIComponent(id)}/learning/batches/${made.id}` });
3508
+ }
3509
+ case "listLearningBatches":
3510
+ await needAgent(id);
3511
+ return send(res, 200, await batches.list(id));
3512
+ case "getLearningBatch":
3513
+ await needAgent(id);
3514
+ return send(res, 200, await batches.read(id, second));
3515
+ case "cancelLearningBatch":
3516
+ await needAgent(id);
3517
+ return send(res, 200, await batches.cancel(id, second));
3518
+ case "listLearningEvals": {
3519
+ await needAgent(id);
3520
+ // The agent's eval records (learning-evals.ts), newest first, the latest the one shown: only ever what was posted.
3521
+ const evals = await evalsOf(store, id);
3522
+ return send(res, 200, { agent: id, latest: evals[0] ?? null, evals });
3523
+ }
3524
+ case "recordLearningEval": {
3525
+ const body = await bodyOf(req);
3526
+ await needAgent(id);
3527
+ const answer = await idempotent(req, `/agents/${id}/learning/evals`, body, async () => {
3528
+ const result = evalOf(body, new Date());
3529
+ await recordEval(store, id, result);
3530
+ return { status: 201, body: result };
3531
+ });
3532
+ return send(res, answer.status, answer.body, answer.headers);
3533
+ }
3534
+ case "getLearningLoop": {
3535
+ await needAgent(id);
3536
+ // The loop's own record over the one store (store-reads/loop.ts): compile turns and guarded steps, aggregates only.
3537
+ // Names cut as the other learning reads cut them; a compile's error texts cut by its run's own cut as its run's
3538
+ // learning read cuts them (run-learning-served.ts), and left out when that run's handed values can't be read.
3539
+ const shown = await learningShown(id);
3540
+ const values = await learningValues(id);
3541
+ const read = await agentLoopOverStore(store, id);
3542
+ const compiles = await Promise.all(read.compiles.map(async (one) => {
3543
+ const cut = await runCutValues({ serverSecrets, signIns }, store, one.run_id).catch(() => "unreadable");
3544
+ const workflow = one.workflow === null ? null : shown.name(one.workflow);
3545
+ if (cut === "unreadable")
3546
+ return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok }) => ({ ok, errors: [] })), draft_errors: [], withheld: true };
3547
+ const all = [...values, ...cut.values];
3548
+ const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
3549
+ return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
3550
+ }));
3551
+ const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
3552
+ return send(res, 200, { agent: id, compiles, guards });
3553
+ }
3065
3554
  case "listLearningNotes":
3066
3555
  case "listLearningLog":
3067
3556
  await needAgent(id);
@@ -3071,6 +3560,9 @@ async function startHolding(options, data, checked, stops) {
3071
3560
  return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
3072
3561
  }
3073
3562
  return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
3563
+ case "listLearnedWorkflowRevisions":
3564
+ await needAgent(id);
3565
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
3074
3566
  case "readLearningFile":
3075
3567
  await needAgent(id);
3076
3568
  return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
@@ -3127,7 +3619,7 @@ async function startHolding(options, data, checked, stops) {
3127
3619
  case "testWebhook":
3128
3620
  return send(res, 200, await webhooks.test());
3129
3621
  case "listWebhookDeliveries":
3130
- return send(res, 200, webhooks.attemptsView());
3622
+ return send(res, 200, await webhooks.attemptsView());
3131
3623
  case "redeliverWebhook":
3132
3624
  return send(res, 200, await webhooks.redeliver(id));
3133
3625
  case "listTriggers":
@@ -3140,7 +3632,8 @@ async function startHolding(options, data, checked, stops) {
3140
3632
  const answer = await idempotent(req, "/triggers", body, async () => {
3141
3633
  const { secret: shown, ...made } = await triggers.create(body);
3142
3634
  secret = shown;
3143
- return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : made, headers: { location: `/v2/triggers/${made.id}` } };
3635
+ // A secret the sender gave is not shown: the trigger answers its metadata, as a read does.
3636
+ return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : withSecretOf(made), headers: { location: `/v2/triggers/${made.id}` } };
3144
3637
  });
3145
3638
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
3146
3639
  const { note: _, ...first } = answer.body;
@@ -3149,26 +3642,32 @@ async function startHolding(options, data, checked, stops) {
3149
3642
  }
3150
3643
  case "listTemplates": {
3151
3644
  // Each package's computer list read against this server now: what an apply here would pick (pickComputer).
3152
- const here = templates.some((one) => one.computer) ? await shellHere() : undefined;
3153
- const pickView = (pkg) => {
3154
- const pick = here && pickComputer(pkg, here);
3155
- if (!pick)
3156
- return null;
3157
- if ("refused" in pick)
3158
- return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
3159
- return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
3160
- };
3161
- return send(res, 200, { templates: templates.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
3645
+ const listed = registry.list();
3646
+ const pickView = await computerHere(listed);
3647
+ return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
3162
3648
  }
3649
+ case "importTemplate": {
3650
+ // Read from GitHub and checked; a dry run answers it (200), else it is stored and served (201). The answer shows the
3651
+ // package whole, its instructions and every skill file, for a person to read before they apply it.
3652
+ const body = await bodyOf(req);
3653
+ const done = new AbortController();
3654
+ res.once("close", () => done.abort());
3655
+ const imported = await importTemplate(importDeps, body, done.signal);
3656
+ const pickView = await computerHere([imported.pkg]);
3657
+ return send(res, imported.status, { template: { ...packageView(imported.pkg), computer_here: pickView(imported.pkg) }, ...(({ instructions, skill_files }) => ({ instructions, skill_files }))(packageDetail(imported.pkg)), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
3658
+ }
3659
+ case "deleteTemplate":
3660
+ await deleteTemplate(importDeps, id);
3661
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3163
3662
  case "applyTemplate": {
3164
- const pkg = templates.find((t) => t.name === id);
3663
+ const pkg = registry.get(id);
3165
3664
  if (!pkg)
3166
3665
  throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
3167
3666
  const body = await bodyOf(req);
3168
3667
  // The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
3169
3668
  // keeps a webhook trigger's secret (below).
3170
3669
  let minted = new Map();
3171
- const answer = await idempotent(req, `/templates/${pkg.name}/apply`, body, async () => {
3670
+ const answer = await idempotent(req, `/templates/${encodeURIComponent(pkg.id)}/apply`, body, async () => {
3172
3671
  const made = await applyTemplate(pkg, body);
3173
3672
  minted = made.minted;
3174
3673
  return { status: 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
@@ -3181,11 +3680,20 @@ async function startHolding(options, data, checked, stops) {
3181
3680
  }
3182
3681
  case "rotateTriggerSecret":
3183
3682
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
3184
- return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3683
+ // A trigger whose sender gives its secret (Composio's) takes it as the body's `secret`; any other is made one.
3684
+ return send(res, 200, await (async () => {
3685
+ const empty = req.headers["transfer-encoding"] === undefined && !Number(req.headers["content-length"]);
3686
+ const body = empty ? {} : await bodyOf(req);
3687
+ const extra = Object.keys(body).filter((key) => key !== "secret");
3688
+ if (extra.length)
3689
+ throw invalid(extra.map((field) => ({ field, reason: "unknown_field", message: `${field} is not a field of this request: only secret` })));
3690
+ return triggerRotated(id, (await triggers.rotate(id, body.secret)).secret, new Date().toISOString());
3691
+ })());
3185
3692
  case "getTrigger":
3186
3693
  return send(res, 200, withSecretOf(await triggers.get(id)));
3187
3694
  case "updateTrigger":
3188
- return send(res, 200, await triggers.update(id, await bodyOf(req)));
3695
+ // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3696
+ return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3189
3697
  case "deleteTrigger":
3190
3698
  await triggers.remove(id);
3191
3699
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -3225,7 +3733,8 @@ async function startHolding(options, data, checked, stops) {
3225
3733
  const handover = await liveViewerFor(store, sealKey, runId, rest);
3226
3734
  if (handover === undefined || !familyReaches(family, handover))
3227
3735
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
3228
- await serveViewerFile(req, res, rest);
3736
+ // A desktop's or a phone's viewer gets the computer viewer's page (computer-viewer.ts), a browser's pi-browser's.
3737
+ await serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
3229
3738
  }
3230
3739
  /** The origin of the address people open (`publicUrl`, AGENTRUN_PUBLIC_URL), lowercased; none, undefined. */
3231
3740
  const publicOrigin = (() => {
@@ -3286,17 +3795,8 @@ async function startHolding(options, data, checked, stops) {
3286
3795
  return void mcp(req, res).catch(fail);
3287
3796
  if (raw === "/llms.txt")
3288
3797
  return void answerLlms(req, res).catch(fail);
3289
- if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3798
+ if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3290
3799
  return;
3291
- // Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
3292
- // a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
3293
- if (options.faux && raw.startsWith(`${FAUX_VIEW_PATH}/`)) {
3294
- const page = fauxOf().viewPage(raw);
3295
- if (page === undefined)
3296
- return fail(new ApiError("not_found", `no faux desktop at ${raw}`));
3297
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(req.method === "HEAD" ? undefined : page);
3298
- return;
3299
- }
3300
3800
  if (!raw.startsWith("/v2/"))
3301
3801
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3302
3802
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -3321,9 +3821,18 @@ async function startHolding(options, data, checked, stops) {
3321
3821
  // away. Its name alone, on any port, as the HTTP routes check it.
3322
3822
  if (names && !names.has(hostName(req.headers.host) ?? ""))
3323
3823
  return deny("403 Forbidden");
3324
- // API-only: a run's live view is the console's, and refused with it.
3824
+ // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings).
3325
3825
  if (options.apiOnly)
3326
3826
  return deny("404 Not Found");
3827
+ // A paired computer's driver dialing its attach socket (computer-attach.ts): its token, not the owner's, lets it in.
3828
+ if (raw === ATTACH_PATH) {
3829
+ return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
3830
+ if (status.startsWith("401"))
3831
+ authFailed(raw, "attach_token");
3832
+ const lines = Object.entries({ ...headers, "content-type": "text/plain; charset=utf-8", "content-length": String(Buffer.byteLength(words)) }).map(([name, value]) => `${name}: ${value}\r\n`).join("");
3833
+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n${lines}\r\n${words}`);
3834
+ });
3835
+ }
3327
3836
  if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3328
3837
  return deny("404 Not Found");
3329
3838
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
@@ -3354,7 +3863,7 @@ async function startHolding(options, data, checked, stops) {
3354
3863
  if (!admitted())
3355
3864
  return deny("401 Unauthorized");
3356
3865
  viewers.watch(socket, admitted);
3357
- proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; });
3866
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
3358
3867
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
3359
3868
  });
3360
3869
  const first = options.port ?? DEFAULT_PORT;
@@ -3397,16 +3906,19 @@ async function startHolding(options, data, checked, stops) {
3397
3906
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
3398
3907
  owner?.attach(options.publicUrl ?? url);
3399
3908
  webhooks.attach(options.publicUrl ?? url);
3400
- mcpServers.attach(options.publicUrl ?? url, url);
3909
+ // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
3910
+ // other services: mcp-oauth.ts mcpServerAt), and only as its operator says (mcpLoopback), never inferred from where it
3911
+ // listens: a hosted container listens on loopback behind its proxy too.
3912
+ const localInstall = options.mcpLoopback === true;
3913
+ mcpServers.attach(options.publicUrl ?? url, url, localInstall);
3401
3914
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
3402
- // to the store and this server runs no run, so it follows the store: each read takes the runs not final yet and the
3403
- // newest runs (one that started and ended between two reads is among them). It tells each end it has not told once the
3404
- // run reads final, and each wait of a run a runner left parked (or let go of) once it reads input_required. The markers
3405
- // are main's (an end's time, a wait's last row), so each webhook-id is the one it always had, and the ledger tells each
3406
- // once across restarts; a start first catches up the ends the ledger lacks, which no server was up to see. A store read
3407
- // of the runs ended (or parked) since a mark would be the cleaner seam than this read of the open runs every 250 ms.
3408
- const RUN_ENDS_POLL_MS = 250;
3409
- const RUN_ENDS_NEWEST = 50;
3915
+ // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
3916
+ // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
3917
+ // kept in this process. It tells each end once the run reads final, and each wait of a run let go once it reads
3918
+ // input_required. The markers are an end's time and a wait's ask (webhooks.ts waitMarkerOf), so each webhook-id is the
3919
+ // same on every read, and the ledger tells each once across restarts. The feed is read every 250 ms; a store that woke its readers on a
3920
+ // change would be the next seam.
3921
+ const RUN_CHANGES_POLL_MS = 250;
3410
3922
  const final = (row) => FINAL_STATES.includes(row.state);
3411
3923
  const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
3412
3924
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
@@ -3436,82 +3948,203 @@ async function startHolding(options, data, checked, stops) {
3436
3948
  const HELD_WAIT_REREAD_MS = 1_000;
3437
3949
  const waitKinds = new Set(["question", "approval", "budget", "browser"]);
3438
3950
  /** 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
3439
- * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). */
3951
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). False when it
3952
+ * is not done (a read that failed, or its notice not saved): it is read again. */
3440
3953
  const tellWait = async (row) => {
3441
3954
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
3442
3955
  if (readWaits.get(row.id) === seen)
3443
- return;
3956
+ return true;
3444
3957
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
3445
3958
  if (view?.status !== "input_required")
3446
- return void readWaits.set(row.id, seen);
3959
+ return (readWaits.set(row.id, seen), true);
3447
3960
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3448
3961
  // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3449
3962
  const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3450
3963
  if (!marker)
3451
- return void readWaits.set(row.id, seen);
3964
+ return (readWaits.set(row.id, seen), true);
3452
3965
  const card = view.pending?.kind;
3453
3966
  const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3454
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
3455
- if ((await webhooks.emit("run.needs_input", notice, marker)) !== "unsaved")
3456
- readWaits.set(row.id, seen);
3967
+ const wait = { kind };
3968
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: wait };
3969
+ if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3970
+ return false;
3971
+ readWaits.set(row.id, seen);
3972
+ return true;
3457
3973
  };
3458
- let openRuns = new Set();
3459
- let endsTimer;
3460
- let endsRead = Promise.resolve();
3461
- const readEnds = async () => {
3462
- const open = new Set();
3463
- for (const state of ["queued", "running", "parked"]) {
3464
- for (const row of await store.runs.list({ state })) {
3465
- open.add(row.id);
3466
- // A run waits on its person once its runner has let it go: parked, or running with no runner. Or held in its claim
3467
- // waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its browser hand-over,
3468
- // tools.ts), which its row's summary says (HELD_WAITS); a new ask sets it anew, so each is read and told once.
3469
- const waitsInClaim = row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3470
- // A held run's next ask in the same claim reads the same row as its last (state, epoch, runner, summary), and the
3471
- // answer between may come and go within one read: so a held wait is read again now and then (HELD_WAIT_REREAD_MS),
3472
- // and told once per ask all the same, since each ask's notice is keyed to its own last row (webhooks.ts emit).
3473
- if (waitsInClaim && Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3474
- heldReadAt.set(row.id, Date.now());
3475
- readWaits.delete(row.id);
3476
- }
3477
- if (!closing && (row.state === "parked" || (row.state === "running" && row.runner === null) || waitsInClaim))
3478
- await tellWait(row).catch(() => undefined);
3974
+ /** Who hears of each run's end and each wait the follower reads (runNotices): the outbound webhook first. Each is called
3975
+ * once a run reads final (onEnded) or is let go waiting on a person (onWaits), and again on a later read while any of
3976
+ * them threw (said once, run_notice_unread): so at least once, and the same moment always comes with the same `marker`
3977
+ * (an end's time, a wait's ask), on which each dedupes in a ledger of its own. An end from while no server was up
3978
+ * reaches the webhook alone, through its own catch-up (webhooks.ts catchUp). */
3979
+ const endedSubscribers = [];
3980
+ const waitSubscribers = [];
3981
+ const runNotices = {
3982
+ onEnded: (tell) => void endedSubscribers.push(tell),
3983
+ onWaits: (tell) => void waitSubscribers.push(tell),
3984
+ };
3985
+ runNotices.onEnded(async (run, marker) => {
3986
+ if ((await webhooks.emit("run.ended", run, marker)) === "unsaved")
3987
+ throw new Error("its run.ended is not saved yet");
3988
+ });
3989
+ runNotices.onWaits(async (run, _wait, marker) => {
3990
+ if ((await webhooks.emit("run.needs_input", run, marker)) === "unsaved")
3991
+ throw new Error("its run.needs_input is not saved yet");
3992
+ });
3993
+ /** Every call of `calls` made: false when one threw (said once for the run), so the run is told again. */
3994
+ const toldAll = async (id, calls) => {
3995
+ let done = true;
3996
+ for (const call of calls) {
3997
+ try {
3998
+ await call();
3999
+ }
4000
+ catch (error) {
4001
+ sayUnread(id, error.message);
4002
+ done = false;
3479
4003
  }
3480
4004
  }
3481
- const newest = await store.runs.list({ limit: RUN_ENDS_NEWEST });
3482
- for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
3483
- if (open.has(id) || closing)
3484
- continue;
3485
- const now = await endToTell(id).catch(() => undefined);
3486
- // Unread (a busy store): read again at the next turn, never lost.
3487
- if (now === undefined) {
3488
- open.add(id);
4005
+ return done;
4006
+ };
4007
+ /** Why a run's notice is not done yet, said once for the run (until it is done): one that stays undone shows. */
4008
+ const unreadSaid = new Set();
4009
+ const sayUnread = (id, error) => {
4010
+ if (unreadSaid.has(id))
4011
+ return;
4012
+ unreadSaid.add(id);
4013
+ log?.(logLine("webhook", { condition: "run_notice_unread", run: id, error }));
4014
+ };
4015
+ /** A run's end, told once the run reads final. False when it is not done (a read that failed, or its notice not saved). */
4016
+ const tellEnd = async (id) => {
4017
+ const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4018
+ if (now === undefined)
4019
+ return false;
4020
+ readWaits.delete(id);
4021
+ heldReadAt.delete(id);
4022
+ if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
4023
+ return (unreadSaid.delete(id), true);
4024
+ if (!(await toldAll(id, endedSubscribers.map((tell) => () => tell(now.notice, now.endedAt)))))
4025
+ return false;
4026
+ toldEnds.set(id, now.endedAt);
4027
+ unreadSaid.delete(id);
4028
+ return true;
4029
+ };
4030
+ /** A run's row as the store holds it now: undefined when there is no such run, UNREAD when the read failed. */
4031
+ const UNREAD = Symbol("unread");
4032
+ const rowNow = (id) => store.runs.get(id).catch(() => UNREAD);
4033
+ /** A run held in its claim waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its
4034
+ * browser hand-over, tools.ts), which its row's summary says (HELD_WAITS). Its row's state and runner do not move, so
4035
+ * the feed has no change for it: each read looks for these among the running runs. */
4036
+ const heldWait = (row) => row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
4037
+ /** A run waiting on its person: let go by its runner (parked, or running with none), or held in its claim (heldWait). */
4038
+ const letGo = (row) => row.state === "parked" || (row.state === "running" && row.runner === null) || heldWait(row);
4039
+ /** One change of the feed, handled: an end told, a wait told, or nothing to tell. One not done goes to endsLeft or
4040
+ * waitsLeft, by its run, which each read tries first until it is: a run that stays undone holds back no other. A wait is
4041
+ * read from the run as it is now (a run gone since, or moved on, has none to tell). */
4042
+ const handle = async (change) => {
4043
+ if (final(change)) {
4044
+ if (!(await tellEnd(change.id)))
4045
+ endsLeft.add(change.id);
4046
+ return;
4047
+ }
4048
+ if (change.state === "parked" || (change.state === "running" && change.runner === null)) {
4049
+ if (!(await tellLetGo(change.id)))
4050
+ waitsLeft.add(change.id);
4051
+ }
4052
+ };
4053
+ /** The wait of run `id` if it is let go now: false when not done (its read failed, or its wait not told). */
4054
+ const tellLetGo = async (id) => {
4055
+ const row = await rowNow(id);
4056
+ if (row === UNREAD)
4057
+ return (sayUnread(id, "its row could not be read"), false);
4058
+ if (row === undefined || !letGo(row))
4059
+ return true;
4060
+ const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
4061
+ if (told)
4062
+ unreadSaid.delete(id);
4063
+ return told;
4064
+ };
4065
+ /** Where the feed is read on from: past each page once its changes are handled, each told or left in endsLeft or
4066
+ * waitsLeft. None is dropped (a run left is tried again on each read), none is skipped, and none is read twice. */
4067
+ let changesCursor;
4068
+ /** The runs whose end, or whose wait, is not told yet (a read that failed, or a notice not saved): from the feed, or from
4069
+ * the start. Each read tries them first, until each is done. */
4070
+ const endsLeft = new Set();
4071
+ const waitsLeft = new Set();
4072
+ const readChanges = async () => {
4073
+ for (const id of [...endsLeft]) {
4074
+ if (closing)
4075
+ return;
4076
+ if (await tellEnd(id))
4077
+ endsLeft.delete(id);
4078
+ }
4079
+ for (const id of [...waitsLeft]) {
4080
+ if (closing)
4081
+ return;
4082
+ if (await tellLetGo(id))
4083
+ waitsLeft.delete(id);
4084
+ }
4085
+ for (;;) {
4086
+ if (closing)
4087
+ return;
4088
+ const page = await store.runs.changedSince(changesCursor, { limit: RUN_CHANGES_PAGE });
4089
+ for (const change of page.changes)
4090
+ await handle(change);
4091
+ changesCursor = page.next;
4092
+ if (page.changes.length < RUN_CHANGES_PAGE)
4093
+ break;
4094
+ }
4095
+ // The held waits, which the feed has no change for. A held run's next ask in the same claim reads the same row as its
4096
+ // last (state, epoch, runner, summary), and the answer between may come and go within one read: so a held wait is read
4097
+ // again now and then (HELD_WAIT_REREAD_MS), and told once per ask all the same, each ask's notice keyed to the ask
4098
+ // itself (webhooks.ts waitMarkerOf), never to the row that shows last.
4099
+ for (const row of await store.runs.list({ state: "running" })) {
4100
+ if (closing)
4101
+ return;
4102
+ if (!heldWait(row))
3489
4103
  continue;
4104
+ if (Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
4105
+ heldReadAt.set(row.id, Date.now());
4106
+ readWaits.delete(row.id);
3490
4107
  }
3491
- readWaits.delete(id);
3492
- heldReadAt.delete(id);
3493
- if (!now?.endedAt || !("notice" in now) || toldEnds.get(id) === now.endedAt)
3494
- continue;
3495
- if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
3496
- toldEnds.set(id, now.endedAt);
4108
+ if (!(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4109
+ waitsLeft.add(row.id);
3497
4110
  }
3498
- openRuns = open;
3499
4111
  };
3500
- const followEnds = () => {
4112
+ let endsTimer;
4113
+ let endsRead = Promise.resolve();
4114
+ /** Whether the start (startFollowing) is done: until it is, each turn runs it again before it reads the feed, so the ends
4115
+ * and waits from while no server was up are told whatever failed it. Said once. */
4116
+ let started = false;
4117
+ let startSaid = false;
4118
+ const followChanges = () => {
3501
4119
  if (closing)
3502
4120
  return;
3503
- endsRead = readEnds()
3504
- .catch((error) => log?.(logLine("webhook", { condition: "run_ends_unread", error: error.message })))
4121
+ const turn = started
4122
+ ? readChanges()
4123
+ : startFollowing().then(() => ((started = true), readChanges()), (error) => void (startSaid || ((startSaid = true), log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))));
4124
+ endsRead = turn
4125
+ .catch((error) => log?.(logLine("webhook", { condition: "run_changes_unread", error: error.message })))
3505
4126
  .finally(() => {
3506
4127
  if (!closing)
3507
- (endsTimer = setTimeout(followEnds, RUN_ENDS_POLL_MS)).unref();
4128
+ (endsTimer = setTimeout(followChanges, RUN_CHANGES_POLL_MS)).unref();
3508
4129
  });
3509
4130
  };
3510
- void store.runs
3511
- .list({})
3512
- .then((rows) => webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), endNotice))
3513
- .catch((error) => log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))
3514
- .finally(followEnds);
4131
+ /** The start, in this order, so no change is lost between its steps: the feed's head first (one read, untold),
4132
+ * then what the store holds now (the ends the ledger lacks, webhooks.ts catchUp, and the waits of the runs let go: the
4133
+ * feed has none from before its table, and none from a time no server read it), then the feed from that head. A change
4134
+ * after the head is read by the feed even when the store's rows already showed it, and the ledger tells it once. */
4135
+ const startFollowing = async () => {
4136
+ changesCursor = await store.runs.changesHead();
4137
+ const rows = await store.runs.list({});
4138
+ // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
4139
+ // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
4140
+ const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
4141
+ for (const id of unsaved)
4142
+ endsLeft.add(id);
4143
+ for (const row of rows)
4144
+ if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4145
+ waitsLeft.add(row.id);
4146
+ };
4147
+ followChanges();
3515
4148
  const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
3516
4149
  /** The server's stop: once (`close` keeps its promise). */
3517
4150
  let stopped;
@@ -3542,9 +4175,12 @@ async function startHolding(options, data, checked, stops) {
3542
4175
  // The ends' follower stops before the webhooks it feeds and the store it reads.
3543
4176
  clearTimeout(endsTimer);
3544
4177
  await endsRead;
4178
+ // A learning batch's loop ends where it stands, still running: it takes up when a server starts on this data again.
4179
+ await batches.halt();
3545
4180
  await webhooks.close();
3546
4181
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
3547
4182
  viewers.close();
4183
+ await attach.close();
3548
4184
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
3549
4185
  await mcpStopped;
3550
4186
  await githubStopped;
@@ -3563,7 +4199,10 @@ async function startHolding(options, data, checked, stops) {
3563
4199
  tokenFile,
3564
4200
  tokenMade: stored?.made ?? false,
3565
4201
  ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
4202
+ ...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
3566
4203
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
4204
+ attachHub,
4205
+ localInstall,
3567
4206
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
3568
4207
  // never writes this data root's record again (the next server's, by then).
3569
4208
  close: () => (stopped ??= stop()),