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

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
package/dist/server.js CHANGED
@@ -1,13 +1,11 @@
1
1
  import { maintainObservations, Observations } from './observation/observer.js';
2
2
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
3
  import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
4
- import { askRouteOf } from "./runner/sdk-ask.js";
5
- import { PI_WIRES } from "./runner/adapter-run-spec.js";
6
- import { routeOf as sdkModelRoute } from "./runner/model-route.js";
4
+ import { learningModelOf } from "./learning-model.js";
7
5
  import { answerSkill } from './skill-route.js';
8
6
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
9
7
  import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
10
- import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED } from "./native/binding.js";
8
+ import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED, NATIVE_CAP_UNSUPPORTED } from "./native/binding.js";
11
9
  import { discoverNative } from "./native/discovery.js";
12
10
  import { isNativeRuntime } from "./native/runtimes.js";
13
11
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
@@ -18,13 +16,14 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from
18
16
  import { createServer } from "node:http";
19
17
  import proxyaddr from "proxy-addr";
20
18
  import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
19
+ import { carriedFields } from "./answer-json.js";
21
20
  import { dirname, join, relative, resolve, sep } from "node:path";
22
21
  import { pathToFileURL } from "node:url";
23
22
  import { Worker } from "node:worker_threads";
24
23
  import { once } from "node:events";
25
24
  import { existsSync } from "node:fs";
26
25
  import { rm } from "node:fs/promises";
27
- import { homedir } from "node:os";
26
+ import { homedir, hostname } from "node:os";
28
27
  import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
29
28
  import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
30
29
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
@@ -43,7 +42,7 @@ import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harn
43
42
  import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, tableIds } from "./harness-table.js";
44
43
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
45
44
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
46
- import { DEFAULT_HOST, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
45
+ import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
47
46
  import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
48
47
  import { answerStoreCall } from "./import-proxy.js";
49
48
  import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
@@ -56,8 +55,9 @@ import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
56
55
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
57
56
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
58
57
  import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
59
- import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
60
- import { hostFix, hostName, loopbackNames } from "./host-check.js";
58
+ import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
59
+ import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
60
+ import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
61
61
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
62
62
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
63
63
  import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
@@ -65,8 +65,10 @@ import { readKept } from "./workspace/computer-kept.js";
65
65
  import { dialHost, liveReachOf, reachForRun } from "./live-reach.js";
66
66
  import { screenWaitEnded } from "./browser-wait-ended.js";
67
67
  import { durationMs, logLine } from "./print.js";
68
+ import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
68
69
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
69
- import { cutOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
70
+ import { builtOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
71
+ import { healEndedCosts } from "./cost-heal.js";
70
72
  import { createLister } from "./run-listing.js";
71
73
  import { HELD_WAITS } from "./runner/journal-kinds.js";
72
74
  import { servedTimelineRows } from "./run-timeline-served.js";
@@ -108,13 +110,15 @@ import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addre
108
110
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
109
111
  import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
110
112
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
111
- import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
113
+ import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
112
114
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
115
+ import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
113
116
  import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
114
117
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
115
118
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
116
119
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
117
120
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
121
+ import { joinedBasis } from "./runner/metrics.js";
118
122
  import { agentLoopOverStore } from "./store-reads/loop.js";
119
123
  import { printable } from "./learn/index.js";
120
124
  import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
@@ -124,17 +128,20 @@ import { toolKeysOverStore } from "./tool-keys-store.js";
124
128
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
125
129
  import { signInsOverStore } from "./sign-ins-store.js";
126
130
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
127
- import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
131
+ import { composioMadeKey, composioPerRun } from "./composio-made.js";
132
+ import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
128
133
  import { ComposioTriggers } from "./composio-triggers.js";
129
134
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
135
+ import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
130
136
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
131
137
  import { privateHostsRoute, saveServerOwn } from "./mcp-private-hosts.js";
132
138
  import { metaToolOf } from "./mcp-meta.js";
133
139
  import { mcpPinOf } from "./mcp-gateway.js";
134
140
  import { LOOPBACK, MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
135
141
  import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
142
+ import { SLACK_EVENTS, SlackPosts } from "./slack.js";
136
143
  import { appPermissionWarnings } from "./template-github-permissions.js";
137
- import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
144
+ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
138
145
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
139
146
  import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
140
147
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
@@ -165,8 +172,10 @@ import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
165
172
  import { recordingsFolder } from "./workspace/paths.js";
166
173
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
167
174
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
175
+ import { runOver } from "./computer-commands.js";
176
+ import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf, viewerExpiry } from "./viewer-credential.js";
168
177
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
169
- import { createAttachRoutes, pairedView, RELAY_STALE_MS } from "./computer-attach.js";
178
+ import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
170
179
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
171
180
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
172
181
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -204,6 +213,8 @@ const IMPORT_STARTS = 3;
204
213
  const IMPORT_HEAP_MB = 2048;
205
214
  const MAX_MESSAGE = 20_000;
206
215
  const MAX_WAIT_MS = 25_000;
216
+ /** How often the server fails the runs still queued while no runner here can take them (runner/presence.ts). */
217
+ const REFUSED_SWEEP_MS = 2_000;
207
218
  const PAGE_ROWS = 500;
208
219
  const FILE_LIST_CAP = 2_000;
209
220
  /** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
@@ -326,6 +337,8 @@ export const ROUTES = [
326
337
  // store-backed take-over lands). The run routes stay together.
327
338
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
328
339
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
340
+ // An API-only server's viewer credential for a run's live view (viewer-credential.ts), minted for its backend.
341
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/viewer$/, name: "createRunComputerViewer" },
329
342
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
330
343
  // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
331
344
  // protocol calls, and keeps its computer after its agent's end until released.
@@ -382,6 +395,11 @@ export const ROUTES = [
382
395
  { method: "PUT", pattern: /^\/settings\/claude-login$/, name: "turnOnClaudeLogin" },
383
396
  { method: "DELETE", pattern: /^\/settings\/claude-login$/, name: "turnOffClaudeLogin" },
384
397
  { method: "POST", pattern: /^\/settings\/claude-login\/login$/, name: "startClaudeLogin" },
398
+ // The model gateway saved in the console (model-gateway.ts): its save, removal and test the owner's session's alone.
399
+ { method: "GET", pattern: /^\/settings\/model-gateway$/, name: "getModelGateway" },
400
+ { method: "PUT", pattern: /^\/settings\/model-gateway$/, name: "saveModelGateway" },
401
+ { method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
402
+ { method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
385
403
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
386
404
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
387
405
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
@@ -408,9 +426,16 @@ export const ROUTES = [
408
426
  { method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
409
427
  { method: "PUT", pattern: /^\/settings\/webhook$/, name: "saveWebhook" },
410
428
  { method: "DELETE", pattern: /^\/settings\/webhook$/, name: "deleteWebhook" },
429
+ { method: "POST", pattern: /^\/settings\/webhook\/secret$/, name: "rotateWebhookSecret" },
411
430
  { method: "POST", pattern: /^\/settings\/webhook\/test$/, name: "testWebhook" },
412
431
  { method: "GET", pattern: /^\/settings\/webhook\/deliveries$/, name: "listWebhookDeliveries" },
413
432
  { method: "POST", pattern: /^\/settings\/webhook\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverWebhook" },
433
+ { method: "GET", pattern: /^\/settings\/slack$/, name: "getSlack" },
434
+ { method: "PUT", pattern: /^\/settings\/slack$/, name: "saveSlack" },
435
+ { method: "DELETE", pattern: /^\/settings\/slack$/, name: "deleteSlack" },
436
+ { method: "POST", pattern: /^\/settings\/slack\/test$/, name: "testSlack" },
437
+ { method: "GET", pattern: /^\/settings\/slack\/deliveries$/, name: "listSlackDeliveries" },
438
+ { method: "POST", pattern: /^\/settings\/slack\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverSlack" },
414
439
  { method: "GET", pattern: /^\/triggers$/, name: "listTriggers" },
415
440
  { method: "POST", pattern: /^\/triggers$/, name: "createTrigger" },
416
441
  { method: "GET", pattern: /^\/triggers\/([^/]+)$/, name: "getTrigger" },
@@ -518,10 +543,13 @@ export function offersEnvOf(env) {
518
543
  delete descriptors[name];
519
544
  return Object.defineProperties({}, descriptors);
520
545
  }
546
+ /** The model gateway's variables, which a gateway saved in the console sets (model-gateway.ts withSavedGateway): which
547
+ * harnesses run, and on what, follow them. */
548
+ const GATEWAY_VARS = ["AGENT_MODEL_BASE_URL", "AGENT_MODEL_GATEWAY_IDS", "AGENT_MODEL", "AGENT_MODEL_FAST", "AGENT_MODEL_STRONG"];
521
549
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
522
550
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
523
551
  * the offers probed again, never shown. */
524
- const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" "), claudeLoginOf(env)?.dir];
552
+ const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), ...GATEWAY_VARS.map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" "), claudeLoginOf(env)?.dir];
525
553
  /** A sign-in step's answer; its refusal (a stale or bad pasted address, no sign-in waiting, OpenAI's no) a 400 in words. */
526
554
  async function planStep(step) {
527
555
  try {
@@ -535,9 +563,10 @@ async function planStep(step) {
535
563
  }
536
564
  async function needsOf(env) {
537
565
  const chosen = await chooseModel(env, undefined);
566
+ const learning_model = await learningModelOf(env);
538
567
  if ("why" in chosen)
539
- return { needs: chosen.needs, priced: null };
540
- return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0 };
568
+ return { needs: chosen.needs, priced: null, learning_model };
569
+ return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0, learning_model };
541
570
  }
542
571
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
543
572
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
@@ -558,6 +587,11 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
558
587
  export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = []) {
559
588
  return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes);
560
589
  }
590
+ /** Those switches as `env` sets them, the CLI's way, for a server whose options name neither. */
591
+ const switchedOnBy = (env, options = {}) => ({
592
+ mcpLoopback: options.mcpLoopback ?? env[MCP_ALLOW_LOOPBACK_ENV] === "1",
593
+ webhookPrivateTargets: options.webhookPrivateTargets ?? env[WEBHOOK_PRIVATE_TARGETS_ENV] === "1",
594
+ });
561
595
  /** The capabilities document as `req`'s caller reads it: approving takes the owner's password session alone, so only
562
596
  * that caller reads `approve: true`; every other (a token, a run, accounts off) reads `approve_needs: "password"`. */
563
597
  export function forCaller(caps, ownerSession) {
@@ -566,8 +600,9 @@ export function forCaller(caps, ownerSession) {
566
600
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
567
601
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
568
602
  * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
569
- * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. */
570
- function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process") {
603
+ * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. `switched`: the two
604
+ * start-time switches the server takes as options (switchedOnBy reads them from `env`, as the CLI sets them). */
605
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, learning_model }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
571
606
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
572
607
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
573
608
  const memory = hostMemory();
@@ -590,6 +625,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
590
625
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
591
626
  places: placesOf(boxes, boxAllowOf(env)),
592
627
  models,
628
+ learning_model,
593
629
  /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
594
630
  * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
595
631
  * `approve_needs` when not. */
@@ -598,6 +634,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
598
634
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
599
635
  * it (tool-keys.ts), when one does. */
600
636
  tools,
637
+ /** The switches only the operator sets, in the server's environment at its start (start-switches.ts): each one's state,
638
+ * the value it read and what it allows. Never a secret's value. */
639
+ switches: startSwitches(env, switched),
601
640
  /** How this server holds its secrets (secrets.ts, the launcher), and what that does not cover. */
602
641
  secrets: {
603
642
  names: [...SECRET_NAMES],
@@ -654,6 +693,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
654
693
  * ends (webhooks.ts); its secret kept sealed under the same seal key. */
655
694
  // Always sealed: the server starts with its seal key (seal-key.ts bootSealKey), so nothing is kept in the clear.
656
695
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
696
+ /** /settings/slack: one Slack incoming-webhook URL each of `events` is posted to as a readable message (slack.ts); the
697
+ * URL kept sealed, never shown. */
698
+ slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
657
699
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
658
700
  triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
659
701
  },
@@ -892,7 +934,7 @@ async function startHolding(options, data, checked, stops) {
892
934
  const reach = liveReachOf(process.env, seal.key);
893
935
  const attach = createAttachRoutes({
894
936
  store, hub: attachHub, machinesOnly: options.apiOnly === true, runnerApart: options.runnerApart === true,
895
- relay: { relays: store.runnerRelays, reach },
937
+ relay: { runners: store.runners, reach },
896
938
  ...(options.attachTiming ? { timing: options.attachTiming } : {}),
897
939
  log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)),
898
940
  });
@@ -916,6 +958,9 @@ async function startHolding(options, data, checked, stops) {
916
958
  const stopping = new AbortController();
917
959
  /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
918
960
  let schemaSealed = Promise.resolve();
961
+ // The start's sweep of ended runs whose stored cost is unknown (cost-heal.ts), once this server listens; stop drains it.
962
+ let costHealed = Promise.resolve();
963
+ let costHealStopped = false;
919
964
  // This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
920
965
  const storedKeys = (name) => toolKeys.value(name);
921
966
  // A stored key that does not open is said once at the start, never a refusal to start.
@@ -968,7 +1013,13 @@ async function startHolding(options, data, checked, stops) {
968
1013
  const loginRefused = whyNotOneOwner({ apiOnly: options.apiOnly === true, tokens: tokens.length });
969
1014
  await dropRefusedLogin(store.settings, loginOff ?? loginRefused, (line) => (log ? log(logLine("claude_login", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)));
970
1015
  let claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
971
- let env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
1016
+ // The model gateway saved in the console (model-gateway.ts), its key opened: laid over every reading of env, where the
1017
+ // environment names no gateway of its own. Read again at each save or removal (gatewayChanged).
1018
+ let savedGateway = await readSavedGateway(store, seal.key);
1019
+ /** The server's environment as a reading of it sees it: its secrets and saved keys, the ChatGPT sign-in, Claude Code's
1020
+ * login, and the saved model gateway. */
1021
+ const readEnv = (from) => withSavedGateway(withClaudeLogin(withPlan(own(withSecrets(from, "all", storedKeys)), plan), claudeLogin), savedGateway);
1022
+ let env = readEnv(base);
972
1023
  let offers;
973
1024
  let caps;
974
1025
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -983,7 +1034,10 @@ async function startHolding(options, data, checked, stops) {
983
1034
  // imports it (runner/beside.ts): its module reaches the runner's, which reach back to this one's.
984
1035
  const { runIsolationName, runIsolationOf } = await import("./runner/run-child-host.js");
985
1036
  const isolation = await runIsolationOf(base, 1, () => { }).then(runIsolationName, () => "process");
986
- const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation));
1037
+ // The start-time switches as this server was started: its options, else the CLI's variables. mcpLoopback is the
1038
+ // option alone, as everywhere it is read here (localInstall): the CLI sets it from AGENTRUN_MCP_ALLOW_LOOPBACK.
1039
+ const switched = { mcpLoopback: options.mcpLoopback === true, webhookPrivateTargets: switchedOnBy(process.env, options).webhookPrivateTargets };
1040
+ const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation, switched));
987
1041
  const recompose = () => void (caps = compose());
988
1042
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
989
1043
  let offersFrom;
@@ -1013,10 +1067,10 @@ async function startHolding(options, data, checked, stops) {
1013
1067
  });
1014
1068
  const keysChanged = async () => {
1015
1069
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
1016
- // serverSecrets live, store-view), and a list builds a listing cut of other keys again (cutOfNow). A failed run's error words
1070
+ // serverSecrets live, store-view), and a list builds a listing cut of other keys again (builtOfNow). A failed run's error words
1017
1071
  // name a refused key by the keys and settings, so those listings are built again.
1018
1072
  await lister.keysChanged();
1019
- env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
1073
+ env = readEnv(base);
1020
1074
  const mine = ++needsAsked;
1021
1075
  const next = await needsOf(env);
1022
1076
  if (mine === needsAsked)
@@ -1027,6 +1081,11 @@ async function startHolding(options, data, checked, stops) {
1027
1081
  else
1028
1082
  await probe("key");
1029
1083
  };
1084
+ /** After the model gateway is saved or removed in the console: the saved gateway read again, then env, as a key's save. */
1085
+ const gatewayChanged = async () => {
1086
+ savedGateway = await readSavedGateway(store, seal.key);
1087
+ await keysChanged();
1088
+ };
1030
1089
  /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
1031
1090
  const planNow = async () => {
1032
1091
  const was = plan.state;
@@ -1085,6 +1144,12 @@ async function startHolding(options, data, checked, stops) {
1085
1144
  const sealKey = seal.key;
1086
1145
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1087
1146
  const sdkSecret = sdkRunSecret(sealKey);
1147
+ // An API-only server's viewer credentials (viewer-credential.ts) are signed with another key from it: every server on
1148
+ // this store checks them alike, across restarts.
1149
+ const viewerKey = viewerCredentialKey(sealKey);
1150
+ /** Whether `credential` opens run `runId`'s live view now: minted for that run, not expired, and its run not ended,
1151
+ * read from the store each time (its revocation). */
1152
+ const viewerHolds = async (credential, runId) => credential !== undefined && viewerCredentialFor(viewerKey, runId, credential, Date.now()) && !(await runOver(store, runId));
1088
1153
  // Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
1089
1154
  const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
1090
1155
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
@@ -1131,8 +1196,8 @@ async function startHolding(options, data, checked, stops) {
1131
1196
  paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves, options.runnerApart === true) },
1132
1197
  runnerApart: options.runnerApart === true,
1133
1198
  // A runner in a process of its own that relays its dials (dial-relay.ts): one whose attach listener said it is there
1134
- // within RELAY_STALE_MS, at a host this server dials.
1135
- relayed: async () => (await store.runnerRelays.list()).some((row) => row.seenAt >= Date.now() - RELAY_STALE_MS && dialHost(row.host, reach) !== undefined),
1199
+ // within PRESENCE_STALE_MS on the store's clock (liveRelays), at a host this server dials.
1200
+ relayed: async () => (await liveRelays(store.runners)).some((row) => dialHost(row.host, reach) !== undefined),
1136
1201
  ...(options.faux
1137
1202
  // --faux's providers stand in for every vendor's, a local one's daemon included.
1138
1203
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -1214,9 +1279,10 @@ async function startHolding(options, data, checked, stops) {
1214
1279
  };
1215
1280
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1216
1281
  const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1217
- /** The run read's path and costs (A8, store-reads/learning.ts runAllInOverStore): `path`; `cost.usd` its own spend, the
1282
+ /** The run read's costs (A8, store-reads/learning.ts runAllInOverStore): `cost.usd` its own spend, the
1218
1283
  * job's (its compile turn is learning's), null while unknown; what learning spent for it
1219
- * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown. */
1284
+ * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown.
1285
+ * `tools_usd`: the part of `usd` its paid tool calls cost (store-view.ts toolsUsdOverStore). */
1220
1286
  const allInViewOf = async (runId, view) => {
1221
1287
  const cost = (view.cost ?? {});
1222
1288
  const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
@@ -1225,7 +1291,7 @@ async function startHolding(options, data, checked, stops) {
1225
1291
  return {};
1226
1292
  // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1227
1293
  // gives): known as it answered even when its compile turn's cost is not; the row's while the run is at work.
1228
- return { path: all.path, cost: { ...cost, ...(cost.upper_bound === true ? {} : { usd: all.usd }), learning_usd: all.learning_usd, all_in_usd: all.all_in_usd } };
1294
+ return { cost: { ...cost, ...(cost.upper_bound === true ? {} : { usd: all.usd }), tools_usd: await toolsUsdOverStore(store, runId), learning_usd: all.learning_usd, all_in_usd: all.all_in_usd } };
1229
1295
  };
1230
1296
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1231
1297
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
@@ -1252,6 +1318,8 @@ async function startHolding(options, data, checked, stops) {
1252
1318
  };
1253
1319
  ({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
1254
1320
  secretStores.add("server", () => tokens.map((entry) => entry.token));
1321
+ // The model gateway's key saved in the console (model-gateway.ts): cut from everything shown, as every saved key is.
1322
+ secretStores.add("model-gateway", () => (savedGateway?.key ? [savedGateway.key] : []));
1255
1323
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1256
1324
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1257
1325
  const emailPasswords = new Set();
@@ -1282,7 +1350,7 @@ async function startHolding(options, data, checked, stops) {
1282
1350
  // Any bound given reaches Webhooks' check (0 and NaN are refused there, never dropped for the default).
1283
1351
  ...(options.webhookTimeoutMs !== undefined ? { timeoutMs: options.webhookTimeoutMs } : {}),
1284
1352
  ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1285
- privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1353
+ privateTargets: switched.webhookPrivateTargets,
1286
1354
  });
1287
1355
  // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
1288
1356
  stops.push(() => webhooks.close());
@@ -1291,6 +1359,19 @@ async function startHolding(options, data, checked, stops) {
1291
1359
  if (existsSync(join(data, WEBHOOK_FILE)))
1292
1360
  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" }));
1293
1361
  secretStores.add("webhook", () => webhooks.signingSecrets());
1362
+ // Slack (slack.ts): the webhook's outbox under its own channel, its URL the credential, sealed and cut like a secret.
1363
+ const slack = new SlackPosts(store, sealKey, (fields) => (log ? log(logLine("slack", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("slack", fields)}\n`)), {
1364
+ ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1365
+ ...(options.webhookTimeoutMs !== undefined ? { timeoutMs: options.webhookTimeoutMs } : {}),
1366
+ ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1367
+ privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1368
+ ...(options.slackTarget ? { sendTo: options.slackTarget } : {}),
1369
+ // Each message's strings (an agent's name, a run's title, a trigger's error) cut of every secret the server holds.
1370
+ serverSecrets: () => serverSecrets(),
1371
+ });
1372
+ stops.push(() => slack.close());
1373
+ await slack.load();
1374
+ secretStores.add("slack", () => slack.urlForms());
1294
1375
  const uploads = new Uploads(join(data, UPLOADS_DIR));
1295
1376
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
1296
1377
  // temp file found now is a crashed one's.
@@ -1332,6 +1413,7 @@ async function startHolding(options, data, checked, stops) {
1332
1413
  // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
1333
1414
  // read once for this server (and again after a read that failed), through the faux one under --faux.
1334
1415
  let pricing;
1416
+ const readPrices = new Map();
1335
1417
  const decisionPrice = async (model) => {
1336
1418
  const making = (pricing ??= (async () => {
1337
1419
  const [{ openrouterProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(fauxEnvOf(options), FAUX_OPENROUTER_ENV)]);
@@ -1340,15 +1422,47 @@ async function startHolding(options, data, checked, stops) {
1340
1422
  // One that could not be made is made again next time: a rejection is never kept.
1341
1423
  const provider = await making.catch((error) => { if (pricing === making)
1342
1424
  pricing = undefined; throw error; });
1343
- return provider.priceOf(model);
1425
+ const price = await provider.priceOf(model);
1426
+ readPrices.set(model, price);
1427
+ return price;
1344
1428
  };
1429
+ /** A decision model's price as a save or a start last read it from the catalog (null: the catalog lists none), and
1430
+ * never a read of the catalog of its own: what a GET, which waits on no other service, prices by. A model none has
1431
+ * priced answers PRICE_NOT_READ, which blockersOf takes for a price (no blocker): whether its run is refused is not
1432
+ * known until a start asks. */
1433
+ const PRICE_NOT_READ = { notRead: true };
1434
+ const readDecisionPrice = async (model) => (readPrices.has(model) ? readPrices.get(model) : PRICE_NOT_READ);
1345
1435
  // The run write half (runs-over-store): the server INSERTs a queued run and its launch (startRun), and writes command
1346
1436
  // rows (message/stop/cancel/raise/approve/archive) a run's runner reads and applies. No per-run process, no HTTP door,
1347
1437
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1348
1438
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1349
1439
  // reads launch.model alone).
1350
1440
  const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1441
+ // Why no runner here can take a run, while every runner there refused to claim (runner/presence.ts): read from the
1442
+ // store at each start, capabilities and health answer, so a runner in another process (or on another host over one
1443
+ // Postgres) counts as the one beside this server does, and a runner that can claim, once there, clears it at once.
1444
+ const refusedNow = () => runnersRefused(store.runners);
1445
+ // While it holds, the runs still queued fail in those words (Runs.failUnclaimed), every REFUSED_SWEEP_MS: a run queued
1446
+ // before the refusal was known never waits for good. A run a runner claimed is not one of them.
1447
+ let refusedSweep = Promise.resolve();
1448
+ let refusedStopped = false;
1449
+ const sweepRefused = () => {
1450
+ refusedSweep = refusedSweep.then(async () => {
1451
+ if (refusedStopped)
1452
+ return;
1453
+ const words = await refusedNow();
1454
+ if (words !== undefined && !refusedStopped)
1455
+ await store.runs.failUnclaimed(refusedEnd(words));
1456
+ }).catch((error) => void process.stderr.write(`agentrun-serve: the runs queued while no runner here can take them could not be failed: ${error.message}\n`));
1457
+ return refusedSweep;
1458
+ };
1459
+ const refusedTimer = setInterval(() => void sweepRefused(), REFUSED_SWEEP_MS);
1460
+ refusedTimer.unref();
1461
+ // The runner beside this server, when its run isolation was refused (cli.ts): its word, kept in this store until the stop.
1462
+ let refusedBeside;
1351
1463
  const startDeps = {
1464
+ // A start while every runner here refused to claim is refused in their words (runner/presence.ts).
1465
+ runnersRefused: refusedNow,
1352
1466
  runBodyIssues,
1353
1467
  boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
1354
1468
  pinnedOf,
@@ -1429,7 +1543,7 @@ async function startHolding(options, data, checked, stops) {
1429
1543
  };
1430
1544
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1431
1545
  const statuses = (agentId) => statusesOf(data, agentId);
1432
- const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
1546
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses });
1433
1547
  // A run read as a whole (its own read, its archive) lists its recordings too, from its recordings folder on this machine
1434
1548
  // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1435
1549
  const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
@@ -1456,7 +1570,7 @@ async function startHolding(options, data, checked, stops) {
1456
1570
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1457
1571
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1458
1572
  // The route frames the SSE around its `page`, which long-polls the journal, byte-identical to the old live run's page.
1459
- const servedTimelineDeps = { serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses };
1573
+ const servedTimelineDeps = { serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses };
1460
1574
  const timelines = runTimelines({
1461
1575
  context: ctx,
1462
1576
  // The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
@@ -1478,7 +1592,10 @@ async function startHolding(options, data, checked, stops) {
1478
1592
  const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1479
1593
  if (view?.status !== "completed")
1480
1594
  return undefined;
1481
- return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null };
1595
+ // The fields its next run is handed when the whole result is too large: its own revision's output schema's, the one
1596
+ // its result.output was checked against (store-view.ts), never the agent's current one.
1597
+ const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
1598
+ return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
1482
1599
  },
1483
1600
  };
1484
1601
  const targets = triggerTargets(store, triggerDeps);
@@ -1637,7 +1754,11 @@ async function startHolding(options, data, checked, stops) {
1637
1754
  // queue a firing takes — how many of a trigger's messages wait for a busy run — is route-1's store.triggers.
1638
1755
  ...targets,
1639
1756
  settings: (adapterId) => triggerSettings.get(adapterId),
1640
- notify: (failed, key) => webhooks.emitTrigger(failed, key),
1757
+ // The webhook and Slack each hear of it: told once both have it (or neither is set), again while either has not.
1758
+ notify: async (failed, key) => {
1759
+ const told = await Promise.all([webhooks.emitTrigger(failed, key), slack.emitTrigger(failed, key)]);
1760
+ return told.find((one) => one === "unsaved" || one === "closed") ?? (told.includes("queued") ? "queued" : "off");
1761
+ },
1641
1762
  // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1642
1763
  upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1643
1764
  });
@@ -2264,13 +2385,40 @@ async function startHolding(options, data, checked, stops) {
2264
2385
  return answer;
2265
2386
  }
2266
2387
  // ---- runs -----------------------------------------------------------------------------------------------------------
2388
+ /** Why a run of the agent's current revision started now with no overrides would be refused (409 agent_not_runnable),
2389
+ * as the run's own check says it (runnable, at the place the run resolves to): its message and fields, for the agent
2390
+ * page to show before Run. Null when nothing keeps it from running, for an agent with no revision or archived (its
2391
+ * page says so), or when the check is not one a read makes: a native or SDK agent's (which launches or asks its
2392
+ * backend), and a revision whose MCP tools its first run pins (pinFirst writes the pin; until then a read would warn
2393
+ * of a pin the run makes). A read asks no other service, so it prices by readDecisionPrice. */
2394
+ async function runBlockersOf(entry) {
2395
+ const revision = entry.revision;
2396
+ if (!revision || entry.agent.archivedAt)
2397
+ return null;
2398
+ const body = revision.body;
2399
+ if (nativeOf(body) || sdkOf(body))
2400
+ return null;
2401
+ const tools = revision.kind === "agentic" ? (body.tools ?? []) : [];
2402
+ if (!revision.mcpPin && tools.some((tool) => mcpToolOf(tool)))
2403
+ return null;
2404
+ try {
2405
+ await runnable(revision, resolvePlace(body.place, fallbackPlace(revision.kind, tools)), { capped: body.maxCostUsd !== undefined, price: readDecisionPrice });
2406
+ return null;
2407
+ }
2408
+ catch (error) {
2409
+ if (error instanceof ApiError && error.code === "agent_not_runnable")
2410
+ return { message: error.message, fields: error.extra.fields ?? [] };
2411
+ return null;
2412
+ }
2413
+ }
2267
2414
  /** A workflow revision's shape as runnable.ts checks it: its workflow, tools, harness, place and tool settings. */
2268
2415
  const workflowShape = ({ workflow, tools, harness, place, toolSettings, approvals }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}), ...(approvals === "never" ? { approvals } : {}) });
2269
2416
  const shapeOf = (revision) => (revision.kind === "agentic" ? { kind: "agentic", ...revision.body } : workflowShape(revision.body));
2270
2417
  /** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
2271
2418
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
2272
- * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
2273
- async function runnable(revision, place, { capped = false } = {}) {
2419
+ * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2420
+ * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
2421
+ async function runnable(revision, place, { capped = false, price = decisionPrice } = {}) {
2274
2422
  if (sdkOf(revision.body))
2275
2423
  throw new ApiError("agent_not_runnable", "This agent runs in its backend SDK. Call its SDK wrapper to start a task; AgentRun does not launch its tools or credentials.");
2276
2424
  const native = nativeOf(revision.body);
@@ -2286,7 +2434,7 @@ async function startHolding(options, data, checked, stops) {
2286
2434
  if (!native.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
2287
2435
  throw new ApiError("agent_not_runnable", "Native connections run only on an AgentRun server bound to loopback on the source machine, without a public URL.");
2288
2436
  if (capped)
2289
- throw new ApiError("agent_not_runnable", "Native runs retain their own limits; AgentRun cannot enforce a dollar cap on this connection. Remove max_cost_usd and use native limits.");
2437
+ throw new ApiError("agent_not_runnable", NATIVE_CAP_UNSUPPORTED);
2290
2438
  if (native.remote)
2291
2439
  await new RemoteConnectors(store).assertReady(native);
2292
2440
  else
@@ -2327,7 +2475,7 @@ async function startHolding(options, data, checked, stops) {
2327
2475
  };
2328
2476
  const monid = revision.monidPin ?? undefined;
2329
2477
  // Claude Code's login on this machine is a runner place's alone: a sandbox run is checked for a key, as it runs.
2330
- const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
2478
+ const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice: price });
2331
2479
  if (!blockers.length)
2332
2480
  return;
2333
2481
  const message = blockers.map((b) => b.message).join(" ");
@@ -2489,8 +2637,9 @@ async function startHolding(options, data, checked, stops) {
2489
2637
  * (NEW_AGENT_TOOLS); elsewhere none named, the runner's own. One rule for a new agent (createAgentOf) and for an apply
2490
2638
  * with agent_id of a package that names none (applyWith), whose agent is where its fresh apply put it. */
2491
2639
  const defaultToolsAt = (place) => (isObject(place) && place.mode === "sandbox" ? NEW_AGENT_TOOLS : undefined);
2492
- /** The definition an apply with agent_id writes onto agent `entry` from its package's `definition`: its id, name and
2493
- * description are the agent's own, kept from its creation; a package that names no tools gets those its agent's place
2640
+ /** The definition an apply with agent_id writes onto agent `entry` from its package's `definition`: its id and name are
2641
+ * the agent's own, kept from its creation, and its description is the agent's as it is now (an edit may have changed
2642
+ * it; the package's never overwrites it); a package that names no tools gets those its agent's place
2494
2643
  * gives one (defaultToolsAt: the shell tools in the box its fresh apply put it in), as a fresh apply would. */
2495
2644
  const updateDefinition = (entry, definition) => {
2496
2645
  const kept = Object.fromEntries(Object.entries(definition).filter(([key]) => key !== "name" && key !== "description"));
@@ -2638,7 +2787,7 @@ async function startHolding(options, data, checked, stops) {
2638
2787
  const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
2639
2788
  const needed = unsaved.filter((need) => need.required);
2640
2789
  if (missing.length || needed.length) {
2641
- const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
2790
+ const fix = "Add it in Settings → API Keys, or set it where AgentRun starts, then apply the template again.";
2642
2791
  throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
2643
2792
  }
2644
2793
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
@@ -2750,7 +2899,7 @@ async function startHolding(options, data, checked, stops) {
2750
2899
  .filter((one) => one.template?.id === pkg.id && one.template.parameters_digest === digest)
2751
2900
  .map((one) => ({ field: "agent_id", reason: "duplicate", message: `The agent ${one.agent.id} was made from the ${pkg.name} template with these parameters, and this apply made another. To change that one instead, apply with agent_id ${one.agent.id}.` }));
2752
2901
  // An update writes the package as a new revision of the agent, as an edit does (its id, name and description are the
2753
- // agent's own, kept from its creation), but what the package owns and leaves out is gone (fromPackage); only onto the
2902
+ // agent's own: the package's never replace them), but what the package owns and leaves out is gone (fromPackage); only onto the
2754
2903
  // revision it read, else 412 with nothing changed. A fresh apply makes the agent as POST /agents does.
2755
2904
  const { entry, warnings } = onto
2756
2905
  ? await reviseAgentOf(onto, { ...made.agent, definition: updateDefinition(onto, made.agent.definition) }, { template: origin, fromPackage: true, ifCurrent: onto.revision?.id ?? null }).catch((error) => {
@@ -2948,12 +3097,25 @@ async function startHolding(options, data, checked, stops) {
2948
3097
  const issues = [];
2949
3098
  const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
2950
3099
  const auth = {};
2951
- for (const [server, headers] of Object.entries(mcp ?? {})) {
3100
+ for (const [server, entry] of Object.entries(mcp ?? {})) {
2952
3101
  const row = await getMcpServer(store, server);
2953
- if (row?.auth !== "per_run")
2954
- issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
3102
+ const field = `mcp_auth.${server}`;
3103
+ if (!row) {
3104
+ issues.push({ field, reason: "not_an_option", message: `No MCP server ${server} is saved here.` });
3105
+ continue;
3106
+ }
3107
+ // A per-run Composio server takes a binding (its key is its own); a per_run server takes headers; no other takes either.
3108
+ const perRunComposio = composioPerRun(row, await store.settings.get(composioMadeKey(server)));
3109
+ if ("composio" in entry) {
3110
+ if (perRunComposio)
3111
+ auth[server] = { composio: entry.composio, origin: new URL(row.url).origin };
3112
+ else
3113
+ issues.push({ field, reason: "not_an_option", message: `The MCP server ${server} is not a per-run Composio server: only one saved through the Composio preset with user_id "${COMPOSIO_PER_RUN}" takes a Composio account from a run.` });
3114
+ }
3115
+ else if (row.auth === "per_run")
3116
+ auth[server] = { headers: entry.headers, origin: new URL(row.url).origin };
2955
3117
  else
2956
- auth[server] = { headers, origin: new URL(row.url).origin };
3118
+ issues.push({ field, reason: "not_an_option", message: perRunComposio ? `The MCP server ${server} takes a Composio account from each run, not headers: send {"composio_user_id": "<user>", "connected_account_id": "ca_..."} (the account optional).` : `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` });
2957
3119
  }
2958
3120
  const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
2959
3121
  if (issues.length)
@@ -3228,8 +3390,9 @@ async function startHolding(options, data, checked, stops) {
3228
3390
  const secrets = serverSecrets();
3229
3391
  const runs = [];
3230
3392
  for (const { row, agentArchivedAt, listing, listMark, behind } of page.rows) {
3231
- // One cut of other secrets (a secret saved since, or the server's own keys at another start) is built again too.
3232
- const kept = listing === null || behind || !cutOfNow(listing, secrets) ? await listNow(row.id, listMark) : listing;
3393
+ // One cut of other secrets (a secret saved since, or the server's own keys at another start) is built again too: at most the page's `limit` builds, and each writes
3394
+ // its listing back, so the next list finds it current.
3395
+ const kept = listing === null || behind || !builtOfNow(listing, secrets) ? await listNow(row.id, listMark) : listing;
3233
3396
  // A run whose status moved between the two reads is left off this page, never shown under a status it has left.
3234
3397
  if (kept && (status === null || kept.item.status === status))
3235
3398
  runs.push(listedItem(kept, origin, row.archivedAt ?? agentArchivedAt, secrets));
@@ -3365,6 +3528,8 @@ async function startHolding(options, data, checked, stops) {
3365
3528
  // Tool calls run with no price (an MCP tool its owner set none for): outside every cost, counted on `tools`.
3366
3529
  let notMetered = 0;
3367
3530
  const total = { usd: 0, unpriced: 0 };
3531
+ // How the runs' costs in the window were reached (metrics.ts joinedBasis over each run's costBasis).
3532
+ const bases = [];
3368
3533
  // The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
3369
3534
  let browserSeconds = 0;
3370
3535
  // A cost that is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it never
@@ -3387,6 +3552,7 @@ async function startHolding(options, data, checked, stops) {
3387
3552
  // A running run's cost is its booked-so-far spend (store-reads/runs listRuns reads it over the store with
3388
3553
  // spentOverStore); an ended run's is its stored cost. A null cost (a running run with none yet) counts unpriced.
3389
3554
  const usd = row.costUsd ?? null;
3555
+ bases.push(row.costBasis);
3390
3556
  const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
3391
3557
  // By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
3392
3558
  // `tokens`, all from the same records: a live run's rows (a call still marked is no charge), else its store as it
@@ -3429,7 +3595,7 @@ async function startHolding(options, data, checked, stops) {
3429
3595
  }
3430
3596
  const round = (v) => Math.round(v * 1e6) / 1e6;
3431
3597
  return {
3432
- from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
3598
+ from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: joinedBasis(bases), group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
3433
3599
  lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced, ...(group === "meter" && key === "tools" && notMetered ? { not_metered_calls: notMetered } : {}) })),
3434
3600
  account: null,
3435
3601
  };
@@ -3680,7 +3846,10 @@ async function startHolding(options, data, checked, stops) {
3680
3846
  await planNow();
3681
3847
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
3682
3848
  // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
3683
- return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
3849
+ // runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
3850
+ // (runner/presence.ts); null while one can, or none is there yet.
3851
+ const runnerRefused = (await refusedNow().catch(() => undefined)) ?? null;
3852
+ return send(res, 200, { ...answer, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
3684
3853
  }
3685
3854
  if (found.name === "getOpenapi")
3686
3855
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -3752,8 +3921,9 @@ async function startHolding(options, data, checked, stops) {
3752
3921
  }
3753
3922
  if (found.name === "getHealth") {
3754
3923
  // The store this server opened (SQLite or Postgres), never a second open of the data directory's file.
3755
- const health = await healthOf(store, data, minFreeBytes);
3756
- return send(res, health.status === "ok" ? 200 : 503, health);
3924
+ // Degraded (every runner here refused to claim) is 200: a platform's health check never restarts it over a setting.
3925
+ const health = await healthOf(store, data, minFreeBytes, undefined, refusedNow);
3926
+ return send(res, health.status === "failing" ? 503 : 200, health);
3757
3927
  }
3758
3928
  // Approving a learned workflow held for its owner's OK (a step calls a tool with no price) takes the owner's
3759
3929
  // signed-in page alone: never a token, which a run's process, an agent's MCP client or a script may hold, nor a
@@ -3776,14 +3946,15 @@ async function startHolding(options, data, checked, stops) {
3776
3946
  throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3777
3947
  }
3778
3948
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
3779
- // approving a note is (never a token a run, an MCP client or a script may hold).
3780
- if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3949
+ // approving a note is (never a token a run, an MCP client or a script may hold). An API-only server has no owner: there
3950
+ // the server's token, its backend's own, takes a run's computer, checked below as every route's token is.
3951
+ if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || (found.name === "getRunComputer" && !options.apiOnly)) && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3781
3952
  const what = found.name.endsWith("Browser") ? "browser" : "computer";
3782
3953
  authFailed(`/v2${path}`, `${what}_without_session`);
3783
3954
  throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
3784
3955
  }
3785
3956
  // A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
3786
- if (COMPUTER_ROUTES.has(found.name) && !byOwnerSession(req) && req.headers.authorization !== undefined)
3957
+ if (COMPUTER_ROUTES.has(found.name) && !options.apiOnly && !byOwnerSession(req) && req.headers.authorization !== undefined)
3787
3958
  authFailed(`/v2${path}`, "computer_without_session");
3788
3959
  // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
3789
3960
  // token, which the run's own process, an agent's MCP client or a script may hold.
@@ -3811,7 +3982,11 @@ async function startHolding(options, data, checked, stops) {
3811
3982
  const checked = { params, store };
3812
3983
  if (await writesSecretFor(found.name, body, checked)) {
3813
3984
  authFailed(`/v2${path}`, "secret_without_session");
3814
- throw new ApiError("forbidden", SECRET_WRITE_REFUSAL);
3985
+ // Where the person finishes it: the operation's console page, filled with what the request held that is no
3986
+ // secret (secretPageFor), at the address people open the console at.
3987
+ const page = await secretPageFor(found.name, body, { params, store });
3988
+ const link = page === undefined ? undefined : `${linkOrigin(req)}${page}`;
3989
+ throw new ApiError("forbidden", secretWriteRefusal(link), link === undefined ? {} : { details: { console_url: link } });
3815
3990
  }
3816
3991
  secretSeen = checked.seen;
3817
3992
  }
@@ -3873,22 +4048,16 @@ async function startHolding(options, data, checked, stops) {
3873
4048
  // A learning SDK run's compile turn is asked on its agent's own model: checked reachable before the run starts.
3874
4049
  let compileModel;
3875
4050
  if (sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3876
- try {
3877
- const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3878
- if (chosen)
3879
- compileModel = `${chosen.provider}/${chosen.modelId}`;
3880
- }
3881
- catch { }
4051
+ const configured = await learningModelOf(env, (await pinnedOf(entry, {})).revision);
4052
+ compileModel = configured.model ?? undefined;
3882
4053
  }
3883
4054
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3884
- const compile = { ...(compileModel ? { model: compileModel } : {}), check: async (model) => {
3885
- try {
3886
- const route = await askRouteOf(model, env, (one) => sdkModelRoute(one, env, "default", PI_WIRES));
3887
- await route.provider.credential();
3888
- }
3889
- catch {
3890
- throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key to compile workflows. Configure Model keys or turn self-improving off.");
3891
- }
4055
+ const compile = { ...(compileModel ? { model: compileModel } : {}), check: async () => {
4056
+ // SdkRuns checks this only after its durable origin lookup, so a successful admission remains recoverable
4057
+ // when the owner has since changed its model or removed its key.
4058
+ const configured = await learningModelOf(env, entry.revision, { checkCredential: true });
4059
+ if (!configured.ready)
4060
+ throw new ApiError("agent_not_runnable", configured.reason ?? "Configure a server learning model in Settings → API Keys.");
3892
4061
  } };
3893
4062
  const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, startDeps, origin, compile, linkOrigin(req)) }));
3894
4063
  // Re-read the pinned receipt even on an in-memory replay: credentials saved since
@@ -3973,7 +4142,7 @@ async function startHolding(options, data, checked, stops) {
3973
4142
  return tool ? toolEffect(tool.annotations) : undefined;
3974
4143
  };
3975
4144
  const tools = revision && tooling ? agentTools(env, settings.get(), tooling, caps.tools.map((tool) => tool.name), await shellOfRevision(revision), effectOf) : [];
3976
- return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
4145
+ return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools, run_blockers: await runBlockersOf(entry) }, { etag: etagOf(entry) });
3977
4146
  }
3978
4147
  case "updateDefinition": {
3979
4148
  const entry = await needAgent(id);
@@ -4307,10 +4476,33 @@ async function startHolding(options, data, checked, stops) {
4307
4476
  // hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
4308
4477
  const run = await needRun(id);
4309
4478
  const answer = await computerRoute(found.name, run.id, {
4310
- ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, accounts: owner !== undefined, body: await bodyOf(req),
4479
+ ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, apiOnly: options.apiOnly === true, accounts: owner !== undefined, body: await bodyOf(req),
4311
4480
  }, store, { context: ctx });
4312
4481
  return send(res, 200, answer, { "cache-control": "no-store" });
4313
4482
  }
4483
+ case "createRunComputerViewer": {
4484
+ // A viewer credential for the run's live view (viewer-credential.ts), for an API-only server's backend to hand its
4485
+ // user: a link on the public address to the run's open viewer, the credential in its query, the viewer's own token
4486
+ // in its fragment. A server with no backend in between has an owner who opens the view in the console: not here.
4487
+ if (!options.apiOnly)
4488
+ throw new ApiError("not_found", "A run's viewer link is minted on an API-only server alone (AGENTRUN_API_ONLY=1): here its owner opens the live view in the console.");
4489
+ const run = await needRun(id);
4490
+ const body = await bodyOf(req);
4491
+ const issues = unknownFields(body, []);
4492
+ if (issues.length)
4493
+ throw invalid(issues);
4494
+ if (!options.publicUrl)
4495
+ throw new ApiError("unsupported_here", "A run's viewer link is on this server's public address, and AGENTRUN_PUBLIC_URL is unset: set it to the address your users' browsers open this server at.");
4496
+ if (await runOver(store, run.id))
4497
+ throw new ApiError("computer_not_live", "This run has ended: its computer has no live view.");
4498
+ const link = await computerViewerLink(store, sealKey, run.id, answers(run.id));
4499
+ if (link === undefined)
4500
+ throw new ApiError("computer_not_live", "This run's computer has no live view open now: ask again once GET /v2/runs/{run_id}/computer reads live.");
4501
+ const { credential, expiresAt } = mintViewerCredential(viewerKey, run.id, Date.now());
4502
+ const [path, fragment] = link.viewer.split("#");
4503
+ const minted = `${options.publicUrl.replace(/\/+$/, "")}${path}?${VIEWER_PARAM}=${credential}${fragment === undefined ? "" : `#${fragment}`}`;
4504
+ return send(res, 201, { url: minted, expires_at: new Date(expiresAt).toISOString() }, { "cache-control": "no-store" });
4505
+ }
4314
4506
  case "startRun":
4315
4507
  case "callRunComputer":
4316
4508
  case "releaseRunComputer": {
@@ -4594,6 +4786,20 @@ async function startHolding(options, data, checked, stops) {
4594
4786
  throw error;
4595
4787
  }
4596
4788
  }
4789
+ // The model gateway saved in the console (model-gateway.ts): never through `idempotent`, as its body may hold the
4790
+ // key; a save or removal makes the reading again (gatewayChanged), so capabilities and the next run see it at once.
4791
+ case "getModelGateway":
4792
+ case "saveModelGateway":
4793
+ case "deleteModelGateway":
4794
+ case "testModelGateway": {
4795
+ // The test's body is optional (none: the gateway in force is asked); a save's is not.
4796
+ const sent = Number(req.headers["content-length"] ?? 0) > 0 || req.headers["transfer-encoding"] !== undefined;
4797
+ const body = found.name === "saveModelGateway" || (found.name === "testModelGateway" && sent) ? await bodyOf(req) : undefined;
4798
+ if ((found.name === "saveModelGateway" || found.name === "deleteModelGateway") && stopping.signal.aborted)
4799
+ throw new ApiError("unavailable", "The server is shutting down: the model gateway was not changed.");
4800
+ const answer = await modelGatewayRoute({ store, sealKey: seal.key, env: own(withSecrets(base, "own")), changed: gatewayChanged }, found.name, { ...(body !== undefined ? { body } : {}), signal: stopping.signal });
4801
+ return send(res, 200, answer, { "cache-control": "no-store" });
4802
+ }
4597
4803
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
4598
4804
  case "listMcpServers":
4599
4805
  return send(res, 200, await mcpServers.list());
@@ -4741,7 +4947,7 @@ async function startHolding(options, data, checked, stops) {
4741
4947
  // they are now and of the agent's own sign-in pointers, live and forgotten (agentPointers); a write as the
4742
4948
  // definition's: an archived agent's too.
4743
4949
  case "getAgentLearning": {
4744
- await needAgent(id);
4950
+ const entry = await needAgent(id);
4745
4951
  // The agent's learning view: its corrections, workflows and log from its learning folder; its run-fared counts and
4746
4952
  // its impact over the one store (agentLearningOverStore), from each run's launch, journal and learning end.
4747
4953
  const { counts, impact } = await agentLearningOverStore(store, id);
@@ -4750,7 +4956,9 @@ async function startHolding(options, data, checked, stops) {
4750
4956
  // that does not run first.
4751
4957
  const records = await promotionsOf(store.settings, id);
4752
4958
  const costStop = await costStopOverStore(store, id);
4753
- return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)));
4959
+ const body = entry.revision?.body;
4960
+ const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
4961
+ return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)), learning_model: await learningModelOf(modelEnv, entry.revision) });
4754
4962
  }
4755
4963
  case "getLearningCost": {
4756
4964
  await needAgent(id);
@@ -4921,6 +5129,15 @@ async function startHolding(options, data, checked, stops) {
4921
5129
  const saved = await webhooks.save(await bodyOf(req));
4922
5130
  return send(res, saved.created ? 201 : 200, webhookSaved(saved.view, saved.secret, mayHoldSecrets(req)));
4923
5131
  }
5132
+ case "rotateWebhookSecret": {
5133
+ // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts). Never
5134
+ // through `idempotent`, whose record would keep the secret. It takes no body, as a trigger's rotation takes none.
5135
+ if (req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? 0) !== 0) {
5136
+ throw invalid([{ field: "body", reason: "not_allowed", message: "Rotating the webhook's secret takes no body: send none, and the new secret is made here." }]);
5137
+ }
5138
+ const rotated = await webhooks.rotate();
5139
+ return send(res, 200, webhookRotated(rotated.view, rotated.secret), { "cache-control": "no-store" });
5140
+ }
4924
5141
  case "deleteWebhook":
4925
5142
  await webhooks.remove();
4926
5143
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -4930,6 +5147,23 @@ async function startHolding(options, data, checked, stops) {
4930
5147
  return send(res, 200, await webhooks.attemptsView());
4931
5148
  case "redeliverWebhook":
4932
5149
  return send(res, 200, await webhooks.redeliver(id));
5150
+ case "getSlack":
5151
+ return send(res, 200, slack.slackView());
5152
+ case "saveSlack": {
5153
+ // A body with `url` is a secret write: the dispatch's one check let only the owner's session this far
5154
+ // (slack.ts registers it). The URL is never in the answer.
5155
+ const saved = await slack.saveSlack(await bodyOf(req));
5156
+ return send(res, saved.created ? 201 : 200, saved.view);
5157
+ }
5158
+ case "deleteSlack":
5159
+ await slack.remove();
5160
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5161
+ case "testSlack":
5162
+ return send(res, 200, await slack.test());
5163
+ case "listSlackDeliveries":
5164
+ return send(res, 200, await slack.attemptsView());
5165
+ case "redeliverSlack":
5166
+ return send(res, 200, await slack.redeliver(id));
4933
5167
  case "listTriggers":
4934
5168
  return send(res, 200, { triggers: (await triggers.list()).triggers.map(withSecretOf) });
4935
5169
  case "createTrigger": {
@@ -5036,6 +5270,30 @@ async function startHolding(options, data, checked, stops) {
5036
5270
  async function liveRoute(req, res, runId, family, rest) {
5037
5271
  if (req.method !== "GET" && req.method !== "HEAD")
5038
5272
  throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
5273
+ if (options.apiOnly) {
5274
+ // API-only: no owner here. The viewer credential its backend minted for this run (viewer-credential.ts), on the
5275
+ // public address alone: a navigation sends no Origin, any other request this page's own. The page's answer sets it as
5276
+ // the cookie its files and socket carry.
5277
+ const sent = req.headers.origin;
5278
+ if (sent !== undefined && sent.toLowerCase() !== publicOrigin) {
5279
+ authFailed(`/v2/runs/${runId}/${family}/live`, "live_view_origin");
5280
+ throw new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone");
5281
+ }
5282
+ const credential = viewerCredentialOf(req);
5283
+ if (credential === undefined) {
5284
+ authFailed(`/v2/runs/${runId}/${family}/live`, "no_credential");
5285
+ throw new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)");
5286
+ }
5287
+ if (!(await viewerHolds(credential, runId))) {
5288
+ authFailed(`/v2/runs/${runId}/${family}/live`, "viewer_credential");
5289
+ throw new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one");
5290
+ }
5291
+ const handover = await liveViewerFor(store, sealKey, runId, rest);
5292
+ if (handover === undefined)
5293
+ throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
5294
+ res.setHeader("set-cookie", viewerCookie(req, runId, credential, viewerExpiry(credential), Date.now()));
5295
+ return serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
5296
+ }
5039
5297
  if (!byOwnerSession(req)) {
5040
5298
  authFailed(`/v2/runs/${runId}/${family}/live`, req.headers.authorization === undefined ? "no_credential" : `${family}_without_session`);
5041
5299
  throw req.headers.authorization === undefined ? new ApiError("unauthenticated", `a run's live ${family} view takes the owner's password sign-in in the console`) : new ApiError("forbidden", `a run's live ${family} view takes the owner's password sign-in in the console, never a token`);
@@ -5059,6 +5317,14 @@ async function startHolding(options, data, checked, stops) {
5059
5317
  return undefined;
5060
5318
  }
5061
5319
  })();
5320
+ // The public address this server last served at, kept in its data folder (public-address.ts): a change signs the owner
5321
+ // out and leaves earlier webhook messages' links on the old address, so the start says so, in one line, once it serves
5322
+ // (below), when it also remembers the new address: a start that fails changes neither.
5323
+ const address = readPublicAddress(data, options.publicUrl);
5324
+ // The earlier address's name (`moved.from`), whose console a browser is redirected from to the new address (`moved.to`,
5325
+ // parsed: a Location header carries no raw name in another script): set only when the server has a public address now
5326
+ // and the earlier name is none it answers to.
5327
+ const moved = movedAddress(address.earlier, options.publicUrl, loopbackNames(host, options.allowHosts, options.publicUrl));
5062
5328
  let names;
5063
5329
  // The listener: the CLI's, bound early and answering warming until the takeover below (listen-first.ts), or a new one.
5064
5330
  const server = options.listener ?? createServer();
@@ -5096,6 +5362,17 @@ async function startHolding(options, data, checked, stops) {
5096
5362
  catch {
5097
5363
  return fail(new ApiError("bad_request", "the request target is not a URL"));
5098
5364
  }
5365
+ // Under the server's earlier public address (public-address.ts): a browser that opens the console is sent on to the new
5366
+ // address, whatever the listener. No other route is: on loopback, the rest is refused as any other name is, in words
5367
+ // that name the new address. That name passes the Host check for this one fixed answer alone, which reads nothing of
5368
+ // the request but its path: it is a name this server's operator set before, and a page that rebound it reads no data.
5369
+ if (moved !== undefined && hostName(req.headers.host) === moved.from) {
5370
+ const browser = /\btext\/html\b/i.test(String(req.headers.accept ?? ""));
5371
+ if (browser && (req.method === "GET" || req.method === "HEAD") && consoleEntry((req.url ?? "/").split("?")[0]))
5372
+ return sendMoved(res, moved.to);
5373
+ if (names)
5374
+ return browser ? sendMovedPage(req, res, moved.to) : fail(new ApiError("forbidden", `unexpected Host header: ${movedFix(moved.to)}`));
5375
+ }
5099
5376
  // On loopback, a Host that is not one of its names (host-check.ts) is a page that rebound a name of its own to this
5100
5377
  // address. A browser is shown a page that says which names work; a script, the same in the error.
5101
5378
  if (names && !names.has(hostName(req.headers.host) ?? "")) {
@@ -5146,9 +5423,10 @@ async function startHolding(options, data, checked, stops) {
5146
5423
  // away. Its name alone, on any port, as the HTTP routes check it.
5147
5424
  if (names && !names.has(hostName(req.headers.host) ?? ""))
5148
5425
  return deny("403 Forbidden");
5149
- // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
5150
- // the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
5151
- if (options.apiOnly && raw !== ATTACH_PATH)
5426
+ // API-only: paired computers are the console's (Settings), and refused with it, whose tokens the attach socket takes as
5427
+ // unknown there (machinesOnly). A run's hosted machine that dials still reaches it, and a run's computer live view takes
5428
+ // its viewer credential (below); a browser's live view stays the console's.
5429
+ if (options.apiOnly && raw !== ATTACH_PATH && viewing?.[2] !== "computer")
5152
5430
  return deny("404 Not Found");
5153
5431
  // A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
5154
5432
  // owner's, lets it in.
@@ -5164,15 +5442,27 @@ async function startHolding(options, data, checked, stops) {
5164
5442
  return deny("404 Not Found");
5165
5443
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
5166
5444
  // (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
5167
- // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing.
5445
+ // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only: the
5446
+ // public address alone, where the minted link opens the page, and the viewer credential for this run (its cookie).
5168
5447
  const sent = String(req.headers.origin ?? "").toLowerCase();
5169
- if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5170
- return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5171
- if (!owner || !signedIn(req, owner))
5172
- return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5448
+ const credential = options.apiOnly ? viewerCredentialOf(req) : undefined;
5449
+ if (options.apiOnly) {
5450
+ if (sent === "" || sent !== publicOrigin)
5451
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5452
+ if (credential === undefined)
5453
+ return (authFailed(raw, "no_credential"), deny("401 Unauthorized"));
5454
+ }
5455
+ else {
5456
+ if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5457
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5458
+ if (!owner || !signedIn(req, owner))
5459
+ return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5460
+ }
5173
5461
  // Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
5174
5462
  let piping = false;
5175
5463
  void (async () => {
5464
+ if (options.apiOnly && !(await viewerHolds(credential, viewing[1])))
5465
+ return (authFailed(raw, "viewer_credential"), deny("403 Forbidden"));
5176
5466
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
5177
5467
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
5178
5468
  // runner holds. A /computer/live socket reaches a viewer of every kind, a
@@ -5185,11 +5475,16 @@ async function startHolding(options, data, checked, stops) {
5185
5475
  if (socket.destroyed || closing)
5186
5476
  return void socket.destroy();
5187
5477
  // Checked again after the lookup, then for as long as the socket is open: the sessions that let it in, and no other.
5188
- const held = heldSessions(req);
5189
- const admitted = () => held.some((value) => owner.valid(value));
5190
- if (!admitted())
5191
- return deny("401 Unauthorized");
5192
- viewers.watch(socket, admitted);
5478
+ // API-only: the credential's run not ended, read from the store (its revocation); its expiry bounds the opening alone.
5479
+ if (options.apiOnly)
5480
+ viewers.watch(socket, async () => !(await runOver(store, run.id)));
5481
+ else {
5482
+ const held = heldSessions(req);
5483
+ const admitted = () => held.some((value) => owner.valid(value));
5484
+ if (!admitted())
5485
+ return deny("401 Unauthorized");
5486
+ viewers.watch(socket, admitted);
5487
+ }
5193
5488
  proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reachForRun(reach, run.id));
5194
5489
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
5195
5490
  };
@@ -5215,8 +5510,9 @@ async function startHolding(options, data, checked, stops) {
5215
5510
  names = loopbackNames(host, options.allowHosts, options.publicUrl);
5216
5511
  // An address of every interface is reached on this machine at its loopback one.
5217
5512
  const url = urlOf(server, host);
5218
- owner?.attach(options.publicUrl ?? url);
5513
+ owner?.attach(options.publicUrl ?? url, options.publicUrl ? [] : elsewhereOf(host, server.address().port));
5219
5514
  webhooks.attach(options.publicUrl ?? url);
5515
+ slack.attach(options.publicUrl ?? url);
5220
5516
  // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
5221
5517
  // other services: mcp-oauth.ts mcpServerAt), and only as its operator says (mcpLoopback), never inferred from where it
5222
5518
  // listens: a hosted container listens on loopback behind its proxy too.
@@ -5230,8 +5526,30 @@ async function startHolding(options, data, checked, stops) {
5230
5526
  await new Promise((done) => server.close(() => done()));
5231
5527
  throw error;
5232
5528
  });
5529
+ // It serves: the public address it serves at is remembered now, and a change of it said (above).
5530
+ address.keep((said) => void process.stderr.write(`agentrun-serve: ${said}\n`));
5531
+ if (address.changed) {
5532
+ const line = logLine("public_url_changed", { from: address.changed.from ?? "none", to: address.changed.to ?? "none", warning: publicAddressChanged });
5533
+ if (log)
5534
+ log(line);
5535
+ else
5536
+ process.stderr.write(`agentrun-serve: ${line}\n`);
5537
+ }
5233
5538
  // The lister's own passes (above), once this server listens and knows its own address (ownOriginOf).
5234
5539
  lister.start();
5540
+ // Then, not waited on: every ended run whose stored cost is unknown heals by its run read's rule, the store's figure
5541
+ // from a priced booking (cost-heal.ts), a page at a time. One count line when it read any run, no ids; a store with
5542
+ // none says nothing. Drained by stop.
5543
+ const costHealSaid = (fields) => {
5544
+ const line = logLine("cost_heal", fields);
5545
+ if (log)
5546
+ log(line);
5547
+ else
5548
+ process.stderr.write(`agentrun-serve: ${line}\n`);
5549
+ };
5550
+ costHealed = healEndedCosts(store, { stopped: () => costHealStopped })
5551
+ .then(({ read, healed, failed }) => (read > 0 ? costHealSaid({ read, healed, failed }) : undefined))
5552
+ .catch((error) => costHealSaid({ condition: "cost_heal_failed", error: error.message }));
5235
5553
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
5236
5554
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
5237
5555
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -5324,6 +5642,15 @@ async function startHolding(options, data, checked, stops) {
5324
5642
  if ((await webhooks.emit("run.needs_input", run, marker)) === "unsaved")
5325
5643
  throw new Error("its run.needs_input is not saved yet");
5326
5644
  });
5645
+ // Slack hears the same moments, under its own ledger (slack.ts).
5646
+ runNotices.onEnded(async (run, marker) => {
5647
+ if ((await slack.emit("run.ended", run, marker)) === "unsaved")
5648
+ throw new Error("its Slack run.ended is not saved yet");
5649
+ });
5650
+ runNotices.onWaits(async (run, _wait, marker) => {
5651
+ if ((await slack.emit("run.needs_input", run, marker)) === "unsaved")
5652
+ throw new Error("its Slack run.needs_input is not saved yet");
5653
+ });
5327
5654
  /** Every call of `calls` made: false when one threw (said once for the run), so the run is told again. */
5328
5655
  const toldAll = async (id, calls) => {
5329
5656
  let done = true;
@@ -5486,9 +5813,12 @@ async function startHolding(options, data, checked, stops) {
5486
5813
  const rows = await store.runs.list({});
5487
5814
  // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
5488
5815
  // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
5489
- const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5816
+ const ends = rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf);
5817
+ const unsaved = await webhooks.catchUp(ends, (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5490
5818
  for (const id of unsaved)
5491
5819
  endsLeft.add(id);
5820
+ for (const id of await slack.catchUp(ends, (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error)))))
5821
+ endsLeft.add(id);
5492
5822
  // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
5493
5823
  for (const row of rows)
5494
5824
  if (!closing && (letGo(row) || stopRow(row)) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
@@ -5531,6 +5861,7 @@ async function startHolding(options, data, checked, stops) {
5531
5861
  clearTimeout(endsTimer);
5532
5862
  await endsRead;
5533
5863
  await webhooks.close();
5864
+ await slack.close();
5534
5865
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
5535
5866
  viewers.close();
5536
5867
  await attach.close();
@@ -5539,8 +5870,17 @@ async function startHolding(options, data, checked, stops) {
5539
5870
  await githubStopped;
5540
5871
  // --faux-github's fake GitHub API, once nothing asks it anything.
5541
5872
  await fauxGitHub?.close();
5542
- // The listings' builder ends its pass before the store it reads and writes closes.
5873
+ // The start's cost heal stops at its next run, and the listings' builder ends its pass, before the store they read
5874
+ // and write closes.
5875
+ costHealStopped = true;
5876
+ await costHealed;
5543
5877
  await lister.stop();
5878
+ // No more sweeps of the runs no runner can take, and the refused word of the runner beside it goes with it: a start
5879
+ // whose runner can claim finds no refusal of this one.
5880
+ refusedStopped = true;
5881
+ clearInterval(refusedTimer);
5882
+ await refusedSweep;
5883
+ await refusedBeside?.close();
5544
5884
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
5545
5885
  await store.close();
5546
5886
  dataLock.release();
@@ -5567,5 +5907,12 @@ async function startHolding(options, data, checked, stops) {
5567
5907
  // No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
5568
5908
  stopping: () => ({ runs: 0, boundMs: 0 }),
5569
5909
  listingSettled: () => lister.settled(),
5910
+ refuseRuns: (words) => {
5911
+ if (refusedBeside || refusedStopped)
5912
+ return;
5913
+ refusedBeside = keepPresence(store.runners, `${hostname()}:${process.pid}:beside`, words, { warn: (line) => void process.stderr.write(`agentrun-serve: ${line}\n`) });
5914
+ // The runs it left queued fail now, not at the next sweep.
5915
+ void sweepRefused();
5916
+ },
5570
5917
  };
5571
5918
  }