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

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 (256) hide show
  1. package/CHANGELOG.md +180 -0
  2. package/NOTICE +4 -0
  3. package/README.md +283 -47
  4. package/dist/acp-package.d.ts +35 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +5 -2
  7. package/dist/adapter-facts.js +6 -3
  8. package/dist/adapters.d.ts +7 -0
  9. package/dist/adapters.js +39 -0
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/api-only.d.ts +7 -10
  13. package/dist/api-only.js +7 -10
  14. package/dist/archil-routes.js +2 -1
  15. package/dist/cap.js +12 -2
  16. package/dist/chatgpt-plan.js +2 -1
  17. package/dist/cli.js +119 -44
  18. package/dist/composio-made.d.ts +19 -2
  19. package/dist/composio-made.js +17 -5
  20. package/dist/composio-preset.d.ts +42 -7
  21. package/dist/composio-preset.js +106 -70
  22. package/dist/composio-triggers.d.ts +9 -4
  23. package/dist/composio-triggers.js +20 -13
  24. package/dist/computer-attach.d.ts +11 -10
  25. package/dist/computer-attach.js +13 -14
  26. package/dist/computer-commands.d.ts +3 -0
  27. package/dist/computer-commands.js +3 -2
  28. package/dist/computer-lost.d.ts +4 -0
  29. package/dist/computer-lost.js +8 -3
  30. package/dist/computer-setting.d.ts +2 -0
  31. package/dist/computer-setting.js +2 -0
  32. package/dist/computers.d.ts +9 -75
  33. package/dist/computers.js +20 -66
  34. package/dist/console/assets/index-BBFzAxLB.js +715 -0
  35. package/dist/console/assets/index-BRi-Rgq6.css +1 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/cost-heal.d.ts +13 -0
  38. package/dist/cost-heal.js +27 -0
  39. package/dist/dial-relay.d.ts +6 -2
  40. package/dist/dial-relay.js +9 -12
  41. package/dist/email/routes.js +2 -1
  42. package/dist/errors.d.ts +2 -0
  43. package/dist/errors.js +5 -0
  44. package/dist/exa-keyless.d.ts +1 -1
  45. package/dist/exa-keyless.js +1 -1
  46. package/dist/faux-computers.d.ts +2 -3
  47. package/dist/faux-computers.js +9 -31
  48. package/dist/github-connection.js +2 -1
  49. package/dist/harness-archive.d.ts +19 -2
  50. package/dist/harness-archive.js +49 -15
  51. package/dist/harness-check.d.ts +73 -0
  52. package/dist/harness-check.js +489 -0
  53. package/dist/harness-cursor.d.ts +45 -0
  54. package/dist/harness-cursor.js +121 -0
  55. package/dist/harness-recipe.d.ts +127 -0
  56. package/dist/harness-recipe.js +357 -0
  57. package/dist/harness-table.d.ts +12 -0
  58. package/dist/harness-table.js +62 -2
  59. package/dist/harness.d.ts +2 -0
  60. package/dist/harness.js +3 -2
  61. package/dist/host-check.d.ts +6 -0
  62. package/dist/host-check.js +14 -0
  63. package/dist/host.d.ts +10 -3
  64. package/dist/host.js +17 -3
  65. package/dist/import-sources.d.ts +2 -0
  66. package/dist/import-sources.js +2 -0
  67. package/dist/import-summary.d.ts +15 -5
  68. package/dist/import-summary.js +24 -8
  69. package/dist/import.d.ts +34 -4
  70. package/dist/import.js +134 -32
  71. package/dist/key-refusal.d.ts +1 -0
  72. package/dist/key-refusal.js +8 -3
  73. package/dist/key-words.d.ts +1 -1
  74. package/dist/key-words.js +4 -4
  75. package/dist/learn/check.d.ts +3 -0
  76. package/dist/learn/check.js +31 -20
  77. package/dist/learn/compile.js +11 -4
  78. package/dist/learn/promote.d.ts +77 -4
  79. package/dist/learn/promote.js +123 -2
  80. package/dist/learned-nodes.d.ts +4 -3
  81. package/dist/learned-workflow.js +4 -1
  82. package/dist/learning-cost.d.ts +6 -16
  83. package/dist/learning-cost.js +6 -12
  84. package/dist/learning-setting.d.ts +17 -6
  85. package/dist/learning-setting.js +41 -5
  86. package/dist/learning-words.d.ts +2 -0
  87. package/dist/learning-words.js +1 -1
  88. package/dist/listen-first.d.ts +10 -0
  89. package/dist/listen-first.js +25 -1
  90. package/dist/llms.txt +1 -1
  91. package/dist/mcp-gateway.d.ts +2 -1
  92. package/dist/mcp-gateway.js +31 -15
  93. package/dist/mcp-probe.d.ts +18 -6
  94. package/dist/mcp-probe.js +41 -8
  95. package/dist/mcp-secret-writes.d.ts +8 -0
  96. package/dist/mcp-secret-writes.js +104 -4
  97. package/dist/mcp-servers-store.d.ts +11 -5
  98. package/dist/mcp-servers-store.js +46 -20
  99. package/dist/model-form.d.ts +2 -1
  100. package/dist/model-form.js +22 -8
  101. package/dist/model-gateway.d.ts +113 -0
  102. package/dist/model-gateway.js +433 -0
  103. package/dist/model.d.ts +2 -1
  104. package/dist/model.js +9 -7
  105. package/dist/monid.js +1 -1
  106. package/dist/native/binding.d.ts +4 -0
  107. package/dist/native/binding.js +9 -0
  108. package/dist/native/cli.d.ts +3 -2
  109. package/dist/native/cli.js +6 -5
  110. package/dist/openapi.d.ts +2 -0
  111. package/dist/openapi.js +326 -41
  112. package/dist/owner.d.ts +4 -2
  113. package/dist/owner.js +10 -4
  114. package/dist/page.d.ts +8 -0
  115. package/dist/page.js +9 -1
  116. package/dist/port-models.js +17 -10
  117. package/dist/provider.d.ts +3 -3
  118. package/dist/provider.js +12 -3
  119. package/dist/public-address.d.ts +28 -0
  120. package/dist/public-address.js +62 -0
  121. package/dist/run-launch.d.ts +1 -1
  122. package/dist/run-launch.js +1 -1
  123. package/dist/run-secrets.d.ts +3 -2
  124. package/dist/run-secrets.js +6 -4
  125. package/dist/runner/adapter-loop.d.ts +10 -7
  126. package/dist/runner/adapter-loop.js +57 -22
  127. package/dist/runner/adapter-run-spec.d.ts +12 -0
  128. package/dist/runner/adapter-run-spec.js +40 -6
  129. package/dist/runner/adapters/index.js +16 -0
  130. package/dist/runner/adapters/pi.d.ts +5 -2
  131. package/dist/runner/adapters/pi.js +7 -4
  132. package/dist/runner/audit.d.ts +7 -0
  133. package/dist/runner/audit.js +24 -6
  134. package/dist/runner/claim-secrets.js +5 -1
  135. package/dist/runner/cli-run-spec.js +15 -7
  136. package/dist/runner/compare-end.d.ts +43 -0
  137. package/dist/runner/compare-end.js +95 -0
  138. package/dist/runner/computer-journal.d.ts +3 -0
  139. package/dist/runner/computer-journal.js +22 -2
  140. package/dist/runner/conformance/harness.js +19 -8
  141. package/dist/runner/conformance/subject.d.ts +6 -0
  142. package/dist/runner/harness-loops.d.ts +6 -1
  143. package/dist/runner/harness-loops.js +94 -54
  144. package/dist/runner/held.d.ts +5 -4
  145. package/dist/runner/journal-kinds.d.ts +4 -1
  146. package/dist/runner/journal-kinds.js +3 -0
  147. package/dist/runner/loop-contract.d.ts +10 -0
  148. package/dist/runner/main.d.ts +5 -5
  149. package/dist/runner/main.js +81 -11
  150. package/dist/runner/mcp-claim.js +40 -12
  151. package/dist/runner/metrics.d.ts +26 -0
  152. package/dist/runner/metrics.js +44 -1
  153. package/dist/runner/presence.d.ts +41 -0
  154. package/dist/runner/presence.js +89 -0
  155. package/dist/runner/promotion.d.ts +10 -3
  156. package/dist/runner/promotion.js +42 -21
  157. package/dist/runner/run-child-host.js +52 -14
  158. package/dist/runner/runner.d.ts +5 -0
  159. package/dist/runner/runner.js +8 -0
  160. package/dist/runner/store-port.d.ts +3 -0
  161. package/dist/runner/store-secrets.js +19 -7
  162. package/dist/runner/workflow-first.d.ts +5 -2
  163. package/dist/runner/workflow-first.js +6 -3
  164. package/dist/runs-over-store.d.ts +6 -2
  165. package/dist/runs-over-store.js +14 -4
  166. package/dist/sdk/runs.d.ts +1 -1
  167. package/dist/sdk/runs.js +6 -1
  168. package/dist/sdk/schema.js +1 -1
  169. package/dist/secret-writes.d.ts +16 -3
  170. package/dist/secret-writes.js +28 -3
  171. package/dist/server-secrets-store.js +5 -0
  172. package/dist/server.d.ts +31 -2
  173. package/dist/server.js +326 -53
  174. package/dist/sign-ins-secrets.js +4 -1
  175. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  176. package/dist/slack-url.d.ts +5 -0
  177. package/dist/slack-url.js +11 -0
  178. package/dist/slack.d.ts +107 -0
  179. package/dist/slack.js +292 -0
  180. package/dist/start-switches.d.ts +28 -0
  181. package/dist/start-switches.js +37 -0
  182. package/dist/stats.d.ts +1 -1
  183. package/dist/stats.js +2 -1
  184. package/dist/stop-signals.d.ts +11 -0
  185. package/dist/stop-signals.js +22 -0
  186. package/dist/store/agent-body.d.ts +1 -1
  187. package/dist/store/agent-body.js +2 -2
  188. package/dist/store/index.d.ts +3 -3
  189. package/dist/store/index.js +1 -1
  190. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  191. package/dist/store/postgres/store.d.ts +1 -1
  192. package/dist/store/postgres/store.js +4 -2
  193. package/dist/store/schema.d.ts +13 -5
  194. package/dist/store/schema.js +20 -11
  195. package/dist/store/seal.d.ts +16 -4
  196. package/dist/store/sqlite/store.d.ts +1 -1
  197. package/dist/store/sqlite/store.js +106 -27
  198. package/dist/store/store.d.ts +75 -23
  199. package/dist/store/store.js +11 -0
  200. package/dist/store-reads/analytics.js +3 -2
  201. package/dist/store-reads/cap.d.ts +7 -0
  202. package/dist/store-reads/cap.js +11 -1
  203. package/dist/store-reads/journal.js +27 -1
  204. package/dist/store-reads/learning.d.ts +23 -2
  205. package/dist/store-reads/learning.js +29 -8
  206. package/dist/store-reads/runs.d.ts +9 -0
  207. package/dist/store-reads/runs.js +19 -6
  208. package/dist/store-reads/stats.d.ts +4 -1
  209. package/dist/store-reads/stats.js +15 -6
  210. package/dist/store-view.d.ts +123 -14
  211. package/dist/store-view.js +154 -21
  212. package/dist/telemetry.d.ts +7 -7
  213. package/dist/telemetry.js +38 -15
  214. package/dist/templates.d.ts +6 -3
  215. package/dist/templates.js +38 -3
  216. package/dist/timeline/timeline.js +18 -0
  217. package/dist/tool-keys-store.js +2 -2
  218. package/dist/tool-keys.js +2 -1
  219. package/dist/tool-plane.js +2 -2
  220. package/dist/trigger-adapter.d.ts +3 -4
  221. package/dist/trigger-adapter.js +2 -2
  222. package/dist/trigger-composio.js +3 -3
  223. package/dist/trigger-email.js +0 -2
  224. package/dist/trigger-feed.js +0 -2
  225. package/dist/trigger-schedule.js +3 -0
  226. package/dist/trigger-secrets-shown.d.ts +6 -3
  227. package/dist/trigger-secrets-shown.js +22 -13
  228. package/dist/trigger-targets.d.ts +1 -1
  229. package/dist/trigger-targets.js +19 -8
  230. package/dist/triggers.d.ts +7 -3
  231. package/dist/triggers.js +2 -1
  232. package/dist/webhooks.d.ts +85 -9
  233. package/dist/webhooks.js +129 -46
  234. package/dist/wires.d.ts +6 -1
  235. package/dist/wires.js +5 -0
  236. package/dist/workspace/attach.d.ts +3 -2
  237. package/dist/workspace/attach.js +2 -1
  238. package/dist/workspace/attached-computers.d.ts +6 -8
  239. package/dist/workspace/attached-computers.js +27 -24
  240. package/dist/workspace/computer-deps.d.ts +2 -3
  241. package/dist/workspace/computer-deps.js +3 -6
  242. package/dist/workspace/computer-for-claim.js +72 -96
  243. package/dist/workspace/computer-kept.d.ts +0 -7
  244. package/dist/workspace/computer-kept.js +0 -17
  245. package/dist/workspace/resolve-computer.d.ts +18 -14
  246. package/dist/workspace/resolve-computer.js +47 -60
  247. package/dist/workspace/synced-folder.d.ts +20 -15
  248. package/dist/workspace/synced-folder.js +33 -43
  249. package/launcher/agentrun-serve +4 -1
  250. package/package.json +10 -10
  251. package/skills/agentrun-serve/SKILL.md +11 -0
  252. package/templates/README.md +1 -1
  253. package/templates/inbound-lead/agent.md +2 -1
  254. package/templates/kyb/agent.md +2 -1
  255. package/dist/console/assets/index-3O2Yl6hZ.js +0 -701
  256. package/dist/console/assets/index-DaFsZuzQ.css +0 -1
package/dist/server.js CHANGED
@@ -7,7 +7,7 @@ import { routeOf as sdkModelRoute } from "./runner/model-route.js";
7
7
  import { answerSkill } from './skill-route.js';
8
8
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
9
9
  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";
10
+ import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED, NATIVE_CAP_UNSUPPORTED } from "./native/binding.js";
11
11
  import { discoverNative } from "./native/discovery.js";
12
12
  import { isNativeRuntime } from "./native/runtimes.js";
13
13
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
@@ -24,7 +24,7 @@ import { Worker } from "node:worker_threads";
24
24
  import { once } from "node:events";
25
25
  import { existsSync } from "node:fs";
26
26
  import { rm } from "node:fs/promises";
27
- import { homedir } from "node:os";
27
+ import { homedir, hostname } from "node:os";
28
28
  import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
29
29
  import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
30
30
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
@@ -43,7 +43,7 @@ import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harn
43
43
  import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, tableIds } from "./harness-table.js";
44
44
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
45
45
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
46
- import { DEFAULT_HOST, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
46
+ import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
47
47
  import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
48
48
  import { answerStoreCall } from "./import-proxy.js";
49
49
  import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
@@ -56,8 +56,9 @@ import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
56
56
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
57
57
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
58
58
  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";
59
+ import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
60
+ import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
61
+ import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
61
62
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
62
63
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
63
64
  import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
@@ -65,8 +66,10 @@ import { readKept } from "./workspace/computer-kept.js";
65
66
  import { dialHost, liveReachOf, reachForRun } from "./live-reach.js";
66
67
  import { screenWaitEnded } from "./browser-wait-ended.js";
67
68
  import { durationMs, logLine } from "./print.js";
69
+ import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
68
70
  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";
71
+ import { builtOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
72
+ import { healEndedCosts } from "./cost-heal.js";
70
73
  import { createLister } from "./run-listing.js";
71
74
  import { HELD_WAITS } from "./runner/journal-kinds.js";
72
75
  import { servedTimelineRows } from "./run-timeline-served.js";
@@ -108,13 +111,15 @@ import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addre
108
111
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
109
112
  import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
110
113
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
111
- import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
114
+ import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
112
115
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
116
+ import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
113
117
  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
118
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
115
119
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
116
120
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
117
121
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
122
+ import { joinedBasis } from "./runner/metrics.js";
118
123
  import { agentLoopOverStore } from "./store-reads/loop.js";
119
124
  import { printable } from "./learn/index.js";
120
125
  import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
@@ -124,17 +129,20 @@ import { toolKeysOverStore } from "./tool-keys-store.js";
124
129
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
125
130
  import { signInsOverStore } from "./sign-ins-store.js";
126
131
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
127
- import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
132
+ import { composioMadeKey, composioPerRun } from "./composio-made.js";
133
+ import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
128
134
  import { ComposioTriggers } from "./composio-triggers.js";
129
135
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
136
+ import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
130
137
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
131
138
  import { privateHostsRoute, saveServerOwn } from "./mcp-private-hosts.js";
132
139
  import { metaToolOf } from "./mcp-meta.js";
133
140
  import { mcpPinOf } from "./mcp-gateway.js";
134
141
  import { LOOPBACK, MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
135
142
  import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
143
+ import { SLACK_EVENTS, SlackPosts } from "./slack.js";
136
144
  import { appPermissionWarnings } from "./template-github-permissions.js";
137
- import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
145
+ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
138
146
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
139
147
  import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
140
148
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
@@ -166,7 +174,7 @@ import { recordingsFolder } from "./workspace/paths.js";
166
174
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
167
175
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
168
176
  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";
177
+ import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
170
178
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
171
179
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
172
180
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -204,6 +212,8 @@ const IMPORT_STARTS = 3;
204
212
  const IMPORT_HEAP_MB = 2048;
205
213
  const MAX_MESSAGE = 20_000;
206
214
  const MAX_WAIT_MS = 25_000;
215
+ /** How often the server fails the runs still queued while no runner here can take them (runner/presence.ts). */
216
+ const REFUSED_SWEEP_MS = 2_000;
207
217
  const PAGE_ROWS = 500;
208
218
  const FILE_LIST_CAP = 2_000;
209
219
  /** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
@@ -382,6 +392,11 @@ export const ROUTES = [
382
392
  { method: "PUT", pattern: /^\/settings\/claude-login$/, name: "turnOnClaudeLogin" },
383
393
  { method: "DELETE", pattern: /^\/settings\/claude-login$/, name: "turnOffClaudeLogin" },
384
394
  { method: "POST", pattern: /^\/settings\/claude-login\/login$/, name: "startClaudeLogin" },
395
+ // The model gateway saved in the console (model-gateway.ts): its save, removal and test the owner's session's alone.
396
+ { method: "GET", pattern: /^\/settings\/model-gateway$/, name: "getModelGateway" },
397
+ { method: "PUT", pattern: /^\/settings\/model-gateway$/, name: "saveModelGateway" },
398
+ { method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
399
+ { method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
385
400
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
386
401
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
387
402
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
@@ -408,9 +423,16 @@ export const ROUTES = [
408
423
  { method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
409
424
  { method: "PUT", pattern: /^\/settings\/webhook$/, name: "saveWebhook" },
410
425
  { method: "DELETE", pattern: /^\/settings\/webhook$/, name: "deleteWebhook" },
426
+ { method: "POST", pattern: /^\/settings\/webhook\/secret$/, name: "rotateWebhookSecret" },
411
427
  { method: "POST", pattern: /^\/settings\/webhook\/test$/, name: "testWebhook" },
412
428
  { method: "GET", pattern: /^\/settings\/webhook\/deliveries$/, name: "listWebhookDeliveries" },
413
429
  { method: "POST", pattern: /^\/settings\/webhook\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverWebhook" },
430
+ { method: "GET", pattern: /^\/settings\/slack$/, name: "getSlack" },
431
+ { method: "PUT", pattern: /^\/settings\/slack$/, name: "saveSlack" },
432
+ { method: "DELETE", pattern: /^\/settings\/slack$/, name: "deleteSlack" },
433
+ { method: "POST", pattern: /^\/settings\/slack\/test$/, name: "testSlack" },
434
+ { method: "GET", pattern: /^\/settings\/slack\/deliveries$/, name: "listSlackDeliveries" },
435
+ { method: "POST", pattern: /^\/settings\/slack\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverSlack" },
414
436
  { method: "GET", pattern: /^\/triggers$/, name: "listTriggers" },
415
437
  { method: "POST", pattern: /^\/triggers$/, name: "createTrigger" },
416
438
  { method: "GET", pattern: /^\/triggers\/([^/]+)$/, name: "getTrigger" },
@@ -518,10 +540,13 @@ export function offersEnvOf(env) {
518
540
  delete descriptors[name];
519
541
  return Object.defineProperties({}, descriptors);
520
542
  }
543
+ /** The model gateway's variables, which a gateway saved in the console sets (model-gateway.ts withSavedGateway): which
544
+ * harnesses run, and on what, follow them. */
545
+ const GATEWAY_VARS = ["AGENT_MODEL_BASE_URL", "AGENT_MODEL_GATEWAY_IDS", "AGENT_MODEL", "AGENT_MODEL_FAST", "AGENT_MODEL_STRONG"];
521
546
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
522
547
  * 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
548
  * 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];
549
+ 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
550
  /** 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
551
  async function planStep(step) {
527
552
  try {
@@ -558,6 +583,11 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
558
583
  export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = []) {
559
584
  return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes);
560
585
  }
586
+ /** Those switches as `env` sets them, the CLI's way, for a server whose options name neither. */
587
+ const switchedOnBy = (env, options = {}) => ({
588
+ mcpLoopback: options.mcpLoopback ?? env[MCP_ALLOW_LOOPBACK_ENV] === "1",
589
+ webhookPrivateTargets: options.webhookPrivateTargets ?? env[WEBHOOK_PRIVATE_TARGETS_ENV] === "1",
590
+ });
561
591
  /** The capabilities document as `req`'s caller reads it: approving takes the owner's password session alone, so only
562
592
  * that caller reads `approve: true`; every other (a token, a run, accounts off) reads `approve_needs: "password"`. */
563
593
  export function forCaller(caps, ownerSession) {
@@ -566,8 +596,9 @@ export function forCaller(caps, ownerSession) {
566
596
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
567
597
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
568
598
  * 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") {
599
+ * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. `switched`: the two
600
+ * start-time switches the server takes as options (switchedOnBy reads them from `env`, as the CLI sets them). */
601
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
571
602
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
572
603
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
573
604
  const memory = hostMemory();
@@ -598,6 +629,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
598
629
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
599
630
  * it (tool-keys.ts), when one does. */
600
631
  tools,
632
+ /** The switches only the operator sets, in the server's environment at its start (start-switches.ts): each one's state,
633
+ * the value it read and what it allows. Never a secret's value. */
634
+ switches: startSwitches(env, switched),
601
635
  /** How this server holds its secrets (secrets.ts, the launcher), and what that does not cover. */
602
636
  secrets: {
603
637
  names: [...SECRET_NAMES],
@@ -654,6 +688,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
654
688
  * ends (webhooks.ts); its secret kept sealed under the same seal key. */
655
689
  // Always sealed: the server starts with its seal key (seal-key.ts bootSealKey), so nothing is kept in the clear.
656
690
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
691
+ /** /settings/slack: one Slack incoming-webhook URL each of `events` is posted to as a readable message (slack.ts); the
692
+ * URL kept sealed, never shown. */
693
+ slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
657
694
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
658
695
  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
696
  },
@@ -892,7 +929,7 @@ async function startHolding(options, data, checked, stops) {
892
929
  const reach = liveReachOf(process.env, seal.key);
893
930
  const attach = createAttachRoutes({
894
931
  store, hub: attachHub, machinesOnly: options.apiOnly === true, runnerApart: options.runnerApart === true,
895
- relay: { relays: store.runnerRelays, reach },
932
+ relay: { runners: store.runners, reach },
896
933
  ...(options.attachTiming ? { timing: options.attachTiming } : {}),
897
934
  log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)),
898
935
  });
@@ -916,6 +953,9 @@ async function startHolding(options, data, checked, stops) {
916
953
  const stopping = new AbortController();
917
954
  /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
918
955
  let schemaSealed = Promise.resolve();
956
+ // The start's sweep of ended runs whose stored cost is unknown (cost-heal.ts), once this server listens; stop drains it.
957
+ let costHealed = Promise.resolve();
958
+ let costHealStopped = false;
919
959
  // This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
920
960
  const storedKeys = (name) => toolKeys.value(name);
921
961
  // A stored key that does not open is said once at the start, never a refusal to start.
@@ -968,7 +1008,13 @@ async function startHolding(options, data, checked, stops) {
968
1008
  const loginRefused = whyNotOneOwner({ apiOnly: options.apiOnly === true, tokens: tokens.length });
969
1009
  await dropRefusedLogin(store.settings, loginOff ?? loginRefused, (line) => (log ? log(logLine("claude_login", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)));
970
1010
  let claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
971
- let env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
1011
+ // The model gateway saved in the console (model-gateway.ts), its key opened: laid over every reading of env, where the
1012
+ // environment names no gateway of its own. Read again at each save or removal (gatewayChanged).
1013
+ let savedGateway = await readSavedGateway(store, seal.key);
1014
+ /** The server's environment as a reading of it sees it: its secrets and saved keys, the ChatGPT sign-in, Claude Code's
1015
+ * login, and the saved model gateway. */
1016
+ const readEnv = (from) => withSavedGateway(withClaudeLogin(withPlan(own(withSecrets(from, "all", storedKeys)), plan), claudeLogin), savedGateway);
1017
+ let env = readEnv(base);
972
1018
  let offers;
973
1019
  let caps;
974
1020
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -983,7 +1029,10 @@ async function startHolding(options, data, checked, stops) {
983
1029
  // imports it (runner/beside.ts): its module reaches the runner's, which reach back to this one's.
984
1030
  const { runIsolationName, runIsolationOf } = await import("./runner/run-child-host.js");
985
1031
  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));
1032
+ // The start-time switches as this server was started: its options, else the CLI's variables. mcpLoopback is the
1033
+ // option alone, as everywhere it is read here (localInstall): the CLI sets it from AGENTRUN_MCP_ALLOW_LOOPBACK.
1034
+ const switched = { mcpLoopback: options.mcpLoopback === true, webhookPrivateTargets: switchedOnBy(process.env, options).webhookPrivateTargets };
1035
+ const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation, switched));
987
1036
  const recompose = () => void (caps = compose());
988
1037
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
989
1038
  let offersFrom;
@@ -1013,10 +1062,10 @@ async function startHolding(options, data, checked, stops) {
1013
1062
  });
1014
1063
  const keysChanged = async () => {
1015
1064
  // 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
1065
+ // serverSecrets live, store-view), and a list builds a listing cut of other keys again (builtOfNow). A failed run's error words
1017
1066
  // name a refused key by the keys and settings, so those listings are built again.
1018
1067
  await lister.keysChanged();
1019
- env = withClaudeLogin(withPlan(own(withSecrets(base, "all", storedKeys)), plan), claudeLogin);
1068
+ env = readEnv(base);
1020
1069
  const mine = ++needsAsked;
1021
1070
  const next = await needsOf(env);
1022
1071
  if (mine === needsAsked)
@@ -1027,6 +1076,11 @@ async function startHolding(options, data, checked, stops) {
1027
1076
  else
1028
1077
  await probe("key");
1029
1078
  };
1079
+ /** After the model gateway is saved or removed in the console: the saved gateway read again, then env, as a key's save. */
1080
+ const gatewayChanged = async () => {
1081
+ savedGateway = await readSavedGateway(store, seal.key);
1082
+ await keysChanged();
1083
+ };
1030
1084
  /** 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
1085
  const planNow = async () => {
1032
1086
  const was = plan.state;
@@ -1131,8 +1185,8 @@ async function startHolding(options, data, checked, stops) {
1131
1185
  paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves, options.runnerApart === true) },
1132
1186
  runnerApart: options.runnerApart === true,
1133
1187
  // 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),
1188
+ // within PRESENCE_STALE_MS on the store's clock (liveRelays), at a host this server dials.
1189
+ relayed: async () => (await liveRelays(store.runners)).some((row) => dialHost(row.host, reach) !== undefined),
1136
1190
  ...(options.faux
1137
1191
  // --faux's providers stand in for every vendor's, a local one's daemon included.
1138
1192
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
@@ -1214,9 +1268,10 @@ async function startHolding(options, data, checked, stops) {
1214
1268
  };
1215
1269
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1216
1270
  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
1271
+ /** The run read's costs (A8, store-reads/learning.ts runAllInOverStore): `cost.usd` its own spend, the
1218
1272
  * 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. */
1273
+ * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown.
1274
+ * `tools_usd`: the part of `usd` its paid tool calls cost (store-view.ts toolsUsdOverStore). */
1220
1275
  const allInViewOf = async (runId, view) => {
1221
1276
  const cost = (view.cost ?? {});
1222
1277
  const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
@@ -1225,7 +1280,7 @@ async function startHolding(options, data, checked, stops) {
1225
1280
  return {};
1226
1281
  // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1227
1282
  // 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 } };
1283
+ 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
1284
  };
1230
1285
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1231
1286
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
@@ -1252,6 +1307,8 @@ async function startHolding(options, data, checked, stops) {
1252
1307
  };
1253
1308
  ({ 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
1309
  secretStores.add("server", () => tokens.map((entry) => entry.token));
1310
+ // The model gateway's key saved in the console (model-gateway.ts): cut from everything shown, as every saved key is.
1311
+ secretStores.add("model-gateway", () => (savedGateway?.key ? [savedGateway.key] : []));
1255
1312
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1256
1313
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1257
1314
  const emailPasswords = new Set();
@@ -1282,7 +1339,7 @@ async function startHolding(options, data, checked, stops) {
1282
1339
  // Any bound given reaches Webhooks' check (0 and NaN are refused there, never dropped for the default).
1283
1340
  ...(options.webhookTimeoutMs !== undefined ? { timeoutMs: options.webhookTimeoutMs } : {}),
1284
1341
  ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1285
- privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1342
+ privateTargets: switched.webhookPrivateTargets,
1286
1343
  });
1287
1344
  // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
1288
1345
  stops.push(() => webhooks.close());
@@ -1291,6 +1348,19 @@ async function startHolding(options, data, checked, stops) {
1291
1348
  if (existsSync(join(data, WEBHOOK_FILE)))
1292
1349
  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
1350
  secretStores.add("webhook", () => webhooks.signingSecrets());
1351
+ // Slack (slack.ts): the webhook's outbox under its own channel, its URL the credential, sealed and cut like a secret.
1352
+ const slack = new SlackPosts(store, sealKey, (fields) => (log ? log(logLine("slack", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("slack", fields)}\n`)), {
1353
+ ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1354
+ ...(options.webhookTimeoutMs !== undefined ? { timeoutMs: options.webhookTimeoutMs } : {}),
1355
+ ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1356
+ privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1357
+ ...(options.slackTarget ? { sendTo: options.slackTarget } : {}),
1358
+ // Each message's strings (an agent's name, a run's title, a trigger's error) cut of every secret the server holds.
1359
+ serverSecrets: () => serverSecrets(),
1360
+ });
1361
+ stops.push(() => slack.close());
1362
+ await slack.load();
1363
+ secretStores.add("slack", () => slack.urlForms());
1294
1364
  const uploads = new Uploads(join(data, UPLOADS_DIR));
1295
1365
  // Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
1296
1366
  // temp file found now is a crashed one's.
@@ -1332,6 +1402,7 @@ async function startHolding(options, data, checked, stops) {
1332
1402
  // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
1333
1403
  // read once for this server (and again after a read that failed), through the faux one under --faux.
1334
1404
  let pricing;
1405
+ const readPrices = new Map();
1335
1406
  const decisionPrice = async (model) => {
1336
1407
  const making = (pricing ??= (async () => {
1337
1408
  const [{ openrouterProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(fauxEnvOf(options), FAUX_OPENROUTER_ENV)]);
@@ -1340,15 +1411,47 @@ async function startHolding(options, data, checked, stops) {
1340
1411
  // One that could not be made is made again next time: a rejection is never kept.
1341
1412
  const provider = await making.catch((error) => { if (pricing === making)
1342
1413
  pricing = undefined; throw error; });
1343
- return provider.priceOf(model);
1414
+ const price = await provider.priceOf(model);
1415
+ readPrices.set(model, price);
1416
+ return price;
1344
1417
  };
1418
+ /** A decision model's price as a save or a start last read it from the catalog (null: the catalog lists none), and
1419
+ * never a read of the catalog of its own: what a GET, which waits on no other service, prices by. A model none has
1420
+ * priced answers PRICE_NOT_READ, which blockersOf takes for a price (no blocker): whether its run is refused is not
1421
+ * known until a start asks. */
1422
+ const PRICE_NOT_READ = { notRead: true };
1423
+ const readDecisionPrice = async (model) => (readPrices.has(model) ? readPrices.get(model) : PRICE_NOT_READ);
1345
1424
  // The run write half (runs-over-store): the server INSERTs a queued run and its launch (startRun), and writes command
1346
1425
  // rows (message/stop/cancel/raise/approve/archive) a run's runner reads and applies. No per-run process, no HTTP door,
1347
1426
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1348
1427
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1349
1428
  // reads launch.model alone).
1350
1429
  const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1430
+ // Why no runner here can take a run, while every runner there refused to claim (runner/presence.ts): read from the
1431
+ // store at each start, capabilities and health answer, so a runner in another process (or on another host over one
1432
+ // Postgres) counts as the one beside this server does, and a runner that can claim, once there, clears it at once.
1433
+ const refusedNow = () => runnersRefused(store.runners);
1434
+ // While it holds, the runs still queued fail in those words (Runs.failUnclaimed), every REFUSED_SWEEP_MS: a run queued
1435
+ // before the refusal was known never waits for good. A run a runner claimed is not one of them.
1436
+ let refusedSweep = Promise.resolve();
1437
+ let refusedStopped = false;
1438
+ const sweepRefused = () => {
1439
+ refusedSweep = refusedSweep.then(async () => {
1440
+ if (refusedStopped)
1441
+ return;
1442
+ const words = await refusedNow();
1443
+ if (words !== undefined && !refusedStopped)
1444
+ await store.runs.failUnclaimed(refusedEnd(words));
1445
+ }).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`));
1446
+ return refusedSweep;
1447
+ };
1448
+ const refusedTimer = setInterval(() => void sweepRefused(), REFUSED_SWEEP_MS);
1449
+ refusedTimer.unref();
1450
+ // The runner beside this server, when its run isolation was refused (cli.ts): its word, kept in this store until the stop.
1451
+ let refusedBeside;
1351
1452
  const startDeps = {
1453
+ // A start while every runner here refused to claim is refused in their words (runner/presence.ts).
1454
+ runnersRefused: refusedNow,
1352
1455
  runBodyIssues,
1353
1456
  boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
1354
1457
  pinnedOf,
@@ -1429,7 +1532,7 @@ async function startHolding(options, data, checked, stops) {
1429
1532
  };
1430
1533
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1431
1534
  const statuses = (agentId) => statusesOf(data, agentId);
1432
- const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
1535
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses });
1433
1536
  // A run read as a whole (its own read, its archive) lists its recordings too, from its recordings folder on this machine
1434
1537
  // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1435
1538
  const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
@@ -1456,7 +1559,7 @@ async function startHolding(options, data, checked, stops) {
1456
1559
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1457
1560
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1458
1561
  // 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 };
1562
+ const servedTimelineDeps = { serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses };
1460
1563
  const timelines = runTimelines({
1461
1564
  context: ctx,
1462
1565
  // The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
@@ -1637,7 +1740,11 @@ async function startHolding(options, data, checked, stops) {
1637
1740
  // queue a firing takes — how many of a trigger's messages wait for a busy run — is route-1's store.triggers.
1638
1741
  ...targets,
1639
1742
  settings: (adapterId) => triggerSettings.get(adapterId),
1640
- notify: (failed, key) => webhooks.emitTrigger(failed, key),
1743
+ // The webhook and Slack each hear of it: told once both have it (or neither is set), again while either has not.
1744
+ notify: async (failed, key) => {
1745
+ const told = await Promise.all([webhooks.emitTrigger(failed, key), slack.emitTrigger(failed, key)]);
1746
+ return told.find((one) => one === "unsaved" || one === "closed") ?? (told.includes("queued") ? "queued" : "off");
1747
+ },
1641
1748
  // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1642
1749
  upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1643
1750
  });
@@ -2264,13 +2371,40 @@ async function startHolding(options, data, checked, stops) {
2264
2371
  return answer;
2265
2372
  }
2266
2373
  // ---- runs -----------------------------------------------------------------------------------------------------------
2374
+ /** Why a run of the agent's current revision started now with no overrides would be refused (409 agent_not_runnable),
2375
+ * as the run's own check says it (runnable, at the place the run resolves to): its message and fields, for the agent
2376
+ * page to show before Run. Null when nothing keeps it from running, for an agent with no revision or archived (its
2377
+ * page says so), or when the check is not one a read makes: a native or SDK agent's (which launches or asks its
2378
+ * backend), and a revision whose MCP tools its first run pins (pinFirst writes the pin; until then a read would warn
2379
+ * of a pin the run makes). A read asks no other service, so it prices by readDecisionPrice. */
2380
+ async function runBlockersOf(entry) {
2381
+ const revision = entry.revision;
2382
+ if (!revision || entry.agent.archivedAt)
2383
+ return null;
2384
+ const body = revision.body;
2385
+ if (nativeOf(body) || sdkOf(body))
2386
+ return null;
2387
+ const tools = revision.kind === "agentic" ? (body.tools ?? []) : [];
2388
+ if (!revision.mcpPin && tools.some((tool) => mcpToolOf(tool)))
2389
+ return null;
2390
+ try {
2391
+ await runnable(revision, resolvePlace(body.place, fallbackPlace(revision.kind, tools)), { capped: body.maxCostUsd !== undefined, price: readDecisionPrice });
2392
+ return null;
2393
+ }
2394
+ catch (error) {
2395
+ if (error instanceof ApiError && error.code === "agent_not_runnable")
2396
+ return { message: error.message, fields: error.extra.fields ?? [] };
2397
+ return null;
2398
+ }
2399
+ }
2267
2400
  /** A workflow revision's shape as runnable.ts checks it: its workflow, tools, harness, place and tool settings. */
2268
2401
  const workflowShape = ({ workflow, tools, harness, place, toolSettings, approvals }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}), ...(approvals === "never" ? { approvals } : {}) });
2269
2402
  const shapeOf = (revision) => (revision.kind === "agentic" ? { kind: "agentic", ...revision.body } : workflowShape(revision.body));
2270
2403
  /** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
2271
2404
  * 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 } = {}) {
2405
+ * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2406
+ * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
2407
+ async function runnable(revision, place, { capped = false, price = decisionPrice } = {}) {
2274
2408
  if (sdkOf(revision.body))
2275
2409
  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
2410
  const native = nativeOf(revision.body);
@@ -2286,7 +2420,7 @@ async function startHolding(options, data, checked, stops) {
2286
2420
  if (!native.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
2287
2421
  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
2422
  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.");
2423
+ throw new ApiError("agent_not_runnable", NATIVE_CAP_UNSUPPORTED);
2290
2424
  if (native.remote)
2291
2425
  await new RemoteConnectors(store).assertReady(native);
2292
2426
  else
@@ -2327,7 +2461,7 @@ async function startHolding(options, data, checked, stops) {
2327
2461
  };
2328
2462
  const monid = revision.monidPin ?? undefined;
2329
2463
  // 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 });
2464
+ 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
2465
  if (!blockers.length)
2332
2466
  return;
2333
2467
  const message = blockers.map((b) => b.message).join(" ");
@@ -2489,8 +2623,9 @@ async function startHolding(options, data, checked, stops) {
2489
2623
  * (NEW_AGENT_TOOLS); elsewhere none named, the runner's own. One rule for a new agent (createAgentOf) and for an apply
2490
2624
  * with agent_id of a package that names none (applyWith), whose agent is where its fresh apply put it. */
2491
2625
  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
2626
+ /** The definition an apply with agent_id writes onto agent `entry` from its package's `definition`: its id and name are
2627
+ * the agent's own, kept from its creation, and its description is the agent's as it is now (an edit may have changed
2628
+ * it; the package's never overwrites it); a package that names no tools gets those its agent's place
2494
2629
  * gives one (defaultToolsAt: the shell tools in the box its fresh apply put it in), as a fresh apply would. */
2495
2630
  const updateDefinition = (entry, definition) => {
2496
2631
  const kept = Object.fromEntries(Object.entries(definition).filter(([key]) => key !== "name" && key !== "description"));
@@ -2638,7 +2773,7 @@ async function startHolding(options, data, checked, stops) {
2638
2773
  const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
2639
2774
  const needed = unsaved.filter((need) => need.required);
2640
2775
  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.";
2776
+ const fix = "Add it in Settings → API Keys, or set it where AgentRun starts, then apply the template again.";
2642
2777
  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
2778
  }
2644
2779
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
@@ -2750,7 +2885,7 @@ async function startHolding(options, data, checked, stops) {
2750
2885
  .filter((one) => one.template?.id === pkg.id && one.template.parameters_digest === digest)
2751
2886
  .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
2887
  // 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
2888
+ // agent's own: the package's never replace them), but what the package owns and leaves out is gone (fromPackage); only onto the
2754
2889
  // revision it read, else 412 with nothing changed. A fresh apply makes the agent as POST /agents does.
2755
2890
  const { entry, warnings } = onto
2756
2891
  ? await reviseAgentOf(onto, { ...made.agent, definition: updateDefinition(onto, made.agent.definition) }, { template: origin, fromPackage: true, ifCurrent: onto.revision?.id ?? null }).catch((error) => {
@@ -2948,12 +3083,25 @@ async function startHolding(options, data, checked, stops) {
2948
3083
  const issues = [];
2949
3084
  const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
2950
3085
  const auth = {};
2951
- for (const [server, headers] of Object.entries(mcp ?? {})) {
3086
+ for (const [server, entry] of Object.entries(mcp ?? {})) {
2952
3087
  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.` });
3088
+ const field = `mcp_auth.${server}`;
3089
+ if (!row) {
3090
+ issues.push({ field, reason: "not_an_option", message: `No MCP server ${server} is saved here.` });
3091
+ continue;
3092
+ }
3093
+ // A per-run Composio server takes a binding (its key is its own); a per_run server takes headers; no other takes either.
3094
+ const perRunComposio = composioPerRun(row, await store.settings.get(composioMadeKey(server)));
3095
+ if ("composio" in entry) {
3096
+ if (perRunComposio)
3097
+ auth[server] = { composio: entry.composio, origin: new URL(row.url).origin };
3098
+ else
3099
+ 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.` });
3100
+ }
3101
+ else if (row.auth === "per_run")
3102
+ auth[server] = { headers: entry.headers, origin: new URL(row.url).origin };
2955
3103
  else
2956
- auth[server] = { headers, origin: new URL(row.url).origin };
3104
+ 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
3105
  }
2958
3106
  const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
2959
3107
  if (issues.length)
@@ -3228,8 +3376,9 @@ async function startHolding(options, data, checked, stops) {
3228
3376
  const secrets = serverSecrets();
3229
3377
  const runs = [];
3230
3378
  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;
3379
+ // 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
3380
+ // its listing back, so the next list finds it current.
3381
+ const kept = listing === null || behind || !builtOfNow(listing, secrets) ? await listNow(row.id, listMark) : listing;
3233
3382
  // A run whose status moved between the two reads is left off this page, never shown under a status it has left.
3234
3383
  if (kept && (status === null || kept.item.status === status))
3235
3384
  runs.push(listedItem(kept, origin, row.archivedAt ?? agentArchivedAt, secrets));
@@ -3365,6 +3514,8 @@ async function startHolding(options, data, checked, stops) {
3365
3514
  // Tool calls run with no price (an MCP tool its owner set none for): outside every cost, counted on `tools`.
3366
3515
  let notMetered = 0;
3367
3516
  const total = { usd: 0, unpriced: 0 };
3517
+ // How the runs' costs in the window were reached (metrics.ts joinedBasis over each run's costBasis).
3518
+ const bases = [];
3368
3519
  // The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
3369
3520
  let browserSeconds = 0;
3370
3521
  // A cost that is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it never
@@ -3387,6 +3538,7 @@ async function startHolding(options, data, checked, stops) {
3387
3538
  // A running run's cost is its booked-so-far spend (store-reads/runs listRuns reads it over the store with
3388
3539
  // spentOverStore); an ended run's is its stored cost. A null cost (a running run with none yet) counts unpriced.
3389
3540
  const usd = row.costUsd ?? null;
3541
+ bases.push(row.costBasis);
3390
3542
  const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
3391
3543
  // By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
3392
3544
  // `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 +3581,7 @@ async function startHolding(options, data, checked, stops) {
3429
3581
  }
3430
3582
  const round = (v) => Math.round(v * 1e6) / 1e6;
3431
3583
  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,
3584
+ 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
3585
  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
3586
  account: null,
3435
3587
  };
@@ -3680,7 +3832,10 @@ async function startHolding(options, data, checked, stops) {
3680
3832
  await planNow();
3681
3833
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
3682
3834
  // 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) } } });
3835
+ // runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
3836
+ // (runner/presence.ts); null while one can, or none is there yet.
3837
+ const runnerRefused = (await refusedNow().catch(() => undefined)) ?? null;
3838
+ 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
3839
  }
3685
3840
  if (found.name === "getOpenapi")
3686
3841
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -3752,8 +3907,9 @@ async function startHolding(options, data, checked, stops) {
3752
3907
  }
3753
3908
  if (found.name === "getHealth") {
3754
3909
  // 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);
3910
+ // Degraded (every runner here refused to claim) is 200: a platform's health check never restarts it over a setting.
3911
+ const health = await healthOf(store, data, minFreeBytes, undefined, refusedNow);
3912
+ return send(res, health.status === "failing" ? 503 : 200, health);
3757
3913
  }
3758
3914
  // Approving a learned workflow held for its owner's OK (a step calls a tool with no price) takes the owner's
3759
3915
  // signed-in page alone: never a token, which a run's process, an agent's MCP client or a script may hold, nor a
@@ -3811,7 +3967,11 @@ async function startHolding(options, data, checked, stops) {
3811
3967
  const checked = { params, store };
3812
3968
  if (await writesSecretFor(found.name, body, checked)) {
3813
3969
  authFailed(`/v2${path}`, "secret_without_session");
3814
- throw new ApiError("forbidden", SECRET_WRITE_REFUSAL);
3970
+ // Where the person finishes it: the operation's console page, filled with what the request held that is no
3971
+ // secret (secretPageFor), at the address people open the console at.
3972
+ const page = await secretPageFor(found.name, body, { params, store });
3973
+ const link = page === undefined ? undefined : `${linkOrigin(req)}${page}`;
3974
+ throw new ApiError("forbidden", secretWriteRefusal(link), link === undefined ? {} : { details: { console_url: link } });
3815
3975
  }
3816
3976
  secretSeen = checked.seen;
3817
3977
  }
@@ -3973,7 +4133,7 @@ async function startHolding(options, data, checked, stops) {
3973
4133
  return tool ? toolEffect(tool.annotations) : undefined;
3974
4134
  };
3975
4135
  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) });
4136
+ return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools, run_blockers: await runBlockersOf(entry) }, { etag: etagOf(entry) });
3977
4137
  }
3978
4138
  case "updateDefinition": {
3979
4139
  const entry = await needAgent(id);
@@ -4594,6 +4754,20 @@ async function startHolding(options, data, checked, stops) {
4594
4754
  throw error;
4595
4755
  }
4596
4756
  }
4757
+ // The model gateway saved in the console (model-gateway.ts): never through `idempotent`, as its body may hold the
4758
+ // key; a save or removal makes the reading again (gatewayChanged), so capabilities and the next run see it at once.
4759
+ case "getModelGateway":
4760
+ case "saveModelGateway":
4761
+ case "deleteModelGateway":
4762
+ case "testModelGateway": {
4763
+ // The test's body is optional (none: the gateway in force is asked); a save's is not.
4764
+ const sent = Number(req.headers["content-length"] ?? 0) > 0 || req.headers["transfer-encoding"] !== undefined;
4765
+ const body = found.name === "saveModelGateway" || (found.name === "testModelGateway" && sent) ? await bodyOf(req) : undefined;
4766
+ if ((found.name === "saveModelGateway" || found.name === "deleteModelGateway") && stopping.signal.aborted)
4767
+ throw new ApiError("unavailable", "The server is shutting down: the model gateway was not changed.");
4768
+ const answer = await modelGatewayRoute({ store, sealKey: seal.key, env: own(withSecrets(base, "own")), changed: gatewayChanged }, found.name, { ...(body !== undefined ? { body } : {}), signal: stopping.signal });
4769
+ return send(res, 200, answer, { "cache-control": "no-store" });
4770
+ }
4597
4771
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
4598
4772
  case "listMcpServers":
4599
4773
  return send(res, 200, await mcpServers.list());
@@ -4921,6 +5095,15 @@ async function startHolding(options, data, checked, stops) {
4921
5095
  const saved = await webhooks.save(await bodyOf(req));
4922
5096
  return send(res, saved.created ? 201 : 200, webhookSaved(saved.view, saved.secret, mayHoldSecrets(req)));
4923
5097
  }
5098
+ case "rotateWebhookSecret": {
5099
+ // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts). Never
5100
+ // through `idempotent`, whose record would keep the secret. It takes no body, as a trigger's rotation takes none.
5101
+ if (req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? 0) !== 0) {
5102
+ 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." }]);
5103
+ }
5104
+ const rotated = await webhooks.rotate();
5105
+ return send(res, 200, webhookRotated(rotated.view, rotated.secret), { "cache-control": "no-store" });
5106
+ }
4924
5107
  case "deleteWebhook":
4925
5108
  await webhooks.remove();
4926
5109
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -4930,6 +5113,23 @@ async function startHolding(options, data, checked, stops) {
4930
5113
  return send(res, 200, await webhooks.attemptsView());
4931
5114
  case "redeliverWebhook":
4932
5115
  return send(res, 200, await webhooks.redeliver(id));
5116
+ case "getSlack":
5117
+ return send(res, 200, slack.slackView());
5118
+ case "saveSlack": {
5119
+ // A body with `url` is a secret write: the dispatch's one check let only the owner's session this far
5120
+ // (slack.ts registers it). The URL is never in the answer.
5121
+ const saved = await slack.saveSlack(await bodyOf(req));
5122
+ return send(res, saved.created ? 201 : 200, saved.view);
5123
+ }
5124
+ case "deleteSlack":
5125
+ await slack.remove();
5126
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5127
+ case "testSlack":
5128
+ return send(res, 200, await slack.test());
5129
+ case "listSlackDeliveries":
5130
+ return send(res, 200, await slack.attemptsView());
5131
+ case "redeliverSlack":
5132
+ return send(res, 200, await slack.redeliver(id));
4933
5133
  case "listTriggers":
4934
5134
  return send(res, 200, { triggers: (await triggers.list()).triggers.map(withSecretOf) });
4935
5135
  case "createTrigger": {
@@ -5059,6 +5259,14 @@ async function startHolding(options, data, checked, stops) {
5059
5259
  return undefined;
5060
5260
  }
5061
5261
  })();
5262
+ // The public address this server last served at, kept in its data folder (public-address.ts): a change signs the owner
5263
+ // out and leaves earlier webhook messages' links on the old address, so the start says so, in one line, once it serves
5264
+ // (below), when it also remembers the new address: a start that fails changes neither.
5265
+ const address = readPublicAddress(data, options.publicUrl);
5266
+ // The earlier address's name (`moved.from`), whose console a browser is redirected from to the new address (`moved.to`,
5267
+ // parsed: a Location header carries no raw name in another script): set only when the server has a public address now
5268
+ // and the earlier name is none it answers to.
5269
+ const moved = movedAddress(address.earlier, options.publicUrl, loopbackNames(host, options.allowHosts, options.publicUrl));
5062
5270
  let names;
5063
5271
  // The listener: the CLI's, bound early and answering warming until the takeover below (listen-first.ts), or a new one.
5064
5272
  const server = options.listener ?? createServer();
@@ -5096,6 +5304,17 @@ async function startHolding(options, data, checked, stops) {
5096
5304
  catch {
5097
5305
  return fail(new ApiError("bad_request", "the request target is not a URL"));
5098
5306
  }
5307
+ // Under the server's earlier public address (public-address.ts): a browser that opens the console is sent on to the new
5308
+ // address, whatever the listener. No other route is: on loopback, the rest is refused as any other name is, in words
5309
+ // that name the new address. That name passes the Host check for this one fixed answer alone, which reads nothing of
5310
+ // the request but its path: it is a name this server's operator set before, and a page that rebound it reads no data.
5311
+ if (moved !== undefined && hostName(req.headers.host) === moved.from) {
5312
+ const browser = /\btext\/html\b/i.test(String(req.headers.accept ?? ""));
5313
+ if (browser && (req.method === "GET" || req.method === "HEAD") && consoleEntry((req.url ?? "/").split("?")[0]))
5314
+ return sendMoved(res, moved.to);
5315
+ if (names)
5316
+ return browser ? sendMovedPage(req, res, moved.to) : fail(new ApiError("forbidden", `unexpected Host header: ${movedFix(moved.to)}`));
5317
+ }
5099
5318
  // 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
5319
  // address. A browser is shown a page that says which names work; a script, the same in the error.
5101
5320
  if (names && !names.has(hostName(req.headers.host) ?? "")) {
@@ -5215,8 +5434,9 @@ async function startHolding(options, data, checked, stops) {
5215
5434
  names = loopbackNames(host, options.allowHosts, options.publicUrl);
5216
5435
  // An address of every interface is reached on this machine at its loopback one.
5217
5436
  const url = urlOf(server, host);
5218
- owner?.attach(options.publicUrl ?? url);
5437
+ owner?.attach(options.publicUrl ?? url, options.publicUrl ? [] : elsewhereOf(host, server.address().port));
5219
5438
  webhooks.attach(options.publicUrl ?? url);
5439
+ slack.attach(options.publicUrl ?? url);
5220
5440
  // 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
5441
  // other services: mcp-oauth.ts mcpServerAt), and only as its operator says (mcpLoopback), never inferred from where it
5222
5442
  // listens: a hosted container listens on loopback behind its proxy too.
@@ -5230,8 +5450,30 @@ async function startHolding(options, data, checked, stops) {
5230
5450
  await new Promise((done) => server.close(() => done()));
5231
5451
  throw error;
5232
5452
  });
5453
+ // It serves: the public address it serves at is remembered now, and a change of it said (above).
5454
+ address.keep((said) => void process.stderr.write(`agentrun-serve: ${said}\n`));
5455
+ if (address.changed) {
5456
+ const line = logLine("public_url_changed", { from: address.changed.from ?? "none", to: address.changed.to ?? "none", warning: publicAddressChanged });
5457
+ if (log)
5458
+ log(line);
5459
+ else
5460
+ process.stderr.write(`agentrun-serve: ${line}\n`);
5461
+ }
5233
5462
  // The lister's own passes (above), once this server listens and knows its own address (ownOriginOf).
5234
5463
  lister.start();
5464
+ // Then, not waited on: every ended run whose stored cost is unknown heals by its run read's rule, the store's figure
5465
+ // 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
5466
+ // none says nothing. Drained by stop.
5467
+ const costHealSaid = (fields) => {
5468
+ const line = logLine("cost_heal", fields);
5469
+ if (log)
5470
+ log(line);
5471
+ else
5472
+ process.stderr.write(`agentrun-serve: ${line}\n`);
5473
+ };
5474
+ costHealed = healEndedCosts(store, { stopped: () => costHealStopped })
5475
+ .then(({ read, healed, failed }) => (read > 0 ? costHealSaid({ read, healed, failed }) : undefined))
5476
+ .catch((error) => costHealSaid({ condition: "cost_heal_failed", error: error.message }));
5235
5477
  // 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
5478
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
5237
5479
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -5245,13 +5487,15 @@ async function startHolding(options, data, checked, stops) {
5245
5487
  * status input_required and idle, a message continues it) and not have ended: its view says which. */
5246
5488
  const stopRow = (row) => row.state === "stopped" && row.outcome === "stopped" && row.importedFrom === null;
5247
5489
  const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}), ...(stopRow(row) ? { stop: true } : {}) });
5490
+ /** Agent `agentId`'s name as the store holds it now, for a webhook notice: its id when it has none, or is gone. */
5491
+ const agentNameOf = async (agentId) => (await store.agents.get(agentId))?.name || agentId;
5248
5492
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
5249
5493
  const endNotice = async (id) => {
5250
5494
  const row = await store.runs.get(id);
5251
5495
  const summary = row && (await summaryOverStore(store, id, viewDepsFor(ownOriginOf())));
5252
5496
  if (!row || !summary)
5253
5497
  return null;
5254
- return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
5498
+ return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, agent_name: await agentNameOf(row.agentId), status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
5255
5499
  };
5256
5500
  /** The run-end read's look at a run: its end from its row alone when it has none, or one told already; else its
5257
5501
  * endNotice. The run's view redacts the run's words (its title, its output) on every build, and the newest runs are
@@ -5297,7 +5541,7 @@ async function startHolding(options, data, checked, stops) {
5297
5541
  // whose card is withheld is a question. A run idle on nothing named (its harness ended its turn on its own) names no kind.
5298
5542
  const kind = typeof card === "string" && waitKinds.has(card) ? card : view.state === "waiting" ? "question" : undefined;
5299
5543
  const wait = kind === undefined ? undefined : { kind };
5300
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
5544
+ const notice = { run_id: row.id, agent_id: row.agentId, agent_name: await agentNameOf(row.agentId), status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
5301
5545
  if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
5302
5546
  return false;
5303
5547
  readWaits.set(row.id, seen);
@@ -5322,6 +5566,15 @@ async function startHolding(options, data, checked, stops) {
5322
5566
  if ((await webhooks.emit("run.needs_input", run, marker)) === "unsaved")
5323
5567
  throw new Error("its run.needs_input is not saved yet");
5324
5568
  });
5569
+ // Slack hears the same moments, under its own ledger (slack.ts).
5570
+ runNotices.onEnded(async (run, marker) => {
5571
+ if ((await slack.emit("run.ended", run, marker)) === "unsaved")
5572
+ throw new Error("its Slack run.ended is not saved yet");
5573
+ });
5574
+ runNotices.onWaits(async (run, _wait, marker) => {
5575
+ if ((await slack.emit("run.needs_input", run, marker)) === "unsaved")
5576
+ throw new Error("its Slack run.needs_input is not saved yet");
5577
+ });
5325
5578
  /** Every call of `calls` made: false when one threw (said once for the run), so the run is told again. */
5326
5579
  const toldAll = async (id, calls) => {
5327
5580
  let done = true;
@@ -5484,9 +5737,12 @@ async function startHolding(options, data, checked, stops) {
5484
5737
  const rows = await store.runs.list({});
5485
5738
  // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
5486
5739
  // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
5487
- const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5740
+ const ends = rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf);
5741
+ const unsaved = await webhooks.catchUp(ends, (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5488
5742
  for (const id of unsaved)
5489
5743
  endsLeft.add(id);
5744
+ for (const id of await slack.catchUp(ends, (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error)))))
5745
+ endsLeft.add(id);
5490
5746
  // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
5491
5747
  for (const row of rows)
5492
5748
  if (!closing && (letGo(row) || stopRow(row)) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
@@ -5529,6 +5785,7 @@ async function startHolding(options, data, checked, stops) {
5529
5785
  clearTimeout(endsTimer);
5530
5786
  await endsRead;
5531
5787
  await webhooks.close();
5788
+ await slack.close();
5532
5789
  // An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
5533
5790
  viewers.close();
5534
5791
  await attach.close();
@@ -5537,8 +5794,17 @@ async function startHolding(options, data, checked, stops) {
5537
5794
  await githubStopped;
5538
5795
  // --faux-github's fake GitHub API, once nothing asks it anything.
5539
5796
  await fauxGitHub?.close();
5540
- // The listings' builder ends its pass before the store it reads and writes closes.
5797
+ // The start's cost heal stops at its next run, and the listings' builder ends its pass, before the store they read
5798
+ // and write closes.
5799
+ costHealStopped = true;
5800
+ await costHealed;
5541
5801
  await lister.stop();
5802
+ // No more sweeps of the runs no runner can take, and the refused word of the runner beside it goes with it: a start
5803
+ // whose runner can claim finds no refusal of this one.
5804
+ refusedStopped = true;
5805
+ clearInterval(refusedTimer);
5806
+ await refusedSweep;
5807
+ await refusedBeside?.close();
5542
5808
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
5543
5809
  await store.close();
5544
5810
  dataLock.release();
@@ -5565,5 +5831,12 @@ async function startHolding(options, data, checked, stops) {
5565
5831
  // No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
5566
5832
  stopping: () => ({ runs: 0, boundMs: 0 }),
5567
5833
  listingSettled: () => lister.settled(),
5834
+ refuseRuns: (words) => {
5835
+ if (refusedBeside || refusedStopped)
5836
+ return;
5837
+ refusedBeside = keepPresence(store.runners, `${hostname()}:${process.pid}:beside`, words, { warn: (line) => void process.stderr.write(`agentrun-serve: ${line}\n`) });
5838
+ // The runs it left queued fail now, not at the next sweep.
5839
+ void sweepRefused();
5840
+ },
5568
5841
  };
5569
5842
  }