@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.46

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 (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  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 +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. 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';
@@ -39,15 +40,15 @@ 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_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf } from "./harness-table.js";
43
- import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.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";
44
45
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
45
46
  import { DEFAULT_HOST, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
46
47
  import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
47
48
  import { answerStoreCall } from "./import-proxy.js";
48
- 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";
49
50
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
50
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowAtDigest, workflowRevisions, writeNote } from "./learning-routes.js";
51
+ import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
51
52
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
52
53
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
53
54
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -61,13 +62,15 @@ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveV
61
62
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
62
63
  import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
63
64
  import { readKept } from "./workspace/computer-kept.js";
64
- import { liveReachOf } from "./live-reach.js";
65
+ import { dialHost, liveReachOf, reachForRun } from "./live-reach.js";
65
66
  import { screenWaitEnded } from "./browser-wait-ended.js";
66
67
  import { durationMs, logLine } from "./print.js";
67
68
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
68
- import { factsOverStore, momentOverStore, settledStatusOf, 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";
69
71
  import { HELD_WAITS } from "./runner/journal-kinds.js";
70
72
  import { servedTimelineRows } from "./run-timeline-served.js";
73
+ import { servedRunTrace } from "./run-trace.js";
71
74
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
72
75
  import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
73
76
  import { runCutValues } from "./run-cut.js";
@@ -83,15 +86,16 @@ import { watchRun } from "./live/stream.js";
83
86
  import { stats as statsOverStore } from "./store-reads/stats.js";
84
87
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
85
88
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
86
- import { openStore, openRunLaunch, sealRunLaunch, StoreOwned, storeTarget } from "./store/index.js";
87
- 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";
88
91
  import { keepGrade } from "./runner/feedback-round.js";
89
92
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
90
93
  import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
91
94
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
92
95
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
93
- import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, shownDeep } from "./learn/promote.js";
96
+ import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
94
97
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
98
+ import { deleteLearning } from "./learn/delete.js";
95
99
  import { runModelRef } from "./model.js";
96
100
  import { REDACTED } from "./secret-cut.js";
97
101
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -106,16 +110,15 @@ import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
106
110
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
107
111
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
108
112
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
109
- 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";
110
115
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
111
116
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
112
117
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
113
118
  import { agentLoopOverStore } from "./store-reads/loop.js";
114
119
  import { printable } from "./learn/index.js";
115
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
116
- import { figuresOf, LearningBatches } from "./learning-batch.js";
120
+ import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
117
121
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
118
- import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
119
122
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
120
123
  import { toolKeysOverStore } from "./tool-keys-store.js";
121
124
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
@@ -163,7 +166,7 @@ import { recordingsFolder } from "./workspace/paths.js";
163
166
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
164
167
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
165
168
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
166
- import { createAttachRoutes, pairedView } from "./computer-attach.js";
169
+ import { createAttachRoutes, pairedView, RELAY_STALE_MS } from "./computer-attach.js";
167
170
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
168
171
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
169
172
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -172,12 +175,16 @@ import { noAccount, openAccount } from "./email/account.js";
172
175
  import { emailRoute } from "./email/routes.js";
173
176
  import { addressForms, openCalendar } from "./calendar/address.js";
174
177
  import { calendarRoute } from "./calendar/routes.js";
175
- import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
178
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKey } from "./archil-settings.js";
176
179
  import { computerOfPlace } from "./computer-setting.js";
177
180
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
178
181
  import { fauxComputers } from "./faux-computers.js";
179
182
  import { writesHeld } from "./workspace.js";
180
- 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";
181
188
  import { keyReader } from "./key-meta.js";
182
189
  export const CONTRACT = "agentrun.v2/0";
183
190
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
@@ -214,7 +221,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
214
221
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
215
222
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
216
223
  * harness's, which scripts the harnesses with or without it. */
217
- 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]];
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]];
218
225
  /** The switches a run's process gets, each module path resolved: the owner's harness modules (harnessModules), and the test
219
226
  * switches, which are empty outside tests. A test's in-process runner takes the same (test/support.mjs
220
227
  * startInProcessRunner). */
@@ -227,6 +234,11 @@ export function fauxEnvOf(options) {
227
234
  for (const [option, name] of FAUX_SWITCHES)
228
235
  if (options[option])
229
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);
230
242
  return env;
231
243
  }
232
244
  const isLoopback = (host) => host === "localhost" || host === "::1" || /^127\./.test(host);
@@ -272,6 +284,7 @@ export const ROUTES = [
272
284
  { method: "POST", pattern: /^\/agents$/, name: "createAgent" },
273
285
  { method: "GET", pattern: /^\/agents$/, name: "listAgents" },
274
286
  { method: "GET", pattern: /^\/agents\/([^/]+)$/, name: "getAgent" },
287
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)$/, name: "deleteAgent" },
275
288
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
276
289
  { method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
277
290
  { method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
@@ -301,6 +314,8 @@ export const ROUTES = [
301
314
  { method: "PUT", pattern: /^\/runs\/([^/]+)\/grade$/, name: "gradeRun" },
302
315
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
303
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" },
304
319
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
305
320
  { method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
306
321
  { method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
@@ -362,6 +377,11 @@ export const ROUTES = [
362
377
  { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
363
378
  { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
364
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" },
365
385
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
366
386
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
367
387
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
@@ -417,22 +437,15 @@ export const ROUTES = [
417
437
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
418
438
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
419
439
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
420
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
421
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
422
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
423
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
424
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
425
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
426
440
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/loop$/, name: "getLearningLoop" },
427
- { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
428
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" },
429
444
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
430
- { method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
431
445
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
432
446
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
433
447
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
434
448
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
435
- { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
436
449
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays$/, name: "startLearnedWorkflowReplay" },
437
450
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays\/([^/]+)$/, name: "getLearnedWorkflowReplay" },
438
451
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
@@ -508,7 +521,7 @@ export function offersEnvOf(env) {
508
521
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
509
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
510
523
  * the offers probed again, never shown. */
511
- 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];
512
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. */
513
526
  async function planStep(step) {
514
527
  try {
@@ -531,32 +544,30 @@ async function needsOf(env) {
531
544
  * AGENTRUN_SERVE_LEARNING's when not given), its tool settings (`toolSettings`, what each web tool resolves to) and the
532
545
  * box offers (`boxes`, what the server found at the start, place-offers.ts), with whether a revision that names no
533
546
  * model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
534
- * (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
535
- * `gradeModel` is its `--grade-model`. */
536
- 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 = []) {
537
549
  const env = withSecrets(base, "all", stored);
538
550
  const offers = await harnessOffers(offersEnvOf(env));
539
- 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) };
540
552
  }
541
553
  /** The capabilities document GET /v2/capabilities answers for `env`: each harness's offer resolved, its `default_model`
542
554
  * included (harnessOffers), and whether a revision that names no model runs here (`models.ready`, and what it `needs`
543
555
  * when not), so what this returns is what the route serves and what the document's schema holds.
544
556
  * `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
545
- * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
546
- * `gradeModel`, its `--grade-model`. */
547
- export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
548
- 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);
549
560
  }
550
561
  /** The capabilities document as `req`'s caller reads it: approving takes the owner's password session alone, so only
551
562
  * that caller reads `approve: true`; every other (a token, a run, accounts off) reads `approve_needs: "password"`. */
552
563
  export function forCaller(caps, ownerSession) {
553
- 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;
554
565
  }
555
566
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
556
567
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
557
568
  * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
558
569
  * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. */
559
- 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") {
560
571
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
561
572
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
562
573
  const memory = hostMemory();
@@ -570,17 +581,19 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
570
581
  server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
571
582
  /** What runs a run here (the contract's `runtimes`, informational): this server's runners, over its one store. */
572
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,
573
587
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
574
588
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
575
589
  harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
576
590
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
577
591
  places: placesOf(boxes, boxAllowOf(env)),
578
592
  models,
579
- /** What grades a run's proposed notes: the model this server names for it (learning.ts gradeModelOf), or null when
580
- * 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
581
- * wait for its owner's OK, served to no run; `approve`: whether the caller can approve one, which takes the owner's
582
- * password session (forCaller), and `approve_needs` when not. */
583
- 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" },
584
597
  /** Every tool a revision may name (the closed table in tools.ts): available here, or the variables it is missing; a
585
598
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
586
599
  * it (tool-keys.ts), when one does. */
@@ -673,6 +686,11 @@ function cursorOf(value) {
673
686
  throw new ApiError("bad_request", "cursor is not one this server gave");
674
687
  return offset;
675
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;
676
694
  const nextCursor = (offset, total) => (offset < total ? Buffer.from(String(offset)).toString("base64url") : null);
677
695
  function limitOf(value) {
678
696
  if (value === null)
@@ -729,7 +747,6 @@ export async function startServe(options) {
729
747
  const boxAllow = boxAllowOf(process.env);
730
748
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
731
749
  const learning = learningOf(process.env, options.learning);
732
- const learningBudget = learningBudgetOf(process.env, options.learningBudget);
733
750
  // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
734
751
  freeModelRequestsOf(process.env);
735
752
  const minFreeMib = minFreeMibOf(process.env);
@@ -745,7 +762,7 @@ export async function startServe(options) {
745
762
  // store handle it opened.
746
763
  const stops = [];
747
764
  try {
748
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates }, stops);
765
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates }, stops);
749
766
  }
750
767
  catch (error) {
751
768
  for (const stop of stops)
@@ -775,7 +792,7 @@ async function whileReplaced(take, held, until, waiting) {
775
792
  }
776
793
  }
777
794
  async function startHolding(options, data, checked, stops) {
778
- const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
795
+ const { maxRuns, minFreeBytes, learning, boxAllow, templates } = checked;
779
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
780
797
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
781
798
  * read (the view never fails for it). */
@@ -800,8 +817,9 @@ async function startHolding(options, data, checked, stops) {
800
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) };
801
818
  // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
802
819
  // the start, in words, before anything else opens.
803
- // The harness ids a definition may name here: the table's, the built-in ones and those the modules add.
804
- const harnesses = harnessIds(base);
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);
805
823
  // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
806
824
  // owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
807
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
@@ -841,7 +859,6 @@ async function startHolding(options, data, checked, stops) {
841
859
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
842
860
  // store is refused above (its owner lock).
843
861
  const attachHub = new AttachHub();
844
- 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`)) });
845
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
846
863
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
847
864
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -869,6 +886,16 @@ async function startHolding(options, data, checked, stops) {
869
886
  // there is no keeping one in the clear.
870
887
  const seal = await bootSealKey(store, data);
871
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
+ });
872
899
  // This server's own key on every environment it reads its secrets from, so a reader opens what this store holds with the
873
900
  // key checked against it, never another data directory's that this process booted too (secrets.ts holds one made key).
874
901
  const own = (env) => withSealKey(env, seal.text);
@@ -934,7 +961,14 @@ async function startHolding(options, data, checked, stops) {
934
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() });
935
962
  await plan.load();
936
963
  stops.push(async () => plan.close());
937
- 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);
938
972
  let offers;
939
973
  let caps;
940
974
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -943,7 +977,13 @@ async function startHolding(options, data, checked, stops) {
943
977
  // With accounts off no one can answer an ask (the answer route takes the owner's session alone): each tool ask is
944
978
  // offered for says it needs the password sign-in, as learning's approve does.
945
979
  const askNeeds = (made) => (options.accounts ? made : { ...made, tools: made.tools.map((tool) => (tool.permissions.includes("ask") ? { ...tool, ask_needs: "password" } : tool)) });
946
- 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));
947
987
  const recompose = () => void (caps = compose());
948
988
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
949
989
  let offersFrom;
@@ -963,10 +1003,20 @@ async function startHolding(options, data, checked, stops) {
963
1003
  * (needsOf may wait, and another write lands meanwhile): the latest write's `needs` stands, an earlier one's that
964
1004
  * finishes after it is dropped. */
965
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
+ });
966
1014
  const keysChanged = async () => {
967
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
968
- // serverSecrets live, store-view), so a key change needs no cache invalidation here.
969
- 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);
970
1020
  const mine = ++needsAsked;
971
1021
  const next = await needsOf(env);
972
1022
  if (mine === needsAsked)
@@ -983,6 +1033,21 @@ async function startHolding(options, data, checked, stops) {
983
1033
  if ((await plan.load()).state !== was)
984
1034
  await keysChanged();
985
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
+ });
986
1051
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
987
1052
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
988
1053
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
@@ -1020,10 +1085,8 @@ async function startHolding(options, data, checked, stops) {
1020
1085
  const sealKey = seal.key;
1021
1086
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1022
1087
  const sdkSecret = sdkRunSecret(sealKey);
1023
- // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
1024
- // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
1025
- const reach = liveReachOf(env, sealKey);
1026
- 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));
1027
1090
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
1028
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
1029
1092
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -1065,7 +1128,11 @@ async function startHolding(options, data, checked, stops) {
1065
1128
  // A provider's key set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name
1066
1129
  // from what the server was started with, as computerReady below reads it.
1067
1130
  store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: withSecrets(process.env, "own"),
1068
- 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),
1069
1136
  ...(options.faux
1070
1137
  // --faux's providers stand in for every vendor's, a local one's daemon included.
1071
1138
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -1148,7 +1215,7 @@ async function startHolding(options, data, checked, stops) {
1148
1215
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1149
1216
  const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1150
1217
  /** The run read's path and costs (A8, store-reads/learning.ts runAllInOverStore): `path`; `cost.usd` its own spend, the
1151
- * job's (its look-back and compile turns are learning's), null while unknown; what learning spent for it
1218
+ * job's (its compile turn is learning's), null while unknown; what learning spent for it
1152
1219
  * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown. */
1153
1220
  const allInViewOf = async (runId, view) => {
1154
1221
  const cost = (view.cost ?? {});
@@ -1157,7 +1224,7 @@ async function startHolding(options, data, checked, stops) {
1157
1224
  if (!all)
1158
1225
  return {};
1159
1226
  // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1160
- // gives): known as it answered even when its look-back's cost is not; the row's while the run is at work.
1227
+ // gives): known as it answered even when its compile turn's cost is not; the row's while the run is at work.
1161
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 } };
1162
1229
  };
1163
1230
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
@@ -1212,6 +1279,8 @@ async function startHolding(options, data, checked, stops) {
1212
1279
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
1213
1280
  const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
1214
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 } : {}),
1215
1284
  ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1216
1285
  privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1217
1286
  });
@@ -1319,19 +1388,12 @@ async function startHolding(options, data, checked, stops) {
1319
1388
  // Whether that is the operator's own setting, not the default: a browser is held to an operator's list alone.
1320
1389
  ...(boxAllowSetIn(process.env) ? { boxAllowSet: true } : {}),
1321
1390
  modelOf,
1322
- // The run's learning start, decided at start as the old file-backed start decided it (learning-run.ts onStart/seedFor):
1323
- // the server's learning switch, the budget its # Learned section fits, the agent's seed read now from its learning folder
1324
- // (git), and the host's secrets as they are shown now to cut the notes a run is given, a loopback address kept (local),
1325
- // as the run's .learning/ files keep it: the run's own machine, which an agent with no read tool learns of only here.
1326
- // runs-over-store.learningStartFor pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed
1327
- // that cannot be read starts the run with nothing learned (a fault never refuses it). The runner's spec builders read
1328
- // it back as the run's end-of-run step (runner/learning-end.ts learningEndOfRun, in adapter-run-spec.ts and
1329
- // 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).
1330
1396
  learning,
1331
- learningBudget,
1332
- // The model the server names to grade what a run proposes (capabilities' learning.grade_model), carried on each learning
1333
- // start for the runner's learning run to grade on: none, the agent's own.
1334
- ...(gradeModelOf(env, options.gradeModel) ? { gradeModel: gradeModelOf(env, options.gradeModel) } : {}),
1335
1397
  seedFor: async (agentId) => {
1336
1398
  // The switch runs no git in this process (learning.ts seedOf: the folder's own script and file API, which checks git
1337
1399
  // itself); a git or folder fault surfaces here as a seedOf error, so the run starts with nothing learned, never refused.
@@ -1342,66 +1404,6 @@ async function startHolding(options, data, checked, stops) {
1342
1404
  },
1343
1405
  shown: () => secretsShown(serverSecrets(), { local: true }),
1344
1406
  };
1345
- /** 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
1346
- * no "at most", so a view cost marked `upper_bound` reads null there, as the run's stored cost does (RunRow.costUsd). */
1347
- const batchRunView = async (runId) => {
1348
- const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1349
- if (!v)
1350
- return undefined;
1351
- 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 };
1352
- };
1353
- // 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
1354
- // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
1355
- // (create's answer, read, list, cancel) cut its text as the learning routes do (learningShown, below).
1356
- const batches = new LearningBatches({
1357
- settings: store.settings,
1358
- learning: async (agentId) => {
1359
- const entry = await needAgent(agentId);
1360
- if (entry.agent.archivedAt)
1361
- return { learns: false, why: "it is archived." };
1362
- if (learning === "off")
1363
- return { learns: false, why: "this server's learning is off (--learning)." };
1364
- // A batch starts runs and sends their follow-ups with no caller's model key: none to spend on a server with none.
1365
- const off = noServerKeyFor(env, "Learning from a CSV");
1366
- if (off)
1367
- return { learns: false, why: off };
1368
- if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1369
- return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1370
- return { learns: true };
1371
- },
1372
- // 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
1373
- // server stopped before its row kept the id is found again, never started twice.
1374
- find: async (key) => (await agents.request(() => agents.store.runOfOrigin(key)))?.runId,
1375
- start: async (agentId, body, key) => (await startRunOf(await needAgent(agentId), body, { origin: { key } })).id,
1376
- view: (runId) => batchRunView(runId),
1377
- // Sent already: a steer the run's commands hold with these words, not refused (a follow-up to an ended run is one too,
1378
- // its reopen's).
1379
- sent: async (runId, content) => (await store.commands(runId, 0)).some((c) => c.kind === "steer" && c.refused === null && c.body?.text === content),
1380
- message: async (runId, content) => void (await message(store, await needRun(runId), content)),
1381
- // A run that is not there has nothing to stop; any other failure is the loop's (the row stays live and owned).
1382
- cancel: async (runId) => {
1383
- const moment = ID.test(runId) ? await momentOverStore(store, runId, viewDepsFor(ownOriginOf())) : undefined;
1384
- if (moment)
1385
- await cancel(store, moment);
1386
- },
1387
- figures: async (runId) => {
1388
- const stored = await store.runs.get(runId);
1389
- if (!stored)
1390
- return undefined;
1391
- // A run still going has no stored cost yet (its column is written at its end): its live cost, from its view, stands in,
1392
- // so a batch's cost now and the cost it books are costRunOf both.
1393
- const run = FINAL_STATES.includes(stored.state) ? stored : { ...stored, costUsd: (await batchRunView(runId))?.cost_usd ?? null };
1394
- // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1395
- const newest = await store.learning.proposal(runId);
1396
- const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1397
- // 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
1398
- // is not known while its audit's shadow run is queued or running (shadowSpendOf): the batch closes no row on it.
1399
- return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends, (await shadowSpendOf(store, runId)).open);
1400
- },
1401
- // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1402
- shown: (agentId) => learningShown(agentId),
1403
- ...(options.batchPollMs ? { pollMs: options.batchPollMs } : {}),
1404
- });
1405
1407
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1406
1408
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1407
1409
  // request) use the server's public address, else its own.
@@ -1449,11 +1451,12 @@ async function startHolding(options, data, checked, stops) {
1449
1451
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1450
1452
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1451
1453
  context: ctx,
1452
- liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers),
1454
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers(runId)),
1453
1455
  };
1454
1456
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1455
1457
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1456
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 };
1457
1460
  const timelines = runTimelines({
1458
1461
  context: ctx,
1459
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
@@ -1461,7 +1464,7 @@ async function startHolding(options, data, checked, stops) {
1461
1464
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1462
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
1463
1466
  // from its journal, which keeps what the run said whole.
1464
- 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),
1465
1468
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1466
1469
  });
1467
1470
  const triggerDeps = {
@@ -1798,7 +1801,6 @@ async function startHolding(options, data, checked, stops) {
1798
1801
  stops.push(async () => triggers.close());
1799
1802
  // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1800
1803
  // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1801
- void batches.resume().catch((error) => void process.stderr.write(`agentrun-serve: the learning batches' resume: ${error.message}\n`));
1802
1804
  void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1803
1805
  // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1804
1806
  // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
@@ -2027,6 +2029,9 @@ async function startHolding(options, data, checked, stops) {
2027
2029
  * a person's start (createRun) and a replay's (startLearnedWorkflowReplay), asks this before it reserves or writes anything. */
2028
2030
  async function needRunnableAgent(id) {
2029
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);
2030
2035
  if (entry.agent.archivedAt)
2031
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() } });
2032
2037
  return entry;
@@ -2038,12 +2043,13 @@ async function startHolding(options, data, checked, stops) {
2038
2043
  const learning = await learningOfAgent(entry);
2039
2044
  const native = nativeOf(entry.revision?.body);
2040
2045
  const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
2041
- 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);
2042
2048
  return {
2043
2049
  ...(nativeStatus ? { nativeStatus } : {}),
2044
2050
  signIns: await signIns.view(entry.agent.id),
2045
2051
  ...(learning ? { learning } : {}),
2046
- runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
2052
+ runs: { count: runs.count, live: runs.live },
2047
2053
  // The agent's own computer (a persistent setting), as this server records it: the view's own_computer.
2048
2054
  ownComputer: agentComputerView(await agentComputerOf(store, entry.agent.id)),
2049
2055
  };
@@ -2056,6 +2062,134 @@ async function startHolding(options, data, checked, stops) {
2056
2062
  .then((done) => (done ? log?.(logLine("agent_computer", { agent: agentId, ...("deleted" in done ? { deleted: done.deleted } : { failed: done.failed }) })) : undefined))
2057
2063
  .catch((error) => log?.(logLine("agent_computer", { agent: agentId, failed: error instanceof Error ? error.message : String(error) })));
2058
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
+ };
2059
2193
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
2060
2194
  // routes read from the store + the run view now, not a live Run.
2061
2195
  async function needRun(id) {
@@ -2093,6 +2227,9 @@ async function startHolding(options, data, checked, stops) {
2093
2227
  for (const [k, v] of idempotency)
2094
2228
  if (now - v.at > IDEMPOTENCY_TTL_S * 1000)
2095
2229
  idempotency.delete(k);
2230
+ for (const [k, at] of forgotten)
2231
+ if (now - at > IDEMPOTENCY_TTL_S * 1000)
2232
+ forgotten.delete(k);
2096
2233
  const known = idempotency.get(slot);
2097
2234
  if (known) {
2098
2235
  if (known.fingerprint !== fingerprint)
@@ -2111,6 +2248,14 @@ async function startHolding(options, data, checked, stops) {
2111
2248
  idempotency.delete(slot);
2112
2249
  throw error;
2113
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
+ }
2114
2259
  // The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
2115
2260
  // instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
2116
2261
  // then: the store keeps its run under the key's origin.
@@ -2181,7 +2326,8 @@ async function startHolding(options, data, checked, stops) {
2181
2326
  });
2182
2327
  };
2183
2328
  const monid = revision.monidPin ?? undefined;
2184
- 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 });
2185
2331
  if (!blockers.length)
2186
2332
  return;
2187
2333
  const message = blockers.map((b) => b.message).join(" ");
@@ -2303,7 +2449,7 @@ async function startHolding(options, data, checked, stops) {
2303
2449
  const listing = await mcpListingOf(revision, previous?.mcpPin);
2304
2450
  const mcp = listing.tools;
2305
2451
  const { monid, warnings: usage = [] } = (await monidPinOf(revision, previous)) ?? {};
2306
- 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 });
2307
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
2308
2454
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
2309
2455
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
@@ -2339,6 +2485,19 @@ async function startHolding(options, data, checked, stops) {
2339
2485
  throw invalid(pinned.refused.map(({ tool, message }) => ({ field: tools.includes(tool) ? `definition.tools[${tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
2340
2486
  return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
2341
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
+ };
2342
2501
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
2343
2502
  * that names no place is given this server's box (place.ts defaultPlaceOf), stamped on its revision, when it names no
2344
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
@@ -2348,13 +2507,46 @@ async function startHolding(options, data, checked, stops) {
2348
2507
  const definition = checkDefinitionBody(body, { harnesses });
2349
2508
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
2350
2509
  const place = fallbackPlace("agentic", definition.definition.tools === undefined ? NEW_AGENT_TOOLS : named);
2510
+ const tools = defaultToolsAt(place);
2351
2511
  const entry = await agents.create(definition, async (revision) => {
2352
2512
  const saved = await saveable(revision);
2353
2513
  warnings = saved.warnings;
2354
2514
  return saved.stamp;
2355
- }, place.mode === "sandbox" ? { place, tools: NEW_AGENT_TOOLS } : undefined, template);
2515
+ }, place.mode === "sandbox" && tools ? { place, tools } : undefined, template);
2356
2516
  return { entry, warnings };
2357
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
+ }
2358
2550
  /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
2359
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
2360
2552
  * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
@@ -2377,51 +2569,6 @@ async function startHolding(options, data, checked, stops) {
2377
2569
  throw error;
2378
2570
  }
2379
2571
  };
2380
- /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
2381
- * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
2382
- * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
2383
- * learned workflow.json, its tools those its call nodes call (each one the source agent has and its gate allows), and
2384
- * the source's policy as it is now: its own tool settings, its approvals and its default cap, never more. Named
2385
- * `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
2386
- * already here. The learned workflow stays where it is, unchanged. */
2387
- async function promoteOf(source, raw, body) {
2388
- const extra = unknownFields(body, ["name"]);
2389
- if (body.name !== undefined && (typeof body.name !== "string" || body.name.trim() === "" || body.name.length > 200))
2390
- extra.push({ field: "name", reason: "wrong_type", message: "name is the new agent's name: text of 1 to 200 characters" });
2391
- if (extra.length)
2392
- throw invalid(extra);
2393
- const id = source.agent.id;
2394
- const learned = await promotable(data, id, raw, { refuse: await learningValues(id), draftTools: () => learnedDraftToolsOf(id, source) });
2395
- // Its policy from the same read of the source as the tools checked above: one revision's, whatever is saved meanwhile.
2396
- const policy = (source.revision?.body ?? {});
2397
- const promoted = (agentId) => ({
2398
- id: agentId,
2399
- name: typeof body.name === "string" ? body.name.trim() : agentId,
2400
- ...(learned.description ? { description: learned.description } : {}),
2401
- workflow: learned.workflow,
2402
- tools: learned.calls,
2403
- ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
2404
- ...(policy.approvals === "never" ? { approvals: "never" } : {}),
2405
- ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
2406
- });
2407
- const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
2408
- // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
2409
- for (let tries = 0;; tries++) {
2410
- const all = [...(await agents.list()), ...(await agents.list({ archived: true }))];
2411
- const taken = new Set(all.flatMap((entry) => [entry.agent.id, entry.agent.name]));
2412
- let n = 1;
2413
- while (taken.has(n === 1 ? learned.name : `${learned.name}-${n}`))
2414
- n++;
2415
- const agentId = n === 1 ? learned.name : `${learned.name}-${n}`;
2416
- try {
2417
- return await createAgentOf({ definition: promoted(agentId), note });
2418
- }
2419
- catch (error) {
2420
- if (!(error instanceof ApiError && error.code === "agent_exists") || tries >= 4)
2421
- throw error;
2422
- }
2423
- }
2424
- }
2425
2572
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
2426
2573
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
2427
2574
  * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, with no permission written
@@ -2430,9 +2577,52 @@ async function startHolding(options, data, checked, stops) {
2430
2577
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
2431
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
2432
2579
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
2433
- * 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. */
2434
2591
  async function applyTemplate(template, body) {
2435
- 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);
2436
2626
  // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2437
2627
  const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
2438
2628
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
@@ -2500,9 +2690,84 @@ async function startHolding(options, data, checked, stops) {
2500
2690
  for (const one of [made.agent, ...made.triggers])
2501
2691
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
2502
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" } });
2503
- // The agent keeps where it came from (its first revision's package): the package's id, version and, imported, its SHA.
2504
- 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.
2505
2768
  const ids = [];
2769
+ // The triggers this apply made (never one it changed in place): what a refusal's undo removes.
2770
+ const madeNow = [];
2506
2771
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
2507
2772
  // /triggers hands back its own, so the owner can give it to the sender.
2508
2773
  const secrets = [];
@@ -2510,13 +2775,49 @@ async function startHolding(options, data, checked, stops) {
2510
2775
  // a composio one Composio can't reach or run as here) is skipped, never the apply: the agent stands, and the answer
2511
2776
  // says what to do (a warning under triggers.<i>). Kept with its refusal, whose words the warning carries.
2512
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 = [];
2513
2781
  try {
2514
2782
  for (const [i, trigger] of made.triggers.entries()) {
2515
2783
  if (emptyFeeds.has(i))
2516
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 };
2517
2788
  try {
2518
- 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 });
2519
2819
  ids.push(madeId);
2820
+ madeNow.push(madeId);
2520
2821
  if (secret)
2521
2822
  secrets.push({ trigger_id: madeId, secret });
2522
2823
  }
@@ -2530,9 +2831,16 @@ async function startHolding(options, data, checked, stops) {
2530
2831
  throw error;
2531
2832
  }
2532
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
+ }
2533
2840
  }
2534
2841
  catch (error) {
2535
- 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()) {
2536
2844
  try {
2537
2845
  await triggers.remove(id);
2538
2846
  }
@@ -2542,7 +2850,8 @@ async function startHolding(options, data, checked, stops) {
2542
2850
  }
2543
2851
  // Archived through the trigger engine, as POST /agents/{id}/archive is: a trigger the undo could not remove is turned
2544
2852
  // off in that same store transaction with the reason agent_archived, never with none, and unarchive answers it.
2545
- 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 })));
2546
2855
  throw error;
2547
2856
  }
2548
2857
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
@@ -2571,8 +2880,8 @@ async function startHolding(options, data, checked, stops) {
2571
2880
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2572
2881
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2573
2882
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2574
- 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] };
2575
- 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 };
2576
2885
  }
2577
2886
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
2578
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
@@ -2874,17 +3183,58 @@ async function startHolding(options, data, checked, stops) {
2874
3183
  // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2875
3184
  const labels = labelFilter(url.searchParams.getAll("label"));
2876
3185
  const vd = viewDepsFor(origin);
2877
- // 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.
2878
- 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
+ };
2879
3212
  if (status !== null) {
2880
- // The v2 status is the run view's (store-view over the journal), per row; a settled run's is its row's (settledStatusOf),
2881
- // so only the runs still going are read over their journals.
2882
- const statuses = await Promise.all(rows.map((row) => settledStatusOf(row.state) ?? viewOverStore(store, row.id, vd).then((v) => v?.status)));
2883
- 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));
2884
3236
  }
2885
- // summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
2886
- const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => summaryOverStore(store, row.id, vd)));
2887
- return { runs: page, next_cursor: nextCursor(offset + limit, rows.length) };
3237
+ return { runs, next_cursor: nextCursor(offset + limit, offset + limit + (page.more ? 1 : 0)) };
2888
3238
  }
2889
3239
  async function timeline(req, res, url, runId) {
2890
3240
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
@@ -3320,6 +3670,8 @@ async function startHolding(options, data, checked, stops) {
3320
3670
  const found = matching.find((r) => r.method === req.method || (req.method === "HEAD" && r.method === "GET"));
3321
3671
  if (!found)
3322
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));
3323
3675
  if (found.name === "getCapabilities") {
3324
3676
  // features.computers: the computer kinds this server offers now (computers.ts), read at each answer, since turning
3325
3677
  // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
@@ -3403,7 +3755,7 @@ async function startHolding(options, data, checked, stops) {
3403
3755
  const health = await healthOf(store, data, minFreeBytes);
3404
3756
  return send(res, health.status === "ok" ? 200 : 503, health);
3405
3757
  }
3406
- // 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
3407
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
3408
3760
  // page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
3409
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,
@@ -3411,20 +3763,14 @@ async function startHolding(options, data, checked, stops) {
3411
3763
  // Restoring a retired one puts it back in every later run, as an approval does: the same owner's session alone.
3412
3764
  if (found.name === "restoreLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3413
3765
  authFailed(`/v2${path}`, "restore_without_session");
3414
- 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).");
3415
3767
  }
3416
3768
  if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3417
3769
  authFailed(`/v2${path}`, "approve_without_session");
3418
- 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).");
3419
- }
3420
- // Making a learned workflow an agent of its own gives it runs of its own, outside any agentic run's turn: the owner's
3421
- // click alone, the same session as an approval.
3422
- if (found.name === "promoteLearnedWorkflow" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3423
- authFailed(`/v2${path}`, "promote_without_session");
3424
- 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).");
3425
3771
  }
3426
3772
  // A replay its owner starts runs the agent's graded inputs again at its cost, and may promote a revision that then
3427
- // serves first: the same session as making one an agent.
3773
+ // serves first: the same session as an approval.
3428
3774
  if (found.name === "startLearnedWorkflowReplay" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3429
3775
  authFailed(`/v2${path}`, "replay_without_session");
3430
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).");
@@ -3524,25 +3870,27 @@ async function startHolding(options, data, checked, stops) {
3524
3870
  if (!req.headers["idempotency-key"])
3525
3871
  throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
3526
3872
  const body = await bodyOf(req), entry = await needAgent(id);
3527
- let gradeModel = gradeModelOf(env, options.gradeModel);
3528
- 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") {
3529
3876
  try {
3530
3877
  const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3531
3878
  if (chosen)
3532
- gradeModel = `${chosen.provider}/${chosen.modelId}`;
3879
+ compileModel = `${chosen.provider}/${chosen.modelId}`;
3533
3880
  }
3534
3881
  catch { }
3535
3882
  }
3536
3883
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3537
- 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) => {
3538
3885
  try {
3539
- const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
3886
+ const route = await askRouteOf(model, env, (one) => sdkModelRoute(one, env, "default", PI_WIRES));
3540
3887
  await route.provider.credential();
3541
3888
  }
3542
3889
  catch {
3543
- 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.");
3544
3891
  }
3545
- }, 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)) }));
3546
3894
  // Re-read the pinned receipt even on an in-memory replay: credentials saved since
3547
3895
  // the first response must still be withheld without reselecting a different seed.
3548
3896
  const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
@@ -3655,15 +4003,7 @@ async function startHolding(options, data, checked, stops) {
3655
4003
  }
3656
4004
  // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
3657
4005
  // the same revision exactly one lands.
3658
- let warnings = [];
3659
- const check = async (revision, on) => {
3660
- // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
3661
- const saved = await saveable(revision, on);
3662
- warnings = saved.warnings;
3663
- return saved.stamp;
3664
- };
3665
- const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false, harnesses }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3666
- reconcileComputer(id);
4006
+ const { entry: edited, warnings } = await reviseAgentOf(entry, contract ? { definition: body } : body, { contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3667
4007
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
3668
4008
  }
3669
4009
  case "listRevisions": {
@@ -3701,6 +4041,18 @@ async function startHolding(options, data, checked, stops) {
3701
4041
  reconcileComputer(id);
3702
4042
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
3703
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
+ }
3704
4056
  case "archiveAgent":
3705
4057
  case "unarchiveAgent": {
3706
4058
  // An agent another system owns is that system's to keep or drop: archiving it here is refused, as an edit is.
@@ -3866,13 +4218,18 @@ async function startHolding(options, data, checked, stops) {
3866
4218
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3867
4219
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3868
4220
  };
3869
- // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3870
- // 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.
3871
- const kept = 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) })));
3872
- // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3873
- // reads it with the shadows'. A row not written now is logged, never the grade refused.
3874
- const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
3875
- 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
+ });
3876
4233
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3877
4234
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3878
4235
  const shown = await learningShown(row.agentId).catch(() => undefined);
@@ -3906,10 +4263,10 @@ async function startHolding(options, data, checked, stops) {
3906
4263
  const view = await computerView({
3907
4264
  viewer: async () => {
3908
4265
  if (family === "browser") {
3909
- const link = await liveViewerLink(store, sealKey, run.id, answers);
4266
+ const link = await liveViewerLink(store, sealKey, run.id, answers(run.id));
3910
4267
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
3911
4268
  }
3912
- return computerViewerLink(store, sealKey, run.id, answers);
4269
+ return computerViewerLink(store, sealKey, run.id, answers(run.id));
3913
4270
  },
3914
4271
  computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family, own)),
3915
4272
  session: (kind) => sessionIn(kind, entries, run.terminal || (parked && kind !== "browser")),
@@ -4020,9 +4377,11 @@ async function startHolding(options, data, checked, stops) {
4020
4377
  const rel = homePath(second, id, true);
4021
4378
  const bytes = await bytesOf(req);
4022
4379
  // Each write lands whole (the Workspace's write is atomic); of two at once, the last one wins.
4023
- const home = await homeWorkspace(id, true);
4024
- await home.write(rel, bytes).catch(homeRefusal);
4025
- 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
+ });
4026
4385
  if (written?.kind !== "file")
4027
4386
  throw new ApiError("not_found", "no such file");
4028
4387
  return send(res, 200, viewOf(rel, written));
@@ -4032,16 +4391,19 @@ async function startHolding(options, data, checked, stops) {
4032
4391
  if (!homeWrites)
4033
4392
  throw new ApiError("unsupported_here", HOME_WRITES_OFF);
4034
4393
  const rel = homePath(second, id, true);
4035
- const home = await homeWorkspace(id, false);
4036
- if (!home)
4037
- throw new ApiError("not_found", "no such file");
4038
- // A file alone: a folder is refused by the listing; a link (never listed) by the Workspace's remove (ESCAPE).
4039
- if ((await entryAt(home, rel))?.kind === "dir")
4040
- throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
4041
- await home.remove(rel).catch((error) => {
4042
- 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)
4043
4398
  throw new ApiError("not_found", "no such file");
4044
- 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
+ });
4045
4407
  });
4046
4408
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4047
4409
  return void res.end();
@@ -4073,6 +4435,11 @@ async function startHolding(options, data, checked, stops) {
4073
4435
  // The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
4074
4436
  // a run whose output is withheld is refused (403), as the route refused it.
4075
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));
4076
4443
  case "pauseRun":
4077
4444
  case "resumeRun": {
4078
4445
  // A workflow run's pause or resume is a command its runner reads and applies (runs-over-store.pauseOrResume): an
@@ -4210,6 +4577,23 @@ async function startHolding(options, data, checked, stops) {
4210
4577
  const { revoked } = await plan.signOut();
4211
4578
  return send(res, 200, revoked ? { revoked } : { revoked, message: SIGN_OUT_UNCONFIRMED });
4212
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
+ }
4213
4597
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
4214
4598
  case "listMcpServers":
4215
4599
  return send(res, 200, await mcpServers.list());
@@ -4358,11 +4742,15 @@ async function startHolding(options, data, checked, stops) {
4358
4742
  // definition's: an archived agent's too.
4359
4743
  case "getAgentLearning": {
4360
4744
  await needAgent(id);
4361
- // The agent's learning view: its notes, skills, workflows and log from its learning folder; its run-fared counts, each
4362
- // note's runs (given it and that read it) and its impact over the one store (agentLearningOverStore), from each run's
4363
- // launch, journal and learning end.
4364
- const { counts, impact, notes } = await agentLearningOverStore(store, id);
4365
- 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)));
4366
4754
  }
4367
4755
  case "getLearningCost": {
4368
4756
  await needAgent(id);
@@ -4389,7 +4777,9 @@ async function startHolding(options, data, checked, stops) {
4389
4777
  const shownRead = promotionsShown(records, shown);
4390
4778
  // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
4391
4779
  const loop = auditLoopOf(entry.revision?.body?.learning);
4392
- 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));
4393
4783
  // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
4394
4784
  // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4395
4785
  const writer = auditWriterOf(entry.revision ?? undefined);
@@ -4426,36 +4816,6 @@ async function startHolding(options, data, checked, stops) {
4426
4816
  const rows = await auditsOfAgent(id);
4427
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) })) });
4428
4818
  }
4429
- case "createLearningBatch": {
4430
- await needAgent(id);
4431
- const made = await batches.create(id, await bodyOf(req));
4432
- return send(res, 202, await batches.read(id, made.id), { location: `/v2/agents/${encodeURIComponent(id)}/learning/batches/${made.id}` });
4433
- }
4434
- case "listLearningBatches":
4435
- await needAgent(id);
4436
- return send(res, 200, await batches.list(id));
4437
- case "getLearningBatch":
4438
- await needAgent(id);
4439
- return send(res, 200, await batches.read(id, second));
4440
- case "cancelLearningBatch":
4441
- await needAgent(id);
4442
- return send(res, 200, await batches.cancel(id, second));
4443
- case "listLearningEvals": {
4444
- await needAgent(id);
4445
- // The agent's eval records (learning-evals.ts), newest first, the latest the one shown: only ever what was posted.
4446
- const evals = await evalsOf(store, id);
4447
- return send(res, 200, { agent: id, latest: evals[0] ?? null, evals });
4448
- }
4449
- case "recordLearningEval": {
4450
- const body = await bodyOf(req);
4451
- await needAgent(id);
4452
- const answer = await idempotent(req, `/agents/${id}/learning/evals`, body, async () => {
4453
- const result = evalOf(body, new Date());
4454
- await recordEval(store, id, result);
4455
- return { status: 201, body: result };
4456
- });
4457
- return send(res, answer.status, answer.body, answer.headers);
4458
- }
4459
4819
  case "getLearningLoop": {
4460
4820
  await needAgent(id);
4461
4821
  // The loop's own record over the one store (store-reads/loop.ts): compile turns, aggregates only.
@@ -4468,52 +4828,48 @@ async function startHolding(options, data, checked, stops) {
4468
4828
  const cut = await runCutValues({ serverSecrets, signIns }, store, one.run_id).catch(() => "unreadable");
4469
4829
  const workflow = one.workflow === null ? null : shown.name(one.workflow);
4470
4830
  if (cut === "unreadable")
4471
- 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 };
4472
4832
  const all = [...values, ...cut.values];
4473
4833
  const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
4474
- 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 };
4475
4835
  }));
4476
4836
  return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles });
4477
4837
  }
4478
- case "listLearningNotes":
4479
4838
  case "listLearningLog":
4480
4839
  await needAgent(id);
4481
- if (found.name === "listLearningNotes") {
4482
- // The notes from the agent's learning folder, each with its runs over the one store (agentLearningOverStore's noteRuns).
4483
- const { notes } = await agentLearningOverStore(store, id);
4484
- return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
4485
- }
4486
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
+ }
4487
4856
  case "listLearnedWorkflowRevisions":
4488
4857
  await needAgent(id);
4489
4858
  return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
4490
4859
  case "readLearningFile":
4491
4860
  await needAgent(id);
4492
- return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
4493
- case "writeLearningFile":
4861
+ return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id)));
4494
4862
  case "retireLearningFile":
4495
4863
  case "approveLearningFile":
4496
4864
  case "restoreLearningFile": {
4497
4865
  await needAgent(id);
4498
- const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
4499
- const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
4500
- // What it refuses is what the reads cut: a note shown cut is never saved over the hidden text.
4501
4866
  const refuse = await learningValues(id);
4502
- 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) });
4503
- // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
4504
- const shown = secretsShown(refuse);
4505
- const located = written.status === 201 && shown.name(written.file) === written.file;
4506
- return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
4507
- }
4508
- case "promoteLearnedWorkflow": {
4509
- // The source read once the body is in, as it is then: what promoteOf checks and what it copies are that one read.
4510
- const body = await bodyOf(req);
4511
- const source = await needAgent(id);
4512
- const answer = await idempotent(req, `/agents/${id}/learning/workflows/${second}/promote`, body, async () => {
4513
- const { entry, warnings } = await promoteOf(source, second, body);
4514
- return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
4515
- });
4516
- 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) });
4517
4873
  }
4518
4874
  case "startLearnedWorkflowReplay": {
4519
4875
  const body = await bodyOf(req);
@@ -4531,7 +4887,8 @@ async function startHolding(options, data, checked, stops) {
4531
4887
  const keyless = noServerKeyFor(env, "An owner's replay");
4532
4888
  if (keyless)
4533
4889
  throw new ApiError("not_continuable", keyless);
4534
- const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
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)));
4535
4892
  return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
4536
4893
  }
4537
4894
  case "getLearnedWorkflowReplay": {
@@ -4621,13 +4978,14 @@ async function startHolding(options, data, checked, stops) {
4621
4978
  const answer = await idempotent(req, `/templates/${encodeURIComponent(pkg.id)}/apply`, body, async () => {
4622
4979
  const made = await applyTemplate(pkg, body);
4623
4980
  minted = made.minted;
4624
- 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}` } };
4625
4983
  });
4626
4984
  // Each webhook trigger's secret, to the owner's session in this first answer alone (trigger-secrets-shown.ts
4627
4985
  // templateApplied): the record above never held it, so a replay under the key shows none.
4628
4986
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
4629
4987
  const shown = replayed ? "replay" : mayHoldSecrets(req) ? "first" : "token";
4630
- 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);
4631
4989
  }
4632
4990
  case "rotateTriggerSecret":
4633
4991
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
@@ -4832,7 +5190,7 @@ async function startHolding(options, data, checked, stops) {
4832
5190
  if (!admitted())
4833
5191
  return deny("401 Unauthorized");
4834
5192
  viewers.watch(socket, admitted);
4835
- proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
5193
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reachForRun(reach, run.id));
4836
5194
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
4837
5195
  };
4838
5196
  // The CLI's early listener answers with this server's routes from here on, where a new one would start to listen.
@@ -4872,6 +5230,8 @@ async function startHolding(options, data, checked, stops) {
4872
5230
  await new Promise((done) => server.close(() => done()));
4873
5231
  throw error;
4874
5232
  });
5233
+ // The lister's own passes (above), once this server listens and knows its own address (ownOriginOf).
5234
+ lister.start();
4875
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
4876
5236
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
4877
5237
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -4885,13 +5245,15 @@ async function startHolding(options, data, checked, stops) {
4885
5245
  * status input_required and idle, a message continues it) and not have ended: its view says which. */
4886
5246
  const stopRow = (row) => row.state === "stopped" && row.outcome === "stopped" && row.importedFrom === null;
4887
5247
  const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}), ...(stopRow(row) ? { stop: true } : {}) });
5248
+ /** Agent `agentId`'s name as the store holds it now, for a webhook notice: its id when it has none, or is gone. */
5249
+ const agentNameOf = async (agentId) => (await store.agents.get(agentId))?.name || agentId;
4888
5250
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
4889
5251
  const endNotice = async (id) => {
4890
5252
  const row = await store.runs.get(id);
4891
5253
  const summary = row && (await summaryOverStore(store, id, viewDepsFor(ownOriginOf())));
4892
5254
  if (!row || !summary)
4893
5255
  return null;
4894
- return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
5256
+ return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, agent_name: await agentNameOf(row.agentId), status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
4895
5257
  };
4896
5258
  /** The run-end read's look at a run: its end from its row alone when it has none, or one told already; else its
4897
5259
  * endNotice. The run's view redacts the run's words (its title, its output) on every build, and the newest runs are
@@ -4924,6 +5286,10 @@ async function startHolding(options, data, checked, stops) {
4924
5286
  return (readWaits.set(row.id, seen), true);
4925
5287
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
4926
5288
  const card = view.pending?.kind;
5289
+ // A stop asked for and not yet taken reads stopped (store-view's stopAsked) before its row ends: it is told once the
5290
+ // runner's end commit ends the row (a change the feed brings), under the one marker that end gives it.
5291
+ if (card === "stopped" && row.endedAt === null)
5292
+ return true;
4927
5293
  // 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
4928
5294
  // its stop ended the row: rows its stopped turn still streams in (a late result, a charge) never move it.
4929
5295
  const marker = card === "stopped" && row.endedAt !== null ? `stopped:${new Date(row.endedAt).toISOString()}` : waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
@@ -4933,7 +5299,7 @@ async function startHolding(options, data, checked, stops) {
4933
5299
  // whose card is withheld is a question. A run idle on nothing named (its harness ended its turn on its own) names no kind.
4934
5300
  const kind = typeof card === "string" && waitKinds.has(card) ? card : view.state === "waiting" ? "question" : undefined;
4935
5301
  const wait = kind === undefined ? undefined : { kind };
4936
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
5302
+ const notice = { run_id: row.id, agent_id: row.agentId, agent_name: await agentNameOf(row.agentId), status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
4937
5303
  if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
4938
5304
  return false;
4939
5305
  readWaits.set(row.id, seen);
@@ -5164,8 +5530,6 @@ async function startHolding(options, data, checked, stops) {
5164
5530
  // The ends' follower stops before the webhooks it feeds and the store it reads.
5165
5531
  clearTimeout(endsTimer);
5166
5532
  await endsRead;
5167
- // A learning batch's loop ends where it stands, still running: it takes up when a server starts on this data again.
5168
- await batches.halt();
5169
5533
  await webhooks.close();
5170
5534
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
5171
5535
  viewers.close();
@@ -5175,6 +5539,8 @@ async function startHolding(options, data, checked, stops) {
5175
5539
  await githubStopped;
5176
5540
  // --faux-github's fake GitHub API, once nothing asks it anything.
5177
5541
  await fauxGitHub?.close();
5542
+ // The listings' builder ends its pass before the store it reads and writes closes.
5543
+ await lister.stop();
5178
5544
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
5179
5545
  await store.close();
5180
5546
  dataLock.release();
@@ -5200,5 +5566,6 @@ async function startHolding(options, data, checked, stops) {
5200
5566
  close: () => (stopped ??= stop()),
5201
5567
  // No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
5202
5568
  stopping: () => ({ runs: 0, boundMs: 0 }),
5569
+ listingSettled: () => lister.settled(),
5203
5570
  };
5204
5571
  }