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

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
package/dist/server.js CHANGED
@@ -31,19 +31,20 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
31
31
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
32
32
  import { IMPORT_ASKED } from "./import.js";
33
33
  import { answerStoreCall } from "./import-proxy.js";
34
- import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, seedOf } from "./learning.js";
35
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
34
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
35
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
36
36
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
37
37
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
38
38
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
39
39
  import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
40
40
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
41
41
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
42
- import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
42
+ import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
43
43
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
44
- import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
44
+ import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
45
45
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
- import { computerView } from "./computer-view.js";
46
+ import { computerView, sessionIn } from "./computer-view.js";
47
+ import { liveReachOf } from "./live-reach.js";
47
48
  import { screenWaitEnded } from "./browser-wait-ended.js";
48
49
  import { durationMs, logLine } from "./print.js";
49
50
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
@@ -65,7 +66,7 @@ import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
65
66
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
66
67
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
67
68
  import { answerOf, logged } from "./agents.js";
68
- import { FINAL_STATES } from "./store/store.js";
69
+ import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
69
70
  import { runModelRef } from "./model.js";
70
71
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
71
72
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
@@ -83,18 +84,21 @@ import { bootSealKey, withSealKey } from "./seal-key.js";
83
84
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
84
85
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
85
86
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
86
- import { agentCostOverStore, agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
87
+ import { agentCostOverStore, agentLearningOverStore, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
88
+ import { figuresOf, LearningBatches } from "./learning-batch.js";
87
89
  import { costCsv, learningCostQuery } from "./learning-cost.js";
90
+ import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
88
91
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
89
92
  import { toolKeysOverStore } from "./tool-keys-store.js";
90
93
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
91
94
  import { signInsOverStore } from "./sign-ins-store.js";
92
- import { MCP_AUTH_TYPES, mcpAuthOf } from "./mcp-probe.js";
95
+ import { MCP_AUTH_TYPES, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
96
+ import { composioSave, composioTools } from "./composio-preset.js";
93
97
  import { mcpServersOverStore } from "./mcp-servers-store.js";
94
98
  import { privateHostsRoute } from "./mcp-private-hosts.js";
95
99
  import { metaToolOf } from "./mcp-meta.js";
96
100
  import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
97
- import { OUTBOUND_WEBHOOK, WEBHOOK_EVENTS, waitMarkerOf, Webhooks } from "./webhooks.js";
101
+ import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
98
102
  import { appPermissionWarnings } from "./template-github-permissions.js";
99
103
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
100
104
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
@@ -102,6 +106,7 @@ import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
102
106
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
103
107
  import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
104
108
  import { GITHUB_API } from "./github.js";
109
+ import { bindingOf, REPO_NAME } from "./run-repo.js";
105
110
  import { HookCut, receivePush } from "./push-handler.js";
106
111
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
107
112
  import { webhook } from "./trigger-webhook.js";
@@ -110,20 +115,23 @@ import { permissionFrom } from "./tool-gate.js";
110
115
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
111
116
  import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
112
117
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
113
- import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
118
+ import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
119
+ import { wakeAnsweredBySetting } from "./settings-wake.js";
114
120
  import { toolSettingsOverStore } from "./tool-settings-store.js";
115
121
  import { readApprovers, writeApprovers } from "./server-approvers.js";
116
122
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
117
123
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
118
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
119
- import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
120
- import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
124
+ import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
125
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
126
+ import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
127
+ import { createAttachRoutes, pairedView } from "./computer-attach.js";
128
+ import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
129
+ import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
121
130
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
122
131
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
123
132
  import { computerOfPlace } from "./computer-setting.js";
124
133
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
125
- import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
126
- import { runComputerField } from "./run-computer.js";
134
+ import { fauxComputers } from "./faux-computers.js";
127
135
  import { writesHeld } from "./workspace.js";
128
136
  import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
129
137
  import { keyReader } from "./key-meta.js";
@@ -232,11 +240,24 @@ export const ROUTES = [
232
240
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
233
241
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
234
242
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
243
+ // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
244
+ // protocol calls, and keeps its computer after its agent's end until released.
245
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/start$/, name: "startRun" },
246
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/call$/, name: "callRunComputer" },
247
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/release$/, name: "releaseRunComputer" },
235
248
  // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
236
249
  // archilRoute): the server switch dispatches them, once the server opens its store.
237
250
  { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
238
251
  { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
239
252
  { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
253
+ { method: "GET", pattern: /^\/computers\/([^/]+)\/choices$/, name: "listComputerChoices" },
254
+ // A person's own computer paired with this server (computer-attach.ts): the owner's code, the driver's trade of it for
255
+ // its token (no token of the server's: the code is the credential), the attach socket (a WebSocket: the server's
256
+ // upgrade takes it; a plain GET is told so), and a computer's removal.
257
+ { method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
258
+ { method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
259
+ { method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
260
+ { method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
240
261
  { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
241
262
  { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
242
263
  { method: "DELETE", pattern: /^\/workspace\/archil$/, name: "deleteWorkspaceArchil" },
@@ -255,8 +276,10 @@ export const ROUTES = [
255
276
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
256
277
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
257
278
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
279
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
258
280
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
259
281
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
282
+ { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
260
283
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
261
284
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
262
285
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -295,6 +318,12 @@ export const ROUTES = [
295
318
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
296
319
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
297
320
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
321
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
322
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
323
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
324
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
325
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
326
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
298
327
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
299
328
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
300
329
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
@@ -302,6 +331,7 @@ export const ROUTES = [
302
331
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
303
332
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
304
333
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
334
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
305
335
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
306
336
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
307
337
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
@@ -660,6 +690,11 @@ async function startHolding(options, data, checked, stops) {
660
690
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
661
691
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
662
692
  stops.push(() => store.close());
693
+ // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
694
+ // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
695
+ // store is refused above (its owner lock).
696
+ const attachHub = new AttachHub();
697
+ const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
663
698
  // The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
664
699
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
665
700
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -820,6 +855,10 @@ async function startHolding(options, data, checked, stops) {
820
855
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
821
856
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
822
857
  const sealKey = seal.key;
858
+ // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
859
+ // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
860
+ const reach = liveReachOf(env, sealKey);
861
+ const answers = (handover) => viewerAnswers(handover, reach);
823
862
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
824
863
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
825
864
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -828,9 +867,9 @@ async function startHolding(options, data, checked, stops) {
828
867
  const browserToolNames = (await import("@parcha/pi-browser")).BROWSER_TOOLS.map((tool) => tool.name);
829
868
  const localTools = new Set(hostToolDefs({ maxExecS: 600, shell: "local" }).map((def) => def.name));
830
869
  const kindTools = (kind) => kind === "none" ? [] : kind === "sandbox" ? hostToolDefs({ maxExecS: 600, shell: "computer" }).map((def) => def.name).filter((name) => !localTools.has(name))
831
- : kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
870
+ : kind === "browser" ? browserToolNames : [...COMPUTER_TOOLS];
832
871
  let faux;
833
- const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
872
+ const fauxOf = () => (faux ??= fauxComputers());
834
873
  /** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
835
874
  * Computers' view and a run's start check (below) both ask it. Where AGENTRUN_BOXES lists Docker and it is no faux
836
875
  * Docker, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
@@ -859,6 +898,7 @@ async function startHolding(options, data, checked, stops) {
859
898
  const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
860
899
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
861
900
  store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
901
+ paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
862
902
  ...(options.faux
863
903
  // --faux's providers stand in for every vendor's, a local one's daemon included.
864
904
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -872,18 +912,29 @@ async function startHolding(options, data, checked, stops) {
872
912
  }));
873
913
  /** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
874
914
  * computerReadiness): over the registry the claim reads (workspace/computer-deps.ts claimKinds, asked with what the
875
- * runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
876
- * now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
915
+ * runner composes with: under --faux, faux's, as runner/main.ts runnerComputers gives its runs' faux; else the
916
+ * package's), in the folder mode of now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
877
917
  * runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
878
918
  * a computer setting, in place of the box check; whether Docker answers here is dockerAnswers', and whether a
879
919
  * provider's program is on this machine is hostWhy's, read at the start. */
880
920
  /** The server's folder mode now: 2 when the owner's Archil settings are saved (the run's folder on the disk), else 1. */
881
921
  const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
882
- const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
922
+ /** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
923
+ const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
924
+ // A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
925
+ // attached to this process's hub.
926
+ const computerReady = async (setting) => {
927
+ const paired = await store.pairedComputers.list();
928
+ const row = paired.find((one) => one.id === setting.provider);
929
+ const offline = row ? pairedRefusal(row, attachHub) : undefined;
930
+ if (offline)
931
+ return { refused: offline };
932
+ return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
933
+ };
883
934
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
884
935
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
885
936
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
886
- const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
937
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
887
938
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
888
939
  * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
889
940
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
@@ -912,16 +963,7 @@ async function startHolding(options, data, checked, stops) {
912
963
  return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
913
964
  };
914
965
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
915
- const runComputerOf = async (runId, view) => {
916
- const run = await store.runs.get(runId);
917
- const body = run ? (await store.agents.revision(run.revisionId))?.body : undefined;
918
- const setting = body?.computer ?? (body?.place ? computerOfPlace(body.place) : undefined);
919
- if (!setting)
920
- return {};
921
- const error = view.error;
922
- const field = runComputerField(setting, { id: runId, status: String(view.status), ...(error && typeof error.code === "string" ? { error: { code: error.code, message: String(error.message ?? "") } } : {}) });
923
- return field ? { computer: field } : {};
924
- };
966
+ const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
925
967
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
926
968
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
927
969
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -951,11 +993,17 @@ async function startHolding(options, data, checked, stops) {
951
993
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
952
994
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
953
995
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
954
- // The outbound webhook and its outbox, in the store; its signing secret among the server's sealed settings, which list it
955
- // (and each one it held before) with the server's own secrets.
956
- const webhooks = new Webhooks(store, triggerSettings.get(OUTBOUND_WEBHOOK.id), (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
957
- await webhooks.load();
996
+ const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
997
+ ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
998
+ privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
999
+ });
1000
+ // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
958
1001
  stops.push(() => webhooks.close());
1002
+ await webhooks.load();
1003
+ // Where an earlier version kept the webhook: no longer read.
1004
+ if (existsSync(join(data, WEBHOOK_FILE)))
1005
+ log?.(logLine("webhook", { condition: "webhook_left_over", file: join(data, WEBHOOK_FILE), effect: "not read: the webhook is kept in the store now; set it again with PUT /v2/settings/webhook" }));
1006
+ secretStores.add("webhook", () => webhooks.signingSecrets());
959
1007
  const uploads = new Uploads(join(data, UPLOADS_DIR));
960
1008
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
961
1009
  // temp file found now is a crashed one's.
@@ -1010,6 +1058,7 @@ async function startHolding(options, data, checked, stops) {
1010
1058
  const modelOf = (_entry, revision) => runModelRef(env, revision);
1011
1059
  const startDeps = {
1012
1060
  runBodyIssues,
1061
+ boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
1013
1062
  pinnedOf,
1014
1063
  inputIssuesOf,
1015
1064
  explainRun,
@@ -1069,6 +1118,59 @@ async function startHolding(options, data, checked, stops) {
1069
1118
  },
1070
1119
  shown: () => secretsShown(serverSecrets(), { local: true }),
1071
1120
  };
1121
+ /** What a learning batch's loop reads of a run, from its view. */
1122
+ const batchRunView = async (runId) => {
1123
+ const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1124
+ if (!v)
1125
+ return undefined;
1126
+ return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1127
+ };
1128
+ // 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
1129
+ // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
1130
+ // (create's answer, read, list, cancel) cut its text as the learning routes do (learningShown, below).
1131
+ const batches = new LearningBatches({
1132
+ settings: store.settings,
1133
+ learning: async (agentId) => {
1134
+ const entry = await needAgent(agentId);
1135
+ if (entry.agent.archivedAt)
1136
+ return { learns: false, why: "it is archived." };
1137
+ if (learning === "off")
1138
+ return { learns: false, why: "this server's learning is off (--learning)." };
1139
+ if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1140
+ return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1141
+ return { learns: true };
1142
+ },
1143
+ // 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
1144
+ // server stopped before its row kept the id is found again, never started twice.
1145
+ find: async (key) => (await agents.request(() => agents.store.runOfOrigin(key)))?.runId,
1146
+ start: async (agentId, body, key) => (await startRunOf(await needAgent(agentId), body, { origin: { key } })).id,
1147
+ view: (runId) => batchRunView(runId),
1148
+ // Sent already: a steer the run's commands hold with these words, not refused (a follow-up to an ended run is one too,
1149
+ // its reopen's).
1150
+ sent: async (runId, content) => (await store.commands(runId, 0)).some((c) => c.kind === "steer" && c.refused === null && c.body?.text === content),
1151
+ message: async (runId, content) => void (await message(store, await needRun(runId), content)),
1152
+ // A run that is not there has nothing to stop; any other failure is the loop's (the row stays live and owned).
1153
+ cancel: async (runId) => {
1154
+ const moment = ID.test(runId) ? await momentOverStore(store, runId, viewDepsFor(ownOriginOf())) : undefined;
1155
+ if (moment)
1156
+ await cancel(store, moment);
1157
+ },
1158
+ figures: async (runId) => {
1159
+ const stored = await store.runs.get(runId);
1160
+ if (!stored)
1161
+ return undefined;
1162
+ // A run still going has no stored cost yet (its column is written at its end): its live cost, from its view, stands in,
1163
+ // so a batch's cost now and the cost it books are costRunOf both.
1164
+ const run = FINAL_STATES.includes(stored.state) ? stored : { ...stored, costUsd: (await batchRunView(runId))?.cost_usd ?? null };
1165
+ // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1166
+ const newest = await store.learning.proposal(runId);
1167
+ const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1168
+ return figuresOf(await costRunOf(store, run, 0), ends);
1169
+ },
1170
+ // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1171
+ shown: (agentId) => learningShown(agentId),
1172
+ ...(options.batchPollMs ? { pollMs: options.batchPollMs } : {}),
1173
+ });
1072
1174
  // A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
1073
1175
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1074
1176
  // request) use the server's public address, else its own.
@@ -1098,7 +1200,7 @@ async function startHolding(options, data, checked, stops) {
1098
1200
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1099
1201
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1100
1202
  context: ctx,
1101
- liveViewer: (runId) => liveViewerLink(store, sealKey, runId),
1203
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers),
1102
1204
  };
1103
1205
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1104
1206
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
@@ -1114,6 +1216,7 @@ async function startHolding(options, data, checked, stops) {
1114
1216
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1115
1217
  });
1116
1218
  const triggerDeps = {
1219
+ ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}),
1117
1220
  start: startDeps,
1118
1221
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1119
1222
  needAgent,
@@ -1145,6 +1248,8 @@ async function startHolding(options, data, checked, stops) {
1145
1248
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1146
1249
  const openSetup = options.openSetup === true && isLoopback(host);
1147
1250
  const owner = options.accounts ? new Owner(data, openSetup, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
1251
+ // With no accounts, the console's sessions: made by the link this start prints, never from the token (page.ts).
1252
+ const consoleSessions = owner ? undefined : new ConsoleSessions();
1148
1253
  // Who a sign-in comes from, for its limit: the socket's peer, or, from a trusted proxy only, the client it forwards for.
1149
1254
  const trusted = (() => {
1150
1255
  if (!options.trustedProxies?.length)
@@ -1247,6 +1352,7 @@ async function startHolding(options, data, checked, stops) {
1247
1352
  stops.push(async () => triggers.close());
1248
1353
  // The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
1249
1354
  // times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
1355
+ void batches.resume().catch((error) => void process.stderr.write(`agentrun-serve: the learning batches' resume: ${error.message}\n`));
1250
1356
  void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
1251
1357
  // The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
1252
1358
  // never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
@@ -1395,7 +1501,24 @@ async function startHolding(options, data, checked, stops) {
1395
1501
  // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1396
1502
  const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1397
1503
  // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1398
- return { tools, gated, deniedBy, ask: { asked, fits: learnedAskFits } };
1504
+ const ask = { asked, fits: learnedAskFits };
1505
+ // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1506
+ // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1507
+ const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1508
+ const providers = await decisionProvidersIn(env);
1509
+ if (!providers)
1510
+ return { tools, gated, deniedBy, ask };
1511
+ const decided = {};
1512
+ const decisionDeniedBy = {};
1513
+ for (const provider of DECISION_PROVIDER_KEYS) {
1514
+ const { permission, from } = gate(provider);
1515
+ if (permission === "allow")
1516
+ continue;
1517
+ decided[provider] = permission;
1518
+ if (permission === "deny")
1519
+ decisionDeniedBy[provider] = from;
1520
+ }
1521
+ return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1399
1522
  }
1400
1523
  async function needAgent(id) {
1401
1524
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1703,9 +1826,10 @@ async function startHolding(options, data, checked, stops) {
1703
1826
  }
1704
1827
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1705
1828
  const unpinned = made.unpinned.map(({ tool, parameters: named }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: `${tool}'s arguments are fixed by ${named.map((one) => `the ${one} parameter`).join(" and ")}, which was not given, so the agent was made with ${tool} set to deny: it can't call it at all. Apply again with ${named.join(" and ")} set to let it.` }));
1706
- // A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
1707
- // MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
1708
- const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
1829
+ // A GitHub tool the package grants that an installation of Connect GitHub's App does not hold the permission for (read
1830
+ // from GitHub, never assumed), where the github MCP server runs on the App's tokens: said now, before a run's first
1831
+ // call is refused; or that the check could not be made (template-github-permissions.ts).
1832
+ const appShort = await appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
1709
1833
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
1710
1834
  const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1711
1835
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
@@ -1907,7 +2031,10 @@ async function startHolding(options, data, checked, stops) {
1907
2031
  }
1908
2032
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
1909
2033
  function runBodyIssues(body) {
1910
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "archil_disk"]);
2034
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "learning", "archil_disk", "repo", "hold", "hold_minutes"]);
2035
+ issues.push(...holdIssues(body));
2036
+ if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2037
+ issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
1911
2038
  if (body.archil_disk !== undefined) {
1912
2039
  const disk = body.archil_disk;
1913
2040
  const extra = isObject(disk) ? Object.keys(disk).filter((key) => key !== "disk_id") : [];
@@ -1928,6 +2055,8 @@ async function startHolding(options, data, checked, stops) {
1928
2055
  issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
1929
2056
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
1930
2057
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2058
+ if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2059
+ issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
1931
2060
  return issues;
1932
2061
  }
1933
2062
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
@@ -2389,6 +2518,10 @@ async function startHolding(options, data, checked, stops) {
2389
2518
  const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, /^\/hooks\/([^/]+)$/.exec(path)[1]);
2390
2519
  return send(res, answer.status, answer.body, answer.headers ?? {});
2391
2520
  }
2521
+ // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
2522
+ // limited by source address before anything in the body is checked.
2523
+ if (found.name === "pairComputer")
2524
+ return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
2392
2525
  // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2393
2526
  // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2394
2527
  if (found.name === "mcpOAuthCallback") {
@@ -2651,7 +2784,7 @@ async function startHolding(options, data, checked, stops) {
2651
2784
  if (content.length > MAX_MESSAGE)
2652
2785
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
2653
2786
  // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
2654
- const { mode, messageId } = await message(store, run, content, seal ? { launchSealed: seal(run.id) } : {});
2787
+ const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal(run.id) } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
2655
2788
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
2656
2789
  const { status, state } = await runStatusState(run.id);
2657
2790
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -2718,18 +2851,24 @@ async function startHolding(options, data, checked, stops) {
2718
2851
  const run = await needRun(id);
2719
2852
  const family = found.name === "getRunBrowser" ? "browser" : "computer";
2720
2853
  // The run's open viewer, from the store's sealed viewer rows the runner publishes its hand-over into (browser-live.ts
2721
- // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store.
2722
- const hold = await computerHoldOf(store, run.id);
2854
+ // liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store,
2855
+ // and where a computer with no viewer is (sessionIn), both over one read of the run's journal.
2856
+ const entries = (await runEntries(store, run.id, ctx));
2857
+ const hold = await computerHoldOf(store, run.id, { entries: async () => entries });
2723
2858
  const kept = await keptBrowserOf(store, run.id);
2859
+ // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
2860
+ // none with its kind, never off as if the agent had none (#2170).
2861
+ const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
2724
2862
  const view = await computerView({
2725
2863
  viewer: async () => {
2726
2864
  if (family === "browser") {
2727
- const link = await liveViewerLink(store, sealKey, run.id);
2865
+ const link = await liveViewerLink(store, sealKey, run.id, answers);
2728
2866
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
2729
2867
  }
2730
- return computerViewerLink(store, sealKey, run.id);
2868
+ return computerViewerLink(store, sealKey, run.id, answers);
2731
2869
  },
2732
- computer: () => computerOf(kept, env, family),
2870
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
2871
+ session: (kind) => sessionIn(kind, entries),
2733
2872
  hold: () => hold,
2734
2873
  // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
2735
2874
  // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
@@ -2770,9 +2909,25 @@ async function startHolding(options, data, checked, stops) {
2770
2909
  }, store, { context: ctx });
2771
2910
  return send(res, 200, answer, { "cache-control": "no-store" });
2772
2911
  }
2912
+ case "startRun":
2913
+ case "callRunComputer":
2914
+ case "releaseRunComputer": {
2915
+ // A call on a run's computer (the computer call channel) and a held computer's start and release
2916
+ // (computer-held-routes.ts), over the store: each a command row the run's runner applies.
2917
+ const run = await needRun(id);
2918
+ return send(res, 200, await heldRoute(found.name, run.id, await bodyOf(req), store, { context: ctx }), { "cache-control": "no-store" });
2919
+ }
2920
+ case "createPairing":
2921
+ return send(res, 201, await attach.createPairing(), { "cache-control": "no-store" });
2922
+ case "attachComputer":
2923
+ throw new ApiError("bad_request", `${ATTACH_PATH} is the attach WebSocket: a paired computer's driver dials it with Upgrade: websocket and its own token`);
2924
+ case "deleteComputer":
2925
+ await attach.remove(id);
2926
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
2773
2927
  case "listComputers":
2774
2928
  case "saveComputerKeys":
2775
- case "testComputer": {
2929
+ case "testComputer":
2930
+ case "listComputerChoices": {
2776
2931
  // Settings → Computers (computers.ts): the rules are the handler's; this sends its answer.
2777
2932
  const provider = found.name === "listComputers" ? undefined : id;
2778
2933
  const body = found.name === "saveComputerKeys" ? await bodyOf(req) : undefined;
@@ -2975,6 +3130,17 @@ async function startHolding(options, data, checked, stops) {
2975
3130
  await refreshMcpMeta();
2976
3131
  return send(res, 200, saved);
2977
3132
  }
3133
+ // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
3134
+ case "listComposioTools":
3135
+ return send(res, 200, await composioTools(await bodyOf(req), options.composioControl ?? {}, stopping.signal), { "cache-control": "no-store" });
3136
+ case "saveComposioServer": {
3137
+ // The name is checked before Composio is called: a refused name leaves nothing made there.
3138
+ mcpNameOf(id);
3139
+ const body = await bodyOf(req);
3140
+ const answer = await composioSave(body, options.composioControl ?? {}, (mcp) => mcpServers.save(id, mcp, stopping.signal), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3141
+ await refreshMcpMeta();
3142
+ return send(res, 200, answer, { "cache-control": "no-store" });
3143
+ }
2978
3144
  case "refreshMcpServer": {
2979
3145
  const refreshed = await mcpServers.refresh(id, stopping.signal);
2980
3146
  await refreshMcpMeta();
@@ -3032,9 +3198,15 @@ async function startHolding(options, data, checked, stops) {
3032
3198
  const issues = settingsIssues(body);
3033
3199
  if (issues.length)
3034
3200
  throw invalid(issues);
3201
+ const before = settings.get();
3035
3202
  await settings.put(body);
3036
3203
  // A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
3037
3204
  recompose();
3205
+ // A run parked on a call whose tool reads allow now, on its pinned revision: woken, so its next claim's gate answers
3206
+ // the ask by the setting (settings-wake.ts), before this answer. The settings as the runner's gate reads them.
3207
+ const woken = await wakeAnsweredBySetting(store, await loadToolSettings(store), before);
3208
+ if (woken.length)
3209
+ log?.(logLine("tool_settings", { condition: "runs_woken", runs: woken.join(",") }));
3038
3210
  return send(res, 200, withDefaults(settings.get()));
3039
3211
  }
3040
3212
  // A person's view and control of what an agent learned (learning-routes.ts). Every text cut of the host's secrets as
@@ -3062,6 +3234,36 @@ async function startHolding(options, data, checked, stops) {
3062
3234
  }
3063
3235
  return send(res, 200, { agent: id, ...cost });
3064
3236
  }
3237
+ case "createLearningBatch": {
3238
+ await needAgent(id);
3239
+ const made = await batches.create(id, await bodyOf(req));
3240
+ return send(res, 202, await batches.read(id, made.id), { location: `/v2/agents/${encodeURIComponent(id)}/learning/batches/${made.id}` });
3241
+ }
3242
+ case "listLearningBatches":
3243
+ await needAgent(id);
3244
+ return send(res, 200, await batches.list(id));
3245
+ case "getLearningBatch":
3246
+ await needAgent(id);
3247
+ return send(res, 200, await batches.read(id, second));
3248
+ case "cancelLearningBatch":
3249
+ await needAgent(id);
3250
+ return send(res, 200, await batches.cancel(id, second));
3251
+ case "listLearningEvals": {
3252
+ await needAgent(id);
3253
+ // The agent's eval records (learning-evals.ts), newest first, the latest the one shown: only ever what was posted.
3254
+ const evals = await evalsOf(store, id);
3255
+ return send(res, 200, { agent: id, latest: evals[0] ?? null, evals });
3256
+ }
3257
+ case "recordLearningEval": {
3258
+ const body = await bodyOf(req);
3259
+ await needAgent(id);
3260
+ const answer = await idempotent(req, `/agents/${id}/learning/evals`, body, async () => {
3261
+ const result = evalOf(body, new Date());
3262
+ await recordEval(store, id, result);
3263
+ return { status: 201, body: result };
3264
+ });
3265
+ return send(res, answer.status, answer.body, answer.headers);
3266
+ }
3065
3267
  case "listLearningNotes":
3066
3268
  case "listLearningLog":
3067
3269
  await needAgent(id);
@@ -3071,6 +3273,9 @@ async function startHolding(options, data, checked, stops) {
3071
3273
  return send(res, 200, await learningNotes(data, id, url.searchParams, await learningShown(id), notes));
3072
3274
  }
3073
3275
  return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
3276
+ case "listLearnedWorkflowRevisions":
3277
+ await needAgent(id);
3278
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
3074
3279
  case "readLearningFile":
3075
3280
  await needAgent(id);
3076
3281
  return sendNote(res, 200, await readNote(data, id, second, await learningShown(id)));
@@ -3127,7 +3332,7 @@ async function startHolding(options, data, checked, stops) {
3127
3332
  case "testWebhook":
3128
3333
  return send(res, 200, await webhooks.test());
3129
3334
  case "listWebhookDeliveries":
3130
- return send(res, 200, webhooks.attemptsView());
3335
+ return send(res, 200, await webhooks.attemptsView());
3131
3336
  case "redeliverWebhook":
3132
3337
  return send(res, 200, await webhooks.redeliver(id));
3133
3338
  case "listTriggers":
@@ -3140,7 +3345,8 @@ async function startHolding(options, data, checked, stops) {
3140
3345
  const answer = await idempotent(req, "/triggers", body, async () => {
3141
3346
  const { secret: shown, ...made } = await triggers.create(body);
3142
3347
  secret = shown;
3143
- return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : made, headers: { location: `/v2/triggers/${made.id}` } };
3348
+ // A secret the sender gave is not shown: the trigger answers its metadata, as a read does.
3349
+ return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : withSecretOf(made), headers: { location: `/v2/triggers/${made.id}` } };
3144
3350
  });
3145
3351
  const replayed = answer.headers?.["idempotent-replayed"] === "true";
3146
3352
  const { note: _, ...first } = answer.body;
@@ -3181,11 +3387,20 @@ async function startHolding(options, data, checked, stops) {
3181
3387
  }
3182
3388
  case "rotateTriggerSecret":
3183
3389
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
3184
- return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3390
+ // A trigger whose sender gives its secret (Composio's) takes it as the body's `secret`; any other is made one.
3391
+ return send(res, 200, await (async () => {
3392
+ const empty = req.headers["transfer-encoding"] === undefined && !Number(req.headers["content-length"]);
3393
+ const body = empty ? {} : await bodyOf(req);
3394
+ const extra = Object.keys(body).filter((key) => key !== "secret");
3395
+ if (extra.length)
3396
+ throw invalid(extra.map((field) => ({ field, reason: "unknown_field", message: `${field} is not a field of this request: only secret` })));
3397
+ return triggerRotated(id, (await triggers.rotate(id, body.secret)).secret, new Date().toISOString());
3398
+ })());
3185
3399
  case "getTrigger":
3186
3400
  return send(res, 200, withSecretOf(await triggers.get(id)));
3187
3401
  case "updateTrigger":
3188
- return send(res, 200, await triggers.update(id, await bodyOf(req)));
3402
+ // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3403
+ return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3189
3404
  case "deleteTrigger":
3190
3405
  await triggers.remove(id);
3191
3406
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -3225,7 +3440,8 @@ async function startHolding(options, data, checked, stops) {
3225
3440
  const handover = await liveViewerFor(store, sealKey, runId, rest);
3226
3441
  if (handover === undefined || !familyReaches(family, handover))
3227
3442
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
3228
- await serveViewerFile(req, res, rest);
3443
+ // A desktop's or a phone's viewer gets the computer viewer's page (computer-viewer.ts), a browser's pi-browser's.
3444
+ await serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
3229
3445
  }
3230
3446
  /** The origin of the address people open (`publicUrl`, AGENTRUN_PUBLIC_URL), lowercased; none, undefined. */
3231
3447
  const publicOrigin = (() => {
@@ -3286,17 +3502,8 @@ async function startHolding(options, data, checked, stops) {
3286
3502
  return void mcp(req, res).catch(fail);
3287
3503
  if (raw === "/llms.txt")
3288
3504
  return void answerLlms(req, res).catch(fail);
3289
- if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3290
- return;
3291
- // Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
3292
- // a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
3293
- if (options.faux && raw.startsWith(`${FAUX_VIEW_PATH}/`)) {
3294
- const page = fauxOf().viewPage(raw);
3295
- if (page === undefined)
3296
- return fail(new ApiError("not_found", `no faux desktop at ${raw}`));
3297
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(req.method === "HEAD" ? undefined : page);
3505
+ if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3298
3506
  return;
3299
- }
3300
3507
  if (!raw.startsWith("/v2/"))
3301
3508
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3302
3509
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -3321,9 +3528,18 @@ async function startHolding(options, data, checked, stops) {
3321
3528
  // away. Its name alone, on any port, as the HTTP routes check it.
3322
3529
  if (names && !names.has(hostName(req.headers.host) ?? ""))
3323
3530
  return deny("403 Forbidden");
3324
- // API-only: a run's live view is the console's, and refused with it.
3531
+ // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings).
3325
3532
  if (options.apiOnly)
3326
3533
  return deny("404 Not Found");
3534
+ // A paired computer's driver dialing its attach socket (computer-attach.ts): its token, not the owner's, lets it in.
3535
+ if (raw === ATTACH_PATH) {
3536
+ return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
3537
+ if (status.startsWith("401"))
3538
+ authFailed(raw, "attach_token");
3539
+ const lines = Object.entries({ ...headers, "content-type": "text/plain; charset=utf-8", "content-length": String(Buffer.byteLength(words)) }).map(([name, value]) => `${name}: ${value}\r\n`).join("");
3540
+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n${lines}\r\n${words}`);
3541
+ });
3542
+ }
3327
3543
  if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3328
3544
  return deny("404 Not Found");
3329
3545
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
@@ -3354,7 +3570,7 @@ async function startHolding(options, data, checked, stops) {
3354
3570
  if (!admitted())
3355
3571
  return deny("401 Unauthorized");
3356
3572
  viewers.watch(socket, admitted);
3357
- proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; });
3573
+ proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
3358
3574
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
3359
3575
  });
3360
3576
  const first = options.port ?? DEFAULT_PORT;
@@ -3397,16 +3613,19 @@ async function startHolding(options, data, checked, stops) {
3397
3613
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
3398
3614
  owner?.attach(options.publicUrl ?? url);
3399
3615
  webhooks.attach(options.publicUrl ?? url);
3400
- mcpServers.attach(options.publicUrl ?? url, url);
3616
+ // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
3617
+ // other services: mcp-oauth.ts mcpServerAt), and only as its operator says (mcpLoopback), never inferred from where it
3618
+ // listens: a hosted container listens on loopback behind its proxy too.
3619
+ const localInstall = options.mcpLoopback === true;
3620
+ mcpServers.attach(options.publicUrl ?? url, url, localInstall);
3401
3621
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
3402
- // to the store and this server runs no run, so it follows the store: each read takes the runs not final yet and the
3403
- // newest runs (one that started and ended between two reads is among them). It tells each end it has not told once the
3404
- // run reads final, and each wait of a run a runner left parked (or let go of) once it reads input_required. The markers
3405
- // are main's (an end's time, a wait's last row), so each webhook-id is the one it always had, and the ledger tells each
3406
- // once across restarts; a start first catches up the ends the ledger lacks, which no server was up to see. A store read
3407
- // of the runs ended (or parked) since a mark would be the cleaner seam than this read of the open runs every 250 ms.
3408
- const RUN_ENDS_POLL_MS = 250;
3409
- const RUN_ENDS_NEWEST = 50;
3622
+ // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
3623
+ // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
3624
+ // kept in this process. It tells each end once the run reads final, and each wait of a run let go once it reads
3625
+ // input_required. The markers are an end's time and a wait's ask (webhooks.ts waitMarkerOf), so each webhook-id is the
3626
+ // same on every read, and the ledger tells each once across restarts. The feed is read every 250 ms; a store that woke its readers on a
3627
+ // change would be the next seam.
3628
+ const RUN_CHANGES_POLL_MS = 250;
3410
3629
  const final = (row) => FINAL_STATES.includes(row.state);
3411
3630
  const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
3412
3631
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
@@ -3436,82 +3655,203 @@ async function startHolding(options, data, checked, stops) {
3436
3655
  const HELD_WAIT_REREAD_MS = 1_000;
3437
3656
  const waitKinds = new Set(["question", "approval", "budget", "browser"]);
3438
3657
  /** The wait of a run its runner left parked (or let go of), or holds in its claim, told once per ask: its marker the
3439
- * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). */
3658
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). False when it
3659
+ * is not done (a read that failed, or its notice not saved): it is read again. */
3440
3660
  const tellWait = async (row) => {
3441
3661
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
3442
3662
  if (readWaits.get(row.id) === seen)
3443
- return;
3663
+ return true;
3444
3664
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
3445
3665
  if (view?.status !== "input_required")
3446
- return void readWaits.set(row.id, seen);
3666
+ return (readWaits.set(row.id, seen), true);
3447
3667
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3448
3668
  // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3449
3669
  const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3450
3670
  if (!marker)
3451
- return void readWaits.set(row.id, seen);
3671
+ return (readWaits.set(row.id, seen), true);
3452
3672
  const card = view.pending?.kind;
3453
3673
  const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3454
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
3455
- if ((await webhooks.emit("run.needs_input", notice, marker)) !== "unsaved")
3456
- readWaits.set(row.id, seen);
3674
+ const wait = { kind };
3675
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: wait };
3676
+ if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3677
+ return false;
3678
+ readWaits.set(row.id, seen);
3679
+ return true;
3457
3680
  };
3458
- let openRuns = new Set();
3459
- let endsTimer;
3460
- let endsRead = Promise.resolve();
3461
- const readEnds = async () => {
3462
- const open = new Set();
3463
- for (const state of ["queued", "running", "parked"]) {
3464
- for (const row of await store.runs.list({ state })) {
3465
- open.add(row.id);
3466
- // A run waits on its person once its runner has let it go: parked, or running with no runner. Or held in its claim
3467
- // waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its browser hand-over,
3468
- // tools.ts), which its row's summary says (HELD_WAITS); a new ask sets it anew, so each is read and told once.
3469
- const waitsInClaim = row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3470
- // A held run's next ask in the same claim reads the same row as its last (state, epoch, runner, summary), and the
3471
- // answer between may come and go within one read: so a held wait is read again now and then (HELD_WAIT_REREAD_MS),
3472
- // and told once per ask all the same, since each ask's notice is keyed to its own last row (webhooks.ts emit).
3473
- if (waitsInClaim && Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3474
- heldReadAt.set(row.id, Date.now());
3475
- readWaits.delete(row.id);
3476
- }
3477
- if (!closing && (row.state === "parked" || (row.state === "running" && row.runner === null) || waitsInClaim))
3478
- await tellWait(row).catch(() => undefined);
3681
+ /** Who hears of each run's end and each wait the follower reads (runNotices): the outbound webhook first. Each is called
3682
+ * once a run reads final (onEnded) or is let go waiting on a person (onWaits), and again on a later read while any of
3683
+ * them threw (said once, run_notice_unread): so at least once, and the same moment always comes with the same `marker`
3684
+ * (an end's time, a wait's ask), on which each dedupes in a ledger of its own. An end from while no server was up
3685
+ * reaches the webhook alone, through its own catch-up (webhooks.ts catchUp). */
3686
+ const endedSubscribers = [];
3687
+ const waitSubscribers = [];
3688
+ const runNotices = {
3689
+ onEnded: (tell) => void endedSubscribers.push(tell),
3690
+ onWaits: (tell) => void waitSubscribers.push(tell),
3691
+ };
3692
+ runNotices.onEnded(async (run, marker) => {
3693
+ if ((await webhooks.emit("run.ended", run, marker)) === "unsaved")
3694
+ throw new Error("its run.ended is not saved yet");
3695
+ });
3696
+ runNotices.onWaits(async (run, _wait, marker) => {
3697
+ if ((await webhooks.emit("run.needs_input", run, marker)) === "unsaved")
3698
+ throw new Error("its run.needs_input is not saved yet");
3699
+ });
3700
+ /** Every call of `calls` made: false when one threw (said once for the run), so the run is told again. */
3701
+ const toldAll = async (id, calls) => {
3702
+ let done = true;
3703
+ for (const call of calls) {
3704
+ try {
3705
+ await call();
3706
+ }
3707
+ catch (error) {
3708
+ sayUnread(id, error.message);
3709
+ done = false;
3479
3710
  }
3480
3711
  }
3481
- const newest = await store.runs.list({ limit: RUN_ENDS_NEWEST });
3482
- for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
3483
- if (open.has(id) || closing)
3484
- continue;
3485
- const now = await endToTell(id).catch(() => undefined);
3486
- // Unread (a busy store): read again at the next turn, never lost.
3487
- if (now === undefined) {
3488
- open.add(id);
3712
+ return done;
3713
+ };
3714
+ /** Why a run's notice is not done yet, said once for the run (until it is done): one that stays undone shows. */
3715
+ const unreadSaid = new Set();
3716
+ const sayUnread = (id, error) => {
3717
+ if (unreadSaid.has(id))
3718
+ return;
3719
+ unreadSaid.add(id);
3720
+ log?.(logLine("webhook", { condition: "run_notice_unread", run: id, error }));
3721
+ };
3722
+ /** A run's end, told once the run reads final. False when it is not done (a read that failed, or its notice not saved). */
3723
+ const tellEnd = async (id) => {
3724
+ const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
3725
+ if (now === undefined)
3726
+ return false;
3727
+ readWaits.delete(id);
3728
+ heldReadAt.delete(id);
3729
+ if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
3730
+ return (unreadSaid.delete(id), true);
3731
+ if (!(await toldAll(id, endedSubscribers.map((tell) => () => tell(now.notice, now.endedAt)))))
3732
+ return false;
3733
+ toldEnds.set(id, now.endedAt);
3734
+ unreadSaid.delete(id);
3735
+ return true;
3736
+ };
3737
+ /** A run's row as the store holds it now: undefined when there is no such run, UNREAD when the read failed. */
3738
+ const UNREAD = Symbol("unread");
3739
+ const rowNow = (id) => store.runs.get(id).catch(() => UNREAD);
3740
+ /** A run held in its claim waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its
3741
+ * browser hand-over, tools.ts), which its row's summary says (HELD_WAITS). Its row's state and runner do not move, so
3742
+ * the feed has no change for it: each read looks for these among the running runs. */
3743
+ const heldWait = (row) => row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
3744
+ /** A run waiting on its person: let go by its runner (parked, or running with none), or held in its claim (heldWait). */
3745
+ const letGo = (row) => row.state === "parked" || (row.state === "running" && row.runner === null) || heldWait(row);
3746
+ /** One change of the feed, handled: an end told, a wait told, or nothing to tell. One not done goes to endsLeft or
3747
+ * waitsLeft, by its run, which each read tries first until it is: a run that stays undone holds back no other. A wait is
3748
+ * read from the run as it is now (a run gone since, or moved on, has none to tell). */
3749
+ const handle = async (change) => {
3750
+ if (final(change)) {
3751
+ if (!(await tellEnd(change.id)))
3752
+ endsLeft.add(change.id);
3753
+ return;
3754
+ }
3755
+ if (change.state === "parked" || (change.state === "running" && change.runner === null)) {
3756
+ if (!(await tellLetGo(change.id)))
3757
+ waitsLeft.add(change.id);
3758
+ }
3759
+ };
3760
+ /** The wait of run `id` if it is let go now: false when not done (its read failed, or its wait not told). */
3761
+ const tellLetGo = async (id) => {
3762
+ const row = await rowNow(id);
3763
+ if (row === UNREAD)
3764
+ return (sayUnread(id, "its row could not be read"), false);
3765
+ if (row === undefined || !letGo(row))
3766
+ return true;
3767
+ const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
3768
+ if (told)
3769
+ unreadSaid.delete(id);
3770
+ return told;
3771
+ };
3772
+ /** Where the feed is read on from: past each page once its changes are handled, each told or left in endsLeft or
3773
+ * waitsLeft. None is dropped (a run left is tried again on each read), none is skipped, and none is read twice. */
3774
+ let changesCursor;
3775
+ /** The runs whose end, or whose wait, is not told yet (a read that failed, or a notice not saved): from the feed, or from
3776
+ * the start. Each read tries them first, until each is done. */
3777
+ const endsLeft = new Set();
3778
+ const waitsLeft = new Set();
3779
+ const readChanges = async () => {
3780
+ for (const id of [...endsLeft]) {
3781
+ if (closing)
3782
+ return;
3783
+ if (await tellEnd(id))
3784
+ endsLeft.delete(id);
3785
+ }
3786
+ for (const id of [...waitsLeft]) {
3787
+ if (closing)
3788
+ return;
3789
+ if (await tellLetGo(id))
3790
+ waitsLeft.delete(id);
3791
+ }
3792
+ for (;;) {
3793
+ if (closing)
3794
+ return;
3795
+ const page = await store.runs.changedSince(changesCursor, { limit: RUN_CHANGES_PAGE });
3796
+ for (const change of page.changes)
3797
+ await handle(change);
3798
+ changesCursor = page.next;
3799
+ if (page.changes.length < RUN_CHANGES_PAGE)
3800
+ break;
3801
+ }
3802
+ // The held waits, which the feed has no change for. A held run's next ask in the same claim reads the same row as its
3803
+ // last (state, epoch, runner, summary), and the answer between may come and go within one read: so a held wait is read
3804
+ // again now and then (HELD_WAIT_REREAD_MS), and told once per ask all the same, each ask's notice keyed to the ask
3805
+ // itself (webhooks.ts waitMarkerOf), never to the row that shows last.
3806
+ for (const row of await store.runs.list({ state: "running" })) {
3807
+ if (closing)
3808
+ return;
3809
+ if (!heldWait(row))
3489
3810
  continue;
3811
+ if (Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
3812
+ heldReadAt.set(row.id, Date.now());
3813
+ readWaits.delete(row.id);
3490
3814
  }
3491
- readWaits.delete(id);
3492
- heldReadAt.delete(id);
3493
- if (!now?.endedAt || !("notice" in now) || toldEnds.get(id) === now.endedAt)
3494
- continue;
3495
- if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
3496
- toldEnds.set(id, now.endedAt);
3815
+ if (!(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
3816
+ waitsLeft.add(row.id);
3497
3817
  }
3498
- openRuns = open;
3499
3818
  };
3500
- const followEnds = () => {
3819
+ let endsTimer;
3820
+ let endsRead = Promise.resolve();
3821
+ /** Whether the start (startFollowing) is done: until it is, each turn runs it again before it reads the feed, so the ends
3822
+ * and waits from while no server was up are told whatever failed it. Said once. */
3823
+ let started = false;
3824
+ let startSaid = false;
3825
+ const followChanges = () => {
3501
3826
  if (closing)
3502
3827
  return;
3503
- endsRead = readEnds()
3504
- .catch((error) => log?.(logLine("webhook", { condition: "run_ends_unread", error: error.message })))
3828
+ const turn = started
3829
+ ? readChanges()
3830
+ : startFollowing().then(() => ((started = true), readChanges()), (error) => void (startSaid || ((startSaid = true), log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))));
3831
+ endsRead = turn
3832
+ .catch((error) => log?.(logLine("webhook", { condition: "run_changes_unread", error: error.message })))
3505
3833
  .finally(() => {
3506
3834
  if (!closing)
3507
- (endsTimer = setTimeout(followEnds, RUN_ENDS_POLL_MS)).unref();
3835
+ (endsTimer = setTimeout(followChanges, RUN_CHANGES_POLL_MS)).unref();
3508
3836
  });
3509
3837
  };
3510
- void store.runs
3511
- .list({})
3512
- .then((rows) => webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), endNotice))
3513
- .catch((error) => log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))
3514
- .finally(followEnds);
3838
+ /** The start, in this order, so no change is lost between its steps: the feed's head first (one read, untold),
3839
+ * then what the store holds now (the ends the ledger lacks, webhooks.ts catchUp, and the waits of the runs let go: the
3840
+ * feed has none from before its table, and none from a time no server read it), then the feed from that head. A change
3841
+ * after the head is read by the feed even when the store's rows already showed it, and the ledger tells it once. */
3842
+ const startFollowing = async () => {
3843
+ changesCursor = await store.runs.changesHead();
3844
+ const rows = await store.runs.list({});
3845
+ // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
3846
+ // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
3847
+ const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
3848
+ for (const id of unsaved)
3849
+ endsLeft.add(id);
3850
+ for (const row of rows)
3851
+ if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
3852
+ waitsLeft.add(row.id);
3853
+ };
3854
+ followChanges();
3515
3855
  const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
3516
3856
  /** The server's stop: once (`close` keeps its promise). */
3517
3857
  let stopped;
@@ -3542,9 +3882,12 @@ async function startHolding(options, data, checked, stops) {
3542
3882
  // The ends' follower stops before the webhooks it feeds and the store it reads.
3543
3883
  clearTimeout(endsTimer);
3544
3884
  await endsRead;
3885
+ // A learning batch's loop ends where it stands, still running: it takes up when a server starts on this data again.
3886
+ await batches.halt();
3545
3887
  await webhooks.close();
3546
3888
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
3547
3889
  viewers.close();
3890
+ await attach.close();
3548
3891
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
3549
3892
  await mcpStopped;
3550
3893
  await githubStopped;
@@ -3563,7 +3906,10 @@ async function startHolding(options, data, checked, stops) {
3563
3906
  tokenFile,
3564
3907
  tokenMade: stored?.made ?? false,
3565
3908
  ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
3909
+ ...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
3566
3910
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
3911
+ attachHub,
3912
+ localInstall,
3567
3913
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
3568
3914
  // never writes this data root's record again (the next server's, by then).
3569
3915
  close: () => (stopped ??= stop()),