@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45

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 (388) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +580 -320
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +92 -22
  28. package/dist/composio-preset.d.ts +4 -3
  29. package/dist/composio-preset.js +81 -11
  30. package/dist/composio-triggers.d.ts +34 -2
  31. package/dist/composio-triggers.js +261 -31
  32. package/dist/computer-attach.d.ts +40 -5
  33. package/dist/computer-attach.js +130 -15
  34. package/dist/computer-keys.d.ts +3 -0
  35. package/dist/computer-keys.js +7 -1
  36. package/dist/computer-live.js +3 -2
  37. package/dist/computer-lost.d.ts +11 -0
  38. package/dist/computer-lost.js +19 -0
  39. package/dist/computer-record.d.ts +10 -2
  40. package/dist/computer-record.js +50 -18
  41. package/dist/computer-setting.d.ts +1 -0
  42. package/dist/computer-setting.js +2 -2
  43. package/dist/computers.d.ts +21 -10
  44. package/dist/computers.js +39 -28
  45. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  46. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decisions.d.ts +1 -1
  49. package/dist/dial-relay.d.ts +29 -0
  50. package/dist/dial-relay.js +94 -0
  51. package/dist/email/tools.js +10 -5
  52. package/dist/env-proxy.d.ts +2 -0
  53. package/dist/env-proxy.js +35 -0
  54. package/dist/errors.d.ts +4 -1
  55. package/dist/errors.js +10 -4
  56. package/dist/faux-computers.d.ts +8 -2
  57. package/dist/faux-computers.js +83 -6
  58. package/dist/harness-archive.d.ts +67 -0
  59. package/dist/harness-archive.js +177 -0
  60. package/dist/harness-goose.d.ts +34 -0
  61. package/dist/harness-goose.js +87 -0
  62. package/dist/harness-install.d.ts +21 -0
  63. package/dist/harness-install.js +24 -11
  64. package/dist/harness-opencode/adapter.js +1 -1
  65. package/dist/harness-table.d.ts +59 -3
  66. package/dist/harness-table.js +119 -14
  67. package/dist/harness.d.ts +17 -1
  68. package/dist/harness.js +22 -11
  69. package/dist/host.d.ts +12 -10
  70. package/dist/host.js +19 -16
  71. package/dist/import-worker.d.ts +3 -0
  72. package/dist/import-worker.js +7 -5
  73. package/dist/import.d.ts +22 -1
  74. package/dist/import.js +141 -28
  75. package/dist/key-check.js +3 -0
  76. package/dist/learn/audit.d.ts +6 -6
  77. package/dist/learn/audit.js +3 -7
  78. package/dist/learn/check.d.ts +26 -89
  79. package/dist/learn/check.js +58 -336
  80. package/dist/learn/commit.d.ts +63 -90
  81. package/dist/learn/commit.js +124 -316
  82. package/dist/learn/compile.d.ts +53 -50
  83. package/dist/learn/compile.js +88 -103
  84. package/dist/learn/corrections.d.ts +13 -0
  85. package/dist/learn/corrections.js +23 -0
  86. package/dist/learn/delete.d.ts +17 -0
  87. package/dist/learn/delete.js +42 -0
  88. package/dist/learn/folder.d.ts +35 -47
  89. package/dist/learn/folder.js +118 -134
  90. package/dist/learn/index.d.ts +3 -5
  91. package/dist/learn/index.js +6 -9
  92. package/dist/learn/learning.sh +45 -15
  93. package/dist/learn/promote.d.ts +20 -2
  94. package/dist/learn/promote.js +17 -4
  95. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
  96. package/dist/learn/{skills.js → workflow-draft.js} +65 -59
  97. package/dist/learn/workflow-nodes.d.ts +22 -1
  98. package/dist/learn/workflow-nodes.js +29 -10
  99. package/dist/learned-workflow.js +2 -2
  100. package/dist/learning-cost.d.ts +127 -13
  101. package/dist/learning-cost.js +142 -10
  102. package/dist/learning-routes.d.ts +99 -170
  103. package/dist/learning-routes.js +199 -420
  104. package/dist/learning-run.d.ts +19 -40
  105. package/dist/learning-run.js +23 -93
  106. package/dist/learning-setting.d.ts +4 -4
  107. package/dist/learning-setting.js +6 -6
  108. package/dist/learning-words.d.ts +28 -74
  109. package/dist/learning-words.js +64 -162
  110. package/dist/learning.d.ts +62 -393
  111. package/dist/learning.js +101 -651
  112. package/dist/listen-first.d.ts +30 -0
  113. package/dist/listen-first.js +115 -0
  114. package/dist/live-reach.d.ts +25 -2
  115. package/dist/live-reach.js +46 -4
  116. package/dist/llms.txt +2 -1
  117. package/dist/local-models.d.ts +3 -11
  118. package/dist/local-models.js +5 -6
  119. package/dist/mcp-servers-store.d.ts +16 -16
  120. package/dist/model-form.js +6 -5
  121. package/dist/model.d.ts +12 -4
  122. package/dist/model.js +41 -16
  123. package/dist/native/binding.js +1 -1
  124. package/dist/native/connection.js +1 -1
  125. package/dist/native/discovery.js +1 -1
  126. package/dist/native/instructions.d.ts +3 -0
  127. package/dist/native/instructions.js +5 -3
  128. package/dist/native/remote-worker-bridge.js +9 -43
  129. package/dist/native/remote.d.ts +8 -15
  130. package/dist/native/remote.js +3 -3
  131. package/dist/native/schema.js +1 -1
  132. package/dist/native/types.d.ts +2 -2
  133. package/dist/openapi.js +375 -347
  134. package/dist/owner.d.ts +8 -0
  135. package/dist/owner.js +11 -0
  136. package/dist/paid-calls.d.ts +14 -0
  137. package/dist/paid-calls.js +31 -1
  138. package/dist/particle-provider.d.ts +11 -0
  139. package/dist/particle-provider.js +135 -0
  140. package/dist/place.d.ts +8 -3
  141. package/dist/place.js +13 -9
  142. package/dist/port-models.d.ts +12 -4
  143. package/dist/port-models.js +28 -11
  144. package/dist/print.d.ts +27 -0
  145. package/dist/print.js +21 -0
  146. package/dist/provider.d.ts +7 -0
  147. package/dist/provider.js +30 -2
  148. package/dist/reflect-range.js +2 -3
  149. package/dist/run-launch.d.ts +14 -28
  150. package/dist/run-launch.js +9 -12
  151. package/dist/run-learning-served.d.ts +16 -90
  152. package/dist/run-listing.d.ts +34 -0
  153. package/dist/run-listing.js +128 -0
  154. package/dist/run-model-key.d.ts +64 -0
  155. package/dist/run-model-key.js +147 -0
  156. package/dist/run-timeline-served.js +5 -3
  157. package/dist/run-trace.d.ts +97 -0
  158. package/dist/run-trace.js +253 -0
  159. package/dist/run-view.d.ts +15 -0
  160. package/dist/run-view.js +9 -0
  161. package/dist/runnable.js +2 -1
  162. package/dist/runner/adapter-loop.d.ts +14 -6
  163. package/dist/runner/adapter-loop.js +25 -14
  164. package/dist/runner/adapter-run-spec.d.ts +22 -7
  165. package/dist/runner/adapter-run-spec.js +130 -77
  166. package/dist/runner/adapters/index.d.ts +4 -2
  167. package/dist/runner/adapters/index.js +35 -4
  168. package/dist/runner/adapters/pi.d.ts +4 -12
  169. package/dist/runner/adapters/pi.js +2 -2
  170. package/dist/runner/audit.d.ts +5 -1
  171. package/dist/runner/audit.js +31 -12
  172. package/dist/runner/beside.d.ts +7 -2
  173. package/dist/runner/beside.js +41 -9
  174. package/dist/runner/claim-secrets.d.ts +66 -1
  175. package/dist/runner/claim-secrets.js +136 -3
  176. package/dist/runner/cli-run-spec.d.ts +2 -1
  177. package/dist/runner/cli-run-spec.js +82 -59
  178. package/dist/runner/commands.d.ts +3 -6
  179. package/dist/runner/conformance/harness.d.ts +6 -0
  180. package/dist/runner/conformance/harness.js +16 -5
  181. package/dist/runner/dispatch.d.ts +2 -2
  182. package/dist/runner/end-of-run.d.ts +6 -14
  183. package/dist/runner/end-of-run.js +8 -33
  184. package/dist/runner/feedback-round.d.ts +5 -4
  185. package/dist/runner/feedback-round.js +14 -10
  186. package/dist/runner/github-app.js +3 -1
  187. package/dist/runner/harness-loops.d.ts +0 -8
  188. package/dist/runner/harness-loops.js +30 -56
  189. package/dist/runner/held.d.ts +170 -0
  190. package/dist/runner/held.js +57 -0
  191. package/dist/runner/journal-kinds.d.ts +7 -3
  192. package/dist/runner/journal-kinds.js +2 -3
  193. package/dist/runner/learned-first.d.ts +40 -0
  194. package/dist/runner/learned-first.js +32 -0
  195. package/dist/runner/learning-end.d.ts +77 -66
  196. package/dist/runner/learning-end.js +250 -299
  197. package/dist/runner/learning-seed.d.ts +15 -33
  198. package/dist/runner/learning-seed.js +24 -45
  199. package/dist/runner/loop-contract.d.ts +8 -3
  200. package/dist/runner/loop-contract.js +4 -0
  201. package/dist/runner/loop.js +6 -2
  202. package/dist/runner/main.d.ts +18 -9
  203. package/dist/runner/main.js +82 -22
  204. package/dist/runner/mcp-run.d.ts +11 -0
  205. package/dist/runner/mcp-run.js +67 -0
  206. package/dist/runner/memory-claim.d.ts +14 -6
  207. package/dist/runner/memory-claim.js +18 -9
  208. package/dist/runner/model-route.d.ts +7 -4
  209. package/dist/runner/model-route.js +22 -10
  210. package/dist/runner/native-loop.d.ts +0 -7
  211. package/dist/runner/native-loop.js +9 -101
  212. package/dist/runner/promotion.d.ts +13 -6
  213. package/dist/runner/promotion.js +63 -17
  214. package/dist/runner/reflect-hook.d.ts +64 -91
  215. package/dist/runner/reflect-hook.js +112 -206
  216. package/dist/runner/run-channel.d.ts +43 -0
  217. package/dist/runner/run-channel.js +467 -0
  218. package/dist/runner/run-child-host.d.ts +169 -0
  219. package/dist/runner/run-child-host.js +1222 -0
  220. package/dist/runner/run-child.d.ts +1 -0
  221. package/dist/runner/run-child.js +254 -0
  222. package/dist/runner/run-errors.d.ts +2 -0
  223. package/dist/runner/run-errors.js +20 -0
  224. package/dist/runner/runner.js +58 -9
  225. package/dist/runner/sdk-ask.d.ts +78 -0
  226. package/dist/runner/sdk-ask.js +158 -0
  227. package/dist/runner/sdk-loop.d.ts +2 -4
  228. package/dist/runner/sdk-loop.js +29 -49
  229. package/dist/runner/store-secrets.d.ts +5 -3
  230. package/dist/runner/store-secrets.js +14 -6
  231. package/dist/runner/workflow-first.d.ts +5 -0
  232. package/dist/runner/workflow-first.js +4 -0
  233. package/dist/runner/workflow-spec.js +17 -4
  234. package/dist/runs-over-store.d.ts +21 -32
  235. package/dist/runs-over-store.js +44 -41
  236. package/dist/sdk/runs.d.ts +6 -11
  237. package/dist/sdk/runs.js +20 -41
  238. package/dist/sdk/schema.js +3 -4
  239. package/dist/sdk/workflows.d.ts +1 -1
  240. package/dist/seal-key.d.ts +5 -0
  241. package/dist/seal-key.js +7 -0
  242. package/dist/secrets.d.ts +3 -0
  243. package/dist/secrets.js +16 -3
  244. package/dist/server.d.ts +119 -83
  245. package/dist/server.js +1121 -419
  246. package/dist/sign-ins-store.d.ts +8 -0
  247. package/dist/sign-ins-store.js +36 -1
  248. package/dist/skills.js +1 -1
  249. package/dist/store/index.d.ts +3 -3
  250. package/dist/store/index.js +2 -2
  251. package/dist/store/journal/storage.js +3 -0
  252. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  253. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  254. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  255. package/dist/store/schema.d.ts +53 -4
  256. package/dist/store/schema.js +137 -6
  257. package/dist/store/seal.d.ts +20 -2
  258. package/dist/store/seal.js +24 -8
  259. package/dist/store/sqlite/connection.d.ts +2 -0
  260. package/dist/store/sqlite/connection.js +3 -1
  261. package/dist/store/sqlite/run-launch.d.ts +4 -1
  262. package/dist/store/sqlite/run-launch.js +12 -0
  263. package/dist/store/sqlite/run-patch.d.ts +0 -17
  264. package/dist/store/sqlite/run-patch.js +4 -33
  265. package/dist/store/sqlite/store.d.ts +3 -2
  266. package/dist/store/sqlite/store.js +360 -75
  267. package/dist/store/sqlite/worker.js +25 -0
  268. package/dist/store/store.d.ts +231 -39
  269. package/dist/store/store.js +25 -3
  270. package/dist/store-reads/analytics.js +11 -1
  271. package/dist/store-reads/learning.d.ts +131 -194
  272. package/dist/store-reads/learning.js +292 -301
  273. package/dist/store-reads/loop.d.ts +0 -1
  274. package/dist/store-reads/loop.js +1 -1
  275. package/dist/store-reads/stats.js +13 -3
  276. package/dist/store-view.d.ts +34 -2
  277. package/dist/store-view.js +108 -41
  278. package/dist/telemetry.d.ts +59 -0
  279. package/dist/telemetry.js +153 -0
  280. package/dist/template-eval.d.ts +3 -6
  281. package/dist/template-eval.js +22 -36
  282. package/dist/templates.d.ts +2 -1
  283. package/dist/templates.js +6 -3
  284. package/dist/timeline/index.d.ts +1 -1
  285. package/dist/timeline/index.js +1 -1
  286. package/dist/timeline/timeline.d.ts +5 -1
  287. package/dist/timeline/timeline.js +16 -0
  288. package/dist/tool-gate.d.ts +0 -7
  289. package/dist/tool-gate.js +1 -15
  290. package/dist/tool-keys-store.d.ts +1 -1
  291. package/dist/tool-keys.d.ts +6 -4
  292. package/dist/tool-keys.js +12 -6
  293. package/dist/tool-plane.d.ts +12 -12
  294. package/dist/tools.d.ts +13 -13
  295. package/dist/tools.js +29 -9
  296. package/dist/trigger-adapter.d.ts +3 -0
  297. package/dist/trigger-adapters.d.ts +4 -0
  298. package/dist/trigger-adapters.js +13 -0
  299. package/dist/trigger-composio.d.ts +58 -1
  300. package/dist/trigger-composio.js +160 -6
  301. package/dist/triggers.d.ts +64 -5
  302. package/dist/triggers.js +141 -17
  303. package/dist/validate.d.ts +11 -7
  304. package/dist/validate.js +9 -8
  305. package/dist/webhooks.d.ts +4 -1
  306. package/dist/webhooks.js +11 -4
  307. package/dist/workspace/agent-computer.d.ts +2 -0
  308. package/dist/workspace/agent-computer.js +2 -0
  309. package/dist/workspace/archil-claim.d.ts +7 -0
  310. package/dist/workspace/archil-claim.js +29 -0
  311. package/dist/workspace/archil.d.ts +9 -1
  312. package/dist/workspace/archil.js +165 -3
  313. package/dist/workspace/attach.d.ts +3 -1
  314. package/dist/workspace/attach.js +2 -0
  315. package/dist/workspace/attached-computers.d.ts +16 -5
  316. package/dist/workspace/attached-computers.js +25 -9
  317. package/dist/workspace/computer-deps.js +1 -1
  318. package/dist/workspace/computer-for-claim.d.ts +22 -8
  319. package/dist/workspace/computer-for-claim.js +339 -46
  320. package/dist/workspace/computer-hold.js +2 -1
  321. package/dist/workspace/computer-kept.d.ts +11 -1
  322. package/dist/workspace/computer-kept.js +24 -3
  323. package/dist/workspace/resolve-computer.d.ts +41 -21
  324. package/dist/workspace/resolve-computer.js +172 -64
  325. package/dist/workspace/revision-skills.d.ts +1 -2
  326. package/dist/workspace/revision-skills.js +3 -4
  327. package/dist/workspace/run-workspace.d.ts +1 -1
  328. package/dist/workspace/run-workspace.js +5 -0
  329. package/dist/workspace/synced-folder.d.ts +85 -0
  330. package/dist/workspace/synced-folder.js +230 -0
  331. package/dist/workspace/workspace.d.ts +4 -0
  332. package/launcher/agentrun-serve +1 -1
  333. package/package.json +10 -9
  334. package/templates/README.md +7 -7
  335. package/templates/inbound-lead/agent.md +3 -3
  336. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  337. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  338. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  339. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  340. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  341. package/templates/inbound-lead/lead.schema.json +6 -5
  342. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  343. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  344. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  345. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  346. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  347. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  348. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  349. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  350. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  351. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  352. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  353. package/dist/console/assets/index-Bz6IWncl.js +0 -711
  354. package/dist/learn/grade.d.ts +0 -138
  355. package/dist/learn/grade.js +0 -682
  356. package/dist/learn/notes.d.ts +0 -81
  357. package/dist/learn/notes.js +0 -178
  358. package/dist/learn/reflect.d.ts +0 -77
  359. package/dist/learn/reflect.js +0 -228
  360. package/dist/learn/relevance.d.ts +0 -24
  361. package/dist/learn/relevance.js +0 -91
  362. package/dist/learn/seed-check.d.ts +0 -74
  363. package/dist/learn/seed-check.js +0 -103
  364. package/dist/learning-batch.d.ts +0 -291
  365. package/dist/learning-batch.js +0 -600
  366. package/dist/learning-evals.d.ts +0 -33
  367. package/dist/learning-evals.js +0 -98
  368. package/dist/native/context.d.ts +0 -6
  369. package/dist/native/context.js +0 -22
  370. package/dist/propose.d.ts +0 -52
  371. package/dist/propose.js +0 -224
  372. package/dist/runner/learning-ask.d.ts +0 -47
  373. package/dist/runner/learning-ask.js +0 -128
  374. package/dist/runner/learning-dispatch.d.ts +0 -45
  375. package/dist/runner/learning-dispatch.js +0 -99
  376. package/dist/runner/learning-factory.d.ts +0 -16
  377. package/dist/runner/learning-factory.js +0 -50
  378. package/dist/runner/learning-loop.d.ts +0 -273
  379. package/dist/runner/learning-loop.js +0 -521
  380. package/dist/usage.d.ts +0 -11
  381. package/dist/usage.js +0 -11
  382. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  383. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  384. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  385. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  386. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  387. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  388. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
package/dist/server.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { maintainObservations, Observations } from './observation/observer.js';
2
2
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
3
  import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
4
- import { gradeRouteFor } from "./runner/harness-loops.js";
4
+ import { askRouteOf } from "./runner/sdk-ask.js";
5
+ import { PI_WIRES } from "./runner/adapter-run-spec.js";
5
6
  import { routeOf as sdkModelRoute } from "./runner/model-route.js";
6
7
  import { answerSkill } from './skill-route.js';
7
8
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
@@ -12,7 +13,7 @@ import { isNativeRuntime } from "./native/runtimes.js";
12
13
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
13
14
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
14
15
  // token.
15
- import { createHash, randomBytes } from "node:crypto";
16
+ import { createHash, createHmac, randomBytes } from "node:crypto";
16
17
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
17
18
  import { createServer } from "node:http";
18
19
  import proxyaddr from "proxy-addr";
@@ -35,18 +36,19 @@ import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView
35
36
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
36
37
  import { deref, explain } from "./explain.js";
37
38
  import { HOME_HOST_OWNED } from "./files.js";
38
- import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
39
+ import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
39
40
  import { homePath, hostOwnedOf } from "./home-path.js";
40
41
  import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
41
42
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
42
- import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
43
- import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
44
- import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
45
- import { IMPORT_ASKED } from "./import.js";
43
+ import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, tableIds } from "./harness-table.js";
44
+ import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
45
+ import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
46
+ import { DEFAULT_HOST, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
47
+ import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
46
48
  import { answerStoreCall } from "./import-proxy.js";
47
- import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningFolderOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
49
+ import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
48
50
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
49
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
51
+ import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
50
52
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
51
53
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
52
54
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -60,17 +62,20 @@ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveV
60
62
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
61
63
  import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
62
64
  import { readKept } from "./workspace/computer-kept.js";
63
- import { liveReachOf } from "./live-reach.js";
65
+ import { dialHost, liveReachOf, reachForRun } from "./live-reach.js";
64
66
  import { screenWaitEnded } from "./browser-wait-ended.js";
65
67
  import { durationMs, logLine } from "./print.js";
66
68
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
67
- import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
69
+ import { cutOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
70
+ import { createLister } from "./run-listing.js";
68
71
  import { HELD_WAITS } from "./runner/journal-kinds.js";
69
72
  import { servedTimelineRows } from "./run-timeline-served.js";
73
+ import { servedRunTrace } from "./run-trace.js";
70
74
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
71
75
  import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
72
76
  import { runCutValues } from "./run-cut.js";
73
77
  import { readLaunchBody } from "./run-launch.js";
78
+ import { modelKeyMisfit, modelKeyOf, modelKeyRequired, noServerKeyFor, runModelOrigin, serverKeyMissing } from "./run-model-key.js";
74
79
  import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
75
80
  import { triggerTargets } from "./trigger-targets.js";
76
81
  import { labelFilter, labelsIssues } from "./run-labels.js";
@@ -81,14 +86,16 @@ import { watchRun } from "./live/stream.js";
81
86
  import { stats as statsOverStore } from "./store-reads/stats.js";
82
87
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
83
88
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
84
- import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
85
- import { answerOf, logged } from "./agents.js";
89
+ import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned, storeTarget } from "./store/index.js";
90
+ import { agentDeleting, answerOf, logged } from "./agents.js";
86
91
  import { keepGrade } from "./runner/feedback-round.js";
87
92
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
88
93
  import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
89
94
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
90
95
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
91
- import { GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf } from "./learn/promote.js";
96
+ import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
97
+ import { workflowNodesOf } from "./learn/workflow-nodes.js";
98
+ import { deleteLearning } from "./learn/delete.js";
92
99
  import { runModelRef } from "./model.js";
93
100
  import { REDACTED } from "./secret-cut.js";
94
101
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -103,16 +110,15 @@ import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
103
110
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
104
111
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
105
112
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
106
- import { bootSealKey, withSealKey } from "./seal-key.js";
113
+ import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
114
+ import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
107
115
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
108
116
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
109
117
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
110
118
  import { agentLoopOverStore } from "./store-reads/loop.js";
111
119
  import { printable } from "./learn/index.js";
112
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
113
- import { figuresOf, LearningBatches } from "./learning-batch.js";
120
+ import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
114
121
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
115
- import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
116
122
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
117
123
  import { toolKeysOverStore } from "./tool-keys-store.js";
118
124
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
@@ -136,7 +142,8 @@ import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js
136
142
  import { GITHUB_API } from "./github.js";
137
143
  import { bindingOf, REPO_NAME } from "./run-repo.js";
138
144
  import { HookCut, receivePush } from "./push-handler.js";
139
- import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
145
+ import { shownTrigger, TRIGGER_ADAPTERS } from "./trigger-adapters.js";
146
+ import { SEALED_FIELD, SEALED_MASK } from "./trigger-composio.js";
140
147
  import { webhook } from "./trigger-webhook.js";
141
148
  import { SCHEME_NAMES } from "./trigger-signatures.js";
142
149
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
@@ -159,7 +166,7 @@ import { recordingsFolder } from "./workspace/paths.js";
159
166
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
160
167
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
161
168
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
162
- import { createAttachRoutes, pairedView } from "./computer-attach.js";
169
+ import { createAttachRoutes, pairedView, RELAY_STALE_MS } from "./computer-attach.js";
163
170
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
164
171
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
165
172
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -168,12 +175,16 @@ import { noAccount, openAccount } from "./email/account.js";
168
175
  import { emailRoute } from "./email/routes.js";
169
176
  import { addressForms, openCalendar } from "./calendar/address.js";
170
177
  import { calendarRoute } from "./calendar/routes.js";
171
- import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
178
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKey } from "./archil-settings.js";
172
179
  import { computerOfPlace } from "./computer-setting.js";
173
180
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
174
181
  import { fauxComputers } from "./faux-computers.js";
175
182
  import { writesHeld } from "./workspace.js";
176
- import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
183
+ import { deleteExternalAgent, oneAtATime } from "./agent-delete.js";
184
+ import { agentComputerHoldKey } from "./workspace/agent-computer.js";
185
+ import { sdkRunKey } from "./sdk/runs.js";
186
+ import { waitEndedKey } from "./browser-wait-ended.js";
187
+ import { agentComputerOf, agentComputerView, agentDirName, agentFolder, agentHomeFolder, claimKinds, runFolder, scratchFolder, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
177
188
  import { keyReader } from "./key-meta.js";
178
189
  export const CONTRACT = "agentrun.v2/0";
179
190
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
@@ -185,6 +196,12 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
185
196
  * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
186
197
  const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
187
198
  const MAX_BODY = 1 << 20;
199
+ /** The starts that may begin setup's import without ending it (a worker that failed, a process that ended) before the
200
+ * owner's yes is dropped: an import that fails the same way each time is not taken up at every start for good. */
201
+ const IMPORT_STARTS = 3;
202
+ /** The heap of the worker that counts or imports this machine's sessions. A run is read whole, at most MAX_RUN_BYTES of
203
+ * files (import.ts), which this holds several times over. */
204
+ const IMPORT_HEAP_MB = 2048;
188
205
  const MAX_MESSAGE = 20_000;
189
206
  const MAX_WAIT_MS = 25_000;
190
207
  const PAGE_ROWS = 500;
@@ -204,17 +221,24 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
204
221
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
205
222
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
206
223
  * harness's, which scripts the harnesses with or without it. */
207
- const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
208
- /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
209
- * takes the same (test/support.mjs startInProcessRunner). */
224
+ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV]];
225
+ /** The switches a run's process gets, each module path resolved: the owner's harness modules (harnessModules), and the test
226
+ * switches, which are empty outside tests. A test's in-process runner takes the same (test/support.mjs
227
+ * startInProcessRunner). */
210
228
  export function fauxEnvOf(options) {
211
- const env = options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {};
229
+ // The owner's harness modules too (not a test switch): a run's process reads the same table as the server.
230
+ const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
212
231
  if (!options.faux)
213
232
  return env;
214
233
  env[FAUX_ENV] = resolve(options.faux);
215
234
  for (const [option, name] of FAUX_SWITCHES)
216
235
  if (options[option])
217
236
  env[name] = resolve(options[option]);
237
+ // The mountinfo the server itself reads (fauxMountinfo in serve), also when its own environment names it: a CLI server
238
+ // in a container hands it to the runner beside it, whose environment drops every faux variable it inherited.
239
+ const mountinfo = options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV];
240
+ if (mountinfo)
241
+ env[FAUX_MOUNTINFO_ENV] = resolve(mountinfo);
218
242
  return env;
219
243
  }
220
244
  const isLoopback = (host) => host === "localhost" || host === "::1" || /^127\./.test(host);
@@ -260,6 +284,7 @@ export const ROUTES = [
260
284
  { method: "POST", pattern: /^\/agents$/, name: "createAgent" },
261
285
  { method: "GET", pattern: /^\/agents$/, name: "listAgents" },
262
286
  { method: "GET", pattern: /^\/agents\/([^/]+)$/, name: "getAgent" },
287
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)$/, name: "deleteAgent" },
263
288
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
264
289
  { method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
265
290
  { method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
@@ -289,6 +314,8 @@ export const ROUTES = [
289
314
  { method: "PUT", pattern: /^\/runs\/([^/]+)\/grade$/, name: "gradeRun" },
290
315
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
291
316
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
317
+ // A run's trace (run-trace.ts): each model request and tool call as a span, with its time, tokens and cost.
318
+ { method: "GET", pattern: /^\/runs\/([^/]+)\/trace$/, name: "getRunTrace" },
292
319
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
293
320
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
294
321
  { method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
@@ -350,6 +377,11 @@ export const ROUTES = [
350
377
  { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
351
378
  { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
352
379
  { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in\/finish$/, name: "finishChatGPTSignIn" },
380
+ // Claude Code's login on this machine (claude-login.ts): the owner's session's alone; 404 by name while switched off.
381
+ { method: "GET", pattern: /^\/settings\/claude-login$/, name: "getClaudeLogin" },
382
+ { method: "PUT", pattern: /^\/settings\/claude-login$/, name: "turnOnClaudeLogin" },
383
+ { method: "DELETE", pattern: /^\/settings\/claude-login$/, name: "turnOffClaudeLogin" },
384
+ { method: "POST", pattern: /^\/settings\/claude-login\/login$/, name: "startClaudeLogin" },
353
385
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
354
386
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
355
387
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
@@ -405,22 +437,15 @@ export const ROUTES = [
405
437
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
406
438
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
407
439
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
408
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
409
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
410
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
411
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
412
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
413
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
414
440
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/loop$/, name: "getLearningLoop" },
415
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
416
441
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
442
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/corrections$/, name: "getLearningCorrections" },
443
+ { method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/corrections$/, name: "putLearningCorrections" },
417
444
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
418
- { method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
419
445
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
420
446
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
421
447
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
422
448
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
423
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
424
449
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays$/, name: "startLearnedWorkflowReplay" },
425
450
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays\/([^/]+)$/, name: "getLearnedWorkflowReplay" },
426
451
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
@@ -496,7 +521,7 @@ export function offersEnvOf(env) {
496
521
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
497
522
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
498
523
  * the offers probed again, never shown. */
499
- const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" ")];
524
+ const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" "), claudeLoginOf(env)?.dir];
500
525
  /** A sign-in step's answer; its refusal (a stale or bad pasted address, no sign-in waiting, OpenAI's no) a 400 in words. */
501
526
  async function planStep(step) {
502
527
  try {
@@ -519,32 +544,30 @@ async function needsOf(env) {
519
544
  * AGENTRUN_SERVE_LEARNING's when not given), its tool settings (`toolSettings`, what each web tool resolves to) and the
520
545
  * box offers (`boxes`, what the server found at the start, place-offers.ts), with whether a revision that names no
521
546
  * model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
522
- * (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
523
- * `gradeModel` is its `--grade-model`. */
524
- export async function readingOf(base, maxRuns, stored, learning, toolSettings = {}, boxes = [], gradeModel) {
547
+ * (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart. */
548
+ export async function readingOf(base, maxRuns, stored, learning, toolSettings = {}, boxes = []) {
525
549
  const env = withSecrets(base, "all", stored);
526
550
  const offers = await harnessOffers(offersEnvOf(env));
527
- return { env, offers, caps: capabilitiesWith(env, maxRuns, offers, learning ?? learningOf(env), await needsOf(env), toolSettings, boxes, gradeModel) };
551
+ return { env, offers, caps: capabilitiesWith(env, maxRuns, offers, learning ?? learningOf(env), await needsOf(env), toolSettings, boxes) };
528
552
  }
529
553
  /** The capabilities document GET /v2/capabilities answers for `env`: each harness's offer resolved, its `default_model`
530
554
  * included (harnessOffers), and whether a revision that names no model runs here (`models.ready`, and what it `needs`
531
555
  * when not), so what this returns is what the route serves and what the document's schema holds.
532
556
  * `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
533
- * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
534
- * `gradeModel`, its `--grade-model`. */
535
- export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
536
- return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
557
+ * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show. */
558
+ export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = []) {
559
+ return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes);
537
560
  }
538
561
  /** The capabilities document as `req`'s caller reads it: approving takes the owner's password session alone, so only
539
562
  * that caller reads `approve: true`; every other (a token, a run, accounts off) reads `approve_needs: "password"`. */
540
563
  export function forCaller(caps, ownerSession) {
541
- return ownerSession ? { ...caps, learning: { grade_model: caps.learning.grade_model, pending: caps.learning.pending, approve: true } } : caps;
564
+ return ownerSession ? { ...caps, learning: { pending: caps.learning.pending, approve: true } } : caps;
542
565
  }
543
566
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
544
567
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
545
568
  * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
546
569
  * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. */
547
- function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, gradeModel, refused = {}, runnerShell) {
570
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process") {
548
571
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
549
572
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
550
573
  const memory = hostMemory();
@@ -558,17 +581,19 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
558
581
  server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
559
582
  /** What runs a run here (the contract's `runtimes`, informational): this server's runners, over its one store. */
560
583
  runtimes: ["runner"],
584
+ /** How a run is kept from another here (run-child-host.ts runIsolationOf): each a process of its own, and `uid`, each
585
+ * a user of its own too. */
586
+ run_isolation: isolation,
561
587
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
562
588
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
563
- harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
589
+ harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
564
590
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
565
591
  places: placesOf(boxes, boxAllowOf(env)),
566
592
  models,
567
- /** What grades a run's proposed notes: the model this server names for it (learning.ts gradeModelOf), or null when
568
- * each run is graded on its agent's own model; and `pending`: a risky rule, the user's or the run's own, is kept to
569
- * wait for its owner's OK, served to no run; `approve`: whether the caller can approve one, which takes the owner's
570
- * password session (forCaller), and `approve_needs` when not. */
571
- learning: { grade_model: gradeModelOf(env, gradeModel) ?? null, pending: true, approve: false, approve_needs: "password" },
593
+ /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
594
+ * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
595
+ * `approve_needs` when not. */
596
+ learning: { pending: true, approve: false, approve_needs: "password" },
572
597
  /** Every tool a revision may name (the closed table in tools.ts): available here, or the variables it is missing; a
573
598
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
574
599
  * it (tool-keys.ts), when one does. */
@@ -620,8 +645,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
620
645
  * (tool-keys-store.ts), never in the clear. */
621
646
  tool_keys: { routes: true, at_rest: "sealed" },
622
647
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
623
- * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
624
- mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...HARNESSES] },
648
+ * which always exists (seal-key.ts), so MCP credentials are always kept sealed. Every harness of the table runs a
649
+ * grant (runnable.ts takes one on any), a module's among them. */
650
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...harnessIds(env)] },
625
651
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
626
652
  learning,
627
653
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -660,6 +686,11 @@ function cursorOf(value) {
660
686
  throw new ApiError("bad_request", "cursor is not one this server gave");
661
687
  return offset;
662
688
  }
689
+ /** How many runs still going whose listing is behind a status-filtered list reads at once before it builds them all and
690
+ * reads its page (runsPage). */
691
+ const UNLISTED_AT_ONCE = 50;
692
+ /** Most builds of one run's listing a list makes when writes keep moving its mark (runsPage listNow). */
693
+ const LIST_TRIES = 3;
663
694
  const nextCursor = (offset, total) => (offset < total ? Buffer.from(String(offset)).toString("base64url") : null);
664
695
  function limitOf(value) {
665
696
  if (value === null)
@@ -685,6 +716,9 @@ export async function startServe(options) {
685
716
  // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
686
717
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
687
718
  delete process.env[HARNESS_TABLE_ENV];
719
+ // So is the harness modules list, from `harnessModules` alone (an operator names them with --harness-module or
720
+ // AGENTRUN_SERVE_HARNESS_MODULES, which the CLI reads into the option).
721
+ delete process.env[HARNESS_MODULES_ENV];
688
722
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
689
723
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
690
724
  const data = await realpath(resolve(options.data));
@@ -713,11 +747,10 @@ export async function startServe(options) {
713
747
  const boxAllow = boxAllowOf(process.env);
714
748
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
715
749
  const learning = learningOf(process.env, options.learning);
716
- const learningBudget = learningBudgetOf(process.env, options.learningBudget);
717
750
  // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
718
751
  freeModelRequestsOf(process.env);
719
- const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
720
- if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
752
+ const minFreeMib = minFreeMibOf(process.env);
753
+ if (minFreeMib === undefined)
721
754
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
722
755
  const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
723
756
  // The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
@@ -729,7 +762,7 @@ export async function startServe(options) {
729
762
  // store handle it opened.
730
763
  const stops = [];
731
764
  try {
732
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates }, stops);
765
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates }, stops);
733
766
  }
734
767
  catch (error) {
735
768
  for (const stop of stops)
@@ -759,7 +792,7 @@ async function whileReplaced(take, held, until, waiting) {
759
792
  }
760
793
  }
761
794
  async function startHolding(options, data, checked, stops) {
762
- const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
795
+ const { maxRuns, minFreeBytes, learning, boxAllow, templates } = checked;
763
796
  /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
764
797
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
765
798
  * read (the view never fails for it). */
@@ -781,7 +814,12 @@ async function startHolding(options, data, checked, stops) {
781
814
  // shown nowhere.
782
815
  let secretStores;
783
816
  let triggerSettings = new Map();
784
- const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
817
+ const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data) };
818
+ // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
819
+ // the start, in words, before anything else opens.
820
+ // The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
821
+ // table hides until its owner installs it (tableIds: Goose), whose save warns with the command that installs it.
822
+ const harnesses = tableIds(base);
785
823
  // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
786
824
  // owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
787
825
  // earlier version wrote, in words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
@@ -821,7 +859,6 @@ async function startHolding(options, data, checked, stops) {
821
859
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
822
860
  // store is refused above (its owner lock).
823
861
  const attachHub = new AttachHub();
824
- const attach = createAttachRoutes({ store, hub: attachHub, machinesOnly: options.apiOnly === true, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
825
862
  // 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
826
863
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
827
864
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -849,6 +886,16 @@ async function startHolding(options, data, checked, stops) {
849
886
  // there is no keeping one in the clear.
850
887
  const seal = await bootSealKey(store, data);
851
888
  stops.push(async () => seal.release());
889
+ // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
890
+ // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled. A hosted machine a runner in a
891
+ // process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
892
+ const reach = liveReachOf(process.env, seal.key);
893
+ const attach = createAttachRoutes({
894
+ store, hub: attachHub, machinesOnly: options.apiOnly === true, runnerApart: options.runnerApart === true,
895
+ relay: { relays: store.runnerRelays, reach },
896
+ ...(options.attachTiming ? { timing: options.attachTiming } : {}),
897
+ log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)),
898
+ });
852
899
  // This server's own key on every environment it reads its secrets from, so a reader opens what this store holds with the
853
900
  // key checked against it, never another data directory's that this process booted too (secrets.ts holds one made key).
854
901
  const own = (env) => withSealKey(env, seal.text);
@@ -867,6 +914,8 @@ async function startHolding(options, data, checked, stops) {
867
914
  };
868
915
  // Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
869
916
  const stopping = new AbortController();
917
+ /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
918
+ let schemaSealed = Promise.resolve();
870
919
  // This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
871
920
  const storedKeys = (name) => toolKeys.value(name);
872
921
  // A stored key that does not open is said once at the start, never a refusal to start.
@@ -912,7 +961,14 @@ async function startHolding(options, data, checked, stops) {
912
961
  const plan = new ChatGPTPlan({ store, sealKey: seal.key, log: (fields) => (log ? log(logLine("chatgpt", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("chatgpt", fields)}\n`)), changed: () => keysChanged() });
913
962
  await plan.load();
914
963
  stops.push(async () => plan.close());
915
- let env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
964
+ // Claude Code's login on this machine (claude-login.ts): env carries where it is while the owner has it on, so
965
+ // claude-agent's model checks see a model without a key. Unset, its switch follows the listen address: there on
966
+ // loopback, off past it. A setting kept where the mode is now off or refused goes first.
967
+ const loginOff = claudeLoginSwitchedOff(base, options.host ?? DEFAULT_HOST);
968
+ const loginRefused = whyNotOneOwner({ apiOnly: options.apiOnly === true, tokens: tokens.length });
969
+ await dropRefusedLogin(store.settings, loginOff ?? loginRefused, (line) => (log ? log(logLine("claude_login", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)));
970
+ let claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
971
+ let env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
916
972
  let offers;
917
973
  let caps;
918
974
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -921,7 +977,13 @@ async function startHolding(options, data, checked, stops) {
921
977
  // With accounts off no one can answer an ask (the answer route takes the owner's session alone): each tool ask is
922
978
  // offered for says it needs the password sign-in, as learning's approve does.
923
979
  const askNeeds = (made) => (options.accounts ? made : { ...made, tools: made.tools.map((tool) => (tool.permissions.includes("ask") ? { ...tool, ask_needs: "password" } : tool)) });
924
- const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel, toolKeys.refused(), runnerShell));
980
+ // How this host keeps runs apart, as its runners decide it from the same setting and helper: `uid` where the helper can
981
+ // switch and AGENTRUN_RUN_USER is not `same`. A helper that cannot switch is a runner that refuses to start, in words
982
+ // naming the setting; no run here is then a user of its own, so `process`. Imported here, as the runner beside it
983
+ // imports it (runner/beside.ts): its module reaches the runner's, which reach back to this one's.
984
+ const { runIsolationName, runIsolationOf } = await import("./runner/run-child-host.js");
985
+ const isolation = await runIsolationOf(base, 1, () => { }).then(runIsolationName, () => "process");
986
+ const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation));
925
987
  const recompose = () => void (caps = compose());
926
988
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
927
989
  let offersFrom;
@@ -941,10 +1003,20 @@ async function startHolding(options, data, checked, stops) {
941
1003
  * (needsOf may wait, and another write lands meanwhile): the latest write's `needs` stands, an earlier one's that
942
1004
  * finishes after it is dropped. */
943
1005
  let needsAsked = 0;
1006
+ // The runs' listings' builder (run-listing.ts): each run's listing, built from its view once per change, so a runs list
1007
+ // reads rows alone. A list builds a listing it finds behind through it too (runsPage). Its own passes start once this
1008
+ // server listens and knows its own address (ownOriginOf, below). Its items keep no console link (a list adds the one for
1009
+ // the address its request reached), so the origin here is never served.
1010
+ const lister = createLister(store, () => viewDepsFor(ownOriginOf()), {
1011
+ log: (what, error) => log?.(logLine(what, { error: error.message })),
1012
+ ...(options.listerIdleMs !== undefined ? { idleMs: options.listerIdleMs } : {}),
1013
+ });
944
1014
  const keysChanged = async () => {
945
1015
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
946
- // serverSecrets live, store-view), so a key change needs no cache invalidation here.
947
- env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
1016
+ // serverSecrets live, store-view), and a list builds a listing cut of other keys again (cutOfNow). A failed run's error words
1017
+ // name a refused key by the keys and settings, so those listings are built again.
1018
+ await lister.keysChanged();
1019
+ env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
948
1020
  const mine = ++needsAsked;
949
1021
  const next = await needsOf(env);
950
1022
  if (mine === needsAsked)
@@ -961,6 +1033,21 @@ async function startHolding(options, data, checked, stops) {
961
1033
  if ((await plan.load()).state !== was)
962
1034
  await keysChanged();
963
1035
  };
1036
+ /** What Claude Code's login routes use: a turn on or off reads the setting again, then env, as a key's save does. A
1037
+ * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here. */
1038
+ const loginDeps = () => ({
1039
+ settings: store.settings,
1040
+ data,
1041
+ env: base,
1042
+ pinned: async () => claudeCliIn(installDirOf(data, LOGIN_HARNESS), (await import("@parcha/agentrun-harness-claude")).claudeAgentPlatform()),
1043
+ refused: loginRefused,
1044
+ sameMachine: isLoopback(host) && !options.publicUrl,
1045
+ claude: () => import("@parcha/agentrun-harness-claude"),
1046
+ changed: async () => {
1047
+ claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
1048
+ await keysChanged();
1049
+ },
1050
+ });
964
1051
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
965
1052
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
966
1053
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
@@ -998,10 +1085,8 @@ async function startHolding(options, data, checked, stops) {
998
1085
  const sealKey = seal.key;
999
1086
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1000
1087
  const sdkSecret = sdkRunSecret(sealKey);
1001
- // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
1002
- // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
1003
- const reach = liveReachOf(env, sealKey);
1004
- const answers = (handover) => viewerAnswers(handover, reach);
1088
+ // Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
1089
+ const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
1005
1090
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
1006
1091
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
1007
1092
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -1043,7 +1128,11 @@ async function startHolding(options, data, checked, stops) {
1043
1128
  // A provider's key set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name
1044
1129
  // from what the server was started with, as computerReady below reads it.
1045
1130
  store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: withSecrets(process.env, "own"),
1046
- paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
1131
+ paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves, options.runnerApart === true) },
1132
+ runnerApart: options.runnerApart === true,
1133
+ // A runner in a process of its own that relays its dials (dial-relay.ts): one whose attach listener said it is there
1134
+ // within RELAY_STALE_MS, at a host this server dials.
1135
+ relayed: async () => (await store.runnerRelays.list()).some((row) => row.seenAt >= Date.now() - RELAY_STALE_MS && dialHost(row.host, reach) !== undefined),
1047
1136
  ...(options.faux
1048
1137
  // --faux's providers stand in for every vendor's, a local one's daemon included.
1049
1138
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -1125,6 +1214,19 @@ async function startHolding(options, data, checked, stops) {
1125
1214
  };
1126
1215
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1127
1216
  const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1217
+ /** The run read's path and costs (A8, store-reads/learning.ts runAllInOverStore): `path`; `cost.usd` its own spend, the
1218
+ * job's (its compile turn is learning's), null while unknown; what learning spent for it
1219
+ * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown. */
1220
+ const allInViewOf = async (runId, view) => {
1221
+ const cost = (view.cost ?? {});
1222
+ const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
1223
+ const all = await runAllInOverStore(store, runId, own);
1224
+ if (!all)
1225
+ return {};
1226
+ // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1227
+ // gives): known as it answered even when its compile turn's cost is not; the row's while the run is at work.
1228
+ return { path: all.path, cost: { ...cost, ...(cost.upper_bound === true ? {} : { usd: all.usd }), learning_usd: all.learning_usd, all_in_usd: all.all_in_usd } };
1229
+ };
1128
1230
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1129
1231
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
1130
1232
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -1177,6 +1279,8 @@ async function startHolding(options, data, checked, stops) {
1177
1279
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
1178
1280
  const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
1179
1281
  ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1282
+ // Any bound given reaches Webhooks' check (0 and NaN are refused there, never dropped for the default).
1283
+ ...(options.webhookTimeoutMs !== undefined ? { timeoutMs: options.webhookTimeoutMs } : {}),
1180
1284
  ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1181
1285
  privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1182
1286
  });
@@ -1284,19 +1388,12 @@ async function startHolding(options, data, checked, stops) {
1284
1388
  // Whether that is the operator's own setting, not the default: a browser is held to an operator's list alone.
1285
1389
  ...(boxAllowSetIn(process.env) ? { boxAllowSet: true } : {}),
1286
1390
  modelOf,
1287
- // The run's learning start, decided at start as the old file-backed start decided it (learning-run.ts onStart/seedFor):
1288
- // the server's learning switch, the budget its # Learned section fits, the agent's seed read now from its learning folder
1289
- // (git), and the host's secrets as they are shown now to cut the notes a run is given, a loopback address kept (local),
1290
- // as the run's .learning/ files keep it: the run's own machine, which an agent with no read tool learns of only here.
1291
- // runs-over-store.learningStartFor pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed
1292
- // that cannot be read starts the run with nothing learned (a fault never refuses it). The runner's spec builders read
1293
- // it back as the run's end-of-run step (runner/learning-end.ts learningEndOfRun, in adapter-run-spec.ts and
1294
- // cli-run-spec.ts).
1391
+ // The run's learning start: the server's learning switch, the agent's seed read now from its learning folder (git), and
1392
+ // the host's secrets as they are shown now to cut the corrections a run is given, a loopback address kept (local): the
1393
+ // run's own machine. runs-over-store.learningStartFor pins the result (seed, section, workflows) in the launch for the
1394
+ // runner; a seed that cannot be read starts the run with nothing learned (a fault never refuses it). The runner's spec
1395
+ // builders read it back as the run's end-of-run step (runner/learning-end.ts learningEndOfRun).
1295
1396
  learning,
1296
- learningBudget,
1297
- // The model the server names to grade what a run proposes (capabilities' learning.grade_model), carried on each learning
1298
- // start for the runner's learning run to grade on: none, the agent's own.
1299
- ...(gradeModelOf(env, options.gradeModel) ? { gradeModel: gradeModelOf(env, options.gradeModel) } : {}),
1300
1397
  seedFor: async (agentId) => {
1301
1398
  // The switch runs no git in this process (learning.ts seedOf: the folder's own script and file API, which checks git
1302
1399
  // itself); a git or folder fault surfaces here as a seedOf error, so the run starts with nothing learned, never refused.
@@ -1307,62 +1404,6 @@ async function startHolding(options, data, checked, stops) {
1307
1404
  },
1308
1405
  shown: () => secretsShown(serverSecrets(), { local: true }),
1309
1406
  };
1310
- /** What a learning batch's loop reads of a run, from its view. Its `cost_usd` is the exact cost: a batch's figures say
1311
- * no "at most", so a view cost marked `upper_bound` reads null there, as the run's stored cost does (RunRow.costUsd). */
1312
- const batchRunView = async (runId) => {
1313
- const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1314
- if (!v)
1315
- return undefined;
1316
- 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.upper_bound !== true ? 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 };
1317
- };
1318
- // 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
1319
- // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
1320
- // (create's answer, read, list, cancel) cut its text as the learning routes do (learningShown, below).
1321
- const batches = new LearningBatches({
1322
- settings: store.settings,
1323
- learning: async (agentId) => {
1324
- const entry = await needAgent(agentId);
1325
- if (entry.agent.archivedAt)
1326
- return { learns: false, why: "it is archived." };
1327
- if (learning === "off")
1328
- return { learns: false, why: "this server's learning is off (--learning)." };
1329
- if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1330
- return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1331
- return { learns: true };
1332
- },
1333
- // 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
1334
- // server stopped before its row kept the id is found again, never started twice.
1335
- find: async (key) => (await agents.request(() => agents.store.runOfOrigin(key)))?.runId,
1336
- start: async (agentId, body, key) => (await startRunOf(await needAgent(agentId), body, { origin: { key } })).id,
1337
- view: (runId) => batchRunView(runId),
1338
- // Sent already: a steer the run's commands hold with these words, not refused (a follow-up to an ended run is one too,
1339
- // its reopen's).
1340
- sent: async (runId, content) => (await store.commands(runId, 0)).some((c) => c.kind === "steer" && c.refused === null && c.body?.text === content),
1341
- message: async (runId, content) => void (await message(store, await needRun(runId), content)),
1342
- // A run that is not there has nothing to stop; any other failure is the loop's (the row stays live and owned).
1343
- cancel: async (runId) => {
1344
- const moment = ID.test(runId) ? await momentOverStore(store, runId, viewDepsFor(ownOriginOf())) : undefined;
1345
- if (moment)
1346
- await cancel(store, moment);
1347
- },
1348
- figures: async (runId) => {
1349
- const stored = await store.runs.get(runId);
1350
- if (!stored)
1351
- return undefined;
1352
- // A run still going has no stored cost yet (its column is written at its end): its live cost, from its view, stands in,
1353
- // so a batch's cost now and the cost it books are costRunOf both.
1354
- const run = FINAL_STATES.includes(stored.state) ? stored : { ...stored, costUsd: (await batchRunView(runId))?.cost_usd ?? null };
1355
- // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1356
- const newest = await store.learning.proposal(runId);
1357
- const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1358
- // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then. Its all-in
1359
- // is not known while its audit's shadow run is queued or running (shadowSpendOf): the batch closes no row on it.
1360
- return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends, (await shadowSpendOf(store, runId)).open);
1361
- },
1362
- // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1363
- shown: (agentId) => learningShown(agentId),
1364
- ...(options.batchPollMs ? { pollMs: options.batchPollMs } : {}),
1365
- });
1366
1407
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1367
1408
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1368
1409
  // request) use the server's public address, else its own.
@@ -1410,11 +1451,12 @@ async function startHolding(options, data, checked, stops) {
1410
1451
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1411
1452
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1412
1453
  context: ctx,
1413
- liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers),
1454
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers(runId)),
1414
1455
  };
1415
1456
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1416
1457
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1417
1458
  // The route frames the SSE around its `page`, which long-polls the journal, byte-identical to the old live run's page.
1459
+ const servedTimelineDeps = { serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses };
1418
1460
  const timelines = runTimelines({
1419
1461
  context: ctx,
1420
1462
  // The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
@@ -1422,7 +1464,7 @@ async function startHolding(options, data, checked, stops) {
1422
1464
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1423
1465
  // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1424
1466
  // from its journal, which keeps what the run said whole.
1425
- timelineRows: (forStore, runId, context, calls) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context, calls),
1467
+ timelineRows: (forStore, runId, context, calls) => servedTimelineRows(servedTimelineDeps, forStore, runId, context, calls),
1426
1468
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1427
1469
  });
1428
1470
  const triggerDeps = {
@@ -1450,9 +1492,25 @@ async function startHolding(options, data, checked, stops) {
1450
1492
  tokenUsed.set(req, id);
1451
1493
  return id !== undefined;
1452
1494
  };
1495
+ // Answered keys are kept in the data directory for the retention capabilities state, and written before the answer
1496
+ // is sent, so a client that retries after a restart gets the first answer back.
1497
+ // A key's fingerprint is an HMAC of its request's body (stable JSON) under a key derived from the server's seal key:
1498
+ // never the body, nor a bare digest of it, since a body can hold a credential (a composio trigger's config) and a short
1499
+ // or guessable one could be found from a bare digest by hashing guesses. A trigger create's answer is kept as a read
1500
+ // answers it (replayed). Entries live IDEMPOTENCY_TTL_S (a day), so one an older server wrote (the body itself as its
1501
+ // fingerprint, a composio key in its answer) can outlive an upgrade: the start rewrites each (below, after the trigger
1502
+ // engine), and says how many alone.
1503
+ const fingerprintKey = createHmac("sha256", sealKey).update("agentrun-serve idempotency fingerprint").digest();
1504
+ const fingerprintOf = (text) => createHmac("sha256", fingerprintKey).update(text).digest("hex");
1505
+ /** A kept answer as its replay sends it, by the route its key was used on: a trigger create's (POST /triggers) with its
1506
+ * source as a read answers it now (shownTrigger); every other route's as it was, a run's input above all. */
1507
+ const replayed = (path, body) => (path === "/triggers" ? shownTrigger(body) : body);
1453
1508
  const keptFile = join(data, IDEMPOTENCY_FILE);
1454
1509
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
1455
1510
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
1511
+ /** How many entries the file held that the start did not keep (expired, or never answered): the file is written again
1512
+ * without them at the start, so no body an older server kept stays on disk past it. */
1513
+ const keptDropped = (kept?.entries?.length ?? 0) - idempotency.size;
1456
1514
  // A failed save rejects only its own caller: the next save starts from a settled chain and writes every kept key.
1457
1515
  let saving = Promise.resolve();
1458
1516
  const keep = () => (saving = saving
@@ -1462,7 +1520,7 @@ async function startHolding(options, data, checked, stops) {
1462
1520
  await writeFile(`${keptFile}.partial`, JSON.stringify({ version: 1, entries }), { mode: 0o600 });
1463
1521
  await rename(`${keptFile}.partial`, keptFile);
1464
1522
  }));
1465
- const host = options.host ?? "127.0.0.1";
1523
+ const host = options.host ?? DEFAULT_HOST;
1466
1524
  // Open setup (no code) only where no one else reaches the port: a loopback listener. Bound to any other address
1467
1525
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1468
1526
  const openSetup = options.openSetup === true && isLoopback(host);
@@ -1592,6 +1650,137 @@ async function startHolding(options, data, checked, stops) {
1592
1650
  signal: stopping.signal,
1593
1651
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1594
1652
  });
1653
+ // A composio trigger kept with a credential of its config in the clear (saved before the config was sealed) is sealed
1654
+ // before the first request: no answer shows it from this start on.
1655
+ // All of it under the store's secureRewrite, so no file of the store keeps the rows' old bytes (the key): when it can't
1656
+ // finish the scrub (a reader held the log back), it is said by a code alone and the next start finishes it.
1657
+ const sealing = options.store ?? store;
1658
+ const sealKept = () => composioTriggers.sealKept(async (id, source) => void (await sealing.triggers.update(id, { source })));
1659
+ await (sealing === store && store.secureRewrite ? store.secureRewrite(sealKept) : sealKept().then((rewritten) => ({ rewritten, left: undefined })))
1660
+ .then(({ left }) => {
1661
+ if (!left)
1662
+ return;
1663
+ const line = logLine("store", { condition: "store_scrub_not_done", reason: left });
1664
+ if (log)
1665
+ log(line);
1666
+ else
1667
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1668
+ })
1669
+ .catch((error) => void process.stderr.write(`agentrun-serve: sealing the composio triggers' config: ${error.message}\n`));
1670
+ // Then, not waited on: a trigger kept with a value in the clear in a field only its event's schema marks, sealed once
1671
+ // the schemas are read from Composio (composio-triggers.ts sealMarked). Drained by stop before the store closes.
1672
+ /** Trigger `id`'s create answer kept under an Idempotency-Key, its fields `source` now seals (sealed_config) masked: the
1673
+ * after-start seal by the events' schemas finds fields the name rule (shownTrigger, at the start's rewrite of the
1674
+ * records) does not, and a replay must not hand one back. The file is written again when one changed. */
1675
+ const cachedMasked = async (id, source) => {
1676
+ if (maskCached(id, source).length)
1677
+ await keep();
1678
+ };
1679
+ /** The records kept under an Idempotency-Key (their slots) that answered trigger `id`'s create with a field `source`
1680
+ * keeps sealed still in the clear, each masked in the map now (not saved: the caller saves). */
1681
+ function maskCached(id, source) {
1682
+ const fields = Array.isArray(source[SEALED_FIELD]) ? source[SEALED_FIELD].filter((name) => typeof name === "string") : [];
1683
+ const changed = [];
1684
+ for (const [slot, v] of idempotency) {
1685
+ const body = v.answer?.body;
1686
+ if (!v.answer || !isObject(body) || body.id !== id || !isObject(body.source) || !isObject(body.source.config))
1687
+ continue;
1688
+ const config = { ...body.source.config };
1689
+ const hit = fields.filter((name) => Object.hasOwn(config, name) && config[name] !== SEALED_MASK);
1690
+ if (!hit.length)
1691
+ continue;
1692
+ for (const name of hit)
1693
+ config[name] = SEALED_MASK;
1694
+ idempotency.set(slot, { ...v, answer: { ...v.answer, body: { ...body, source: { ...body.source, config, [SEALED_FIELD]: fields } } } });
1695
+ changed.push(slot);
1696
+ }
1697
+ return changed;
1698
+ }
1699
+ /** The records answering trigger `id`'s create once the trigger is gone (deleted, or not read): no trigger is left to
1700
+ * say which of its fields are sealed, so every field of each answer's config is masked in the map (not saved: the
1701
+ * caller saves). A replay of a deleted trigger's create needs none of its values. */
1702
+ function maskCachedGone(id) {
1703
+ const changed = [];
1704
+ for (const [slot, v] of idempotency) {
1705
+ const body = v.answer?.body;
1706
+ if (!v.answer || !isObject(body) || body.id !== id || !isObject(body.source) || !isObject(body.source.config))
1707
+ continue;
1708
+ const names = Object.keys(body.source.config);
1709
+ if (names.every((name) => body.source.config[name] === SEALED_MASK))
1710
+ continue;
1711
+ const config = Object.fromEntries(names.map((name) => [name, SEALED_MASK]));
1712
+ idempotency.set(slot, { ...v, answer: { ...v.answer, body: { ...body, source: { ...body.source, config, [SEALED_FIELD]: names } } } });
1713
+ changed.push(slot);
1714
+ }
1715
+ return changed;
1716
+ }
1717
+ const idempotencySaid = (fields) => {
1718
+ const line = logLine("idempotency", fields);
1719
+ if (log)
1720
+ log(line);
1721
+ else
1722
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1723
+ };
1724
+ const scrubSaid = ({ left }) => {
1725
+ if (!left)
1726
+ return;
1727
+ const line = logLine("store", { condition: "store_scrub_not_done", reason: left });
1728
+ if (log)
1729
+ log(line);
1730
+ else
1731
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1732
+ };
1733
+ schemaSealed = composioTriggers
1734
+ // Compare-and-set on the updatedAt the trigger was read at; and no VACUUM while serving (the marker stays, the next
1735
+ // start's scrub runs it before it serves).
1736
+ .sealMarked(async (id, source, updatedAt, read) => {
1737
+ const written = (await sealing.triggers.update(id, { source }, undefined, updatedAt === undefined ? { ifSource: read } : { ifUpdatedAt: updatedAt, ifSource: read })) !== undefined;
1738
+ // Once the trigger is written its seal stands: a failed save of the cached answers is said, never thrown (the seal
1739
+ // would be undone with the value's one copy). The map holds them masked already, so the next save writes them so.
1740
+ if (written)
1741
+ await cachedMasked(id, source).catch((error) => idempotencySaid({ condition: "idempotency_not_saved", trigger: id, error: typeof error?.code === "string" ? error.code : "error" }));
1742
+ return written;
1743
+ }, async (work) => (sealing === store && store.secureRewrite ? scrubSaid(await store.secureRewrite(work, { vacuum: false })) : void (await work())))
1744
+ .catch((error) => void (stopping.signal.aborted || process.stderr.write(`agentrun-serve: sealing the composio triggers' config by their events' schemas: ${error.message}\n`)));
1745
+ // Each Idempotency-Key record an older server wrote, rewritten before the first request: its fingerprint keyed (the body
1746
+ // it held as its fingerprint is gone) and its answer as a read answers it now. Said with how many alone.
1747
+ {
1748
+ // Each record rewritten, counted once whichever of the two passes below rewrote it.
1749
+ const scrubbed = new Set();
1750
+ // Each cached create answer checked against its trigger as stored, whatever its field's name: a field sealed since
1751
+ // (by its event's schema, whose save of this file failed before a restart) is masked before the first request.
1752
+ const answered = new Set();
1753
+ for (const [slot, v] of idempotency) {
1754
+ const body = v.answer?.body;
1755
+ if (slot.startsWith("/triggers\n") && isObject(body) && typeof body.id === "string")
1756
+ answered.add(body.id);
1757
+ }
1758
+ for (const id of answered) {
1759
+ const row = await sealing.triggers.get(id).catch(() => undefined);
1760
+ // A trigger gone (deleted before this start, by a server that did not mask its answers at the delete) or not read:
1761
+ // every field of its cached answers is masked, as no trigger is left to say which are sealed.
1762
+ const slots = row && isObject(row.source) ? maskCached(id, row.source) : row ? [] : maskCachedGone(id);
1763
+ for (const slot of slots)
1764
+ scrubbed.add(slot);
1765
+ }
1766
+ for (const [slot, v] of idempotency) {
1767
+ const fingerprint = /^[0-9a-f]{64}$/.test(String(v.fingerprint)) ? v.fingerprint : fingerprintOf(String(v.fingerprint));
1768
+ const answer = v.answer && { ...v.answer, body: replayed(slot.slice(0, slot.indexOf("\n")), v.answer.body) };
1769
+ if (fingerprint === v.fingerprint && JSON.stringify(answer?.body) === JSON.stringify(v.answer?.body))
1770
+ continue;
1771
+ idempotency.set(slot, { ...v, fingerprint, ...(answer ? { answer } : {}) });
1772
+ scrubbed.add(slot);
1773
+ }
1774
+ if (scrubbed.size || keptDropped > 0)
1775
+ await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
1776
+ if (scrubbed.size) {
1777
+ const line = logLine("idempotency", { condition: "idempotency_records_scrubbed", count: scrubbed.size });
1778
+ if (log)
1779
+ log(line);
1780
+ else
1781
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1782
+ }
1783
+ }
1595
1784
  /** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
1596
1785
  const SAVE_AFTER_TRIGGERS = "then save the server again";
1597
1786
  /** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
@@ -1612,7 +1801,6 @@ async function startHolding(options, data, checked, stops) {
1612
1801
  stops.push(async () => triggers.close());
1613
1802
  // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1614
1803
  // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1615
- void batches.resume().catch((error) => void process.stderr.write(`agentrun-serve: the learning batches' resume: ${error.message}\n`));
1616
1804
  void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1617
1805
  // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1618
1806
  // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
@@ -1624,18 +1812,21 @@ async function startHolding(options, data, checked, stops) {
1624
1812
  let closing = false;
1625
1813
  const workers = new Map();
1626
1814
  // Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
1627
- const onWorker = (task) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
1815
+ const onWorker = (task, projects) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
1628
1816
  const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
1629
1817
  // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
1630
1818
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1631
1819
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1632
1820
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1633
- 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]]; })) },
1821
+ workerData: { task, data, ...(projects ? { projects } : {}), 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]]; })) },
1634
1822
  // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
1635
1823
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1636
1824
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
1637
1825
  // runner's child holds many).
1638
1826
  ...(process.execArgv.some((arg) => arg.startsWith("--input-type")) ? { execArgv: workerArgs(process.execArgv) } : {}),
1827
+ // Its own heap, at most IMPORT_HEAP_MB whatever the machine's memory: an import that needs more ends as a failed
1828
+ // worker (said, and counted: IMPORT_STARTS), never as a process the system ends for the memory it took.
1829
+ resourceLimits: { maxOldGenerationSizeMb: IMPORT_HEAP_MB },
1639
1830
  });
1640
1831
  workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
1641
1832
  let answer;
@@ -1666,7 +1857,7 @@ async function startHolding(options, data, checked, stops) {
1666
1857
  if (count)
1667
1858
  return;
1668
1859
  count = { state: "counting" };
1669
- onWorker("plan").then((answer) => void (count = "sessions" in answer ? { state: "counted", projects: answer.projects, sessions: answer.sessions } : undefined), (error) => {
1860
+ onWorker("plan").then((answer) => void (count = "sessions" in answer ? { state: "counted", projects: answer.projects, sessions: answer.sessions, candidates: answer.candidates } : undefined), (error) => {
1670
1861
  count = { state: "failed" };
1671
1862
  process.stderr.write(`agentrun-serve: the count of this machine's sessions failed: ${error.message}\n`);
1672
1863
  });
@@ -1675,25 +1866,69 @@ async function startHolding(options, data, checked, stops) {
1675
1866
  if (task === "plan")
1676
1867
  worker.postMessage("stop"); };
1677
1868
  // The owner's yes, kept until the import ends: a server stopped (or killed) mid-import goes on with it at its next start.
1869
+ // With it: the projects chosen (none named: every project), what earlier starts took, and how many starts began the
1870
+ // import and neither ended it nor were stopped (`starts`).
1678
1871
  const importAsked = join(data, IMPORT_ASKED);
1872
+ /** The yes as kept, or undefined when it cannot be read as one (a file that will not open, text that is no JSON
1873
+ * object, `projects` that is no list of ids): never taken for "every project", which only an empty file or one that
1874
+ * names no projects means. */
1875
+ const askedOf = async () => {
1876
+ const text = await readFile(importAsked, "utf8").catch(() => undefined);
1877
+ if (text === undefined)
1878
+ return undefined;
1879
+ // The yes as an earlier version's setup wrote it is empty: every project, and no earlier start took anything.
1880
+ if (!text.trim())
1881
+ return { agents: [], runs: 0, starts: 0 };
1882
+ let kept;
1883
+ try {
1884
+ kept = JSON.parse(text);
1885
+ }
1886
+ catch {
1887
+ return undefined;
1888
+ }
1889
+ if (typeof kept !== "object" || kept === null || Array.isArray(kept))
1890
+ return undefined;
1891
+ const ids = (value) => (Array.isArray(value) && value.every((id) => typeof id === "string") ? value : undefined);
1892
+ const projects = ids(kept.projects);
1893
+ if (kept.projects !== undefined && !projects)
1894
+ return undefined;
1895
+ return { ...(projects ? { projects } : {}), agents: ids(kept.agents) ?? [], runs: typeof kept.runs === "number" ? kept.runs : 0, starts: typeof kept.starts === "number" ? kept.starts : 0 };
1896
+ };
1679
1897
  let importing;
1680
- /** The import at setup as the owner's console reads it: running, done with what it took, or stopped (the next start
1681
- * goes on with it). */
1898
+ /** The import at setup as the owner's console reads it: running, done with what it took, stopped (the next start
1899
+ * goes on with it), or failed (IMPORT_STARTS starts did not end it: given up, never tried again on its own). */
1682
1900
  let importState;
1683
1901
  /** Never rejects: whatever stops it (the store held past its wait, a file) is said on stderr, and the server goes on. */
1684
1902
  const importAtSetup = () => (importing ??= (async () => {
1685
1903
  importState = { state: "running" };
1904
+ // An import that fails, or ends the process, the same way at every start would be taken up at every start for good:
1905
+ // after IMPORT_STARTS such starts the yes is dropped, and said.
1906
+ const giveUp = async (why) => {
1907
+ await rm(importAsked, { force: true }).catch(() => undefined);
1908
+ importState = { state: "failed" };
1909
+ process.stderr.write(`agentrun-serve: the import at setup was given up (${why}): run the import command where the sessions are to try again\n`);
1910
+ };
1911
+ let asked;
1686
1912
  try {
1687
- const answer = await onWorker("import");
1688
- if (!("took" in answer))
1913
+ asked = await askedOf();
1914
+ // A choice that cannot be read is never widened to every project: nothing is imported.
1915
+ if (!asked)
1916
+ return await giveUp("the record of which projects to import could not be read");
1917
+ if (asked.starts >= IMPORT_STARTS)
1918
+ return await giveUp(`${IMPORT_STARTS} starts did not end it: the server ended during each`);
1919
+ // This start counted before its worker runs, so one the process does not outlive is counted too.
1920
+ await writeDurable(importAsked, JSON.stringify({ ...asked, starts: asked.starts + 1 }));
1921
+ const answer = await onWorker("import", asked.projects);
1922
+ // Stopped by the server's close, before it took anything or between two sessions: not a start that failed.
1923
+ if (!("took" in answer)) {
1924
+ await writeDurable(importAsked, JSON.stringify(asked));
1689
1925
  return void (importState = { state: "stopped" });
1926
+ }
1690
1927
  // The whole import, every start's part of it: what earlier starts took is kept with the owner's yes.
1691
- // The yes as setup wrote it is empty: no earlier start took anything.
1692
- const before = (await readJson(importAsked));
1693
- const agents = [...new Set([...(Array.isArray(before?.agents) ? before.agents.filter((id) => typeof id === "string") : []), ...answer.took.agents])];
1694
- const runs = (typeof before?.runs === "number" ? before.runs : 0) + answer.took.runs;
1928
+ const agents = [...new Set([...asked.agents, ...answer.took.agents])];
1929
+ const runs = asked.runs + answer.took.runs;
1695
1930
  if (answer.stopped) {
1696
- await writeDurable(importAsked, JSON.stringify({ agents, runs }));
1931
+ await writeDurable(importAsked, JSON.stringify({ ...asked, agents, runs }));
1697
1932
  return void (importState = { state: "stopped" });
1698
1933
  }
1699
1934
  await rm(importAsked, { force: true });
@@ -1702,9 +1937,18 @@ async function startHolding(options, data, checked, stops) {
1702
1937
  process.stdout.write(`${logLine("import", took)}\n`);
1703
1938
  }
1704
1939
  catch (error) {
1705
- importState = { state: "stopped" };
1706
- if (!closing)
1940
+ // A worker the close ended is no failed start; another failure is, and the last one allowed gives the import up.
1941
+ if (closing) {
1942
+ importState = { state: "stopped" };
1943
+ if (asked)
1944
+ await writeDurable(importAsked, JSON.stringify(asked)).catch(() => undefined);
1945
+ }
1946
+ else if (asked && asked.starts + 1 >= IMPORT_STARTS)
1947
+ await giveUp(`${IMPORT_STARTS} starts did not end it: ${error.message}`);
1948
+ else {
1949
+ importState = { state: "stopped" };
1707
1950
  process.stderr.write(`agentrun-serve: the import at setup stopped (the next start goes on with it): ${error.message}\n`);
1951
+ }
1708
1952
  }
1709
1953
  })());
1710
1954
  // ---- helpers --------------------------------------------------------------------------------------------------------
@@ -1785,6 +2029,9 @@ async function startHolding(options, data, checked, stops) {
1785
2029
  * a person's start (createRun) and a replay's (startLearnedWorkflowReplay), asks this before it reserves or writes anything. */
1786
2030
  async function needRunnableAgent(id) {
1787
2031
  const entry = await needAgent(id);
2032
+ // Another system's agent is archived only by its delete (its archive route is refused).
2033
+ if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2034
+ throw agentDeleting(id);
1788
2035
  if (entry.agent.archivedAt)
1789
2036
  throw new ApiError("agent_not_runnable", `The agent ${id} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
1790
2037
  return entry;
@@ -1796,12 +2043,13 @@ async function startHolding(options, data, checked, stops) {
1796
2043
  const learning = await learningOfAgent(entry);
1797
2044
  const native = nativeOf(entry.revision?.body);
1798
2045
  const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1799
- const runs = (await listRunsOverStore(store, { agent: entry.agent.id }, ctx)).filter((run) => !isShadowRun(run.id));
2046
+ // Counted in the store, one read per agent: no run is read for it.
2047
+ const runs = await store.runs.counts(entry.agent.id);
1800
2048
  return {
1801
2049
  ...(nativeStatus ? { nativeStatus } : {}),
1802
2050
  signIns: await signIns.view(entry.agent.id),
1803
2051
  ...(learning ? { learning } : {}),
1804
- runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
2052
+ runs: { count: runs.count, live: runs.live },
1805
2053
  // The agent's own computer (a persistent setting), as this server records it: the view's own_computer.
1806
2054
  ownComputer: agentComputerView(await agentComputerOf(store, entry.agent.id)),
1807
2055
  };
@@ -1814,6 +2062,134 @@ async function startHolding(options, data, checked, stops) {
1814
2062
  .then((done) => (done ? log?.(logLine("agent_computer", { agent: agentId, ...("deleted" in done ? { deleted: done.deleted } : { failed: done.failed }) })) : undefined))
1815
2063
  .catch((error) => log?.(logLine("agent_computer", { agent: agentId, failed: error instanceof Error ? error.message : String(error) })));
1816
2064
  };
2065
+ /** The runs and agents a delete forgot the kept answers of (forgetKept), as "run:<id>" or "agent:<id>", with when: kept
2066
+ * as long as a request under a key could still be at work (IDEMPOTENCY_TTL_S). */
2067
+ const forgotten = new Map();
2068
+ /** Whether a kept answer, by its request's path and its body, names run or agent `id`. */
2069
+ const namesForgotten = (kind, id, path, body) => path.startsWith(`/${kind}s/${id}/`) || (isObject(body) && body[kind === "run" ? "run_id" : "agent_id"] === id);
2070
+ /** Whether an answer, by its request's path and its body, names a run or an agent a delete forgot. */
2071
+ const keptForgotten = (path, body) => {
2072
+ const named = /^\/(runs|agents)\/([^/]+)\//.exec(path);
2073
+ if (named && forgotten.has(`${named[1] === "runs" ? "run" : "agent"}:${named[2]}`))
2074
+ return true;
2075
+ if (!isObject(body))
2076
+ return false;
2077
+ return (typeof body.run_id === "string" && forgotten.has(`run:${body.run_id}`)) || (typeof body.agent_id === "string" && forgotten.has(`agent:${body.agent_id}`));
2078
+ };
2079
+ /** The answers kept under idempotency keys (the in-memory map and its file) that name run or agent `id`, by the request's
2080
+ * path and the answer's body, dropped and the file written again: a deleted agent's and its runs' (agent-delete.ts). The
2081
+ * file is written every time, dropped or not: a save that failed before left the file holding answers memory no longer has,
2082
+ * so a retry that found nothing to drop still writes it (a restart in between reads them from the file again). A
2083
+ * failed write throws, and the delete stops before the rows that name them go. The run or agent is noted as forgotten
2084
+ * first (`forgotten`): a request under a key still at work when this passed keeps no answer naming it (idempotent). */
2085
+ const forgetKept = async (kind, id) => {
2086
+ forgotten.set(`${kind}:${id}`, Date.now());
2087
+ for (const [slot, one] of idempotency)
2088
+ if (namesForgotten(kind, id, slot.slice(0, slot.indexOf("\n")), one.answer?.body))
2089
+ idempotency.delete(slot);
2090
+ await keep();
2091
+ };
2092
+ const deleteInTurn = oneAtATime();
2093
+ /** `work`, a write to agent `id`'s home or learning (files a delete removes with the agent's folders, settings it leaves
2094
+ * to deleteLearning, answers kept under its path), done in the agent's delete turn, the agent read there: a write sent
2095
+ * while a DELETE runs waits for it, then finds the agent gone (404) or still being deleted (409 agent_not_runnable),
2096
+ * so nothing is written after the delete passed over it. The request's body is read before, outside the turn. */
2097
+ const agentWrite = (id, work) => deleteInTurn(id, async () => {
2098
+ const entry = await needAgent(id);
2099
+ if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2100
+ throw agentDeleting(id);
2101
+ return work();
2102
+ });
2103
+ const AGAIN = "It starts no run meanwhile: send the DELETE again to finish it.";
2104
+ /** `work`, a thing a deleted agent owns elsewhere deleted there: a refusal of one of `codes` (it is not deleted there
2105
+ * yet) answered as the delete answers each such one, 503 unavailable, retryable, saying to send the DELETE again. */
2106
+ const notYetWith = async (work, codes = ["unavailable"]) => {
2107
+ try {
2108
+ await work();
2109
+ }
2110
+ catch (error) {
2111
+ if (!(error instanceof ApiError && codes.includes(error.code)))
2112
+ throw error;
2113
+ throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${AGAIN}`, { retry_after_ms: 5_000 });
2114
+ }
2115
+ };
2116
+ /** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
2117
+ /** Step 2 of DELETE /agents/{id}: the learning module's delete over the agent's learning folder on this server's disk,
2118
+ * as the learning routes open it (learningFolderOf), which deleteLearning ends in its finally. A learning folder on
2119
+ * the agent's Archil disk goes with that disk in step 3. */
2120
+ const learningDelete = options.deleteLearning ?? ((given, agentId) => deleteLearning(given, agentId, learningFolderOf(data, agentId)));
2121
+ const agentDeleteHost = {
2122
+ store,
2123
+ deleteLearning: learningDelete,
2124
+ refuse: async (agentId) => void (await triggers.agentArchived(agentId)),
2125
+ cancel: async (runId) => {
2126
+ const moment = await momentOverStore(store, runId, viewDepsFor(ownOriginOf()));
2127
+ if (!moment)
2128
+ return true;
2129
+ if (moment.importedSource !== undefined)
2130
+ return false;
2131
+ try {
2132
+ await cancel(store, moment);
2133
+ return true;
2134
+ }
2135
+ catch (error) {
2136
+ // An SDK run: only its application ends it (runs-over-store.ts refuseSdkStop).
2137
+ if (error instanceof ApiError && error.code === "not_continuable")
2138
+ return false;
2139
+ throw error;
2140
+ }
2141
+ },
2142
+ removeTriggerThere: (triggerId) => notYetWith(() => triggers.removeThere(triggerId)),
2143
+ removeTriggerSettings: (triggerId) => triggers.removeSettings(triggerId),
2144
+ removeTrigger: (triggerId) => triggers.removeHere(triggerId),
2145
+ forgetSignIns: (agentId) => notYetWith(() => signIns.forgetAll(agentId)),
2146
+ removeOwnComputer: async (agentId) => {
2147
+ // Archived, the agent has no use for its own computer: deleted at its provider now, waited for.
2148
+ await reconcileAgentComputer(store, agentId, (provider, image) => computersOf().providerFor(provider, image));
2149
+ const left = await agentComputerOf(store, agentId);
2150
+ if (left)
2151
+ throw new ApiError("unavailable", `The agent ${agentId}'s own computer ${left.name} is not deleted yet${left.why ? ` (${left.why})` : ""}. It starts no run meanwhile: send the DELETE again to finish it.`, { retry_after_ms: 5_000 });
2152
+ await store.settings.remove(agentComputerHoldKey(agentId));
2153
+ },
2154
+ removeDisk: async (agentId) => {
2155
+ // The disk stored on the agent, read whatever the Archil settings are now: with Archil off the route below removes
2156
+ // nothing, and the agent's row going would leave its disk at Archil with nothing here to reach it.
2157
+ const stored = await agentDiskOf(store, agentId);
2158
+ if (!stored)
2159
+ return;
2160
+ if (!(await archil.agentView(agentId)).on)
2161
+ throw new ApiError("unavailable", `The agent ${agentId}'s Archil disk ${stored.diskId} is not deleted yet: Archil is off on this server, so it can't be deleted there. Turn Archil on again (PUT /v2/workspace/archil). ${AGAIN}`, { retry_after_ms: 5_000 });
2162
+ // Archil's failure (424), a live run of another agent on the disk (412) or no key (503): each is retried by the next DELETE.
2163
+ await notYetWith(() => archil.removeAgentDisk({ id: agentId, archived: true, external: true, liveOn: (diskId) => liveRunsOnDisk(store.runs, agentId, diskId) }), ["upstream_failed", "precondition_failed", "unavailable"]);
2164
+ },
2165
+ forgetRun: async (agentId, runId) => {
2166
+ // Its own folder on a disk its launch named (the caller's disk, which stays): read from its launch record, which goes
2167
+ // with the run's rows after this, so a failure or a stop here leaves the record that names the disk for the next
2168
+ // DELETE. A run on its agent's own disk has none: that disk went whole (removeDisk), its folder with it.
2169
+ const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
2170
+ if (launched?.kind === "launch")
2171
+ await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"]);
2172
+ // The run's folder (its work and what sits beside it), its scratch and its native context, on this machine.
2173
+ for (const folder of [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId), join(data, "native-context", runId)])
2174
+ await rm(folder, { recursive: true, force: true });
2175
+ // Its settings: an SDK run's row, its browser wait's end, the Archil disk it resolved to. Its kept computer's row
2176
+ // (workspace/computer-kept.ts) is left to the janitor, which deletes the computer of a run no longer there and then
2177
+ // the row: removed here, the computer would have nothing left to reach it.
2178
+ await store.settings.remove(sdkRunKey(runId));
2179
+ await store.settings.remove(waitEndedKey(runId));
2180
+ await store.settings.remove(runDiskKey(runId));
2181
+ await forgetKept("run", runId);
2182
+ },
2183
+ forgetAgent: async (agentId) => {
2184
+ // The agent's folder (its runs' folders, its home, its learning folder) and its scratch folder.
2185
+ await rm(agentFolder(data, agentId), { recursive: true, force: true });
2186
+ await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
2187
+ await forgetKept("agent", agentId);
2188
+ },
2189
+ waitMs: options.agentDeleteWaitMs ?? 30_000,
2190
+ pollMs: 200,
2191
+ ...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
2192
+ };
1817
2193
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
1818
2194
  // routes read from the store + the run view now, not a live Run.
1819
2195
  async function needRun(id) {
@@ -1845,11 +2221,15 @@ async function startHolding(options, data, checked, stops) {
1845
2221
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
1846
2222
  throw new ApiError("bad_request", "Idempotency-Key is 1 to 255 characters");
1847
2223
  const slot = `${path}\n${key}`;
1848
- const fingerprint = stable(body);
2224
+ const text = stable(body);
2225
+ const fingerprint = fingerprintOf(text);
1849
2226
  const now = Date.now();
1850
2227
  for (const [k, v] of idempotency)
1851
2228
  if (now - v.at > IDEMPOTENCY_TTL_S * 1000)
1852
2229
  idempotency.delete(k);
2230
+ for (const [k, at] of forgotten)
2231
+ if (now - at > IDEMPOTENCY_TTL_S * 1000)
2232
+ forgotten.delete(k);
1853
2233
  const known = idempotency.get(slot);
1854
2234
  if (known) {
1855
2235
  if (known.fingerprint !== fingerprint)
@@ -1861,16 +2241,25 @@ async function startHolding(options, data, checked, stops) {
1861
2241
  idempotency.set(slot, { fingerprint, at: now });
1862
2242
  let answer;
1863
2243
  try {
1864
- answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(fingerprint) });
2244
+ // The run's origin keeps the SHA-256 it always has: a run the store made under a key before this start compares to it.
2245
+ answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(text) });
1865
2246
  }
1866
2247
  catch (error) {
1867
2248
  idempotency.delete(slot);
1868
2249
  throw error;
1869
2250
  }
2251
+ await options.beforeKeep?.(path, answer.body);
2252
+ // A DELETE /agents/{id} that forgot the run or agent this answer names while the work was in flight (forgetKept): the
2253
+ // key keeps no answer, so it never replays a deleted run, even after a restart. The request's own answer is given.
2254
+ // Read and dropped with no wait in between, so no sweep comes between them.
2255
+ if (keptForgotten(path, answer.body)) {
2256
+ idempotency.delete(slot);
2257
+ return answer;
2258
+ }
1870
2259
  // The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
1871
2260
  // instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
1872
2261
  // then: the store keeps its run under the key's origin.
1873
- idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: answer.body, headers: answer.headers ?? {} } });
2262
+ idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: replayed(path, answer.body), headers: answer.headers ?? {} } });
1874
2263
  await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
1875
2264
  return answer;
1876
2265
  }
@@ -1937,7 +2326,8 @@ async function startHolding(options, data, checked, stops) {
1937
2326
  });
1938
2327
  };
1939
2328
  const monid = revision.monidPin ?? undefined;
1940
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
2329
+ // Claude Code's login on this machine is a runner place's alone: a sandbox run is checked for a key, as it runs.
2330
+ const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
1941
2331
  if (!blockers.length)
1942
2332
  return;
1943
2333
  const message = blockers.map((b) => b.message).join(" ");
@@ -1959,7 +2349,7 @@ async function startHolding(options, data, checked, stops) {
1959
2349
  throw new ApiError("agent_not_runnable", message, { fields, details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
1960
2350
  }
1961
2351
  /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1962
- const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
2352
+ const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, toolOf);
1963
2353
  /** What a save of `revision` pins of the MCP tools it grants (an agentic revision's: a workflow's nodes bind none): each
1964
2354
  * granted server listed once, now, with its saved credential (McpServersOverStore.pinListing), as `tools` each server's
1965
2355
  * listing in the harnesses' shape for the save's checks (blockersOf's `mcp`), and `pin` making the pin from them. A server
@@ -2049,7 +2439,8 @@ async function startHolding(options, data, checked, stops) {
2049
2439
  if (sdkOf(body))
2050
2440
  return { warnings: [], stamp: {} };
2051
2441
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
2052
- const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
2442
+ const harnessId = revision.kind === "agentic" ? harnessOfBody(body) : undefined;
2443
+ const install = harnessId !== undefined && Object.hasOwn(installs, harnessId) ? installs[harnessId] : undefined;
2053
2444
  if (install) {
2054
2445
  void install.ensure().catch((error) => log?.(logLine("harness_install_failed", { harness: install.entry.id, message: error.message })));
2055
2446
  }
@@ -2058,7 +2449,7 @@ async function startHolding(options, data, checked, stops) {
2058
2449
  const listing = await mcpListingOf(revision, previous?.mcpPin);
2059
2450
  const mcp = listing.tools;
2060
2451
  const { monid, warnings: usage = [] } = (await monidPinOf(revision, previous)) ?? {};
2061
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid });
2452
+ const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid });
2062
2453
  // 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
2063
2454
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
2064
2455
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
@@ -2094,21 +2485,68 @@ async function startHolding(options, data, checked, stops) {
2094
2485
  throw invalid(pinned.refused.map(({ tool, message }) => ({ field: tools.includes(tool) ? `definition.tools[${tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
2095
2486
  return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
2096
2487
  }
2488
+ /** The tools an agentic definition that names none is given where it runs (`place`): in a box, the box's shell tools
2489
+ * (NEW_AGENT_TOOLS); elsewhere none named, the runner's own. One rule for a new agent (createAgentOf) and for an apply
2490
+ * with agent_id of a package that names none (applyWith), whose agent is where its fresh apply put it. */
2491
+ const defaultToolsAt = (place) => (isObject(place) && place.mode === "sandbox" ? NEW_AGENT_TOOLS : undefined);
2492
+ /** The definition an apply with agent_id writes onto agent `entry` from its package's `definition`: its id, name and
2493
+ * description are the agent's own, kept from its creation; a package that names no tools gets those its agent's place
2494
+ * gives one (defaultToolsAt: the shell tools in the box its fresh apply put it in), as a fresh apply would. */
2495
+ const updateDefinition = (entry, definition) => {
2496
+ const kept = Object.fromEntries(Object.entries(definition).filter(([key]) => key !== "name" && key !== "description"));
2497
+ const current = (entry.revision?.body ?? {});
2498
+ const tools = kept.tools === undefined && kept.workflow === undefined && kept.computer === undefined ? defaultToolsAt(kept.place ?? current.place) : undefined;
2499
+ return tools ? { ...kept, tools: [...tools] } : kept;
2500
+ };
2097
2501
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
2098
- * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
2099
- * tool the box refuses (browser) keeps the runner. */
2502
+ * that names no place is given this server's box (place.ts defaultPlaceOf), stamped on its revision, when it names no
2503
+ * tools (it gets bash) or a tool that needs a shell; one whose tools need none, or that names a tool the box refuses
2504
+ * (browser), keeps the runner. */
2100
2505
  async function createAgentOf(body, template) {
2101
2506
  let warnings = [];
2102
- const definition = checkDefinitionBody(body);
2507
+ const definition = checkDefinitionBody(body, { harnesses });
2103
2508
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
2104
- const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
2509
+ const place = fallbackPlace("agentic", definition.definition.tools === undefined ? NEW_AGENT_TOOLS : named);
2510
+ const tools = defaultToolsAt(place);
2105
2511
  const entry = await agents.create(definition, async (revision) => {
2106
2512
  const saved = await saveable(revision);
2107
2513
  warnings = saved.warnings;
2108
2514
  return saved.stamp;
2109
- }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
2515
+ }, place.mode === "sandbox" && tools ? { place, tools } : undefined, template);
2110
2516
  return { entry, warnings };
2111
2517
  }
2518
+ /** A definition edit's body made into a new revision of agent `entry`, as PUT /agents/{id}/definition makes one
2519
+ * (commitAgent: the definition's checks and what this host refuses of it, saveable), with what this host still lacks for
2520
+ * it; then its computer reconciled. `template`: the package an apply with agent_id wrote it from; `fromPackage`: the
2521
+ * body is that package's whole definition, so what it leaves out that the package owns is gone (commitAgent). */
2522
+ async function reviseAgentOf(entry, body, options = {}) {
2523
+ let warnings = [];
2524
+ const check = async (revision, on) => {
2525
+ // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
2526
+ const saved = await saveable(revision, on);
2527
+ warnings = saved.warnings;
2528
+ return saved.stamp;
2529
+ };
2530
+ const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options });
2531
+ reconcileComputer(entry.agent.id);
2532
+ return { entry: edited, warnings };
2533
+ }
2534
+ /** The agent an apply with agent_id writes onto: one the template `pkg` made (the package id its revisions keep), live.
2535
+ * None by that id is 404; one made otherwise, or from another template, is 422 under agent_id, in words that say which;
2536
+ * an archived one is 409 agent_archived. */
2537
+ async function templateAgentOf(id, pkg) {
2538
+ const entry = await needAgent(id);
2539
+ const from = entry.template?.id;
2540
+ if (from !== pkg.id) {
2541
+ const message = from
2542
+ ? `The agent ${id} was made from the ${from} template, not ${pkg.id}: apply ${from} with agent_id to update it, or apply ${pkg.id} without agent_id to make a new agent.`
2543
+ : `The agent ${id} was not made from a template, so the ${pkg.name} template can't update it: apply without agent_id to make a new agent.`;
2544
+ throw invalid([{ field: "agent_id", reason: "not_an_option", message }]);
2545
+ }
2546
+ if (entry.agent.archivedAt)
2547
+ throw new ApiError("agent_archived", `The agent ${id} is archived: unarchive it, then apply the ${pkg.name} template onto it again.`);
2548
+ return entry;
2549
+ }
2112
2550
  /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
2113
2551
  * reads it, cut of the host's secrets as the learning reads cut them, and a replay run's launch made as a run's start
2114
2552
  * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
@@ -2131,51 +2569,6 @@ async function startHolding(options, data, checked, stops) {
2131
2569
  throw error;
2132
2570
  }
2133
2571
  };
2134
- /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
2135
- * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
2136
- * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
2137
- * learned workflow.json, its tools those its call nodes call (each one the source agent has and its gate allows), and
2138
- * the source's policy as it is now: its own tool settings, its approvals and its default cap, never more. Named
2139
- * `body.name`, else the workflow's own; its id is the workflow's name, with -2, -3 and on past an agent's id or name
2140
- * already here. The learned workflow stays where it is, unchanged. */
2141
- async function promoteOf(source, raw, body) {
2142
- const extra = unknownFields(body, ["name"]);
2143
- if (body.name !== undefined && (typeof body.name !== "string" || body.name.trim() === "" || body.name.length > 200))
2144
- extra.push({ field: "name", reason: "wrong_type", message: "name is the new agent's name: text of 1 to 200 characters" });
2145
- if (extra.length)
2146
- throw invalid(extra);
2147
- const id = source.agent.id;
2148
- const learned = await promotable(data, id, raw, { refuse: await learningValues(id), draftTools: () => learnedDraftToolsOf(id, source) });
2149
- // Its policy from the same read of the source as the tools checked above: one revision's, whatever is saved meanwhile.
2150
- const policy = (source.revision?.body ?? {});
2151
- const promoted = (agentId) => ({
2152
- id: agentId,
2153
- name: typeof body.name === "string" ? body.name.trim() : agentId,
2154
- ...(learned.description ? { description: learned.description } : {}),
2155
- workflow: learned.workflow,
2156
- tools: learned.calls,
2157
- ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
2158
- ...(policy.approvals === "never" ? { approvals: "never" } : {}),
2159
- ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
2160
- });
2161
- const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
2162
- // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
2163
- for (let tries = 0;; tries++) {
2164
- const all = [...(await agents.list()), ...(await agents.list({ archived: true }))];
2165
- const taken = new Set(all.flatMap((entry) => [entry.agent.id, entry.agent.name]));
2166
- let n = 1;
2167
- while (taken.has(n === 1 ? learned.name : `${learned.name}-${n}`))
2168
- n++;
2169
- const agentId = n === 1 ? learned.name : `${learned.name}-${n}`;
2170
- try {
2171
- return await createAgentOf({ definition: promoted(agentId), note });
2172
- }
2173
- catch (error) {
2174
- if (!(error instanceof ApiError && error.code === "agent_exists") || tries >= 4)
2175
- throw error;
2176
- }
2177
- }
2178
- }
2179
2572
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
2180
2573
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
2181
2574
  * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, with no permission written
@@ -2184,9 +2577,52 @@ async function startHolding(options, data, checked, stops) {
2184
2577
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
2185
2578
  * 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
2186
2579
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
2187
- * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
2580
+ * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one.
2581
+ * With `agent_id` (an agent this template made, templateAgentOf), the same checks, then a new revision of that agent in
2582
+ * place of a new one (its runs and its learning stay), and its triggers reconciled by name (below); a refused trigger
2583
+ * removes the ones this apply made, and the agent is not archived. A fresh apply warns of a live agent the same
2584
+ * package and parameters made (the keyed digest of the parameters kept on its revision: never the parameters).
2585
+ *
2586
+ * Overlapping updates of one agent: this server runs them one after the other (`applying`, a chain per agent id), each
2587
+ * from its read of the agent to its last trigger removed, so two never reconcile the same triggers at once. And each
2588
+ * writes its revision only onto the revision it read (ifCurrent): one whose read went stale meanwhile (an edit, or an
2589
+ * apply on another server) is 412 precondition_failed before it touches a trigger. Across several servers sharing one
2590
+ * store the chain is per process, so the 412 is what holds there. */
2188
2591
  async function applyTemplate(template, body) {
2189
- const { parameters, grants: asked, servers: picks, model: override, choice, approvals } = applyBodyOf(template, body);
2592
+ const id = typeof body.agent_id === "string" && body.agent_id.trim() ? body.agent_id.trim() : undefined;
2593
+ if (id === undefined)
2594
+ return applyWith(template, body);
2595
+ const turn = (applying.get(id) ?? Promise.resolve()).then(() => applyWith(template, body));
2596
+ const settled = turn.then(() => undefined, () => undefined);
2597
+ applying.set(id, settled);
2598
+ try {
2599
+ return await turn;
2600
+ }
2601
+ finally {
2602
+ if (applying.get(id) === settled)
2603
+ applying.delete(id);
2604
+ }
2605
+ }
2606
+ /** The template applies with agent_id in flight on this server, by agent id: each one's turn settled (applyTemplate). */
2607
+ const applying = new Map();
2608
+ /** A trigger write an update made on its agent's condition (TriggerOwn.onAgent) that found no such trigger there:
2609
+ * false, for one a PATCH moved to another agent (or a delete removed) meanwhile; any other failure as it is. */
2610
+ const movedAway = (error) => {
2611
+ if (error instanceof ApiError && error.code === "not_found")
2612
+ return false;
2613
+ throw error;
2614
+ };
2615
+ /** applyTemplate's work, in its turn on the agent where it has agent_id. */
2616
+ async function applyWith(template, body) {
2617
+ const { parameters, grants: asked, servers: picks, model: override, choice, approvals, agentId } = applyBodyOf(template, body);
2618
+ // With agent_id, the apply writes a new revision of that agent (one this template made) in place of making another:
2619
+ // everything below checks the package as a fresh apply does, through the same code.
2620
+ const onto = agentId === undefined ? undefined : await templateAgentOf(agentId, template);
2621
+ // An update's triggers are reconciled by name with the ones the agent has (below), read with the agent: each write to
2622
+ // one is made only while it is still this agent's (TriggerOwn.onAgent), so one a PATCH moves away meanwhile is left.
2623
+ const had = onto ? await store.triggers.list(onto.agent.id) : [];
2624
+ if (onto && options.templateApplyRead)
2625
+ await options.templateApplyRead(onto.agent.id);
2190
2626
  // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2191
2627
  const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
2192
2628
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
@@ -2254,9 +2690,84 @@ async function startHolding(options, data, checked, stops) {
2254
2690
  for (const one of [made.agent, ...made.triggers])
2255
2691
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
2256
2692
  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" } });
2257
- // The agent keeps where it came from (its first revision's package): the package's id, version and, imported, its SHA.
2258
- const { entry, warnings } = await createAgentOf(made.agent, { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null });
2693
+ // The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either).
2694
+ const listed = new Set(made.triggers.flatMap((trigger, i) => (emptyFeeds.has(i) ? [] : [String(trigger.name).trim()])));
2695
+ // The triggers to remove: each of the agent's that an apply of this package marked as its own (TriggerRow.templateId)
2696
+ // and whose name the package no longer lists. A trigger the owner made, one a PATCH moved here from another agent (or
2697
+ // away and back), and one made before the mark was kept carry none, and are left. One whose removal fails keeps its
2698
+ // mark, so the next update removes it.
2699
+ const removing = had.filter((row) => row.templateId === pkg.id && !listed.has(row.name));
2700
+ const hadByName = new Map(had.map((row) => [row.name, row]));
2701
+ // A Composio trigger the update keeps by name whose fixed part is unchanged (its server, event and config, each sealed
2702
+ // value the package sends again, filled in from a parameter in the clear, the same as the one sealed:
2703
+ // ComposioTriggers.resent) is changed in place, its sealed values left out of the PATCH so it keeps them sealed. One
2704
+ // whose fixed part changed (another key too) is made again, as one of another kind is (below): its instance on
2705
+ // Composio was made from that part. Read before the revision is written; neither holds a sealed value.
2706
+ const resent = new Map();
2707
+ const remade = new Set();
2708
+ for (const [i, trigger] of made.triggers.entries()) {
2709
+ const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
2710
+ if (!was || !isObject(trigger.source) || trigger.source.kind !== "composio" || !isObject(was.source) || was.source.kind !== "composio")
2711
+ continue;
2712
+ try {
2713
+ resent.set(i, composioTriggers.resent(was.source, was.id, trigger.source));
2714
+ }
2715
+ catch (error) {
2716
+ if (!(error instanceof ApiError && error.code === "input_invalid"))
2717
+ throw error;
2718
+ remade.add(i);
2719
+ }
2720
+ }
2721
+ // A trigger the agent has by a package trigger's name is the package's to keep by its mark (TriggerRow.templateId).
2722
+ // Marked with this package, it is changed in place, or made again when its kind or its Composio fixed part changed.
2723
+ // Unmarked (the owner's, or made by an apply before the mark was kept: the two can't be told apart), it is adopted only
2724
+ // by a change in place, and marked then. Marked with another package, it is not this one's. One this package would
2725
+ // have to make again without being its own, or another package's, refuses the apply with nothing written (409 under
2726
+ // triggers.<i>): the owner renames or deletes it, then applies again.
2727
+ const notOurs = made.triggers.flatMap((trigger, i) => {
2728
+ const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
2729
+ if (!was || was.templateId === pkg.id)
2730
+ return [];
2731
+ const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
2732
+ const wasKind = isObject(was.source) ? String(was.source.kind) : "";
2733
+ if (was.templateId === null && kind === wasKind && !remade.has(i))
2734
+ return [];
2735
+ const why = was.templateId !== null
2736
+ ? `is another template package's (${was.templateId}), not the ${pkg.name} template's`
2737
+ : `is not the ${pkg.name} template's, and keeping it would mean removing it and making it again: ${kind === wasKind ? "its Composio server, event or config differs from the package's" : `it is a ${wasKind} trigger, and the package's is a ${kind} one`}`;
2738
+ return [{ field: `triggers.${i}.name`, reason: "not_allowed", message: `The agent's trigger ${was.name} ${why}. Nothing was changed: rename or delete that trigger, then apply the template again.` }];
2739
+ });
2740
+ if (notOurs.length)
2741
+ throw new ApiError("name_taken", notOurs.length === 1 ? notOurs[0].message : `${notOurs.length} of the agent's triggers have the names of the ${pkg.name} template's and are not its own. Nothing was changed: rename or delete each, then apply the template again.`, { fields: notOurs });
2742
+ // The agent keeps where it came from (the package on the revision the apply writes): the package's id, version and,
2743
+ // imported, its SHA; and a keyed digest of the parameters it was given (never the parameters: one may be a credential).
2744
+ // Which triggers are the package's is on each trigger (its mark), not here.
2745
+ const digest = parametersDigest(sealKey, stable(parameters));
2746
+ const origin = { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null, parameters_digest: digest };
2747
+ // A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
2748
+ // which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
2749
+ const twins = onto ? [] : (await agents.list())
2750
+ .filter((one) => one.template?.id === pkg.id && one.template.parameters_digest === digest)
2751
+ .map((one) => ({ field: "agent_id", reason: "duplicate", message: `The agent ${one.agent.id} was made from the ${pkg.name} template with these parameters, and this apply made another. To change that one instead, apply with agent_id ${one.agent.id}.` }));
2752
+ // An update writes the package as a new revision of the agent, as an edit does (its id, name and description are the
2753
+ // agent's own, kept from its creation), but what the package owns and leaves out is gone (fromPackage); only onto the
2754
+ // revision it read, else 412 with nothing changed. A fresh apply makes the agent as POST /agents does.
2755
+ const { entry, warnings } = onto
2756
+ ? await reviseAgentOf(onto, { ...made.agent, definition: updateDefinition(onto, made.agent.definition) }, { template: origin, fromPackage: true, ifCurrent: onto.revision?.id ?? null }).catch((error) => {
2757
+ if (error instanceof ApiError && error.code === "precondition_failed")
2758
+ throw new ApiError("precondition_failed", `The agent ${onto.agent.id} changed while this apply of the ${pkg.name} template read it (an edit, or another apply, wrote a revision): nothing was changed. Apply it with agent_id again to update the agent as it is now.`);
2759
+ throw error;
2760
+ })
2761
+ : await createAgentOf(made.agent, origin);
2762
+ // An update's triggers are reconciled by name with the ones the agent has: the package's trigger of a name the agent
2763
+ // has (of the same kind) is changed in place, keeping its id, a feed's seen items, a webhook's secret and whether the
2764
+ // owner turned it off (an unmarked one is adopted so, and only so: notOurs above), its settings the package's whole
2765
+ // (catchup_window_s and max_active_runs the package leaves out back to their defaults, as a fresh apply makes them); a new name is made; one the package
2766
+ // marked and no longer lists is removed (`removing`). Each trigger the apply makes or keeps is marked as the package's; each write to one the agent had is made only while it
2767
+ // is still the agent's: one a PATCH moved away meanwhile is neither changed nor removed, and its name is made anew.
2259
2768
  const ids = [];
2769
+ // The triggers this apply made (never one it changed in place): what a refusal's undo removes.
2770
+ const madeNow = [];
2260
2771
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
2261
2772
  // /triggers hands back its own, so the owner can give it to the sender.
2262
2773
  const secrets = [];
@@ -2264,13 +2775,49 @@ async function startHolding(options, data, checked, stops) {
2264
2775
  // a composio one Composio can't reach or run as here) is skipped, never the apply: the agent stands, and the answer
2265
2776
  // says what to do (a warning under triggers.<i>). Kept with its refusal, whose words the warning carries.
2266
2777
  const unconnected = new Map();
2778
+ // Each trigger the package no longer lists whose sender kept what it has of it (a Composio instance): kept here, marked,
2779
+ // for the next update to remove, and said in the answer.
2780
+ const leftThere = [];
2267
2781
  try {
2268
2782
  for (const [i, trigger] of made.triggers.entries()) {
2269
2783
  if (emptyFeeds.has(i))
2270
2784
  continue;
2785
+ const aimed = { ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } };
2786
+ let was = hadByName.get(String(trigger.name).trim());
2787
+ const own = { templateId: pkg.id, onAgent: entry.agent.id };
2271
2788
  try {
2272
- const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
2789
+ if (was && isObject(trigger.source) && isObject(was.source) && was.source.kind === trigger.source.kind && !remade.has(i)) {
2790
+ const { enabled: _owners, source: given, ...sent } = aimed;
2791
+ // The package's source, sent only when it says something other than the stored one: a PATCH's source puts the
2792
+ // trigger on from now (its next time and an every_s grid restarted, a poll kicked), so an update that leaves a
2793
+ // schedule as it was never moves it. An every_s schedule with no start_at is the stored one's grid (the time
2794
+ // its first apply made it), as it says no other; a Composio one is its `resent` form.
2795
+ const ours = resent.get(i) ?? (isObject(given) && given.kind === "schedule" && given.every_s !== undefined && given.start_at === undefined && isObject(was.source) && was.source.every_s === given.every_s && typeof was.source.start_at === "string" ? { ...given, start_at: was.source.start_at } : given);
2796
+ // Compared as a create keeps it (Triggers.sourceAsKept: a feed's every_s the package leaves out is the default the
2797
+ // trigger was made with), so a package that says no more than it did never moves it.
2798
+ const source = stable(resent.has(i) ? ours : (triggers.sourceAsKept(ours) ?? ours)) === stable(was.source) ? undefined : ours;
2799
+ // The package's settings whole: one its version leaves out goes back to what a fresh apply makes (POST
2800
+ // /triggers' default), never kept from the version before. PATCH reads null as no cap.
2801
+ const patch = { ...sent, catchup_window_s: sent.catchup_window_s ?? CATCHUP_WINDOW_S, max_active_runs: sent.max_active_runs ?? null };
2802
+ if (await triggers.update(was.id, source ? { ...patch, source } : patch, own).then(() => true, movedAway)) {
2803
+ ids.push(was.id);
2804
+ continue;
2805
+ }
2806
+ was = undefined;
2807
+ }
2808
+ // Of another kind now (a trigger's source kind is fixed), or a Composio one whose fixed part changed: the old one
2809
+ // goes, then the new one is made, off where the owner turned the old one off. The old one's instance on Composio
2810
+ // goes first (Triggers.remove on its agent's condition): one Composio did not delete leaves the old trigger here
2811
+ // as it was (on or off, marked, its config sealed) and the new one unmade, so two instances never watch, and the
2812
+ // apply fails with its revision standing, as a refused trigger's does; the next apply finds the old one again.
2813
+ const left = was ? await triggers.remove(was.id, own).catch(movedAway) : false;
2814
+ if (left === false)
2815
+ was = undefined;
2816
+ else if (isObject(left) && isObject(left.composio) && left.composio.done === false)
2817
+ throw new ApiError("upstream_failed", `The ${pkg.name} template's trigger ${String(trigger.name).trim()} changed, so its old Composio trigger instance must go before the new one is made, and Composio didn't delete it: the new one was not made, and the old trigger is kept here as it was. ${String(left.composio.note ?? "")} Then apply again.`.trim());
2818
+ const { id: madeId, secret } = await triggers.create(was && !was.enabled ? { ...aimed, enabled: false } : aimed, { templateId: pkg.id });
2273
2819
  ids.push(madeId);
2820
+ madeNow.push(madeId);
2274
2821
  if (secret)
2275
2822
  secrets.push({ trigger_id: madeId, secret });
2276
2823
  }
@@ -2284,9 +2831,16 @@ async function startHolding(options, data, checked, stops) {
2284
2831
  throw error;
2285
2832
  }
2286
2833
  }
2834
+ // Each trigger the package marked and no longer lists, while it is still the agent's.
2835
+ for (const row of removing) {
2836
+ const left = await triggers.remove(row.id, { onAgent: entry.agent.id }).catch(movedAway);
2837
+ if (isObject(left) && isObject(left.composio) && left.composio.done === false)
2838
+ leftThere.push({ field: "triggers", reason: "upstream_failed", message: `The trigger ${row.name} (${row.id}), which the ${pkg.name} template no longer lists, is kept until its Composio trigger instance is gone. ${String(left.composio.note ?? "")} The next update of the agent from the template removes the trigger.` });
2839
+ }
2287
2840
  }
2288
2841
  catch (error) {
2289
- for (const id of ids.reverse()) {
2842
+ // An update's revision and the triggers it changed stand; what it made is removed. A fresh apply is undone whole.
2843
+ for (const id of madeNow.reverse()) {
2290
2844
  try {
2291
2845
  await triggers.remove(id);
2292
2846
  }
@@ -2296,7 +2850,8 @@ async function startHolding(options, data, checked, stops) {
2296
2850
  }
2297
2851
  // Archived through the trigger engine, as POST /agents/{id}/archive is: a trigger the undo could not remove is turned
2298
2852
  // off in that same store transaction with the reason agent_archived, never with none, and unarchive answers it.
2299
- await triggers.agentArchived(entry.agent.id).catch((undo) => log?.(logLine("template_undo_failed", { template: pkg.name, agent: entry.agent.id, message: undo.message })));
2853
+ if (!onto)
2854
+ await triggers.agentArchived(entry.agent.id).catch((undo) => log?.(logLine("template_undo_failed", { template: pkg.name, agent: entry.agent.id, message: undo.message })));
2300
2855
  throw error;
2301
2856
  }
2302
2857
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
@@ -2325,8 +2880,8 @@ async function startHolding(options, data, checked, stops) {
2325
2880
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2326
2881
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2327
2882
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2328
- 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, ...composioSkipped, ...feedsSkipped, ...appShort] };
2329
- return { applied, minted };
2883
+ 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, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
2884
+ return { applied, minted, updated: onto !== undefined };
2330
2885
  }
2331
2886
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
2332
2887
  * (`{content: string}` with none), with the documented run bodies;a workflow run's its workflow's input schema, never the agentic example. Each value
@@ -2376,37 +2931,89 @@ async function startHolding(options, data, checked, stops) {
2376
2931
  * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
2377
2932
  * at the public URL or the server's own address. */
2378
2933
  const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
2379
- /** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
2380
- * its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
2381
- * timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
2382
- * seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
2383
- * each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
2384
- * entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
2385
- * answer even when the server has since changed or gone, since it does no new work. */
2386
- function handedMcpAuth(body) {
2387
- if (body.mcp_auth === undefined)
2388
- return { body, sealer: async () => undefined };
2389
- const { mcp_auth, ...rest } = body;
2390
- const sealer = async () => {
2934
+ /** A run body's launch secrets taken out of it, before anything else reads the body: `mcp_auth`, the credentials a run's
2935
+ * caller hands its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf), and `model_key`, the run's own model
2936
+ * key (run-model-key.ts), such as a LiteLLM virtual key minted for it. They never reach the run's saved body, its
2937
+ * timeline, an idempotency fingerprint (a retry with a fresh credential or key replays its first answer) or a log: only
2938
+ * the seal made of them, sealed for the run's id into its launch row (store/seal.ts sealRunLaunch), each MCP credential
2939
+ * bound to its server's origin then and the model key to the gateway's (AGENT_MODEL_BASE_URL). `handed` is called only
2940
+ * for new work, inside the request's idempotent work: there each mcp_auth entry must name a saved per_run server, and
2941
+ * the model key must be text, else 422, nothing written. A retry its key already answered replays that answer even
2942
+ * when the server has since changed or gone, since it does no new work. */
2943
+ function handedLaunchSecrets(body) {
2944
+ if (body.mcp_auth === undefined && body.model_key === undefined)
2945
+ return { body, handed: async () => ({}) };
2946
+ const { mcp_auth, model_key, ...rest } = body;
2947
+ const handed = async () => {
2391
2948
  const issues = [];
2392
- const handed = mcpAuthOf(mcp_auth, issues);
2949
+ const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
2393
2950
  const auth = {};
2394
- for (const [server, headers] of Object.entries(handed ?? {})) {
2951
+ for (const [server, headers] of Object.entries(mcp ?? {})) {
2395
2952
  const row = await getMcpServer(store, server);
2396
2953
  if (row?.auth !== "per_run")
2397
2954
  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.` });
2398
2955
  else
2399
2956
  auth[server] = { headers, origin: new URL(row.url).origin };
2400
2957
  }
2958
+ const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
2401
2959
  if (issues.length)
2402
2960
  throw invalid(issues);
2403
- return (runId) => sealRunMcpAuth(sealKey, runId, auth);
2961
+ return { ...(mcp_auth !== undefined ? { mcp: auth } : {}), ...(model !== undefined ? { model } : {}) };
2962
+ };
2963
+ return { body: rest, handed };
2964
+ }
2965
+ /** The 422 for a model key where the run's model never takes it (run-model-key.ts modelKeyMisfit), at `model_key`. */
2966
+ const misfit = (why) => invalid([{ field: "model_key", reason: "not_an_option", message: why }]);
2967
+ /** A start's launch seal of `handed` (handedLaunchSecrets), made once the start prepared the run's launch: a model key
2968
+ * where the run's model never takes it is refused (modelKeyMisfit), and a start that hands other secrets but no key
2969
+ * is refused where the server holds no key for the run's route (serverKeyMissing). Undefined when nothing is handed:
2970
+ * the start's own check (runs-over-store keyedOrRefused) refuses that one where it has no key to spend. */
2971
+ function startSeal(handed) {
2972
+ if (handed.mcp === undefined && handed.model === undefined)
2973
+ return undefined;
2974
+ return (runId, launch, kind) => {
2975
+ const target = { kind, model: launch.model, native: Boolean(launch.native) };
2976
+ if (handed.model !== undefined) {
2977
+ const why = modelKeyMisfit(env, target);
2978
+ if (why)
2979
+ throw misfit(why);
2980
+ }
2981
+ else if (serverKeyMissing(env, target))
2982
+ throw modelKeyRequired(false);
2983
+ const origin = runModelOrigin(env);
2984
+ return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}) });
2985
+ };
2986
+ }
2987
+ /** A message's launch secrets for run `run` (its kind and launch as stored): what it hands replaces that part of the
2988
+ * run's, inside the write that takes the message (store LaunchSealed: a function of what the launch holds then), and a
2989
+ * part it does not hand is kept as the run holds it (none after its turn's end erased it). A model key is refused
2990
+ * where the run's model never takes it. One is required where the server holds no key for the run's route and the
2991
+ * run holds none when the message is written (its last turn ended): 422 model_key_required from inside that write,
2992
+ * which then writes nothing, so a turn never starts with no key to spend. */
2993
+ async function messageSeal(run, handed) {
2994
+ const launch = readLaunchBody((await store.runs.launch(run.id)).body);
2995
+ const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
2996
+ if (handed.model !== undefined) {
2997
+ const why = modelKeyMisfit(env, target);
2998
+ if (why)
2999
+ throw misfit(why);
3000
+ }
3001
+ const needsKey = handed.model === undefined && serverKeyMissing(env, target);
3002
+ if (handed.mcp === undefined && handed.model === undefined && !needsKey)
3003
+ return undefined;
3004
+ const origin = runModelOrigin(env);
3005
+ return (current) => {
3006
+ const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
3007
+ const mcp = handed.mcp ?? held.mcp;
3008
+ const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
3009
+ if (!model && needsKey)
3010
+ throw modelKeyRequired(true);
3011
+ return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}) });
2404
3012
  };
2405
- return { body: rest, sealer };
2406
3013
  }
2407
3014
  async function createRun(req, agentId) {
2408
3015
  const entry = await needRunnableAgent(agentId);
2409
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
3016
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2410
3017
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
2411
3018
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
2412
3019
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -2416,7 +3023,7 @@ async function startHolding(options, data, checked, stops) {
2416
3023
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2417
3024
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2418
3025
  }
2419
- const seal = await sealer();
3026
+ const seal = startSeal(await handed());
2420
3027
  const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2421
3028
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
2422
3029
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
@@ -2428,7 +3035,7 @@ async function startHolding(options, data, checked, stops) {
2428
3035
  * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
2429
3036
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
2430
3037
  async function createInlineRun(req) {
2431
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
3038
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2432
3039
  if (isObject(body.definition) && body.definition.native !== undefined)
2433
3040
  throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
2434
3041
  const { external, definition, skills, note, revision: pinned, ...run } = body;
@@ -2437,13 +3044,13 @@ async function startHolding(options, data, checked, stops) {
2437
3044
  ...externalIssues(external),
2438
3045
  ...(pinned !== undefined ? [{ field: "revision", reason: "not_allowed", message: "An inline run pins no revision: it runs the revision of its external version.", fix: "Remove revision." }] : []),
2439
3046
  ...runBodyIssues(run),
2440
- ...definitionBodyIssues(given),
3047
+ ...definitionBodyIssues(given, { harnesses }),
2441
3048
  // The agent's id is this server's, one per external reference, and its version is the reference's.
2442
3049
  ...["id", "version"].flatMap((key) => (isObject(definition) && definition[key] !== undefined ? [{ field: `definition.${key}`, reason: "not_allowed", message: `An inline agent's ${key} is its external reference's: the definition names none.`, fix: `Remove definition.${key}.` }] : [])),
2443
3050
  ];
2444
3051
  if (issues.length)
2445
3052
  throw invalid(issues);
2446
- const checked = checkDefinitionBody(given);
3053
+ const checked = checkDefinitionBody(given, { harnesses });
2447
3054
  const made = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
2448
3055
  // A version's first run is its save: refused where POST /agents refuses the definition (one this host can never run),
2449
3056
  // its MCP tools pinned as a save pins them (a server down keeps the agent's current pin when this version grants nothing
@@ -2471,7 +3078,7 @@ async function startHolding(options, data, checked, stops) {
2471
3078
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2472
3079
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2473
3080
  }
2474
- const seal = await sealer();
3081
+ const seal = startSeal(await handed());
2475
3082
  const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2476
3083
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
2477
3084
  });
@@ -2576,16 +3183,58 @@ async function startHolding(options, data, checked, stops) {
2576
3183
  // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2577
3184
  const labels = labelFilter(url.searchParams.getAll("label"));
2578
3185
  const vd = viewDepsFor(origin);
2579
- // An audit's shadow run is no row of the list (learn/audit.ts): it is read by id, and its cost is its served run's.
2580
- let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived && !isShadowRun(row.id));
3186
+ // The page from the runs' rows alone (store/schema.ts RUN_LISTING_COLUMNS): filtered (`status` on the listing's status),
3187
+ // ordered and cut to the page in one query, so a list costs the same at ten runs and at thousands, however long their
3188
+ // journals. An audit's shadow run is no row of the list (learn/audit.ts): it is read by id, and its cost is its served
3189
+ // run's. A run's archive is its own or its agent's.
3190
+ const where = { ...(filter.agent !== undefined ? { agentId: filter.agent } : {}), ...(filter.revision !== undefined ? { revisionId: filter.revision } : {}), ...(labels ? { labels } : {}), archived };
3191
+ // A listing is built by the server's lister (run-listing.ts) once per change, so a list finds it current. One that is
3192
+ // behind (a write landed since, or the lister has not reached it since the store was upgraded) is built here, written
3193
+ // back, and shown as built: for a status filter, first every run still going whose listing is behind (its row's
3194
+ // list_status may say what it was, or nothing; a settled run's says what it is, from the write that settled it), all
3195
+ // of them read before any is built, UNLISTED_AT_ONCE to a read, so the page's offset counts the rows as they now stand;
3196
+ // then any row of the page. With nothing running, none is behind: two reads, whatever the runs. The runs still going
3197
+ // are all a filter builds beside its page, and the lister builds them too, so only a list soon after an upgrade
3198
+ // builds many.
3199
+ // A write that lands while a listing is built moves the run's mark, so the listing is not written (Runs.putListing),
3200
+ // and a run still going is left with no status on its row: the build is made again from the mark that write left, up
3201
+ // to LIST_TRIES builds, so a filter never leaves off a run because a write met its build. Each is the lister's build
3202
+ // (Lister.build), so a held listing built here has its agent's learning folder read by the lister's passes after it.
3203
+ const listNow = async (runId, read) => {
3204
+ for (let mark = read, tries = 1;; tries++) {
3205
+ const { listing, written } = await lister.build(runId, mark, vd);
3206
+ if (!listing || written || tries === LIST_TRIES)
3207
+ return listing;
3208
+ if ((mark = await store.runs.listMark(runId)) === undefined)
3209
+ return listing;
3210
+ }
3211
+ };
2581
3212
  if (status !== null) {
2582
- // The v2 status is the run view's (store-view over the journal), per row.
2583
- const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
2584
- rows = rows.filter((_, i) => statuses[i] === status);
3213
+ const going = [];
3214
+ // Each read starts after the last row read (ListedFilter.after), never at an offset: the lister may build a row read
3215
+ // before the next read, which would shift an offset past a row not read yet.
3216
+ for (let after;;) {
3217
+ const read = await store.runs.listed({ ...where, going: true, limit: UNLISTED_AT_ONCE, ...(after ? { after } : {}) });
3218
+ going.push(...read.rows.map(({ row, listMark }) => ({ id: row.id, mark: listMark })));
3219
+ const last = read.rows.at(-1)?.row;
3220
+ if (!read.more || !last)
3221
+ break;
3222
+ after = { startedAt: last.startedAt, id: last.id };
3223
+ }
3224
+ for (const { id, mark } of going)
3225
+ await listNow(id, mark);
3226
+ }
3227
+ const page = await store.runs.listed({ ...where, ...(status !== null ? { status } : {}), limit, offset });
3228
+ const secrets = serverSecrets();
3229
+ const runs = [];
3230
+ for (const { row, agentArchivedAt, listing, listMark, behind } of page.rows) {
3231
+ // One cut of other secrets (a secret saved since, or the server's own keys at another start) is built again too.
3232
+ const kept = listing === null || behind || !cutOfNow(listing, secrets) ? await listNow(row.id, listMark) : listing;
3233
+ // A run whose status moved between the two reads is left off this page, never shown under a status it has left.
3234
+ if (kept && (status === null || kept.item.status === status))
3235
+ runs.push(listedItem(kept, origin, row.archivedAt ?? agentArchivedAt, secrets));
2585
3236
  }
2586
- // summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
2587
- const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => summaryOverStore(store, row.id, vd)));
2588
- return { runs: page, next_cursor: nextCursor(offset + limit, rows.length) };
3237
+ return { runs, next_cursor: nextCursor(offset + limit, offset + limit + (page.more ? 1 : 0)) };
2589
3238
  }
2590
3239
  async function timeline(req, res, url, runId) {
2591
3240
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
@@ -2811,7 +3460,7 @@ async function startHolding(options, data, checked, stops) {
2811
3460
  throw invalid(issues);
2812
3461
  return { password: body.password, body };
2813
3462
  }
2814
- /** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
3463
+ /** POST /v2/setup, POST /v2/setup/code, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
2815
3464
  * /v2/auth/session, answered before any credential: their own checks are the setup code (or the token), the password,
2816
3465
  * and the session. */
2817
3466
  async function ownerRoute(req, res, path, me) {
@@ -2826,13 +3475,18 @@ async function startHolding(options, data, checked, stops) {
2826
3475
  if (!byToken)
2827
3476
  fromPage(req);
2828
3477
  const { password, body } = await passwordIn(req, ["password", "code", "import"]);
2829
- if (body.import !== undefined && typeof body.import !== "boolean")
2830
- throw invalid([{ field: "import", reason: "wrong_type", message: "import is true or false" }]);
2831
- if (body.import === true && !offersImport)
3478
+ // The owner's choice: the projects to import, by the ids the offer named them with (GET /v2/setup/import's
3479
+ // candidates); `true` is every project, as before; `false`, none named or the field left out is no import.
3480
+ const named = Array.isArray(body.import) ? body.import : undefined;
3481
+ if (body.import !== undefined && typeof body.import !== "boolean" && !(named && named.length <= MAX_CANDIDATES && named.every((id) => typeof id === "string" && /^imp-[0-9a-f]{32}$/.test(id))))
3482
+ throw invalid([{ field: "import", reason: "wrong_type", message: `import is true, false, or at most ${MAX_CANDIDATES} of the project ids GET /v2/setup/import names` }]);
3483
+ const chosen = named ? [...new Set(named)] : undefined;
3484
+ const takes = body.import === true || (chosen !== undefined && chosen.length > 0);
3485
+ if (takes && !offersImport)
2832
3486
  throw invalid([{ field: "import", reason: "not_allowed", message: "Only a server on this machine (no public address, on loopback) imports its sessions at setup: run the import command where they are." }]);
2833
3487
  // The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
2834
3488
  // cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
2835
- const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
3489
+ const along = takes ? { keep: () => writeDurable(importAsked, chosen ? JSON.stringify({ projects: chosen }) : ""), drop: () => rm(importAsked, { force: true }) } : undefined;
2836
3490
  // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
2837
3491
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2838
3492
  const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
@@ -2849,23 +3503,38 @@ async function startHolding(options, data, checked, stops) {
2849
3503
  viewers.recheck();
2850
3504
  // The count is for the offer, now answered: it stops.
2851
3505
  stopCount();
2852
- // Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
2853
- if (body.import === true)
3506
+ // Only on a choice made: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
3507
+ if (takes)
2854
3508
  void importAtSetup();
2855
- return send(res, 201, { signed_in: true, ...(body.import === true ? { importing: true } : {}) }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
3509
+ return send(res, 201, { signed_in: true, ...(takes ? { importing: true } : {}) }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
3510
+ }
3511
+ // A setup code to use, asked for with no credential (the person at the Setup code field, or whoever started the
3512
+ // server for them): a new one goes to the log only when the last is expired or spent; one still good is kept, so
3513
+ // this request never voids a link someone holds. The answer says which and when it runs out, never the code.
3514
+ // No origin check and no rate limit, unlike setup and sign-in: the documented caller is a bare curl, the answer
3515
+ // holds nothing secret, and all a caller gets is at most one log line per code's 30 minutes. Counting asks with
3516
+ // sign-in tries would let one visitor behind a shared proxy hold the button shut for everyone.
3517
+ case "/setup/code": {
3518
+ if (me.hasPassword())
3519
+ throw new ApiError("forbidden", "this server has its owner: sign in");
3520
+ const code = me.renewSetupCode();
3521
+ if (!code)
3522
+ throw new ApiError("forbidden", "no setup code to give: this server's setup takes no code, or its password is being set now");
3523
+ return send(res, 200, { printed: code.printed, expires_at: new Date(code.until).toISOString() });
2856
3524
  }
2857
3525
  case "/setup/import": {
2858
3526
  // No offer is an answer, `{ offer: false }`, never a 404: the console reads this on its first page, and a browser
2859
3527
  // logs every 404 as an error.
2860
3528
  // Before the owner is set, to the setup page: none on a server that cannot import, else that it can (202 while it
2861
- // counts), and then how many projects and sessions it would, or null for each when the count failed.
3529
+ // counts), and then how many projects and sessions it would and the projects to choose from (`candidates`, the
3530
+ // latest active first, at most MAX_CANDIDATES), or null for each count when the count failed.
2862
3531
  if (!me.hasPassword()) {
2863
3532
  pageRead(req);
2864
3533
  if (!offersImport)
2865
3534
  return send(res, 200, { offer: false });
2866
3535
  countSessions();
2867
3536
  if (count?.state === "counted")
2868
- return send(res, 200, { projects: count.projects, sessions: count.sessions });
3537
+ return send(res, 200, { projects: count.projects, sessions: count.sessions, candidates: count.candidates });
2869
3538
  if (count?.state === "failed")
2870
3539
  return send(res, 200, { projects: null, sessions: null });
2871
3540
  return send(res, 202, { counting: true });
@@ -2961,14 +3630,14 @@ async function startHolding(options, data, checked, stops) {
2961
3630
  const bodies = new WeakMap();
2962
3631
  /** The check of a whole body a route makes before anything else, by operation, for the body sent: what a suggested
2963
3632
  * value must pass. PUT .../definition's contract body (the definition itself) has none here. */
2964
- const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating });
3633
+ const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating, harnesses });
2965
3634
  const BODY_CHECKS = {
2966
3635
  createAgent: () => definitionCheck(true),
2967
3636
  updateDefinition: (sent) => ("definition" in sent ? definitionCheck(false) : undefined),
2968
3637
  // POST /runs' agent, given inline, is POST /agents' body inside its own: checked as that one is.
2969
3638
  createInlineRun: () => (body) => {
2970
3639
  const { definition, skills, note } = isObject(body) ? body : {};
2971
- return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) });
3640
+ return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) }, { harnesses });
2972
3641
  },
2973
3642
  };
2974
3643
  /** An operation's documented request bodies (its JSON media type's examples), each its value. */
@@ -3001,6 +3670,8 @@ async function startHolding(options, data, checked, stops) {
3001
3670
  const found = matching.find((r) => r.method === req.method || (req.method === "HEAD" && r.method === "GET"));
3002
3671
  if (!found)
3003
3672
  throw new ApiError("method_not_allowed", `${req.method} is not a method of ${path}`, {}, { allow: [...new Set(matching.map((r) => r.method))].join(", ") });
3673
+ if (CLAUDE_LOGIN_ROUTES.has(found.name) && loginOff)
3674
+ throw new ApiError("not_found", claudeLoginRouteOff(found.name, loginOff));
3004
3675
  if (found.name === "getCapabilities") {
3005
3676
  // features.computers: the computer kinds this server offers now (computers.ts), read at each answer, since turning
3006
3677
  // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
@@ -3084,7 +3755,7 @@ async function startHolding(options, data, checked, stops) {
3084
3755
  const health = await healthOf(store, data, minFreeBytes);
3085
3756
  return send(res, health.status === "ok" ? 200 : 503, health);
3086
3757
  }
3087
- // Approving a note the grader held for its owner's OK (a risky rule a run's user asked for) takes the owner's
3758
+ // Approving a learned workflow held for its owner's OK (a step calls a tool with no price) takes the owner's
3088
3759
  // signed-in page alone: never a token, which a run's process, an agent's MCP client or a script may hold, nor a
3089
3760
  // page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
3090
3761
  // with a JSON body (page.ts), so this is CSRF-checked as every page write is. With no credential at all it is 401,
@@ -3092,20 +3763,14 @@ async function startHolding(options, data, checked, stops) {
3092
3763
  // Restoring a retired one puts it back in every later run, as an approval does: the same owner's session alone.
3093
3764
  if (found.name === "restoreLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3094
3765
  authFailed(`/v2${path}`, "restore_without_session");
3095
- throw new ApiError("forbidden", owner ? "Restoring a retired note takes the owner's password sign-in in the console, never a token." : "Restoring a retired note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3766
+ throw new ApiError("forbidden", owner ? "Restoring a retired workflow takes the owner's password sign-in in the console, never a token." : "Restoring a retired workflow takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3096
3767
  }
3097
3768
  if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3098
3769
  authFailed(`/v2${path}`, "approve_without_session");
3099
- throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3100
- }
3101
- // Making a learned workflow an agent of its own gives it runs of its own, outside any agentic run's turn: the owner's
3102
- // click alone, the same session as an approval.
3103
- if (found.name === "promoteLearnedWorkflow" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3104
- authFailed(`/v2${path}`, "promote_without_session");
3105
- throw new ApiError("forbidden", owner ? "Making a learned workflow an agent takes the owner's password sign-in in the console, never a token." : "Making a learned workflow an agent takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3770
+ throw new ApiError("forbidden", owner ? "Approving a workflow takes the owner's password sign-in in the console, never a token." : "Approving a workflow takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3106
3771
  }
3107
3772
  // A replay its owner starts runs the agent's graded inputs again at its cost, and may promote a revision that then
3108
- // serves first: the same session as making one an agent.
3773
+ // serves first: the same session as an approval.
3109
3774
  if (found.name === "startLearnedWorkflowReplay" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3110
3775
  authFailed(`/v2${path}`, "replay_without_session");
3111
3776
  throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
@@ -3205,25 +3870,27 @@ async function startHolding(options, data, checked, stops) {
3205
3870
  if (!req.headers["idempotency-key"])
3206
3871
  throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
3207
3872
  const body = await bodyOf(req), entry = await needAgent(id);
3208
- let gradeModel = gradeModelOf(env, options.gradeModel);
3209
- if (!gradeModel && sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3873
+ // A learning SDK run's compile turn is asked on its agent's own model: checked reachable before the run starts.
3874
+ let compileModel;
3875
+ if (sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3210
3876
  try {
3211
3877
  const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3212
3878
  if (chosen)
3213
- gradeModel = `${chosen.provider}/${chosen.modelId}`;
3879
+ compileModel = `${chosen.provider}/${chosen.modelId}`;
3214
3880
  }
3215
3881
  catch { }
3216
3882
  }
3217
3883
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3218
- const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3884
+ const compile = { ...(compileModel ? { model: compileModel } : {}), check: async (model) => {
3219
3885
  try {
3220
- const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
3886
+ const route = await askRouteOf(model, env, (one) => sdkModelRoute(one, env, "default", PI_WIRES));
3221
3887
  await route.provider.credential();
3222
3888
  }
3223
3889
  catch {
3224
- throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key and grading model. Configure Model keys or turn self-improving off.");
3890
+ throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key to compile workflows. Configure Model keys or turn self-improving off.");
3225
3891
  }
3226
- }, linkOrigin(req)) }));
3892
+ } };
3893
+ const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, startDeps, origin, compile, linkOrigin(req)) }));
3227
3894
  // Re-read the pinned receipt even on an in-memory replay: credentials saved since
3228
3895
  // the first response must still be withheld without reselecting a different seed.
3229
3896
  const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
@@ -3336,15 +4003,7 @@ async function startHolding(options, data, checked, stops) {
3336
4003
  }
3337
4004
  // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
3338
4005
  // the same revision exactly one lands.
3339
- let warnings = [];
3340
- const check = async (revision, on) => {
3341
- // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
3342
- const saved = await saveable(revision, on);
3343
- warnings = saved.warnings;
3344
- return saved.stamp;
3345
- };
3346
- const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3347
- reconcileComputer(id);
4006
+ const { entry: edited, warnings } = await reviseAgentOf(entry, contract ? { definition: body } : body, { contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3348
4007
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
3349
4008
  }
3350
4009
  case "listRevisions": {
@@ -3382,6 +4041,18 @@ async function startHolding(options, data, checked, stops) {
3382
4041
  reconcileComputer(id);
3383
4042
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
3384
4043
  }
4044
+ case "deleteAgent": {
4045
+ // Another system's agent, deleted whole (agent-delete.ts); one delete of an agent at a time, the agent read in its
4046
+ // turn, so a DELETE after one that finished is 404.
4047
+ await deleteInTurn(id, async () => {
4048
+ const entry = await needAgent(id);
4049
+ if (entry.agent.externalRef === null)
4050
+ throw new ApiError("agent_not_external", `The agent ${id} was made here, not by another system's inline run, and is not deleted: archive it instead (POST /v2/agents/${id}/archive), which keeps its runs and stops new ones.`);
4051
+ await deleteExternalAgent(agentDeleteHost, id);
4052
+ });
4053
+ res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4054
+ return void res.end();
4055
+ }
3385
4056
  case "archiveAgent":
3386
4057
  case "unarchiveAgent": {
3387
4058
  // An agent another system owns is that system's to keep or drop: archiving it here is refused, as an edit is.
@@ -3439,7 +4110,7 @@ async function startHolding(options, data, checked, stops) {
3439
4110
  const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
3440
4111
  if (!view)
3441
4112
  throw new ApiError("not_found", `no run ${id}`);
3442
- return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
4113
+ return send(res, 200, { ...view, ...(await runComputerOf(id, view)), ...(await allInViewOf(id, view)) });
3443
4114
  }
3444
4115
  case "getTimeline":
3445
4116
  await needRun(id);
@@ -3450,9 +4121,9 @@ async function startHolding(options, data, checked, stops) {
3450
4121
  const run = await needRun(id);
3451
4122
  if (run.kind === "workflow")
3452
4123
  throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
3453
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
4124
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3454
4125
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
3455
- const seal = await sealer();
4126
+ const seal = await messageSeal(run, await handed());
3456
4127
  const extra = unknownFields(body, ["content"]);
3457
4128
  if (extra.length)
3458
4129
  throw invalid(extra);
@@ -3461,8 +4132,8 @@ async function startHolding(options, data, checked, stops) {
3461
4132
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
3462
4133
  if (content.length > MAX_MESSAGE)
3463
4134
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
3464
- // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
3465
- const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal(run.id) } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
4135
+ // Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
4136
+ const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
3466
4137
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
3467
4138
  const { status, state } = await runStatusState(run.id);
3468
4139
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -3547,12 +4218,18 @@ async function startHolding(options, data, checked, stops) {
3547
4218
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3548
4219
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3549
4220
  };
3550
- // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3551
- const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3552
- // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3553
- // reads it with the shadows'. A row not written now is logged, never the grade refused.
3554
- const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
3555
- await gradeRow({ store, agentId: row.agentId, revisionId: row.revisionId, context: ctx, folder: () => learningFolderOf(data, row.agentId), shown: () => learningShown(row.agentId), log: said }, row, body.correct).catch((error) => said(`the grade wrote no audit row (${error?.message ?? error})`));
4221
+ // The grade and its audit row are written to the agent's learning in its delete turn (agentWrite): a grade whose body
4222
+ // came in while a DELETE ran waits for it and finds the agent gone, so nothing is written after its learning went.
4223
+ const kept = await agentWrite(row.agentId, async () => {
4224
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
4225
+ // Its feedback round is a turn with no caller's model key: on the server's key for the run's route, else not opened.
4226
+ const graded = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined, (launch) => !serverKeyMissing(env, { kind: "agentic", model: launch.model, native: Boolean(launch.native) })));
4227
+ // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
4228
+ // reads it with the shadows'. A row not written now is logged, never the grade refused.
4229
+ const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
4230
+ await gradeRow({ store, agentId: row.agentId, revisionId: row.revisionId, context: ctx, folder: () => learningFolderOf(data, row.agentId), shown: () => learningShown(row.agentId), log: said }, row, grade.correct).catch((error) => said(`the grade wrote no audit row (${error?.message ?? error})`));
4231
+ return graded;
4232
+ });
3556
4233
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3557
4234
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3558
4235
  const shown = await learningShown(row.agentId).catch(() => undefined);
@@ -3586,10 +4263,10 @@ async function startHolding(options, data, checked, stops) {
3586
4263
  const view = await computerView({
3587
4264
  viewer: async () => {
3588
4265
  if (family === "browser") {
3589
- const link = await liveViewerLink(store, sealKey, run.id, answers);
4266
+ const link = await liveViewerLink(store, sealKey, run.id, answers(run.id));
3590
4267
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
3591
4268
  }
3592
- return computerViewerLink(store, sealKey, run.id, answers);
4269
+ return computerViewerLink(store, sealKey, run.id, answers(run.id));
3593
4270
  },
3594
4271
  computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family, own)),
3595
4272
  session: (kind) => sessionIn(kind, entries, run.terminal || (parked && kind !== "browser")),
@@ -3700,9 +4377,11 @@ async function startHolding(options, data, checked, stops) {
3700
4377
  const rel = homePath(second, id, true);
3701
4378
  const bytes = await bytesOf(req);
3702
4379
  // Each write lands whole (the Workspace's write is atomic); of two at once, the last one wins.
3703
- const home = await homeWorkspace(id, true);
3704
- await home.write(rel, bytes).catch(homeRefusal);
3705
- const written = await entryAt(home, rel);
4380
+ const written = await agentWrite(id, async () => {
4381
+ const home = await homeWorkspace(id, true);
4382
+ await home.write(rel, bytes).catch(homeRefusal);
4383
+ return entryAt(home, rel);
4384
+ });
3706
4385
  if (written?.kind !== "file")
3707
4386
  throw new ApiError("not_found", "no such file");
3708
4387
  return send(res, 200, viewOf(rel, written));
@@ -3712,16 +4391,19 @@ async function startHolding(options, data, checked, stops) {
3712
4391
  if (!homeWrites)
3713
4392
  throw new ApiError("unsupported_here", HOME_WRITES_OFF);
3714
4393
  const rel = homePath(second, id, true);
3715
- const home = await homeWorkspace(id, false);
3716
- if (!home)
3717
- throw new ApiError("not_found", "no such file");
3718
- // A file alone: a folder is refused by the listing; a link (never listed) by the Workspace's remove (ESCAPE).
3719
- if ((await entryAt(home, rel))?.kind === "dir")
3720
- throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
3721
- await home.remove(rel).catch((error) => {
3722
- if (isWorkspaceError(error, "NOT_FOUND"))
4394
+ // A remove is a write to the agent's home: in its delete turn (agentWrite), as a file's write is.
4395
+ await agentWrite(id, async () => {
4396
+ const home = await homeWorkspace(id, false);
4397
+ if (!home)
3723
4398
  throw new ApiError("not_found", "no such file");
3724
- homeRefusal(error);
4399
+ // A file alone: a folder is refused by the listing; a link (never listed) by the Workspace's remove (ESCAPE).
4400
+ if ((await entryAt(home, rel))?.kind === "dir")
4401
+ throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
4402
+ await home.remove(rel).catch((error) => {
4403
+ if (isWorkspaceError(error, "NOT_FOUND"))
4404
+ throw new ApiError("not_found", "no such file");
4405
+ homeRefusal(error);
4406
+ });
3725
4407
  });
3726
4408
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
3727
4409
  return void res.end();
@@ -3753,6 +4435,11 @@ async function startHolding(options, data, checked, stops) {
3753
4435
  // The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
3754
4436
  // a run whose output is withheld is refused (403), as the route refused it.
3755
4437
  return send(res, 200, await runGraphView(store, id, runReadsDeps));
4438
+ case "getRunTrace":
4439
+ await needRun(id);
4440
+ // The run's spans over its served Timeline rows and its journal (run-trace.ts): cut by the run's one cut, as its
4441
+ // Timeline is; a run withheld is refused (403), as its graph is.
4442
+ return send(res, 200, await servedRunTrace(servedTimelineDeps, store, id, ctx));
3756
4443
  case "pauseRun":
3757
4444
  case "resumeRun": {
3758
4445
  // A workflow run's pause or resume is a command its runner reads and applies (runs-over-store.pauseOrResume): an
@@ -3890,6 +4577,23 @@ async function startHolding(options, data, checked, stops) {
3890
4577
  const { revoked } = await plan.signOut();
3891
4578
  return send(res, 200, revoked ? { revoked } : { revoked, message: SIGN_OUT_UNCONFIRMED });
3892
4579
  }
4580
+ // Claude Code's login on this machine (claude-login.ts): only its status is read, by asking the CLI.
4581
+ case "getClaudeLogin":
4582
+ case "turnOnClaudeLogin":
4583
+ case "turnOffClaudeLogin":
4584
+ case "startClaudeLogin": {
4585
+ const body = found.name === "turnOnClaudeLogin" ? await bodyOf(req) : undefined;
4586
+ const deps = loginDeps();
4587
+ try {
4588
+ const view = found.name === "getClaudeLogin" ? await claudeLoginView(deps) : found.name === "turnOnClaudeLogin" ? await turnOnClaudeLogin(deps, body) : found.name === "turnOffClaudeLogin" ? await turnOffClaudeLogin(deps) : await startLoginHere(deps);
4589
+ return send(res, 200, view, { "cache-control": "no-store" });
4590
+ }
4591
+ catch (error) {
4592
+ if (error instanceof ClaudeLoginRefused)
4593
+ throw new ApiError(error.code, error.message);
4594
+ throw error;
4595
+ }
4596
+ }
3893
4597
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
3894
4598
  case "listMcpServers":
3895
4599
  return send(res, 200, await mcpServers.list());
@@ -4038,11 +4742,15 @@ async function startHolding(options, data, checked, stops) {
4038
4742
  // definition's: an archived agent's too.
4039
4743
  case "getAgentLearning": {
4040
4744
  await needAgent(id);
4041
- // The agent's learning view: its notes, skills, workflows and log from its learning folder; its run-fared counts, each
4042
- // note's runs (given it and that read it) and its impact over the one store (agentLearningOverStore), from each run's
4043
- // launch, journal and learning end.
4044
- const { counts, impact, notes } = await agentLearningOverStore(store, id);
4045
- return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, notes));
4745
+ // The agent's learning view: its corrections, workflows and log from its learning folder; its run-fared counts and
4746
+ // its impact over the one store (agentLearningOverStore), from each run's launch, journal and learning end.
4747
+ const { counts, impact } = await agentLearningOverStore(store, id);
4748
+ // Each workflow's status past its README.md's: where it stands as GET .../learning/promotions says it (servingStateOf
4749
+ // over the same records and the money rule's decision, costStopOverStore), so the view never says a workflow serves
4750
+ // that does not run first.
4751
+ const records = await promotionsOf(store.settings, id);
4752
+ const costStop = await costStopOverStore(store, id);
4753
+ return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)));
4046
4754
  }
4047
4755
  case "getLearningCost": {
4048
4756
  await needAgent(id);
@@ -4051,7 +4759,7 @@ async function startHolding(options, data, checked, stops) {
4051
4759
  const read = await agentCostOverStore(store, id, limit);
4052
4760
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
4053
4761
  const shown = await learningShown(id);
4054
- 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) })) };
4762
+ 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) })), bill: { ...read.bill, revisions: read.bill.revisions.map((one) => ({ ...one, workflow: shown.name(one.workflow) })), holds: read.bill.holds.map((one) => ({ ...one, workflow: shown.name(one.workflow), reason: shown.text(one.reason) })) } };
4055
4763
  if (csv) {
4056
4764
  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"` });
4057
4765
  return void res.end(costCsv(cost.runs));
@@ -4069,14 +4777,34 @@ async function startHolding(options, data, checked, stops) {
4069
4777
  const shownRead = promotionsShown(records, shown);
4070
4778
  // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
4071
4779
  const loop = auditLoopOf(entry.revision?.body?.learning);
4072
- const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop);
4780
+ // Each one's state with the money rule's decision a run's launch reads (costStopOverStore): a champion it stopped
4781
+ // running first reads `stopped`.
4782
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop, await costStopOverStore(store, id));
4073
4783
  // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
4074
4784
  // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4075
4785
  const writer = auditWriterOf(entry.revision ?? undefined);
4076
4786
  const auditsOff = writer === undefined ? null : shown.text(auditsOffWords(writer));
4787
+ // The champion's own revision, read by its recorded digest at the learning commits its records name (newest
4788
+ // first), then main: never by paging the workflow's history. Its nodes with their tiers and code checks, and the
4789
+ // check it was promoted on; nodes null when no commit read holds its text (or the folder can't be read now).
4790
+ const championRead = async (workflow, digest) => {
4791
+ const champion = championOf(records, workflow);
4792
+ const record = champion?.digest === digest ? champion : undefined;
4793
+ const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
4794
+ const read = await workflowAtDigest(data, id, workflow, digest, commits).catch(() => undefined);
4795
+ let doc;
4796
+ try {
4797
+ doc = read ? JSON.parse(read.text) : undefined;
4798
+ }
4799
+ catch {
4800
+ doc = undefined;
4801
+ }
4802
+ return shownDeep({ digest, commit: read?.commit ?? null, nodes: doc === undefined ? null : workflowNodesOf(doc), check: record?.check ?? null }, shown);
4803
+ };
4077
4804
  const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
4078
4805
  ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
4079
4806
  not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
4807
+ champion: one.digest === null ? null : await championRead(one.workflow, one.digest),
4080
4808
  })));
4081
4809
  return send(res, 200, { agent: id, promotions: shownRead.promotions, serving });
4082
4810
  }
@@ -4088,36 +4816,6 @@ async function startHolding(options, data, checked, stops) {
4088
4816
  const rows = await auditsOfAgent(id);
4089
4817
  return send(res, 200, { agent: id, audits: rows.map((row) => ({ ...row, workflow: shown.name(row.workflow), run: shown.text(row.run), shadow_run: row.shadow_run === null ? null : shown.text(row.shadow_run), digest: shown.text(row.digest) })) });
4090
4818
  }
4091
- case "createLearningBatch": {
4092
- await needAgent(id);
4093
- const made = await batches.create(id, await bodyOf(req));
4094
- return send(res, 202, await batches.read(id, made.id), { location: `/v2/agents/${encodeURIComponent(id)}/learning/batches/${made.id}` });
4095
- }
4096
- case "listLearningBatches":
4097
- await needAgent(id);
4098
- return send(res, 200, await batches.list(id));
4099
- case "getLearningBatch":
4100
- await needAgent(id);
4101
- return send(res, 200, await batches.read(id, second));
4102
- case "cancelLearningBatch":
4103
- await needAgent(id);
4104
- return send(res, 200, await batches.cancel(id, second));
4105
- case "listLearningEvals": {
4106
- await needAgent(id);
4107
- // The agent's eval records (learning-evals.ts), newest first, the latest the one shown: only ever what was posted.
4108
- const evals = await evalsOf(store, id);
4109
- return send(res, 200, { agent: id, latest: evals[0] ?? null, evals });
4110
- }
4111
- case "recordLearningEval": {
4112
- const body = await bodyOf(req);
4113
- await needAgent(id);
4114
- const answer = await idempotent(req, `/agents/${id}/learning/evals`, body, async () => {
4115
- const result = evalOf(body, new Date());
4116
- await recordEval(store, id, result);
4117
- return { status: 201, body: result };
4118
- });
4119
- return send(res, answer.status, answer.body, answer.headers);
4120
- }
4121
4819
  case "getLearningLoop": {
4122
4820
  await needAgent(id);
4123
4821
  // The loop's own record over the one store (store-reads/loop.ts): compile turns, aggregates only.
@@ -4130,52 +4828,48 @@ async function startHolding(options, data, checked, stops) {
4130
4828
  const cut = await runCutValues({ serverSecrets, signIns }, store, one.run_id).catch(() => "unreadable");
4131
4829
  const workflow = one.workflow === null ? null : shown.name(one.workflow);
4132
4830
  if (cut === "unreadable")
4133
- return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok }) => ({ ok, errors: [] })), draft_errors: [], withheld: true };
4831
+ return { ...one, workflow, attempts: one.attempts.map(({ ok }) => ({ ok, errors: [] })), draft_errors: [], withheld: true };
4134
4832
  const all = [...values, ...cut.values];
4135
4833
  const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
4136
- 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 };
4834
+ return { ...one, workflow, attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
4137
4835
  }));
4138
4836
  return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles });
4139
4837
  }
4140
- case "listLearningNotes":
4141
4838
  case "listLearningLog":
4142
4839
  await needAgent(id);
4143
- if (found.name === "listLearningNotes") {
4144
- // The notes from the agent's learning folder, each with its runs over the one store (agentLearningOverStore's noteRuns).
4145
- const { notes } = await agentLearningOverStore(store, id);
4146
- return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
4147
- }
4148
4840
  return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
4841
+ case "getLearningCorrections": {
4842
+ await needAgent(id);
4843
+ // corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
4844
+ const read = await correctionsView(data, id, await learningShown(id));
4845
+ return send(res, 200, read, { etag: read.etag });
4846
+ }
4847
+ case "putLearningCorrections": {
4848
+ await needAgent(id);
4849
+ const text = await textBody(req, MAX_BODY);
4850
+ // What it refuses is what the reads cut: the host's secrets and the agent's sign-in pointers.
4851
+ const refuse = await learningValues(id);
4852
+ // A write to the agent's learning: in its delete turn (agentWrite), the body read before, outside it.
4853
+ const written = await agentWrite(id, () => correctionsWrite(data, id, { text, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse }));
4854
+ return send(res, 200, written, { etag: written.etag });
4855
+ }
4149
4856
  case "listLearnedWorkflowRevisions":
4150
4857
  await needAgent(id);
4151
4858
  return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
4152
4859
  case "readLearningFile":
4153
4860
  await needAgent(id);
4154
- return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
4155
- case "writeLearningFile":
4861
+ return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id)));
4156
4862
  case "retireLearningFile":
4157
4863
  case "approveLearningFile":
4158
4864
  case "restoreLearningFile": {
4159
4865
  await needAgent(id);
4160
- const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
4161
- const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
4162
- // What it refuses is what the reads cut: a note shown cut is never saved over the hidden text.
4163
4866
  const refuse = await learningValues(id);
4164
- const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse, approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile", draftTools: () => learnedDraftToolsOf(id) });
4165
- // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
4166
- const shown = secretsShown(refuse);
4167
- const located = written.status === 201 && shown.name(written.file) === written.file;
4168
- return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
4169
- }
4170
- case "promoteLearnedWorkflow": {
4171
- // The source read once the body is in, as it is then: what promoteOf checks and what it copies are that one read.
4172
- const body = await bodyOf(req);
4173
- const source = await needAgent(id);
4174
- const answer = await idempotent(req, `/agents/${id}/learning/workflows/${second}/promote`, body, async () => {
4175
- const { entry, warnings } = await promoteOf(source, second, body);
4176
- return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
4177
- });
4178
- return send(res, answer.status, answer.body, answer.headers);
4867
+ const action = found.name === "approveLearningFile" ? "approve" : found.name === "restoreLearningFile" ? "restore" : "retire";
4868
+ // A change to a workflow is a write to the agent's learning: in its delete turn (agentWrite).
4869
+ const written = await agentWrite(id, () => changeWorkflow(data, id, second, { action, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse, draftTools: () => learnedDraftToolsOf(id) }));
4870
+ // A run's list row that read a workflow held for the owner's OK says what the folder says now, at the next list.
4871
+ await lister.learningChanged(id);
4872
+ return sendText(res, written.status, { ...written, text: secretsShown(refuse).text(written.text) });
4179
4873
  }
4180
4874
  case "startLearnedWorkflowReplay": {
4181
4875
  const body = await bodyOf(req);
@@ -4189,7 +4883,12 @@ async function startHolding(options, data, checked, stops) {
4189
4883
  throw new ApiError("bad_request", `inputs is "held" (the runs the revision was last checked on, the default) or a whole number from 1 to ${COMPILE_AFTER_MAX}: that many of the agent's newest completed runs.`);
4190
4884
  }
4191
4885
  const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
4192
- const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
4886
+ // Its replay runs are started by no caller, with no model key: none to spend on a server that holds none.
4887
+ const keyless = noServerKeyFor(env, "An owner's replay");
4888
+ if (keyless)
4889
+ throw new ApiError("not_continuable", keyless);
4890
+ // Reserved in the agent's promotions record, in its delete turn (agentWrite), as every write to its learning is.
4891
+ const started = await agentWrite(id, () => replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs)));
4193
4892
  return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
4194
4893
  }
4195
4894
  case "getLearnedWorkflowReplay": {
@@ -4279,13 +4978,14 @@ async function startHolding(options, data, checked, stops) {
4279
4978
  const answer = await idempotent(req, `/templates/${encodeURIComponent(pkg.id)}/apply`, body, async () => {
4280
4979
  const made = await applyTemplate(pkg, body);
4281
4980
  minted = made.minted;
4282
- return { status: 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
4981
+ // 200 for an update of the agent agent_id named, 201 for an agent made.
4982
+ return { status: made.updated ? 200 : 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
4283
4983
  });
4284
4984
  // Each webhook trigger's secret, to the owner's session in this first answer alone (trigger-secrets-shown.ts
4285
4985
  // templateApplied): the record above never held it, so a replay under the key shows none.
4286
4986
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
4287
4987
  const shown = replayed ? "replay" : mayHoldSecrets(req) ? "first" : "token";
4288
- return send(res, answer.status, answer.status === 201 ? templateApplied(answer.body, minted, shown) : answer.body, answer.headers);
4988
+ return send(res, answer.status, answer.status === 201 || answer.status === 200 ? templateApplied(answer.body, minted, shown) : answer.body, answer.headers);
4289
4989
  }
4290
4990
  case "rotateTriggerSecret":
4291
4991
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
@@ -4303,6 +5003,10 @@ async function startHolding(options, data, checked, stops) {
4303
5003
  case "deleteTrigger": {
4304
5004
  // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4305
5005
  const said = await triggers.remove(id);
5006
+ // Its cached create answers are masked now and saved, so no later start has to find the trigger to mask them. A
5007
+ // failed save is said by a code; the map is masked already, so a replay is too.
5008
+ if (maskCachedGone(id).length)
5009
+ await keep().catch((error) => idempotencySaid({ condition: "idempotency_not_saved", trigger: id, error: typeof error?.code === "string" ? error.code : "error" }));
4306
5010
  if (said)
4307
5011
  return send(res, 200, { deleted: true, ...said });
4308
5012
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -4356,7 +5060,9 @@ async function startHolding(options, data, checked, stops) {
4356
5060
  }
4357
5061
  })();
4358
5062
  let names;
4359
- const server = createServer((req, res) => {
5063
+ // The listener: the CLI's, bound early and answering warming until the takeover below (listen-first.ts), or a new one.
5064
+ const server = options.listener ?? createServer();
5065
+ const onRequest = (req, res) => {
4360
5066
  const requestId = `req_${randomBytes(8).toString("hex")}`;
4361
5067
  res.setHeader("x-request-id", requestId);
4362
5068
  if (log && !quiet) {
@@ -4404,7 +5110,7 @@ async function startHolding(options, data, checked, stops) {
4404
5110
  if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
4405
5111
  return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
4406
5112
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
4407
- if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw.startsWith("/v2/auth/")))
5113
+ if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw === "/v2/setup/code" || raw.startsWith("/v2/auth/")))
4408
5114
  return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
4409
5115
  if (raw === MCP_PATH)
4410
5116
  return void mcp(req, res).catch(fail);
@@ -4424,13 +5130,13 @@ async function startHolding(options, data, checked, stops) {
4424
5130
  if (viewing)
4425
5131
  return ID.test(viewing[1]) ? void liveRoute(req, res, viewing[1], viewing[2], viewing[3]).catch(fail) : fail(new ApiError("not_found", "no run's live view at that address"));
4426
5132
  route(req, res, url, raw.slice(3)).catch(fail);
4427
- });
5133
+ };
4428
5134
  // A request's headers come within 10 s, whatever its route: nothing sends more than a few kilobytes of them. Its body
4429
5135
  // keeps Node's 5-minute request timeout, which an upload of a large file needs; the token-less hook route has its own
4430
5136
  // 30 s for its body (push-handler.ts HOOK_BODY_MS), so dribbling senders hold no socket for long.
4431
5137
  server.headersTimeout = 10_000;
4432
5138
  // The one upgrade this server takes: a run's live computer viewer's WebSocket (browser-live.ts). Every other is refused.
4433
- server.on("upgrade", (req, socket, head) => {
5139
+ const onUpgrade = (req, socket, head) => {
4434
5140
  socket.on("error", () => socket.destroy());
4435
5141
  const raw = (req.url ?? "/").split("?")[0];
4436
5142
  const viewing = LIVE_PATH.exec(raw);
@@ -4484,30 +5190,16 @@ async function startHolding(options, data, checked, stops) {
4484
5190
  if (!admitted())
4485
5191
  return deny("401 Unauthorized");
4486
5192
  viewers.watch(socket, admitted);
4487
- proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
5193
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reachForRun(reach, run.id));
4488
5194
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
4489
- });
4490
- const first = options.port ?? DEFAULT_PORT;
4491
- const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
4492
- for (let port = first;; port++) {
4493
- try {
4494
- // Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind.
4495
- await new Promise((done, reject) => {
4496
- const onError = (error) => (server.off("listening", onListening), reject(error));
4497
- const onListening = () => (server.off("error", onError), done());
4498
- server.once("error", onError);
4499
- server.once("listening", onListening);
4500
- server.listen(port, host);
4501
- });
4502
- break;
4503
- }
4504
- catch (error) {
4505
- if (error.code !== "EADDRINUSE")
4506
- throw error;
4507
- if (port < last)
4508
- continue;
4509
- throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
4510
- }
5195
+ };
5196
+ // The CLI's early listener answers with this server's routes from here on, where a new one would start to listen.
5197
+ if (options.listener)
5198
+ takeOver(server, onRequest, onUpgrade);
5199
+ else {
5200
+ server.on("request", onRequest);
5201
+ server.on("upgrade", onUpgrade);
5202
+ await listenOn(server, host, options.port ?? DEFAULT_PORT, options.nextFreePort === true);
4511
5203
  }
4512
5204
  // The tool keys the server is started with, each checked once against its provider, in the background, once it
4513
5205
  // listens: a start that fails sends no check, and the start never waits on one. Capabilities are made again as each
@@ -4519,12 +5211,10 @@ async function startHolding(options, data, checked, stops) {
4519
5211
  void importAtSetup();
4520
5212
  else if (offersImport && options.countSessions && owner && !owner.hasPassword())
4521
5213
  countSessions();
4522
- const address = server.address();
4523
5214
  if (isLoopback(host))
4524
5215
  names = loopbackNames(host, options.allowHosts, options.publicUrl);
4525
5216
  // An address of every interface is reached on this machine at its loopback one.
4526
- const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
4527
- const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
5217
+ const url = urlOf(server, host);
4528
5218
  owner?.attach(options.publicUrl ?? url);
4529
5219
  webhooks.attach(options.publicUrl ?? url);
4530
5220
  // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
@@ -4540,6 +5230,8 @@ async function startHolding(options, data, checked, stops) {
4540
5230
  await new Promise((done) => server.close(() => done()));
4541
5231
  throw error;
4542
5232
  });
5233
+ // The lister's own passes (above), once this server listens and knows its own address (ownOriginOf).
5234
+ lister.start();
4543
5235
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
4544
5236
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
4545
5237
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -4592,6 +5284,10 @@ async function startHolding(options, data, checked, stops) {
4592
5284
  return (readWaits.set(row.id, seen), true);
4593
5285
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
4594
5286
  const card = view.pending?.kind;
5287
+ // A stop asked for and not yet taken reads stopped (store-view's stopAsked) before its row ends: it is told once the
5288
+ // runner's end commit ends the row (a change the feed brings), under the one marker that end gives it.
5289
+ if (card === "stopped" && row.endedAt === null)
5290
+ return true;
4595
5291
  // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last. A stop's is when
4596
5292
  // its stop ended the row: rows its stopped turn still streams in (a late result, a charge) never move it.
4597
5293
  const marker = card === "stopped" && row.endedAt !== null ? `stopped:${new Date(row.endedAt).toISOString()}` : waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
@@ -4650,6 +5346,10 @@ async function startHolding(options, data, checked, stops) {
4650
5346
  };
4651
5347
  /** 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). */
4652
5348
  const tellEnd = async (id) => {
5349
+ // An audit's shadow run is no host's run (learn/audit.ts): it sends no notice of any kind; its cost reaches a host as
5350
+ // the audited run's cost.learning_usd alone.
5351
+ if (isShadowRun(id))
5352
+ return true;
4653
5353
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4654
5354
  if (now === undefined)
4655
5355
  return false;
@@ -4784,7 +5484,7 @@ async function startHolding(options, data, checked, stops) {
4784
5484
  const rows = await store.runs.list({});
4785
5485
  // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
4786
5486
  // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
4787
- const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5487
+ const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
4788
5488
  for (const id of unsaved)
4789
5489
  endsLeft.add(id);
4790
5490
  // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
@@ -4822,13 +5522,12 @@ async function startHolding(options, data, checked, stops) {
4822
5522
  }
4823
5523
  await Promise.all([...workers.values()].map((w) => w.exit));
4824
5524
  await importing;
5525
+ await schemaSealed;
4825
5526
  await installStopped;
4826
5527
  await observationStopped;
4827
5528
  // The ends' follower stops before the webhooks it feeds and the store it reads.
4828
5529
  clearTimeout(endsTimer);
4829
5530
  await endsRead;
4830
- // A learning batch's loop ends where it stands, still running: it takes up when a server starts on this data again.
4831
- await batches.halt();
4832
5531
  await webhooks.close();
4833
5532
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
4834
5533
  viewers.close();
@@ -4838,6 +5537,8 @@ async function startHolding(options, data, checked, stops) {
4838
5537
  await githubStopped;
4839
5538
  // --faux-github's fake GitHub API, once nothing asks it anything.
4840
5539
  await fauxGitHub?.close();
5540
+ // The listings' builder ends its pass before the store it reads and writes closes.
5541
+ await lister.stop();
4841
5542
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
4842
5543
  await store.close();
4843
5544
  dataLock.release();
@@ -4846,7 +5547,7 @@ async function startHolding(options, data, checked, stops) {
4846
5547
  return {
4847
5548
  url,
4848
5549
  baseUrl: `${url}/v2`,
4849
- port: address.port,
5550
+ port: server.address().port,
4850
5551
  token,
4851
5552
  tokenIds: tokens.map((entry) => entry.id),
4852
5553
  tokenFile,
@@ -4863,5 +5564,6 @@ async function startHolding(options, data, checked, stops) {
4863
5564
  close: () => (stopped ??= stop()),
4864
5565
  // No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
4865
5566
  stopping: () => ({ runs: 0, boundMs: 0 }),
5567
+ listingSettled: () => lister.settled(),
4866
5568
  };
4867
5569
  }