@parcha/agentrun-serve 0.1.0-beta.54 → 0.1.0-beta.56

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 (234) hide show
  1. package/CHANGELOG.md +142 -2
  2. package/README.md +310 -98
  3. package/dist/adapters.d.ts +11 -0
  4. package/dist/adapters.js +49 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +6 -13
  7. package/dist/agents-store.js +6 -5
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-only.d.ts +16 -4
  11. package/dist/api-only.js +23 -7
  12. package/dist/calendar/tools.js +3 -2
  13. package/dist/chatgpt-plan.d.ts +16 -1
  14. package/dist/chatgpt-plan.js +116 -12
  15. package/dist/claude-login.d.ts +34 -5
  16. package/dist/claude-login.js +31 -7
  17. package/dist/claude-sign-in.d.ts +35 -0
  18. package/dist/claude-sign-in.js +90 -0
  19. package/dist/cli.js +5 -3
  20. package/dist/composio-made.d.ts +26 -1
  21. package/dist/composio-made.js +39 -2
  22. package/dist/composio-preset.d.ts +3 -2
  23. package/dist/composio-preset.js +46 -14
  24. package/dist/computer-held-routes.js +2 -3
  25. package/dist/computer-setting.d.ts +4 -2
  26. package/dist/computer-setting.js +0 -2
  27. package/dist/computers-running.d.ts +8 -0
  28. package/dist/computers-running.js +27 -0
  29. package/dist/console/assets/backend-Boh7tC4i.js +166 -0
  30. package/dist/console/assets/index-CQ3cJRzI.js +746 -0
  31. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/docker-host-addresses.d.ts +23 -3
  34. package/dist/docker-host-addresses.js +90 -18
  35. package/dist/exa-keyless.d.ts +2 -3
  36. package/dist/exa-keyless.js +43 -127
  37. package/dist/firecrawl-keyless.d.ts +41 -0
  38. package/dist/firecrawl-keyless.js +152 -0
  39. package/dist/handed-secret.d.ts +3 -1
  40. package/dist/handed-secret.js +4 -2
  41. package/dist/harness-keys.d.ts +98 -0
  42. package/dist/harness-keys.js +247 -0
  43. package/dist/harness-recipe-entry.d.ts +14 -9
  44. package/dist/harness-recipe-entry.js +25 -14
  45. package/dist/harness-table.d.ts +16 -1
  46. package/dist/harness-table.js +19 -7
  47. package/dist/harness.d.ts +4 -0
  48. package/dist/harness.js +12 -1
  49. package/dist/host-check.d.ts +6 -0
  50. package/dist/host-check.js +10 -0
  51. package/dist/import-summary.d.ts +1 -1
  52. package/dist/import-summary.js +1 -1
  53. package/dist/import.d.ts +5 -5
  54. package/dist/import.js +54 -67
  55. package/dist/key-refusal.d.ts +21 -5
  56. package/dist/key-refusal.js +231 -37
  57. package/dist/keyless-mcp.d.ts +36 -0
  58. package/dist/keyless-mcp.js +127 -0
  59. package/dist/learn/audit.d.ts +3 -3
  60. package/dist/learn/audit.js +3 -3
  61. package/dist/learn/commit.d.ts +8 -7
  62. package/dist/learn/commit.js +60 -20
  63. package/dist/learn/compile.d.ts +4 -3
  64. package/dist/learn/compile.js +7 -5
  65. package/dist/learn/folder.d.ts +16 -3
  66. package/dist/learn/folder.js +46 -13
  67. package/dist/learn/promote.d.ts +37 -13
  68. package/dist/learn/promote.js +112 -40
  69. package/dist/learn/secrets.d.ts +20 -10
  70. package/dist/learn/secrets.js +44 -176
  71. package/dist/learning-routes.d.ts +22 -17
  72. package/dist/learning-routes.js +40 -39
  73. package/dist/learning.js +2 -2
  74. package/dist/llms.txt +1 -1
  75. package/dist/manifest.d.ts +10 -0
  76. package/dist/manifest.js +30 -0
  77. package/dist/mcp-pin-first.d.ts +4 -2
  78. package/dist/mcp-pin-first.js +5 -2
  79. package/dist/mcp-secret-writes.d.ts +16 -7
  80. package/dist/mcp-secret-writes.js +35 -27
  81. package/dist/mcp-servers-store.d.ts +30 -6
  82. package/dist/mcp-servers-store.js +112 -28
  83. package/dist/mcp-sources.d.ts +10 -2
  84. package/dist/mcp-sources.js +9 -2
  85. package/dist/mcp-store.d.ts +13 -7
  86. package/dist/mcp-store.js +12 -9
  87. package/dist/model-form.d.ts +3 -2
  88. package/dist/model-form.js +11 -7
  89. package/dist/model.d.ts +20 -4
  90. package/dist/model.js +68 -9
  91. package/dist/native/history.d.ts +1 -1
  92. package/dist/native/history.js +2 -2
  93. package/dist/ollama-provider.d.ts +92 -0
  94. package/dist/ollama-provider.js +495 -0
  95. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  96. package/dist/openapi.d.ts +3 -3
  97. package/dist/openapi.js +197 -55
  98. package/dist/page.d.ts +11 -3
  99. package/dist/page.js +22 -7
  100. package/dist/place-offers.d.ts +25 -1
  101. package/dist/place-offers.js +62 -8
  102. package/dist/print.js +1 -1
  103. package/dist/purged-workflow.d.ts +35 -7
  104. package/dist/purged-workflow.js +73 -26
  105. package/dist/redact/match.d.ts +74 -0
  106. package/dist/redact/match.js +771 -0
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/run-timeline-served.d.ts +1 -1
  119. package/dist/run-timeline-served.js +4 -4
  120. package/dist/runner/adapter-loop.d.ts +9 -3
  121. package/dist/runner/adapter-loop.js +34 -15
  122. package/dist/runner/adapter-run-spec.d.ts +3 -0
  123. package/dist/runner/adapter-run-spec.js +9 -4
  124. package/dist/runner/audit.js +8 -4
  125. package/dist/runner/beside.d.ts +2 -1
  126. package/dist/runner/beside.js +13 -5
  127. package/dist/runner/claim-secrets.d.ts +5 -8
  128. package/dist/runner/claim-secrets.js +6 -0
  129. package/dist/runner/cli-run-spec.d.ts +1 -1
  130. package/dist/runner/cli-run-spec.js +41 -7
  131. package/dist/runner/harness-loops.d.ts +22 -9
  132. package/dist/runner/harness-loops.js +21 -11
  133. package/dist/runner/held.d.ts +3 -0
  134. package/dist/runner/learning-end.d.ts +1 -1
  135. package/dist/runner/learning-end.js +8 -3
  136. package/dist/runner/loop-contract.d.ts +9 -4
  137. package/dist/runner/main.js +12 -6
  138. package/dist/runner/mcp-claim.d.ts +3 -0
  139. package/dist/runner/mcp-claim.js +26 -2
  140. package/dist/runner/mcp-run.d.ts +3 -0
  141. package/dist/runner/mcp-run.js +2 -1
  142. package/dist/runner/metrics.d.ts +10 -10
  143. package/dist/runner/metrics.js +19 -38
  144. package/dist/runner/model-route.d.ts +3 -0
  145. package/dist/runner/model-route.js +6 -2
  146. package/dist/runner/presence.d.ts +4 -3
  147. package/dist/runner/presence.js +4 -2
  148. package/dist/runner/promotion.d.ts +15 -9
  149. package/dist/runner/promotion.js +25 -15
  150. package/dist/runner/run-child-host.d.ts +2 -0
  151. package/dist/runner/run-child-host.js +19 -9
  152. package/dist/runner/run-child.js +3 -1
  153. package/dist/runner/runner.d.ts +4 -0
  154. package/dist/runner/runner.js +33 -3
  155. package/dist/runner/sdk-loop.js +2 -0
  156. package/dist/runner/workflow-loop.d.ts +2 -2
  157. package/dist/runner/workflow-loop.js +1 -2
  158. package/dist/runner/workflow-spec.d.ts +1 -1
  159. package/dist/runner/workflow-spec.js +6 -6
  160. package/dist/sdk/check.d.ts +4 -1
  161. package/dist/sdk/check.js +2 -1
  162. package/dist/sdk/runs.d.ts +2 -2
  163. package/dist/sdk/runs.js +8 -6
  164. package/dist/secret-cut.js +2 -1
  165. package/dist/secret-writes.d.ts +3 -2
  166. package/dist/secret-writes.js +1 -1
  167. package/dist/server.d.ts +49 -10
  168. package/dist/server.js +324 -118
  169. package/dist/standard-webhooks.d.ts +11 -0
  170. package/dist/standard-webhooks.js +20 -2
  171. package/dist/store/dialect.d.ts +3 -0
  172. package/dist/store/dialect.js +1 -0
  173. package/dist/store/index.d.ts +2 -2
  174. package/dist/store/index.js +1 -1
  175. package/dist/store/postgres/dialect.js +3 -0
  176. package/dist/store/schema.js +5 -2
  177. package/dist/store/sqlite/store.js +133 -47
  178. package/dist/store/store.d.ts +64 -15
  179. package/dist/store/store.js +7 -0
  180. package/dist/store-reads/journal.d.ts +7 -2
  181. package/dist/store-reads/journal.js +9 -6
  182. package/dist/store-reads/learning.d.ts +12 -9
  183. package/dist/store-reads/learning.js +18 -24
  184. package/dist/store-view.d.ts +0 -5
  185. package/dist/store-view.js +10 -9
  186. package/dist/template-eval.d.ts +51 -6
  187. package/dist/template-eval.js +177 -53
  188. package/dist/template-import.js +4 -2
  189. package/dist/templates.d.ts +5 -3
  190. package/dist/templates.js +19 -40
  191. package/dist/timeline/index.d.ts +1 -1
  192. package/dist/timeline/index.js +1 -1
  193. package/dist/timeline/labels.d.ts +2 -2
  194. package/dist/timeline/labels.js +2 -2
  195. package/dist/timeline/timeline.d.ts +14 -9
  196. package/dist/timeline/timeline.js +15 -7
  197. package/dist/tool-gate.js +3 -1
  198. package/dist/tool-plane.d.ts +17 -9
  199. package/dist/tool-plane.js +38 -17
  200. package/dist/tools.js +2 -2
  201. package/dist/trigger-launch-hook.d.ts +16 -8
  202. package/dist/trigger-launch-hook.js +32 -23
  203. package/dist/trigger-targets.d.ts +18 -8
  204. package/dist/trigger-targets.js +42 -19
  205. package/dist/triggers.d.ts +85 -23
  206. package/dist/triggers.js +303 -96
  207. package/dist/validate.js +1 -1
  208. package/dist/web-fake.js +3 -3
  209. package/dist/web-fetch-direct.d.ts +4 -0
  210. package/dist/web-fetch-direct.js +8 -1
  211. package/dist/web-fetch.d.ts +12 -3
  212. package/dist/web-fetch.js +47 -14
  213. package/dist/web-search.d.ts +33 -4
  214. package/dist/web-search.js +100 -41
  215. package/dist/webhooks.js +4 -5
  216. package/dist/workspace/computer-deps.d.ts +2 -1
  217. package/dist/workspace/computer-deps.js +5 -4
  218. package/dist/workspace/computer-for-claim.d.ts +8 -2
  219. package/dist/workspace/computer-for-claim.js +28 -9
  220. package/dist/workspace/computer-janitor.d.ts +15 -7
  221. package/dist/workspace/computer-janitor.js +33 -8
  222. package/dist/workspace/computer-kept.d.ts +52 -4
  223. package/dist/workspace/computer-kept.js +118 -6
  224. package/dist/workspace/run-end-computers.d.ts +5 -1
  225. package/dist/workspace/run-end-computers.js +27 -1
  226. package/dist/wrapped.d.ts +57 -0
  227. package/dist/wrapped.js +51 -0
  228. package/launcher/agentrun-serve +5 -1
  229. package/package.json +17 -13
  230. package/templates/README.md +10 -9
  231. package/dist/console/assets/index-B_85An2t.js +0 -745
  232. package/dist/console/assets/index-n1YsbnYh.css +0 -1
  233. package/dist/import-sources.d.ts +0 -116
  234. package/dist/import-sources.js +0 -693
package/dist/server.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CALLS_PAGE_ROWS } from "./timeline/index.js";
1
2
  import { prepareProjectSkillEdit } from "./source-sync/skill-edits.js";
2
3
  import { sourceSyncOf } from "./source-sync/types.js";
3
4
  import { sourceService, SOURCE_BODY_BYTES } from "./source-sync/service.js";
@@ -31,7 +32,7 @@ import { createServer } from "node:http";
31
32
  import proxyaddr from "proxy-addr";
32
33
  import { API_ONLY_HOOKED_KINDS, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
33
34
  import { RUN_KEYS_ENV } from "./env-switch.js";
34
- import { declaredKeys, keysOwed, keysOwedRefusal, packageKeysOf, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
35
+ import { declaredKeys, keysOwed, keysOwedRefusal, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
35
36
  import { capacityOverStore, capacityWindowOf } from "./capacity.js";
36
37
  import { carriedFields } from "./answer-json.js";
37
38
  import { dirname, join, relative, resolve, sep } from "node:path";
@@ -50,15 +51,16 @@ import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_
50
51
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
51
52
  import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid, PRICED_BY_USAGE } from "./monid.js";
52
53
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
54
+ import { FAUX_FIRECRAWL_ENV } from "./firecrawl-keyless.js";
53
55
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
54
56
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
55
57
  import { deref, explain } from "./explain.js";
56
58
  import { HOME_HOST_OWNED } from "./files.js";
57
59
  import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
58
60
  import { homePath, hostOwnedOf } from "./home-path.js";
59
- import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
61
+ import { asksOllama, chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
60
62
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
61
- import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_RECIPES_ENV, HARNESS_RECIPES_SETTING, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, harnessRecipesEnv, recipeHarness, tableIds } from "./harness-table.js";
63
+ import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_RECIPES_ENV, HARNESS_RECIPES_SETTING, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, harnessRecipesEnv, planRecipesOf, recipeHarness, tableIds } from "./harness-table.js";
62
64
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
63
65
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
64
66
  import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
@@ -67,7 +69,7 @@ import { answerStoreCall } from "./import-proxy.js";
67
69
  import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf, withAgentRepo } from "./learning.js";
68
70
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
69
71
  import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, forgetRunLearning, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
70
- import { purgedRun } from "./purged-workflow.js";
72
+ import { purgedRun, refusedIn } from "./purged-workflow.js";
71
73
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
72
74
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
73
75
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -75,8 +77,8 @@ import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
75
77
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
76
78
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
77
79
  import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
78
- import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
79
- import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
80
+ import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownerCookieName, ownOrigin, sessionsAtEveryPort, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
81
+ import { hostFix, hostName, isLoopbackName, loopbackNames, movedFix } from "./host-check.js";
80
82
  import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
81
83
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
82
84
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
@@ -125,6 +127,7 @@ import { championOf, forgetRunCopies, GRADE_SOURCES, gradeView, LABEL_MAX, promo
125
127
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
126
128
  import { deleteLearning } from "./learn/delete.js";
127
129
  import { runModelRef } from "./model.js";
130
+ import { ollamaHostOf, ollamaHostRefused, ollamaListing, ollamaModels } from "./ollama-provider.js";
128
131
  import { REDACTED } from "./secret-cut.js";
129
132
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
130
133
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
@@ -132,7 +135,7 @@ import { runLines } from "./usage-lines.js";
132
135
  import { boxesByDefault, boxesLog, enabledBoxes, placeOffers, withNetworks } from "./place-offers.js";
133
136
  import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
134
137
  import { dockerDaemonCheck } from "./docker-daemon.js";
135
- import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
138
+ import { hostAddressesOnce, noHostAddresses, retryHostAddresses, unionOf } from "./docker-host-addresses.js";
136
139
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
137
140
  import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
138
141
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
@@ -140,12 +143,14 @@ import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWri
140
143
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
141
144
  import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
142
145
  import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, loopback, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
146
+ import { ClaudeSignIns } from "./claude-sign-in.js";
143
147
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
144
148
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
145
149
  import { recordDataRoot } from "./runner/disk-free.js";
146
150
  import { recordRunEnv, runFacingNames } from "./runner/runner-check.js";
147
151
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
148
152
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
153
+ import { readWrapped, wrappedView } from "./wrapped.js";
149
154
  import { joinedBasis } from "./runner/metrics.js";
150
155
  import { unifiedUsage } from "./unified-usage.js";
151
156
  import { agentLoopOverStore } from "./store-reads/loop.js";
@@ -154,10 +159,11 @@ import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learning
154
159
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
155
160
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
156
161
  import { toolKeysOverStore } from "./tool-keys-store.js";
162
+ import { HarnessKeysOverStore, harnessKeysSavedHere } from "./harness-keys.js";
157
163
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
158
164
  import { signInsOverStore } from "./sign-ins-store.js";
159
165
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
160
- import { composioMadeKey, composioPerRun } from "./composio-made.js";
166
+ import { composioEnvKey, composioMadeKey, composioPerRun } from "./composio-made.js";
161
167
  import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
162
168
  import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
163
169
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
@@ -216,8 +222,9 @@ import { emailRoute } from "./email/routes.js";
216
222
  import { addressForms, openCalendar } from "./calendar/address.js";
217
223
  import { calendarRoute } from "./calendar/routes.js";
218
224
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, loadArchilSettings, runDiskKept, runDiskKey } from "./archil-settings.js";
219
- import { computerOfPlace } from "./computer-setting.js";
225
+ import { computerOfPlace, settingOfDefinition } from "./computer-setting.js";
220
226
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
227
+ import { runningComputers } from "./computers-running.js";
221
228
  import { fauxComputers } from "./faux-computers.js";
222
229
  import { writesHeld } from "./workspace.js";
223
230
  import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
@@ -248,6 +255,9 @@ const IMPORT_STARTS = 3;
248
255
  const IMPORT_HEAP_MB = 2048;
249
256
  const MAX_MESSAGE = 20_000;
250
257
  const MAX_WAIT_MS = 25_000;
258
+ /** A run body's fields that a launch hook's host can't set on a firing's run (RunCreate `trigger_firing`): its trigger's
259
+ * target fixes them. */
260
+ const HANDED_FIXED = ["revision", "hold", "hold_minutes"];
251
261
  /** How often the server fails the runs still queued while no runner here can take them (runner/presence.ts). */
252
262
  const REFUSED_SWEEP_MS = 2_000;
253
263
  const PAGE_ROWS = 500;
@@ -280,6 +290,9 @@ export function fauxEnvOf(options) {
280
290
  for (const [option, name] of FAUX_SWITCHES)
281
291
  if (options[option])
282
292
  env[name] = resolve(options[option]);
293
+ // A URL, so never resolved as a path.
294
+ if (options.fauxFirecrawl)
295
+ env[FAUX_FIRECRAWL_ENV] = options.fauxFirecrawl;
283
296
  // The mountinfo the server itself reads (fauxMountinfo in serve), also when its own environment names it: a CLI server
284
297
  // in a container hands it to the runner beside it, whose environment drops every faux variable it inherited.
285
298
  const mountinfo = options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV];
@@ -404,6 +417,7 @@ export const ROUTES = [
404
417
  // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
405
418
  // archilRoute): the server switch dispatches them, once the server opens its store.
406
419
  { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
420
+ { method: "GET", pattern: /^\/computers\/running$/, name: "listRunningComputers" },
407
421
  { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
408
422
  { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
409
423
  { method: "GET", pattern: /^\/computers\/([^/]+)\/choices$/, name: "listComputerChoices" },
@@ -431,9 +445,15 @@ export const ROUTES = [
431
445
  { method: "GET", pattern: /^\/stats$/, name: "getStats" },
432
446
  // The runs waiting and held, the live runners and their free slots, and the recent hand-backs (capacity.ts).
433
447
  { method: "GET", pattern: /^\/capacity$/, name: "getCapacity" },
448
+ // A year of the work under this machine's home (wrapped.ts), on a server on the person's own machine alone.
449
+ { method: "GET", pattern: /^\/wrapped$/, name: "getWrapped" },
434
450
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
435
451
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
436
452
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
453
+ // The keys a plan-billed harness recipe runs on, saved for that harness alone (harness-keys.ts): the owner's session's.
454
+ { method: "GET", pattern: /^\/settings\/harness-keys$/, name: "listHarnessKeys" },
455
+ { method: "PUT", pattern: /^\/settings\/harness-keys\/([^/]+)\/([^/]+)$/, name: "saveHarnessKey" },
456
+ { method: "DELETE", pattern: /^\/settings\/harness-keys\/([^/]+)\/([^/]+)$/, name: "deleteHarnessKey" },
437
457
  // The server's email account (email/routes.ts): the owner's session's alone, its password in no answer.
438
458
  { method: "GET", pattern: /^\/settings\/email$/, name: "getEmailAccount" },
439
459
  { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
@@ -617,9 +637,10 @@ export function offersEnvOf(env) {
617
637
  * harnesses run, and on what, follow them. */
618
638
  const GATEWAY_VARS = ["AGENT_MODEL_BASE_URL", "AGENT_MODEL_GATEWAY_IDS", "AGENT_MODEL", "AGENT_MODEL_FAST", "AGENT_MODEL_STRONG"];
619
639
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
620
- * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
621
- * the offers probed again, never shown. */
622
- 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];
640
+ * saved key is one of those; the rest of the environment is the server's start's), and the models the Ollama here
641
+ * listed when last asked (ollamaListing). Held to tell whether a write, or a new listing, needs the offers probed again,
642
+ * never shown. */
643
+ 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, ollamaListing(env)];
623
644
  /** 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. */
624
645
  async function planStep(step) {
625
646
  try {
@@ -690,8 +711,12 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
690
711
  * a user of its own too. */
691
712
  run_isolation: isolation,
692
713
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
693
- // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
694
- harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
714
+ // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here. Served `available` is
715
+ // whether a run of it can start now on some model it offers: one whose every model lacks a key or the sign-in
716
+ // (noModelRuns: pi with neither) is not, though a save and a run read it as a harness that runs here (runnable.ts), so
717
+ // their words name the model it lacks. One whose default lacks a key while another model runs is (its `needs` says
718
+ // what the default lacks).
719
+ harnesses: harnesses.map(({ keys: _keys, noModelRuns, ...offer }) => ({ ...offer, available: offer.available && !noModelRuns, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
695
720
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
696
721
  places: placesOf(boxes, boxAllowOf(env)),
697
722
  models,
@@ -753,6 +778,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
753
778
  /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the server's seal key
754
779
  * (tool-keys-store.ts), never in the clear. */
755
780
  tool_keys: { routes: true, at_rest: "sealed" },
781
+ /** GET /settings/harness-keys and PUT/DELETE of one key: a plan-billed recipe's keys, saved for that harness alone
782
+ * (harness-keys.ts); `harnesses` its ids here, so the console offers the page only where there is one. */
783
+ harness_keys: { routes: true, at_rest: "sealed", harnesses: planRecipesOf(env).map((recipe) => recipe.id) },
756
784
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
757
785
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. Every harness of the table runs a
758
786
  * grant (runnable.ts takes one on any), a module's among them. */
@@ -823,17 +851,18 @@ function integerParam(value, name, max) {
823
851
  }
824
852
  /** A start with --harness-sign-in on a server that is not one owner's own, on their own machine. */
825
853
  export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
826
- /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
827
- * it may. One owner's own server on their own machine: it listens on loopback alone, with no public address; its store
828
- * is the SQLite one in its data directory (no AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside
829
- * it as its own user (`ownUser`: runIsolationOf's `process`), never under --no-runner or a user of their own; and one
830
- * person starts them, as Claude Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one
831
- * API token. A check, a schedule and a shared server run on a key (HARNESS.md#sign-in). */
832
- export function harnessSignInRefusal(options, data, ownUser) {
854
+ /** Why `options` on `data` is not one owner's own server on their own machine, each reason in words; none when it is. One
855
+ * owner's own: it listens on loopback alone, with no public address; its store is the SQLite one in its data directory (no
856
+ * AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside it as its own user (`ownUser`:
857
+ * runIsolationOf's `process`), never under --no-runner or a user of their own; and one person starts them, as Claude
858
+ * Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one API token. What --harness-sign-in
859
+ * starts under (harnessSignInRefusal), and where the Ollama at this machine's default address is a model of the person
860
+ * who starts runs (ollama-provider.ts ollamaHostOf). */
861
+ export function whyNotOwnMachine(options, data, ownUser) {
833
862
  const host = options.host ?? DEFAULT_HOST;
834
863
  // Every token the server takes (acceptedTokens): AGENTRUN_TOKEN's as `default` beside the list's, or else DIR/.token's alone.
835
864
  const tokens = (options.token === undefined ? 0 : 1) + (options.tokens?.length ?? 0);
836
- const why = [
865
+ return [
837
866
  ...(loopback(host) ? [] : [`listens on ${host}, past loopback`]),
838
867
  ...(options.publicUrl ? [`has a public address (${options.publicUrl})`] : []),
839
868
  ...(options.apiOnly ? ["has no owner (the API-only profile), so anyone with its token starts runs"] : []),
@@ -842,6 +871,12 @@ export function harnessSignInRefusal(options, data, ownUser) {
842
871
  ...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
843
872
  ...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
844
873
  ];
874
+ }
875
+ /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
876
+ * it may: one owner's own server on their own machine alone (whyNotOwnMachine). A check, a schedule and a shared server
877
+ * run on a key (HARNESS.md#sign-in). */
878
+ export function harnessSignInRefusal(options, data, ownUser) {
879
+ const why = whyNotOwnMachine(options, data, ownUser);
845
880
  return why.length ? `${HARNESS_SIGN_IN_NOT_LOCAL}: --harness-sign-in runs a recipe on its owner's own sign-in on one owner's own machine alone, and this server ${why.join("; ")}. Start it without --harness-sign-in: its plan-billed recipes run on keys.` : undefined;
846
881
  }
847
882
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
@@ -861,12 +896,16 @@ export async function startServe(options) {
861
896
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
862
897
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
863
898
  const data = await realpath(resolve(options.data));
899
+ const { runsAsOwnUser } = await import("./runner/run-child-host.js");
900
+ const ownUser = runsAsOwnUser(process.env);
864
901
  if (options.harnessSignIn) {
865
- const { runsAsOwnUser } = await import("./runner/run-child-host.js");
866
- const refused = harnessSignInRefusal(options, data, runsAsOwnUser(process.env));
902
+ const refused = harnessSignInRefusal(options, data, ownUser);
867
903
  if (refused)
868
904
  throw new Error(refused);
869
905
  }
906
+ // The Ollama this server asks, and its runner beside it: OLLAMA_HOST, else the default address on one owner's own machine
907
+ // alone (ollamaHostOf). Read once, at the start: a refused one is said once, here, in the base rule's words.
908
+ const ollamaHost = ollamaHostOf(process.env, whyNotOwnMachine(options, data, ownUser).length === 0);
870
909
  const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
871
910
  if (tokenRefused)
872
911
  throw new Error(tokenRefused);
@@ -907,7 +946,7 @@ export async function startServe(options) {
907
946
  // store handle it opened.
908
947
  const stops = [];
909
948
  try {
910
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates }, stops);
949
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates, ollamaHost }, stops);
911
950
  }
912
951
  catch (error) {
913
952
  for (const stop of stops)
@@ -937,7 +976,7 @@ async function whileReplaced(take, held, until, waiting) {
937
976
  }
938
977
  }
939
978
  async function startHolding(options, data, checked, stops) {
940
- const { maxRuns, minFreeBytes, learning, boxAllow, templates } = checked;
979
+ const { maxRuns, minFreeBytes, learning, boxAllow, templates, ollamaHost } = checked;
941
980
  /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
942
981
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
943
982
  * read (the view never fails for it). */
@@ -959,7 +998,12 @@ async function startHolding(options, data, checked, stops) {
959
998
  // shown nowhere.
960
999
  let secretStores;
961
1000
  let triggerSettings = new Map();
962
- const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data), ...harnessRecipesEnv(options.harnessRecipes ?? [], data, { signIn: options.harnessSignIn === true }) };
1001
+ const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data), ...harnessRecipesEnv(options.harnessRecipes ?? [], data, { signIn: options.harnessSignIn === true }), ...(ollamaHost ? { OLLAMA_HOST: ollamaHost } : {}) };
1002
+ // A refused OLLAMA_HOST lists nothing (ollama-provider.ts baseOf): said once, at the start, in the base rule's words,
1003
+ // which never hold the value (a user or password in it stays unsaid).
1004
+ const ollamaRefused = ollamaHostRefused(base);
1005
+ if (ollamaRefused)
1006
+ log ? log(logLine("ollama_host_refused", { line: ollamaRefused })) : void process.stderr.write(`agentrun-serve: ${ollamaRefused}\n`);
963
1007
  // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
964
1008
  // the start, in words, before anything else opens.
965
1009
  // The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
@@ -1060,6 +1104,10 @@ async function startHolding(options, data, checked, stops) {
1060
1104
  // call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
1061
1105
  const toolKeys = toolKeysOverStore(store, own(withSecrets(base, "own")), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
1062
1106
  await toolKeys.load();
1107
+ // The keys each plan-billed harness recipe this server names runs on, saved for that harness alone (harness-keys.ts):
1108
+ // sealed rows in the store, loaded once here and kept in step with every save, so its listing reads them at once.
1109
+ const harnessKeys = new HarnessKeysOverStore(store, seal.key, planRecipesOf(base), data);
1110
+ await harnessKeys.load();
1063
1111
  // A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
1064
1112
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
1065
1113
  const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
@@ -1070,7 +1118,9 @@ async function startHolding(options, data, checked, stops) {
1070
1118
  return fake ? (await import(pathToFileURL(resolve(fake)).href)).default : undefined;
1071
1119
  };
1072
1120
  // Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
1121
+ // A start that fails aborts it too: what began on it (the host-address read's retry) stops with that start.
1073
1122
  const stopping = new AbortController();
1123
+ stops.push(async () => stopping.abort());
1074
1124
  /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
1075
1125
  let schemaSealed = Promise.resolve();
1076
1126
  // The start's sweep of ended runs whose stored cost is unknown (cost-heal.ts), once this server listens; stop drains it.
@@ -1083,16 +1133,22 @@ async function startHolding(options, data, checked, stops) {
1083
1133
  const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
1084
1134
  if (options.githubMcpOrigin)
1085
1135
  mcpServers.appOrigin = options.githubMcpOrigin;
1136
+ if (options.composioMcpOrigin)
1137
+ mcpServers.composioOrigin = options.composioMcpOrigin;
1086
1138
  mcpServers.standIns = options.mcpStandIns === true;
1087
1139
  // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the checks read in step (which
1088
1140
  // servers are saved, a workflow's grants, the template apply): the server is the one writer of these rows (a save,
1089
1141
  // refresh, sign-in or delete), so the snapshot is refreshed after each of those and reads what is saved now. An agent's
1090
1142
  // save lists its granted servers live and pins their tools on its revision (saveable, mcpListingOf); the runner reads
1091
1143
  // that pin and the credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP
1092
- // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on.
1144
+ // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on,
1145
+ // and the variable a Composio server saved with api_key_env reads its key from (`keyEnv`), which a run's start checks.
1093
1146
  let mcpMeta = new Map();
1094
1147
  const refreshMcpMeta = async () => {
1095
- mcpMeta = new Map(await Promise.all((await listMcpServers(store)).map(async (row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [], source: await mcpServers.sourceOf(row) }])));
1148
+ mcpMeta = new Map(await Promise.all((await listMcpServers(store)).map(async (row) => {
1149
+ const keyEnv = await mcpServers.keyEnvOf(row);
1150
+ return [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [], source: await mcpServers.sourceOf(row), ...(keyEnv ? { keyEnv } : {}) }];
1151
+ })));
1096
1152
  };
1097
1153
  await refreshMcpMeta();
1098
1154
  // Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
@@ -1159,6 +1215,9 @@ async function startHolding(options, data, checked, stops) {
1159
1215
  let probes = 0;
1160
1216
  const probe = async (why) => {
1161
1217
  const mine = ++probes;
1218
+ // The Ollama listing the offers are made from is read before they are, so the first capabilities do not remake them.
1219
+ if (asksOllama(env))
1220
+ await ollamaModels(env);
1162
1221
  const from = offersInputs(env);
1163
1222
  const started = performance.now();
1164
1223
  const next = await harnessOffers(offersEnvOf(env));
@@ -1180,6 +1239,8 @@ async function startHolding(options, data, checked, stops) {
1180
1239
  log: (what, error) => log?.(logLine(what, { error: error.message })),
1181
1240
  ...(options.listerIdleMs !== undefined ? { idleMs: options.listerIdleMs } : {}),
1182
1241
  });
1242
+ /** Whether the offers held now were made from `inputs` (offersInputs). */
1243
+ const offersMadeFrom = (inputs) => offersFrom !== undefined && inputs.length === offersFrom.length && inputs.every((value, i) => value === offersFrom[i]);
1183
1244
  const keysChanged = async () => {
1184
1245
  // 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
1185
1246
  // serverSecrets live, store-view), and a list builds a listing cut of other keys again (builtOfNow). A failed run's error words
@@ -1190,26 +1251,48 @@ async function startHolding(options, data, checked, stops) {
1190
1251
  const next = await needsOf(env);
1191
1252
  if (mine === needsAsked)
1192
1253
  needs = next;
1193
- const inputs = offersInputs(env);
1194
- if (offersFrom && inputs.length === offersFrom.length && inputs.every((value, i) => value === offersFrom[i]))
1254
+ if (offersMadeFrom(offersInputs(env)))
1195
1255
  recompose();
1196
1256
  else
1197
1257
  await probe("key");
1198
1258
  };
1259
+ /** The Ollama here, as capabilities read it: its listing asked again behind the answer once stale (ollamaModels), and
1260
+ * the reading made again, as a key's save does, once a listing differs from the one the offers were made from. So a
1261
+ * model pulled, or Ollama started after this server, shows in a later answer with no restart. */
1262
+ const ollamaNow = async () => {
1263
+ if (!asksOllama(env))
1264
+ return;
1265
+ void ollamaModels(env);
1266
+ if (offersFrom && !offersMadeFrom(offersInputs(env)))
1267
+ await keysChanged();
1268
+ };
1269
+ /** After a harness key is saved or removed (harness-keys.ts): the listings built again, cut of it, and the offers probed
1270
+ * again, as a recipe is offered once every key it runs on is saved here (harnessKeysSavedHere). No environment changes. */
1271
+ const harnessKeysChanged = async () => {
1272
+ await lister.keysChanged();
1273
+ await probe("harness-key");
1274
+ };
1199
1275
  /** After the model gateway is saved or removed in the console: the saved gateway read again, then env, as a key's save. */
1200
1276
  const gatewayChanged = async () => {
1201
1277
  savedGateway = await readSavedGateway(store, seal.key);
1202
1278
  await keysChanged();
1203
1279
  };
1204
- /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
1280
+ /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again;
1281
+ * so does a sign-in's change this server failed to take (changed_failed), until it takes. */
1205
1282
  const planNow = async () => {
1206
1283
  const was = plan.state;
1207
1284
  if ((await plan.load()).state !== was)
1208
1285
  await keysChanged();
1286
+ else
1287
+ await plan.changeAgain();
1209
1288
  };
1210
1289
  /** What Claude Code's login routes use: a turn on or off reads the setting again, then env, as a key's save does. A
1211
- * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here. */
1290
+ * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here; it is
1291
+ * kept for this process (claude-sign-in.ts), and one still waiting is ended at the stop. */
1292
+ const claudeSignIns = new ClaudeSignIns({ limitMs: options.claudeSignInLimitMs });
1293
+ stops.push(async () => claudeSignIns.close());
1212
1294
  const loginDeps = () => ({
1295
+ signIns: claudeSignIns,
1213
1296
  settings: store.settings,
1214
1297
  data,
1215
1298
  env: base,
@@ -1226,7 +1309,9 @@ async function startHolding(options, data, checked, stops) {
1226
1309
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
1227
1310
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
1228
1311
  const fauxDocker = Boolean(options.faux) && options.fauxDocker === true;
1229
- const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker });
1312
+ // A faux server's probe is on a host, as its Docker paths are below, so a test reads the same words in a container;
1313
+ // `probeContainer` sets it for a test of a real one.
1314
+ const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker, ...(options.probeContainer ? { container: options.probeContainer } : options.faux ? { container: { inside: false } } : {}) });
1230
1315
  const docker = found.some((offer) => offer.id === "docker" && offer.available);
1231
1316
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
1232
1317
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
@@ -1247,13 +1332,35 @@ async function startHolding(options, data, checked, stops) {
1247
1332
  // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
1248
1333
  // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
1249
1334
  // runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
1335
+ // A read that failed with none known is read again in the background (retryHostAddresses) until one answers and the
1336
+ // helper containers the failed reads left are gone, or this server stops: the boxes are made again from the answer and
1337
+ // said again, so Docker is offered with no restart. Every reader of boxOffers reads it when it is called; capabilities
1338
+ // are composed again.
1339
+ const boxesOf = (hostAddresses) => {
1340
+ if (hostAddresses)
1341
+ log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
1342
+ const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
1343
+ // Each box with what it reaches (place-offers.ts withNetworks).
1344
+ const offers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
1345
+ log?.(logLine("boxes", boxesLog(offers, enabledBoxes(env))));
1346
+ return offers;
1347
+ };
1250
1348
  const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
1251
- if (hostAddresses)
1252
- log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
1253
- const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
1254
- // Each box with what it reaches (place-offers.ts withNetworks).
1255
- const boxOffers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
1256
- log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
1349
+ let boxOffers = boxesOf(hostAddresses);
1350
+ if (hostAddresses?.why !== undefined && hostAddresses.addresses.length === 0) {
1351
+ void retryHostAddresses({
1352
+ env,
1353
+ read: () => hostAddressesOnce(env),
1354
+ found: (read) => {
1355
+ boxOffers = boxesOf(unionOf(read, dockerHostAddressesOf(env)));
1356
+ // Capabilities are first composed at the start's probe, below; before it, there is nothing to compose again.
1357
+ if (caps)
1358
+ recompose();
1359
+ },
1360
+ signal: stopping.signal,
1361
+ ...(options.hostReadWait ? { wait: options.hostReadWait } : {}),
1362
+ });
1363
+ }
1257
1364
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
1258
1365
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
1259
1366
  const sealKey = seal.key;
@@ -1393,10 +1500,8 @@ async function startHolding(options, data, checked, stops) {
1393
1500
  * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
1394
1501
  const shellOfRevision = async (revision) => {
1395
1502
  const body = revision.body;
1396
- return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
1503
+ return shellOf(settingOfDefinition(body)?.computer ?? computerOfPlace(fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : [])));
1397
1504
  };
1398
- /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1399
- const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1400
1505
  /** The run read's costs (A8, store-reads/learning.ts runAllInOverStore): `cost.usd` its own spend, the
1401
1506
  * job's (its compile turn is learning's), null while unknown; what learning spent for it
1402
1507
  * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown.
@@ -1404,12 +1509,26 @@ async function startHolding(options, data, checked, stops) {
1404
1509
  const allInViewOf = async (runId, view) => {
1405
1510
  const cost = (view.cost ?? {});
1406
1511
  const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
1407
- const all = await runAllInOverStore(store, runId, own);
1512
+ // A purge gate that can't be asked (its store read of a writer's row fails) leaves this read without its answer, never
1513
+ // a 500: the revision ledger its `learning_usd` and `all_in_usd` share is read from takes the champion with no record
1514
+ // skipped (as before the purge), so a revision a purged run wrote may be the one it counts as serving, for this read
1515
+ // alone. Figures only: no text is read or shown. Every write that asks the gate still fails closed (decideCheck
1516
+ // throws, so no promote lands; recordPromotion trims nothing). Such a read says so: `cost.degraded`.
1517
+ let degraded = false;
1518
+ const all = await runAllInOverStore(store, runId, own, (agentId, records) => refusedFor(agentId, records).catch((error) => {
1519
+ degraded = true;
1520
+ const line = `learning: run ${runId}: its costs were read without the purge gate's answer: ${error instanceof Error ? error.message : String(error)}`;
1521
+ if (log)
1522
+ log(logLine("learning", { line }));
1523
+ else
1524
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1525
+ return Object.assign(() => false, { unread: true });
1526
+ }));
1408
1527
  if (!all)
1409
1528
  return {};
1410
1529
  // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1411
1530
  // gives): known as it answered even when its compile turn's cost is not; the row's while the run is at work.
1412
- 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 } };
1531
+ 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, ...(degraded ? { degraded: true } : {}) } };
1413
1532
  };
1414
1533
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1415
1534
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
@@ -1438,6 +1557,9 @@ async function startHolding(options, data, checked, stops) {
1438
1557
  secretStores.add("server", () => tokens.map((entry) => entry.token));
1439
1558
  // The model gateway's key saved in the console (model-gateway.ts): cut from everything shown, as every saved key is.
1440
1559
  secretStores.add("model-gateway", () => (savedGateway?.key ? [savedGateway.key] : []));
1560
+ // Each harness key saved, and each replaced or removed one still kept sealed (harness-keys.ts RETIRED_KEPT): a timeline
1561
+ // written while one was live stays cut after it changes.
1562
+ secretStores.add("harness-keys", () => harnessKeys.values());
1441
1563
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1442
1564
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1443
1565
  const emailPasswords = new Set();
@@ -1732,12 +1854,10 @@ async function startHolding(options, data, checked, stops) {
1732
1854
  return [...serverSecrets(), ...pointers];
1733
1855
  };
1734
1856
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1735
- // Which runs a learning folder's log names are purged, by each one's row (its purge time): the history reads serve none
1736
- // of their merges.
1737
- const purgedOf = async (runIds) => {
1738
- const rows = await Promise.all(runIds.map((runId) => store.runs.get(runId)));
1739
- return new Set(runIds.filter((_, i) => rows[i] !== undefined && rows[i].purgedAt !== null));
1740
- };
1857
+ // What championOf skips of the agent's promotion records (purged-workflow.ts refusedIn): a champion the purge gate
1858
+ // refuses at its commit, so the views name the champion a run's claim serves. A folder whose end() throws after the ask
1859
+ // is logged, never the read's 500.
1860
+ const refusedFor = (agentId, records) => refusedIn(() => learningFolderOf(data, agentId), store, (line) => (log ? log(logLine("learning", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)))(records);
1741
1861
  // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1742
1862
  const auditsOfAgent = async (agentId) => {
1743
1863
  const { workspace, end } = learningFolderOf(data, agentId);
@@ -1755,6 +1875,11 @@ async function startHolding(options, data, checked, stops) {
1755
1875
  // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1756
1876
  const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
1757
1877
  const runReadDepsFor = (origin) => ({ ...viewDepsFor(origin), recordings });
1878
+ /** A run as GET /v2/runs/{run_id} answers it, its links at `origin`. */
1879
+ const runRead = async (runId, origin) => {
1880
+ const view = await viewOverStore(store, runId, runReadDepsFor(origin));
1881
+ return view && { ...view, ...(await runComputerRead(store, runId, view, { context: ctx })), ...(await allInViewOf(runId, view)) };
1882
+ };
1758
1883
  const ownOriginOf = () => options.publicUrl ?? url;
1759
1884
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1760
1885
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
@@ -1794,8 +1919,10 @@ async function startHolding(options, data, checked, stops) {
1794
1919
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1795
1920
  needAgent,
1796
1921
  momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1797
- // A trigger never messages a run on a plan-billed recipe: its turn would run on its owner's own sign-in.
1798
- planRecipe: (harness) => recipeHarness(base, harness) === "plan",
1922
+ // A trigger never messages a run on a plan-billed recipe whose keys are not all saved: its turn would run on its
1923
+ // owner's own sign-in. With them saved, the turn runs on them (harness-keys.ts), and a claim that opens not every one
1924
+ // is refused (cli-run-spec.ts).
1925
+ planRecipe: (harness) => recipeHarness(base, harness) === "plan" && !harnessKeysSavedHere(data, harness),
1799
1926
  // Read when a firing's message is sent (declared below, with the delete turn).
1800
1927
  runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
1801
1928
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
@@ -2640,7 +2767,7 @@ async function startHolding(options, data, checked, stops) {
2640
2767
  // purged or kept as the purge had got, and the next DELETE does it again.
2641
2768
  forgetCopies: async (agentId, runId) => {
2642
2769
  await forgetRunCopies(store.settings, agentId, runId);
2643
- await notYetWith(() => forgetRunLearning(data, agentId, runId), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
2770
+ await notYetWith(() => forgetRunLearning(data, agentId, runId, store), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
2644
2771
  },
2645
2772
  // /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
2646
2773
  // learning ended as /stats counts it (its state and reason alone).
@@ -2825,6 +2952,18 @@ async function startHolding(options, data, checked, stops) {
2825
2952
  });
2826
2953
  if (unpinned.length)
2827
2954
  throw new ApiError("agent_not_runnable", unpinned.map((one) => one.message).join(" "), { fields: unpinned.map(({ tool: _tool, ...issue }) => issue), details: { unbound: unpinned.map((one) => one.tool), missing: {} } });
2955
+ // A granted tool of a Composio server that reads its key from the environment (api_key_env) while that variable is
2956
+ // unset, or whose address is off Composio's origin: refused by its name before the run starts, never launched
2957
+ // without the server's tools, and nothing sent (composioEnvKey).
2958
+ const unset = (revision.body.tools ?? []).flatMap((tool, index) => {
2959
+ const named = mcpToolOf(tool);
2960
+ const saved = named ? mcpMeta.get(named.server) : undefined;
2961
+ const keyEnv = saved?.keyEnv;
2962
+ const got = named && saved && keyEnv ? composioEnvKey(named.server, saved.url, keyEnv, mcpServers.composioOrigin) : undefined;
2963
+ return got && "refused" in got ? [{ field: `definition.tools[${index}]`, reason: got.reason, message: got.refused, tool, keyEnv: keyEnv, unset: got.reason === "missing" }] : [];
2964
+ });
2965
+ if (unset.length)
2966
+ throw new ApiError("agent_not_runnable", [...new Set(unset.map((one) => one.message))].join(" "), { fields: unset.map(({ tool: _tool, keyEnv: _keyEnv, unset: _unset, ...issue }) => issue), details: { unbound: [], missing: Object.fromEntries(unset.filter((one) => one.unset).map((one) => [one.tool, [one.keyEnv]])) } });
2828
2967
  }
2829
2968
  const pinnedTools = (server) => {
2830
2969
  const saved = mcpMeta.get(server);
@@ -3133,11 +3272,15 @@ async function startHolding(options, data, checked, stops) {
3133
3272
  return false;
3134
3273
  throw error;
3135
3274
  };
3275
+ /** A fresh apply's twins: the live agents here made from the package `pkgId` with the parameters `digest` digests. The
3276
+ * apply still makes another and warns of each (applyWith); its plan names them first (planTemplate). None for an
3277
+ * apply onto an agent (`onto`). */
3278
+ const twinsOf = async (onto, pkgId, digest) => onto ? [] : (await agents.list()).filter((one) => one.template?.id === pkgId && one.template.parameters_digest === digest).map((one) => one.agent.id);
3136
3279
  /** POST /templates/{id}/apply {dry_run: true}: the apply's plan, from the same reads and checks as the apply
3137
3280
  * (prepareApply), with nothing written: whether it makes an agent or revises the one agent_id names (and its current
3138
- * revision), the keys and MCP servers this server lacks (where the apply would refuse with 409, the plan lists them),
3139
- * what becomes of each trigger (made, changed in place, removed, or skipped for a connection this server lacks), and
3140
- * the computer it picks. Any other refusal is the apply's own. */
3281
+ * revision), the agents a fresh one would make a twin of, the keys and MCP servers this server lacks (where the apply
3282
+ * would refuse with 409, the plan lists them), what becomes of each trigger (made, changed in place, removed, or
3283
+ * skipped for a connection this server lacks), and the computer it picks. Any other refusal is the apply's own. */
3141
3284
  async function planTemplate(template, body) {
3142
3285
  const p = await prepareApply(template, body, { plan: true });
3143
3286
  // A monid grant is pinned to monid's listing when the agent is saved (saveable: monidPinOf), read with the monid key:
@@ -3148,6 +3291,8 @@ async function startHolding(options, data, checked, stops) {
3148
3291
  const was = p.onto?.revision?.kind === "agentic" ? p.onto.revision : undefined;
3149
3292
  const unread = !env[MONID_KEY_ENV]?.trim() && (await pinMonid(tools, { key: undefined, ...(was ? { previous: { grants: was.body.tools ?? [], pin: was.monidPin ?? null } } : {}) }));
3150
3293
  const missing = unread && "refused" in unread && !p.missing.includes(MONID_KEY_ENV) ? [...p.missing, MONID_KEY_ENV] : p.missing;
3294
+ // A skip's `code` is the apply's warning's for it: not_set_up_here for one this server makes once it is set up (a
3295
+ // connection, a feed's URLs, a launch hook), not_an_option for one it never makes.
3151
3296
  const planned = [];
3152
3297
  for (const [i, trigger] of p.made.triggers.entries()) {
3153
3298
  const name = String(trigger.name).trim();
@@ -3155,11 +3300,11 @@ async function startHolding(options, data, checked, stops) {
3155
3300
  // On an API-only server, skipped in the apply's own words (prepareApply).
3156
3301
  const hostSkip = p.hostless.get(i);
3157
3302
  if (hostSkip) {
3158
- planned.push({ name, kind, action: "skip", reason: hostSkip.message });
3303
+ planned.push({ name, kind, action: "skip", code: hostSkip.reason, reason: hostSkip.message });
3159
3304
  continue;
3160
3305
  }
3161
3306
  if (p.emptyFeeds.has(i)) {
3162
- planned.push({ name, kind, action: "skip", reason: feedTriggerEmpty(p.pkg.name, trigger, isObject(p.pkg.triggers[i]?.source) ? p.pkg.triggers[i].source.urls : undefined) });
3307
+ planned.push({ name, kind, action: "skip", code: NOT_SET_UP, reason: feedTriggerEmpty(p.pkg.name, trigger, isObject(p.pkg.triggers[i]?.source) ? p.pkg.triggers[i].source.urls : undefined) });
3163
3308
  continue;
3164
3309
  }
3165
3310
  const was = p.hadByName.get(name);
@@ -3172,7 +3317,7 @@ async function startHolding(options, data, checked, stops) {
3172
3317
  // (any trigger, on or off), read here; its account and subscription are Composio's to answer, which a plan never asks.
3173
3318
  const refusal = kind === "composio" && !options.publicUrl ? composioNoPublicUrl() : trigger.enabled !== false && !(was && !was.enabled) ? await triggerUnavailable(kind) : undefined;
3174
3319
  if (refusal && notSetUpYet(kind, refusal.code))
3175
- planned.push({ name, kind, action: "skip", reason: refusal.message });
3320
+ planned.push({ name, kind, action: "skip", code: NOT_SET_UP, reason: refusal.message });
3176
3321
  else if (refusal)
3177
3322
  throw refusal;
3178
3323
  else
@@ -3186,6 +3331,7 @@ async function startHolding(options, data, checked, stops) {
3186
3331
  action: p.onto ? "revise" : "create",
3187
3332
  agent_id: p.onto?.agent.id ?? null,
3188
3333
  current_revision_id: p.onto?.revision?.id ?? null,
3334
+ twins: await twinsOf(p.onto, p.pkg.id, p.digest),
3189
3335
  missing_secrets: missing,
3190
3336
  unmatched_mcp: p.unsaved.map((need) => ({ source: need.source, toolkit: need.toolkit, required: need.required })),
3191
3337
  triggers: planned,
@@ -3287,11 +3433,16 @@ async function startHolding(options, data, checked, stops) {
3287
3433
  // A trigger is made only when its firings have somewhere to go: on an API-only server, a schedule or a feed with the
3288
3434
  // launch hook set (api-only.ts); under the run-keys setting, for an agent whose runs owe keys, only with the launch
3289
3435
  // hook, the one way a firing's run carries them (run-keys.ts). Each other is said, and stays listed, so a trigger the
3290
- // agent has by its name is left as it is, never removed.
3436
+ // agent has by its name is left as it is, never removed. One left on still fires, so its skip says so and how to stop it.
3291
3437
  const hooked = options.launchHook !== undefined;
3292
3438
  const hostless = new Map(made.triggers.flatMap((trigger, i) => {
3293
3439
  const skip = (options.apiOnly ? apiOnlyTriggerSkipped(pkg.name, trigger, hooked) : undefined) ?? runKeysTriggerSkipped(pkg.name, trigger, brought, hooked);
3294
- return skip ? [[i, skip]] : [];
3440
+ if (!skip)
3441
+ return [];
3442
+ const keptOn = had.find((row) => row.enabled && row.name === String(trigger.name).trim());
3443
+ // An API-only server serves no trigger route: its archive is what turns the agent's triggers off.
3444
+ const off = options.apiOnly ? "archiving the agent turns it off" : `PATCH /v2/triggers/${keptOn?.id} with {"enabled": false} turns it off`;
3445
+ return [[i, keptOn ? { ...skip, message: `${skip.message} The agent's trigger ${keptOn.id} of that name is kept as it was, and still fires: ${off}.` } : skip]];
3295
3446
  }));
3296
3447
  const unmade = (i) => emptyFeeds.has(i) || hostless.has(i);
3297
3448
  const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !unmade(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
@@ -3366,9 +3517,8 @@ async function startHolding(options, data, checked, stops) {
3366
3517
  const { pkg, onto, saved, mapped, grants, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned } = await prepareApply(template, body, { plan: false });
3367
3518
  // A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
3368
3519
  // which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
3369
- const twins = onto ? [] : (await agents.list())
3370
- .filter((one) => one.template?.id === pkg.id && one.template.parameters_digest === digest)
3371
- .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}.` }));
3520
+ const twins = (await twinsOf(onto, pkg.id, digest))
3521
+ .map((id) => ({ field: "agent_id", reason: "duplicate", message: `The 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 ${id}.` }));
3372
3522
  // An update writes the package as a new revision of the agent, as an edit does (its id, name and description are the
3373
3523
  // agent's own: the package's never replace them), but what the package owns and leaves out is gone (fromPackage); only onto the
3374
3524
  // revision it read, else 412 with nothing changed. A fresh apply makes the agent as POST /agents does.
@@ -3657,7 +3807,7 @@ async function startHolding(options, data, checked, stops) {
3657
3807
  if (undeclared.length)
3658
3808
  throw invalid(undeclared);
3659
3809
  }
3660
- const owed = options.runKeys && revision ? packageKeysOf(revision).filter((name) => !env[name]) : [];
3810
+ const owed = options.runKeys && revision ? keysOwed(revision, env, []) : [];
3661
3811
  const needsKey = handed.model === undefined && serverKeyMissing(env, target);
3662
3812
  if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined && !needsKey && !owed.length)
3663
3813
  return undefined;
@@ -3669,9 +3819,9 @@ async function startHolding(options, data, checked, stops) {
3669
3819
  const keys = handed.keys ?? held.keys;
3670
3820
  if (!model && needsKey)
3671
3821
  throw modelKeyRequired(true);
3672
- const unpaid = revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3673
- if (owed.length && unpaid.length)
3674
- throw new ApiError("agent_not_runnable", unpaid.map((one) => one.message).join(" "), { fields: unpaid });
3822
+ const unpaid = owed.length && revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3823
+ if (unpaid.length)
3824
+ throw keysOwedRefusal(unpaid);
3675
3825
  return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) });
3676
3826
  };
3677
3827
  }
@@ -3679,21 +3829,24 @@ async function startHolding(options, data, checked, stops) {
3679
3829
  const entry = await needRunnableAgent(agentId);
3680
3830
  const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3681
3831
  // The host's run for a firing the launch hook handed it: the firing's own run, under the firing's key (a second start
3682
- // answers that run), with the trigger, input origin and title a start here would give it, and capped as a trigger's
3683
- // run is. The firing is its key, so it takes no Idempotency-Key, whose check across a restart is the run's origin.
3832
+ // answers that run), started by the trigger's target policy as a firing here starts one (its cap, which the host's may
3833
+ // lower, its effort when it sets one, its previous result, its trigger, origin and title), with the host's body and
3834
+ // launch secrets over it. The firing is its key, so it takes no Idempotency-Key, whose check across a restart is the run's origin.
3684
3835
  if (body.trigger_firing !== undefined) {
3685
3836
  if (req.headers["idempotency-key"] !== undefined)
3686
3837
  throw invalid([{ field: "trigger_firing", reason: "not_allowed", message: "A run for a trigger firing is keyed by the firing, and a second start answers its run: send it without Idempotency-Key." }]);
3838
+ // It starts on its trigger's target as a firing here would: on the agent's current revision, holding no computer.
3839
+ const fixed = HANDED_FIXED.filter((field) => body[field] !== undefined);
3840
+ if (fixed.length)
3841
+ throw invalid(fixed.map((field) => ({ field, reason: "not_allowed", message: `A run for a trigger firing starts on its trigger's target, on the agent's current revision and holding no computer: send it without ${field}.` })));
3687
3842
  const { trigger_firing: given, ...rest } = body;
3688
- const firing = await triggers.handedStart(given, agentId);
3689
- if ("run_id" in firing)
3690
- return { status: 202, body: await viewOverStore(store, firing.run_id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${firing.run_id}`, "idempotent-replayed": "true" } };
3691
- const secrets = await handed();
3692
- const seal = startSeal(secrets);
3693
- const run = await startRunOf(entry, rest, { origin: { key: firing.key }, trigger: firing.trigger, from: firing.from, title: firing.title, capped: !nativeOf(entry.revision?.body), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3694
- // A host that answered its hook first started this run after: the firing is started with it now.
3695
- await triggers.handedRan(firing.trigger.id, firing.key, run.id);
3696
- return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3843
+ // The firing's room is checked and held as drive's is while its run is written; the firing is started with the run.
3844
+ const run = await triggers.handedStart(given, agentId, async (firing) => {
3845
+ const secrets = await handed();
3846
+ const seal = startSeal(secrets);
3847
+ return targets.start(firing.target, rest.input, firing.trigger, firing.from, firing.title, firing.previous, { body: rest, ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3848
+ });
3849
+ return { status: 202, body: await viewOverStore(store, run.run_id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.run_id}`, ...(run.replayed ? { "idempotent-replayed": "true" } : {}) } };
3697
3850
  }
3698
3851
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
3699
3852
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -3925,16 +4078,18 @@ async function startHolding(options, data, checked, stops) {
3925
4078
  async function timeline(req, res, url, runId) {
3926
4079
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
3927
4080
  const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
3928
- // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
3929
- const asked = url.searchParams.get("limit");
3930
- if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
3931
- throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
3932
- const limit = asked === null ? PAGE_ROWS : Number(asked);
3933
- // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
4081
+ // `calls=whole`: each call's arguments and its output too, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), for a grader.
3934
4082
  const shape = url.searchParams.get("calls");
3935
4083
  if (shape !== null && shape !== "whole")
3936
4084
  throw new ApiError("bad_request", "calls is whole, or absent");
3937
4085
  const calls = shape === "whole";
4086
+ // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's). A
4087
+ // calls=whole page holds at most CALLS_PAGE_ROWS, as each row's result may be CALL_RESULT_CHARS long.
4088
+ const most = calls ? CALLS_PAGE_ROWS : PAGE_ROWS;
4089
+ const asked = url.searchParams.get("limit");
4090
+ if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= most))
4091
+ throw new ApiError("bad_request", `limit is an integer from 1 to ${most}${calls ? " with calls=whole" : ""}`);
4092
+ const limit = asked === null ? most : Number(asked);
3938
4093
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
3939
4094
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
3940
4095
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
@@ -4265,16 +4420,19 @@ async function startHolding(options, data, checked, stops) {
4265
4420
  return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
4266
4421
  }
4267
4422
  // This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
4268
- // cleared; every other browser's session left as it is. A viewer watching with it is cut off.
4423
+ // cleared; every other browser's session left as it is. A viewer watching with it is cut off. Its sessions at this
4424
+ // server's other ports go too (page.ts sessionsAtEveryPort: a browser sends a host's cookies to every port), each
4425
+ // name cleared; a cookie this server did not make (another server's on the same host) is left as it is.
4269
4426
  case "/auth/sign-out": {
4270
4427
  fromPage(req);
4271
4428
  if (!signedIn(req, me))
4272
4429
  throw new ApiError("unauthenticated", "this browser is not signed in");
4273
- for (const value of heldSessions(req))
4274
- if (me.valid(value))
4275
- me.revoke(value);
4430
+ const ended = sessionsAtEveryPort(req).filter(({ value }) => me.valid(value));
4431
+ for (const { value } of ended)
4432
+ me.revoke(value);
4276
4433
  viewers.recheck();
4277
- return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
4434
+ const names = new Set([ownerCookieName(req), ...ended.map(({ name }) => name)]);
4435
+ return send(res, 200, { signed_out: true }, { "set-cookie": [...names].map((name) => ownerCookie(req, "", 0, name)) });
4278
4436
  }
4279
4437
  // Every browser and phone: the sessions' epoch moves on, so every cookie made before is none, this one's too.
4280
4438
  case "/auth/sign-out-everywhere": {
@@ -4368,6 +4526,7 @@ async function startHolding(options, data, checked, stops) {
4368
4526
  // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
4369
4527
  const runnerShell = shellTools(await shellOf({ kind: "none" }));
4370
4528
  await planNow();
4529
+ await ollamaNow();
4371
4530
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
4372
4531
  // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
4373
4532
  // runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
@@ -4377,10 +4536,10 @@ async function startHolding(options, data, checked, stops) {
4377
4536
  // skew check; left out when the store cannot say (a read that failed).
4378
4537
  const state = await store.schemaState?.().catch(() => undefined);
4379
4538
  const storeSchema = state ? { store_schema: { version: state.version, runner_floor: state.runnerFloor, known: state.known } } : {};
4380
- return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
4539
+ return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) }, claude_login: !loginOff && !options.apiOnly } });
4381
4540
  }
4382
4541
  if (found.name === "getOpenapi")
4383
- return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
4542
+ return send(res, 200, servedOpenapi(openapi, ownerCookieName(req)));
4384
4543
  // With accounts off there is no owner, and the console still asks whether it may save a secret: secret-writes.ts'
4385
4544
  // verdict over the request the page just marked, never a signed-in user it doesn't have.
4386
4545
  if (found.name === "getAuthSession")
@@ -4502,8 +4661,13 @@ async function startHolding(options, data, checked, stops) {
4502
4661
  // non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
4503
4662
  // What a stored predicate read to let the request through (SecretRequest.seen): the operation's write is refused if
4504
4663
  // that changed before it lands, so a write allowed against one stored credential never lands over another.
4664
+ // `byToken`: the gate read this request as the API token's, so an MCP server it saves is recorded as the token's, and
4665
+ // it saves over or removes only one the token saved (mcp-secret-writes.ts tokenWriteOverRefused), compared again in
4666
+ // the statement that writes or removes the row (mcp-servers-store.ts save, remove).
4505
4667
  let secretSeen;
4668
+ let byToken = false;
4506
4669
  if (isSecretWriteOperation(found.name) && req.headers.authorization !== undefined && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4670
+ byToken = true;
4507
4671
  const body = req.method === "DELETE" || req.method === "GET" ? undefined : await bodyOf(req).catch(() => undefined);
4508
4672
  // A segment that is not valid percent-encoding is taken as it came: the request goes on to the token's own check.
4509
4673
  const params = (found.pattern.exec(path) ?? []).slice(1).map((part) => {
@@ -4514,7 +4678,7 @@ async function startHolding(options, data, checked, stops) {
4514
4678
  return part;
4515
4679
  }
4516
4680
  });
4517
- const checked = { params, store };
4681
+ const checked = { params, store, apiOnly: options.apiOnly === true };
4518
4682
  if (await writesSecretFor(found.name, body, checked)) {
4519
4683
  authFailed(`/v2${path}`, "secret_without_session");
4520
4684
  // Where the person finishes it: the operation's console page, filled with what the request held that is no
@@ -5056,10 +5220,10 @@ async function startHolding(options, data, checked, stops) {
5056
5220
  return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
5057
5221
  }
5058
5222
  case "getRun": {
5059
- const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
5060
- if (!view)
5223
+ const run = await runRead(id, linkOrigin(req));
5224
+ if (!run)
5061
5225
  throw new ApiError("not_found", `no run ${id}`);
5062
- return send(res, 200, { ...view, ...(await runComputerOf(id, view)), ...(await allInViewOf(id, view)) });
5226
+ return send(res, 200, run);
5063
5227
  }
5064
5228
  case "getTimeline":
5065
5229
  await needRun(id);
@@ -5118,13 +5282,8 @@ async function startHolding(options, data, checked, stops) {
5118
5282
  const row = ID.test(id) ? await store.runs.get(id) : undefined;
5119
5283
  if (!row)
5120
5284
  throw new ApiError("not_found", `no run ${id}`);
5121
- // API-only (api-only.ts): a run of an agent another system owns alone, for the backend whose inline runs made it,
5122
- // as it deletes that agent; a run of an agent made here is the profile's refusal, in its words, as before.
5123
- if (options.apiOnly) {
5124
- const agent = await store.agents.get(row.agentId);
5125
- if (!agent || !ownedElsewhere(agent))
5126
- throw new ApiError("not_found", apiOnlyRefusal(`/v2${path}`));
5127
- }
5285
+ // API-only (api-only.ts) purges a run wherever its token may delete the run's whole agent, which is any agent:
5286
+ // another system's, and one made here once archived. One run is less than all of them, so it is served alike.
5128
5287
  await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
5129
5288
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
5130
5289
  return void res.end();
@@ -5319,6 +5478,10 @@ async function startHolding(options, data, checked, stops) {
5319
5478
  case "deleteComputer":
5320
5479
  await attach.remove(id);
5321
5480
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5481
+ case "listRunningComputers": {
5482
+ const origin = linkOrigin(req);
5483
+ return send(res, 200, await runningComputers(store, (runId) => runRead(runId, origin)), { "cache-control": "no-store" });
5484
+ }
5322
5485
  case "listComputers":
5323
5486
  case "saveComputerKeys":
5324
5487
  case "testComputer":
@@ -5497,6 +5660,19 @@ async function startHolding(options, data, checked, stops) {
5497
5660
  return send(res, 200, await usage(url));
5498
5661
  case "getCapacity":
5499
5662
  return send(res, 200, await capacityOverStore(store.runners, capacityWindowOf(url)));
5663
+ case "getWrapped": {
5664
+ // The session files of the machine this server runs on: only a server bound to loopback with no public URL answers.
5665
+ // A name an operator allowed (--allow-host) passes the server's Host check for its other routes, but a page that rebound
5666
+ // one to this address must not read the machine's files: here the Host is a loopback name or address, or it is refused.
5667
+ if (options.apiOnly || options.publicUrl || !isLoopback(host) || !isLoopbackName(hostName(req.headers.host)))
5668
+ throw new ApiError("forbidden", "wrapped reads this machine's own session files, so only a server on loopback with no public URL, reached by a loopback name, answers it");
5669
+ const given = url.searchParams.get("year");
5670
+ const year = given === null ? new Date().getFullYear() : Number(given);
5671
+ if (given !== null && !/^[1-9]\d{3}$/.test(given))
5672
+ throw new ApiError("bad_request", "year is a four-digit year");
5673
+ const [{ wrapped, unread }, analytics] = await Promise.all([readWrapped(year), analyticsOverStore(store, { from: new Date(year, 0, 1).toISOString(), to: new Date(year + 1, 0, 1).toISOString() })]);
5674
+ return send(res, 200, wrappedView(wrapped, analytics.bySource.filter((g) => g.source !== "live").map((g) => ({ source: g.source, runs: g.runs })), unread));
5675
+ }
5500
5676
  case "getStats": {
5501
5677
  const filter = analyticsFilter(url);
5502
5678
  // The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
@@ -5533,6 +5709,25 @@ async function startHolding(options, data, checked, stops) {
5533
5709
  await toolKeys.remove(id);
5534
5710
  await keysChanged();
5535
5711
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5712
+ case "listHarnessKeys":
5713
+ return send(res, 200, harnessKeys.list());
5714
+ // Never through `idempotent`: its record keeps the body, and this body is the value. The owner's session alone (the
5715
+ // dispatch's secret-write check, harness-keys.ts registerSecretWrite), for a recipe this server names and a key it
5716
+ // runs on; the next claim of a run on that harness opens it, with no restart. Then the listings are built again, cut
5717
+ // of it, and the harness offers probed again: whether the recipe is offered turns on its keys being saved.
5718
+ case "saveHarnessKey": {
5719
+ const recipe = harnessKeys.recipe(id);
5720
+ const body = await bodyOf(req);
5721
+ if (stopping.signal.aborted)
5722
+ throw new ApiError("unavailable", "The server is shutting down: the key was not saved.");
5723
+ await harnessKeys.save(recipe, decodeURIComponent(second), body);
5724
+ await harnessKeysChanged();
5725
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5726
+ }
5727
+ case "deleteHarnessKey":
5728
+ await harnessKeys.remove(harnessKeys.recipe(id), decodeURIComponent(second));
5729
+ await harnessKeysChanged();
5730
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5536
5731
  // Never through `idempotent`: its record keeps the body, and the body holds the password.
5537
5732
  case "getEmailAccount":
5538
5733
  case "saveEmailAccount":
@@ -5625,7 +5820,7 @@ async function startHolding(options, data, checked, stops) {
5625
5820
  const body = await bodyOf(req);
5626
5821
  // A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
5627
5822
  if (!(await mcpServers.composioPreset(id))) {
5628
- const saved = await mcpServers.save(id, body, stopping.signal, secretSeen);
5823
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, undefined, undefined, byToken);
5629
5824
  await refreshMcpMeta();
5630
5825
  return send(res, 200, saved);
5631
5826
  }
@@ -5643,7 +5838,7 @@ async function startHolding(options, data, checked, stops) {
5643
5838
  }),
5644
5839
  inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS),
5645
5840
  };
5646
- const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard);
5841
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard, byToken);
5647
5842
  await refreshMcpMeta();
5648
5843
  return send(res, 200, over.note ? { ...saved, composio: over.note } : saved);
5649
5844
  }
@@ -5658,11 +5853,14 @@ async function startHolding(options, data, checked, stops) {
5658
5853
  // made and what that save made that this one no longer stands on (an account of another user, an auth config of
5659
5854
  // another toolkit), with the key it was made with, and says so as a delete does; what another saved server uses is
5660
5855
  // that one's now, and said too. A save as another user or auth config is refused while Composio triggers use the
5661
- // server, in the delete's words, checked in its project's turn before the row is written.
5856
+ // server, in the delete's words, checked in its project's turn before the row is written. An API-only server's token
5857
+ // saves one that names its key by api_key_env (the secret-write gate), and over a saved server only one it saved
5858
+ // (mcp-secret-writes.ts tokenWriteOverRefused), landing only while the row still has the credential the gate read
5859
+ // (secretSeen) and the token's mark. The body names no address or headers (composioSave refuses them).
5662
5860
  const answer = await inComposioTurn(async () => {
5663
5861
  const over = {};
5664
5862
  const guard = { turn: (work) => composioTriggers.inTurnOf(id, work), inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS) };
5665
- const saved = await composioSave(body, options.composioControl ?? {}, (mcp, made, stands) => mcpServers.save(id, mcp, stopping.signal, undefined, made, stands, (left) => (over.dropped = left), guard), id, stopping.signal, async () => (await mcpServers.get(id)).url);
5863
+ const saved = await composioSave(body, options.composioControl ?? {}, (mcp, made, stands) => mcpServers.save(id, mcp, stopping.signal, secretSeen, made, stands, (left) => (over.dropped = left), guard, byToken), id, stopping.signal, async () => (await mcpServers.get(id)).url);
5666
5864
  await refreshMcpMeta();
5667
5865
  return over.dropped ? { ...saved, composio: await composioLeft(id, over.dropped) } : saved;
5668
5866
  });
@@ -5756,7 +5954,7 @@ async function startHolding(options, data, checked, stops) {
5756
5954
  // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting). All of
5757
5955
  // it in the Composio turn, so a Composio save still at work finishes first and its record is counted.
5758
5956
  const forgotten = await inComposioTurn(async () => {
5759
- const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
5957
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen, byToken));
5760
5958
  await refreshMcpMeta();
5761
5959
  return !made ? undefined : "unusable" in made ? composioNote(id, made.cleanup) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal, made.cleanup);
5762
5960
  });
@@ -5796,16 +5994,17 @@ async function startHolding(options, data, checked, stops) {
5796
5994
  // over the same records and the money rule's decision, costStopOverStore), so the view never says a workflow serves
5797
5995
  // that does not run first.
5798
5996
  const records = await promotionsOf(store.settings, id);
5997
+ const refused = await refusedFor(id, records);
5799
5998
  const costStop = await costStopOverStore(store, id);
5800
5999
  const body = entry.revision?.body;
5801
6000
  const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
5802
- return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop), purgedOf), learning_model: await learningModelOf(modelEnv, entry.revision) });
6001
+ return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop, refused), store), learning_model: await learningModelOf(modelEnv, entry.revision) });
5803
6002
  }
5804
6003
  case "getLearningCost": {
5805
6004
  await needAgent(id);
5806
6005
  // The agent's cost per run over the one store (agentCostOverStore): each ended run's figures and path, aggregates only.
5807
6006
  const { limit, csv } = learningCostQuery(url);
5808
- const read = await agentCostOverStore(store, id, limit);
6007
+ const read = await agentCostOverStore(store, id, limit, refusedFor);
5809
6008
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
5810
6009
  const shown = await learningShown(id);
5811
6010
  const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })), workflows: read.workflows.map((one) => ({ ...one, workflow: shown.name(one.workflow) })), bill: { ...read.bill, revisions: read.bill.revisions.map((one) => ({ ...one, workflow: shown.name(one.workflow) })), holds: read.bill.holds.map((one) => ({ ...one, workflow: shown.name(one.workflow), reason: shown.text(one.reason) })) } };
@@ -5822,13 +6021,15 @@ async function startHolding(options, data, checked, stops) {
5822
6021
  // (promotionsShown: a reason as well as each workflow's name). Beside what serves, each one's state, its check's
5823
6022
  // numbers and its audit line (learn/audit.ts servingLinesOf), at the agent's numbers.
5824
6023
  const records = await promotionsOf(store.settings, id);
6024
+ // Every champion below skips a record the purge gate refuses at its commit, as a run's claim does (championOf).
6025
+ const refused = await refusedFor(id, records);
5825
6026
  const shown = await learningShown(id);
5826
- const shownRead = promotionsShown(records, shown);
6027
+ const shownRead = promotionsShown(records, shown, refused);
5827
6028
  // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
5828
6029
  const loop = auditLoopOf(entry.revision?.body?.learning);
5829
6030
  // Each one's state with the money rule's decision a run's launch reads (costStopOverStore): a champion it stopped
5830
6031
  // running first reads `stopped`.
5831
- const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop, await costStopOverStore(store, id));
6032
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop, await costStopOverStore(store, id), refused);
5832
6033
  // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
5833
6034
  // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
5834
6035
  const writer = auditWriterOf(entry.revision ?? undefined);
@@ -5837,7 +6038,7 @@ async function startHolding(options, data, checked, stops) {
5837
6038
  // first), then main: never by paging the workflow's history. Its nodes with their tiers and code checks, and the
5838
6039
  // check it was promoted on; nodes null when no commit read holds its text (or the folder can't be read now).
5839
6040
  const championRead = async (workflow, digest) => {
5840
- const champion = championOf(records, workflow);
6041
+ const champion = championOf(records, workflow, refused);
5841
6042
  const record = champion?.digest === digest ? champion : undefined;
5842
6043
  const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
5843
6044
  const read = await workflowAtDigest(data, id, workflow, digest, commits, store).catch(() => undefined);
@@ -5850,7 +6051,7 @@ async function startHolding(options, data, checked, stops) {
5850
6051
  }
5851
6052
  return shownDeep({ digest, commit: read?.commit ?? null, nodes: doc === undefined ? null : workflowNodesOf(doc), check: record?.check ?? null }, shown);
5852
6053
  };
5853
- const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
6054
+ const serving = await Promise.all(servingOf(records, refused).map(async (one, i) => ({
5854
6055
  ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
5855
6056
  not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
5856
6057
  champion: one.digest === null ? null : await championRead(one.workflow, one.digest),
@@ -5886,7 +6087,7 @@ async function startHolding(options, data, checked, stops) {
5886
6087
  }
5887
6088
  case "listLearningLog":
5888
6089
  await needAgent(id);
5889
- return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), purgedOf));
6090
+ return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), store));
5890
6091
  case "getLearningCorrections": {
5891
6092
  await needAgent(id);
5892
6093
  // corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
@@ -5913,7 +6114,7 @@ async function startHolding(options, data, checked, stops) {
5913
6114
  }
5914
6115
  case "listLearnedWorkflowRevisions":
5915
6116
  await needAgent(id);
5916
- return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), purgedOf));
6117
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), store));
5917
6118
  case "readLearningFile":
5918
6119
  await needAgent(id);
5919
6120
  return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id), store));
@@ -5924,7 +6125,7 @@ async function startHolding(options, data, checked, stops) {
5924
6125
  const refuse = await learningValues(id);
5925
6126
  const action = found.name === "approveLearningFile" ? "approve" : found.name === "restoreLearningFile" ? "restore" : "retire";
5926
6127
  // A change to a workflow is a write to the agent's learning: in its delete turn (agentWrite).
5927
- const written = await agentWrite(id, () => changeWorkflow(data, id, second, { action, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse, draftTools: () => learnedDraftToolsOf(id) }));
6128
+ const written = await agentWrite(id, () => changeWorkflow(data, id, second, { action, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse, draftTools: () => learnedDraftToolsOf(id), store }));
5928
6129
  // A run's list row that read a workflow held for the owner's OK says what the folder says now, at the next list.
5929
6130
  await lister.learningChanged(id);
5930
6131
  return sendText(res, written.status, { ...written, text: secretsShown(refuse).text(written.text) });
@@ -6705,6 +6906,9 @@ async function startHolding(options, data, checked, stops) {
6705
6906
  clearInterval(localSourceTimer);
6706
6907
  // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
6707
6908
  plan.close();
6909
+ // The CLI's sign-in still waiting for its browser ends with the server, which forgets it: left running, its CLI would
6910
+ // keep the browser's callback port from the next server's sign-in. Awaited until its process is gone.
6911
+ const signInStopped = claudeSignIns.close();
6708
6912
  const observationStopped = stopObservationRetention();
6709
6913
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
6710
6914
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
@@ -6724,6 +6928,7 @@ async function startHolding(options, data, checked, stops) {
6724
6928
  await importing;
6725
6929
  await schemaSealed;
6726
6930
  await installStopped;
6931
+ await signInStopped;
6727
6932
  await observationStopped;
6728
6933
  await localSourceSweep;
6729
6934
  // The ends' follower stops before the webhooks it feeds and the store it reads.
@@ -6769,6 +6974,7 @@ async function startHolding(options, data, checked, stops) {
6769
6974
  attachHub,
6770
6975
  dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
6771
6976
  localInstall,
6977
+ ollamaHost,
6772
6978
  own: mcpServers.own,
6773
6979
  ...(fauxGitHub ? { fauxGitHub: { api: fauxGitHub.url, ...(fauxGitHub.web ? { web: fauxGitHub.web } : {}) } } : {}),
6774
6980
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started