@parcha/agentrun-serve 0.1.0-beta.53 → 0.1.0-beta.55

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 (224) hide show
  1. package/CHANGELOG.md +138 -3
  2. package/README.md +346 -99
  3. package/dist/adapters.d.ts +10 -0
  4. package/dist/adapters.js +46 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +7 -14
  7. package/dist/agent-rows.d.ts +1 -1
  8. package/dist/agents-store.js +7 -6
  9. package/dist/api-only.d.ts +17 -6
  10. package/dist/api-only.js +22 -9
  11. package/dist/cli.js +11 -4
  12. package/dist/composio-made.d.ts +26 -1
  13. package/dist/composio-made.js +39 -2
  14. package/dist/composio-preset.d.ts +6 -4
  15. package/dist/composio-preset.js +50 -17
  16. package/dist/computer-held-routes.js +2 -3
  17. package/dist/computer-needs.d.ts +1 -1
  18. package/dist/computer-needs.js +1 -1
  19. package/dist/computer-setting.d.ts +8 -4
  20. package/dist/computer-setting.js +0 -2
  21. package/dist/computers-running.d.ts +8 -0
  22. package/dist/computers-running.js +27 -0
  23. package/dist/computers.d.ts +0 -2
  24. package/dist/computers.js +1 -1
  25. package/dist/console/assets/backend-D5EmB4N3.js +166 -0
  26. package/dist/console/assets/index-DUYLaqiR.js +746 -0
  27. package/dist/console/assets/index-DYhU4adm.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/docker-host-addresses.d.ts +23 -3
  30. package/dist/docker-host-addresses.js +90 -18
  31. package/dist/errors.d.ts +4 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/exa-keyless.d.ts +2 -3
  34. package/dist/exa-keyless.js +43 -127
  35. package/dist/firecrawl-keyless.d.ts +41 -0
  36. package/dist/firecrawl-keyless.js +152 -0
  37. package/dist/github-connection.d.ts +50 -1
  38. package/dist/github-connection.js +96 -3
  39. package/dist/github-faux.d.ts +11 -2
  40. package/dist/github-faux.js +138 -7
  41. package/dist/github-pull-request.d.ts +37 -0
  42. package/dist/github-pull-request.js +110 -0
  43. package/dist/handed-secret.d.ts +3 -1
  44. package/dist/handed-secret.js +4 -2
  45. package/dist/harness-keys.d.ts +98 -0
  46. package/dist/harness-keys.js +247 -0
  47. package/dist/harness-recipe-entry.d.ts +14 -9
  48. package/dist/harness-recipe-entry.js +25 -14
  49. package/dist/harness-table.d.ts +16 -1
  50. package/dist/harness-table.js +19 -7
  51. package/dist/harness.d.ts +4 -0
  52. package/dist/harness.js +12 -1
  53. package/dist/host-check.d.ts +2 -0
  54. package/dist/host-check.js +6 -0
  55. package/dist/import-summary.d.ts +1 -1
  56. package/dist/import-summary.js +1 -1
  57. package/dist/import.d.ts +5 -5
  58. package/dist/import.js +54 -67
  59. package/dist/keyless-mcp.d.ts +36 -0
  60. package/dist/keyless-mcp.js +127 -0
  61. package/dist/learn/audit.d.ts +3 -3
  62. package/dist/learn/audit.js +3 -3
  63. package/dist/learn/commit.d.ts +8 -7
  64. package/dist/learn/commit.js +60 -20
  65. package/dist/learn/compile.d.ts +4 -3
  66. package/dist/learn/compile.js +7 -5
  67. package/dist/learn/folder.d.ts +16 -3
  68. package/dist/learn/folder.js +46 -13
  69. package/dist/learn/promote.d.ts +37 -13
  70. package/dist/learn/promote.js +112 -40
  71. package/dist/learn/secrets.js +10 -2
  72. package/dist/learning-routes.d.ts +22 -17
  73. package/dist/learning-routes.js +40 -39
  74. package/dist/learning.js +2 -2
  75. package/dist/live-reach.d.ts +34 -7
  76. package/dist/live-reach.js +76 -11
  77. package/dist/manifest.d.ts +10 -0
  78. package/dist/manifest.js +30 -0
  79. package/dist/mcp-pin-first.d.ts +4 -2
  80. package/dist/mcp-pin-first.js +5 -2
  81. package/dist/mcp-probe.js +2 -2
  82. package/dist/mcp-secret-writes.d.ts +16 -7
  83. package/dist/mcp-secret-writes.js +35 -27
  84. package/dist/mcp-servers-store.d.ts +30 -6
  85. package/dist/mcp-servers-store.js +112 -28
  86. package/dist/mcp-sources.d.ts +10 -2
  87. package/dist/mcp-sources.js +9 -2
  88. package/dist/mcp-store.d.ts +13 -7
  89. package/dist/mcp-store.js +12 -9
  90. package/dist/model-form.d.ts +3 -2
  91. package/dist/model-form.js +11 -7
  92. package/dist/model.d.ts +20 -4
  93. package/dist/model.js +68 -9
  94. package/dist/native/history.d.ts +1 -1
  95. package/dist/native/history.js +2 -2
  96. package/dist/ollama-provider.d.ts +92 -0
  97. package/dist/ollama-provider.js +495 -0
  98. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  99. package/dist/openapi.js +235 -41
  100. package/dist/page.d.ts +11 -3
  101. package/dist/page.js +22 -7
  102. package/dist/place-offers.d.ts +17 -1
  103. package/dist/place-offers.js +46 -5
  104. package/dist/print.js +1 -1
  105. package/dist/purged-workflow.d.ts +35 -7
  106. package/dist/purged-workflow.js +73 -26
  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/runner/adapter-loop.d.ts +6 -3
  119. package/dist/runner/adapter-loop.js +34 -15
  120. package/dist/runner/adapter-run-spec.d.ts +3 -0
  121. package/dist/runner/adapter-run-spec.js +6 -4
  122. package/dist/runner/audit.js +8 -4
  123. package/dist/runner/beside.d.ts +2 -1
  124. package/dist/runner/beside.js +6 -2
  125. package/dist/runner/claim-secrets.d.ts +5 -8
  126. package/dist/runner/claim-secrets.js +6 -0
  127. package/dist/runner/cli-run-spec.d.ts +1 -1
  128. package/dist/runner/cli-run-spec.js +39 -7
  129. package/dist/runner/harness-loops.d.ts +22 -9
  130. package/dist/runner/harness-loops.js +21 -11
  131. package/dist/runner/held.d.ts +3 -0
  132. package/dist/runner/learning-end.d.ts +1 -1
  133. package/dist/runner/learning-end.js +8 -3
  134. package/dist/runner/loop-contract.d.ts +5 -4
  135. package/dist/runner/main.js +4 -2
  136. package/dist/runner/mcp-claim.d.ts +3 -0
  137. package/dist/runner/mcp-claim.js +26 -2
  138. package/dist/runner/mcp-run.d.ts +3 -0
  139. package/dist/runner/mcp-run.js +2 -1
  140. package/dist/runner/metrics.d.ts +10 -8
  141. package/dist/runner/metrics.js +20 -27
  142. package/dist/runner/model-route.d.ts +3 -0
  143. package/dist/runner/model-route.js +6 -2
  144. package/dist/runner/pr-checkout.d.ts +21 -4
  145. package/dist/runner/pr-checkout.js +103 -4
  146. package/dist/runner/promotion.d.ts +15 -9
  147. package/dist/runner/promotion.js +25 -15
  148. package/dist/runner/run-child-host.js +24 -11
  149. package/dist/runner/run-child.js +3 -1
  150. package/dist/runner/runner-check.d.ts +3 -0
  151. package/dist/runner/runner-check.js +23 -0
  152. package/dist/runner/sdk-loop.js +2 -0
  153. package/dist/runner/workflow-loop.d.ts +2 -2
  154. package/dist/runner/workflow-loop.js +1 -2
  155. package/dist/runner/workflow-spec.d.ts +1 -1
  156. package/dist/runner/workflow-spec.js +6 -6
  157. package/dist/sdk/check.d.ts +4 -1
  158. package/dist/sdk/check.js +2 -1
  159. package/dist/sdk/runs.d.ts +2 -2
  160. package/dist/sdk/runs.js +8 -6
  161. package/dist/secret-cut.js +2 -1
  162. package/dist/secret-writes.d.ts +3 -2
  163. package/dist/secret-writes.js +1 -1
  164. package/dist/server.d.ts +55 -8
  165. package/dist/server.js +363 -118
  166. package/dist/standard-webhooks.d.ts +11 -0
  167. package/dist/standard-webhooks.js +20 -2
  168. package/dist/store/agent-body.d.ts +2 -2
  169. package/dist/store/agent-body.js +2 -2
  170. package/dist/store/index.d.ts +1 -1
  171. package/dist/store/schema.js +5 -2
  172. package/dist/store/sqlite/store.js +90 -34
  173. package/dist/store/store.d.ts +54 -14
  174. package/dist/store-reads/journal.d.ts +7 -2
  175. package/dist/store-reads/journal.js +9 -6
  176. package/dist/store-reads/learning.d.ts +12 -9
  177. package/dist/store-reads/learning.js +18 -24
  178. package/dist/store-view.d.ts +0 -5
  179. package/dist/store-view.js +9 -8
  180. package/dist/suggestions.d.ts +282 -0
  181. package/dist/suggestions.js +919 -0
  182. package/dist/telemetry.d.ts +8 -1
  183. package/dist/telemetry.js +12 -4
  184. package/dist/template-eval.d.ts +49 -4
  185. package/dist/template-eval.js +168 -45
  186. package/dist/template-import.d.ts +17 -0
  187. package/dist/template-import.js +36 -2
  188. package/dist/templates.d.ts +83 -76
  189. package/dist/templates.js +29 -48
  190. package/dist/timeline/labels.d.ts +2 -2
  191. package/dist/timeline/labels.js +2 -2
  192. package/dist/timeline/timeline.d.ts +2 -2
  193. package/dist/timeline/timeline.js +1 -1
  194. package/dist/tool-plane.d.ts +17 -9
  195. package/dist/tool-plane.js +38 -17
  196. package/dist/tools.js +2 -2
  197. package/dist/trigger-launch-hook.d.ts +19 -9
  198. package/dist/trigger-launch-hook.js +35 -25
  199. package/dist/trigger-targets.d.ts +18 -8
  200. package/dist/trigger-targets.js +42 -19
  201. package/dist/triggers.d.ts +85 -23
  202. package/dist/triggers.js +303 -96
  203. package/dist/validate.d.ts +1 -1
  204. package/dist/validate.js +2 -2
  205. package/dist/web-fake.js +3 -3
  206. package/dist/web-fetch-direct.d.ts +4 -0
  207. package/dist/web-fetch-direct.js +8 -1
  208. package/dist/web-fetch.d.ts +12 -3
  209. package/dist/web-fetch.js +47 -14
  210. package/dist/web-search.d.ts +33 -4
  211. package/dist/web-search.js +100 -41
  212. package/dist/webhooks.js +4 -5
  213. package/dist/workspace/synced-folder.d.ts +1 -1
  214. package/dist/workspace/synced-folder.js +11 -14
  215. package/launcher/agentrun-serve +5 -1
  216. package/package.json +17 -13
  217. package/templates/README.md +5 -4
  218. package/templates/agent-scout/agent.md +46 -0
  219. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  220. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  221. package/dist/console/assets/index-BFgyZzF_.js +0 -734
  222. package/dist/console/assets/index-DbilxljH.css +0 -1
  223. package/dist/import-sources.d.ts +0 -116
  224. package/dist/import-sources.js +0 -693
package/dist/server.js CHANGED
@@ -31,7 +31,7 @@ import { createServer } from "node:http";
31
31
  import proxyaddr from "proxy-addr";
32
32
  import { API_ONLY_HOOKED_KINDS, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
33
33
  import { RUN_KEYS_ENV } from "./env-switch.js";
34
- import { declaredKeys, keysOwed, keysOwedRefusal, packageKeysOf, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
34
+ import { declaredKeys, keysOwed, keysOwedRefusal, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
35
35
  import { capacityOverStore, capacityWindowOf } from "./capacity.js";
36
36
  import { carriedFields } from "./answer-json.js";
37
37
  import { dirname, join, relative, resolve, sep } from "node:path";
@@ -50,15 +50,16 @@ import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_
50
50
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
51
51
  import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid, PRICED_BY_USAGE } from "./monid.js";
52
52
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
53
+ import { FAUX_FIRECRAWL_ENV } from "./firecrawl-keyless.js";
53
54
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
54
55
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
55
56
  import { deref, explain } from "./explain.js";
56
57
  import { HOME_HOST_OWNED } from "./files.js";
57
58
  import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
58
59
  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";
60
+ import { asksOllama, chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
60
61
  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";
62
+ 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
63
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
63
64
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
64
65
  import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
@@ -67,7 +68,7 @@ import { answerStoreCall } from "./import-proxy.js";
67
68
  import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf, withAgentRepo } from "./learning.js";
68
69
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
69
70
  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";
71
+ import { purgedRun, refusedIn } from "./purged-workflow.js";
71
72
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
72
73
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
73
74
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -75,7 +76,7 @@ import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
75
76
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
76
77
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
77
78
  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 { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownerCookieName, ownOrigin, sessionsAtEveryPort, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
79
80
  import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
80
81
  import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
81
82
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
@@ -125,6 +126,7 @@ import { championOf, forgetRunCopies, GRADE_SOURCES, gradeView, LABEL_MAX, promo
125
126
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
126
127
  import { deleteLearning } from "./learn/delete.js";
127
128
  import { runModelRef } from "./model.js";
129
+ import { ollamaHostOf, ollamaHostRefused, ollamaListing, ollamaModels } from "./ollama-provider.js";
128
130
  import { REDACTED } from "./secret-cut.js";
129
131
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
130
132
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
@@ -132,7 +134,7 @@ import { runLines } from "./usage-lines.js";
132
134
  import { boxesByDefault, boxesLog, enabledBoxes, placeOffers, withNetworks } from "./place-offers.js";
133
135
  import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
134
136
  import { dockerDaemonCheck } from "./docker-daemon.js";
135
- import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
137
+ import { hostAddressesOnce, noHostAddresses, retryHostAddresses, unionOf } from "./docker-host-addresses.js";
136
138
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
137
139
  import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
138
140
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
@@ -154,10 +156,11 @@ import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learning
154
156
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
155
157
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
156
158
  import { toolKeysOverStore } from "./tool-keys-store.js";
159
+ import { HarnessKeysOverStore, harnessKeysSavedHere } from "./harness-keys.js";
157
160
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
158
161
  import { signInsOverStore } from "./sign-ins-store.js";
159
162
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
160
- import { composioMadeKey, composioPerRun } from "./composio-made.js";
163
+ import { composioEnvKey, composioMadeKey, composioPerRun } from "./composio-made.js";
161
164
  import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
162
165
  import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
163
166
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
@@ -174,6 +177,7 @@ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, trigger
174
177
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
175
178
  import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
176
179
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
180
+ import { SCOUT_TEMPLATE, Suggestions } from "./suggestions.js";
177
181
  import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
178
182
  import { GITHUB_API } from "./github.js";
179
183
  import { bindingOf, REPO_NAME } from "./run-repo.js";
@@ -187,7 +191,7 @@ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
187
191
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
188
192
  import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
189
193
  import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, feedLeftEmpty, feedTriggerEmpty, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
190
- import { deleteTemplate, dropRemovedUploads, importTemplate, loadImported, UPLOAD_PREFIX } from "./template-import.js";
194
+ import { applyImported, deleteTemplate, dropRemovedUploads, importTemplate, loadImported, UPLOAD_PREFIX } from "./template-import.js";
191
195
  import { templateInstallLink, templateLink, templatesLink } from "./console-links.js";
192
196
  import { GITHUB_HOSTS, IMPORT_LIMITS } from "./template-source.js";
193
197
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
@@ -215,8 +219,9 @@ import { emailRoute } from "./email/routes.js";
215
219
  import { addressForms, openCalendar } from "./calendar/address.js";
216
220
  import { calendarRoute } from "./calendar/routes.js";
217
221
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, loadArchilSettings, runDiskKept, runDiskKey } from "./archil-settings.js";
218
- import { computerOfPlace } from "./computer-setting.js";
222
+ import { computerOfPlace, settingOfDefinition } from "./computer-setting.js";
219
223
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
224
+ import { runningComputers } from "./computers-running.js";
220
225
  import { fauxComputers } from "./faux-computers.js";
221
226
  import { writesHeld } from "./workspace.js";
222
227
  import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
@@ -247,6 +252,9 @@ const IMPORT_STARTS = 3;
247
252
  const IMPORT_HEAP_MB = 2048;
248
253
  const MAX_MESSAGE = 20_000;
249
254
  const MAX_WAIT_MS = 25_000;
255
+ /** 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
256
+ * target fixes them. */
257
+ const HANDED_FIXED = ["revision", "hold", "hold_minutes"];
250
258
  /** How often the server fails the runs still queued while no runner here can take them (runner/presence.ts). */
251
259
  const REFUSED_SWEEP_MS = 2_000;
252
260
  const PAGE_ROWS = 500;
@@ -279,6 +287,9 @@ export function fauxEnvOf(options) {
279
287
  for (const [option, name] of FAUX_SWITCHES)
280
288
  if (options[option])
281
289
  env[name] = resolve(options[option]);
290
+ // A URL, so never resolved as a path.
291
+ if (options.fauxFirecrawl)
292
+ env[FAUX_FIRECRAWL_ENV] = options.fauxFirecrawl;
282
293
  // The mountinfo the server itself reads (fauxMountinfo in serve), also when its own environment names it: a CLI server
283
294
  // in a container hands it to the runner beside it, whose environment drops every faux variable it inherited.
284
295
  const mountinfo = options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV];
@@ -403,6 +414,7 @@ export const ROUTES = [
403
414
  // Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
404
415
  // archilRoute): the server switch dispatches them, once the server opens its store.
405
416
  { method: "GET", pattern: /^\/computers$/, name: "listComputers" },
417
+ { method: "GET", pattern: /^\/computers\/running$/, name: "listRunningComputers" },
406
418
  { method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
407
419
  { method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
408
420
  { method: "GET", pattern: /^\/computers\/([^/]+)\/choices$/, name: "listComputerChoices" },
@@ -433,6 +445,10 @@ export const ROUTES = [
433
445
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
434
446
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
435
447
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
448
+ // The keys a plan-billed harness recipe runs on, saved for that harness alone (harness-keys.ts): the owner's session's.
449
+ { method: "GET", pattern: /^\/settings\/harness-keys$/, name: "listHarnessKeys" },
450
+ { method: "PUT", pattern: /^\/settings\/harness-keys\/([^/]+)\/([^/]+)$/, name: "saveHarnessKey" },
451
+ { method: "DELETE", pattern: /^\/settings\/harness-keys\/([^/]+)\/([^/]+)$/, name: "deleteHarnessKey" },
436
452
  // The server's email account (email/routes.ts): the owner's session's alone, its password in no answer.
437
453
  { method: "GET", pattern: /^\/settings\/email$/, name: "getEmailAccount" },
438
454
  { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
@@ -458,7 +474,6 @@ export const ROUTES = [
458
474
  { method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
459
475
  { method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
460
476
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
461
- // The saved servers' names alone, for a host that builds runs from them (served API-only too: api-only.ts).
462
477
  { method: "GET", pattern: /^\/settings\/mcp-server-names$/, name: "listMcpServerNames" },
463
478
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
464
479
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
@@ -516,6 +531,14 @@ export const ROUTES = [
516
531
  { method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
517
532
  { method: "GET", pattern: /^\/integrations\/github\/callback$/, name: "gitHubCallback" },
518
533
  { method: "GET", pattern: /^\/integrations\/github\/installed$/, name: "gitHubInstalled" },
534
+ { method: "GET", pattern: /^\/integrations\/github\/repositories$/, name: "listGitHubRepositories" },
535
+ // Suggested agents (suggestions.ts): what the agent-scout template finds in a repository, and what a person decides.
536
+ { method: "GET", pattern: /^\/suggestions$/, name: "listSuggestions" },
537
+ { method: "POST", pattern: /^\/suggestions\/scans$/, name: "scanForSuggestions" },
538
+ { method: "GET", pattern: /^\/suggestions\/([^/]+)$/, name: "getSuggestion" },
539
+ { method: "POST", pattern: /^\/suggestions\/([^/]+)\/discard$/, name: "discardSuggestion" },
540
+ { method: "POST", pattern: /^\/suggestions\/([^/]+)\/restore$/, name: "restoreSuggestion" },
541
+ { method: "POST", pattern: /^\/suggestions\/([^/]+)\/create$/, name: "createSuggestedAgent" },
519
542
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
520
543
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
521
544
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
@@ -609,9 +632,10 @@ export function offersEnvOf(env) {
609
632
  * harnesses run, and on what, follow them. */
610
633
  const GATEWAY_VARS = ["AGENT_MODEL_BASE_URL", "AGENT_MODEL_GATEWAY_IDS", "AGENT_MODEL", "AGENT_MODEL_FAST", "AGENT_MODEL_STRONG"];
611
634
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
612
- * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
613
- * the offers probed again, never shown. */
614
- 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];
635
+ * saved key is one of those; the rest of the environment is the server's start's), and the models the Ollama here
636
+ * listed when last asked (ollamaListing). Held to tell whether a write, or a new listing, needs the offers probed again,
637
+ * never shown. */
638
+ 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)];
615
639
  /** 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. */
616
640
  async function planStep(step) {
617
641
  try {
@@ -682,8 +706,12 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
682
706
  * a user of its own too. */
683
707
  run_isolation: isolation,
684
708
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
685
- // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
686
- harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
709
+ // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here. Served `available` is
710
+ // whether a run of it can start now on some model it offers: one whose every model lacks a key or the sign-in
711
+ // (noModelRuns: pi with neither) is not, though a save and a run read it as a harness that runs here (runnable.ts), so
712
+ // their words name the model it lacks. One whose default lacks a key while another model runs is (its `needs` says
713
+ // what the default lacks).
714
+ harnesses: harnesses.map(({ keys: _keys, noModelRuns, ...offer }) => ({ ...offer, available: offer.available && !noModelRuns, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
687
715
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
688
716
  places: placesOf(boxes, boxAllowOf(env)),
689
717
  models,
@@ -745,6 +773,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
745
773
  /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the server's seal key
746
774
  * (tool-keys-store.ts), never in the clear. */
747
775
  tool_keys: { routes: true, at_rest: "sealed" },
776
+ /** GET /settings/harness-keys and PUT/DELETE of one key: a plan-billed recipe's keys, saved for that harness alone
777
+ * (harness-keys.ts); `harnesses` its ids here, so the console offers the page only where there is one. */
778
+ harness_keys: { routes: true, at_rest: "sealed", harnesses: planRecipesOf(env).map((recipe) => recipe.id) },
748
779
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
749
780
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. Every harness of the table runs a
750
781
  * grant (runnable.ts takes one on any), a module's among them. */
@@ -815,17 +846,18 @@ function integerParam(value, name, max) {
815
846
  }
816
847
  /** A start with --harness-sign-in on a server that is not one owner's own, on their own machine. */
817
848
  export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
818
- /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
819
- * it may. One owner's own server on their own machine: it listens on loopback alone, with no public address; its store
820
- * is the SQLite one in its data directory (no AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside
821
- * it as its own user (`ownUser`: runIsolationOf's `process`), never under --no-runner or a user of their own; and one
822
- * person starts them, as Claude Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one
823
- * API token. A check, a schedule and a shared server run on a key (HARNESS.md#sign-in). */
824
- export function harnessSignInRefusal(options, data, ownUser) {
849
+ /** Why `options` on `data` is not one owner's own server on their own machine, each reason in words; none when it is. One
850
+ * owner's own: it listens on loopback alone, with no public address; its store is the SQLite one in its data directory (no
851
+ * AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside it as its own user (`ownUser`:
852
+ * runIsolationOf's `process`), never under --no-runner or a user of their own; and one person starts them, as Claude
853
+ * Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one API token. What --harness-sign-in
854
+ * starts under (harnessSignInRefusal), and where the Ollama at this machine's default address is a model of the person
855
+ * who starts runs (ollama-provider.ts ollamaHostOf). */
856
+ export function whyNotOwnMachine(options, data, ownUser) {
825
857
  const host = options.host ?? DEFAULT_HOST;
826
858
  // Every token the server takes (acceptedTokens): AGENTRUN_TOKEN's as `default` beside the list's, or else DIR/.token's alone.
827
859
  const tokens = (options.token === undefined ? 0 : 1) + (options.tokens?.length ?? 0);
828
- const why = [
860
+ return [
829
861
  ...(loopback(host) ? [] : [`listens on ${host}, past loopback`]),
830
862
  ...(options.publicUrl ? [`has a public address (${options.publicUrl})`] : []),
831
863
  ...(options.apiOnly ? ["has no owner (the API-only profile), so anyone with its token starts runs"] : []),
@@ -834,6 +866,12 @@ export function harnessSignInRefusal(options, data, ownUser) {
834
866
  ...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
835
867
  ...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
836
868
  ];
869
+ }
870
+ /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
871
+ * it may: one owner's own server on their own machine alone (whyNotOwnMachine). A check, a schedule and a shared server
872
+ * run on a key (HARNESS.md#sign-in). */
873
+ export function harnessSignInRefusal(options, data, ownUser) {
874
+ const why = whyNotOwnMachine(options, data, ownUser);
837
875
  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;
838
876
  }
839
877
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
@@ -853,12 +891,16 @@ export async function startServe(options) {
853
891
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
854
892
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
855
893
  const data = await realpath(resolve(options.data));
894
+ const { runsAsOwnUser } = await import("./runner/run-child-host.js");
895
+ const ownUser = runsAsOwnUser(process.env);
856
896
  if (options.harnessSignIn) {
857
- const { runsAsOwnUser } = await import("./runner/run-child-host.js");
858
- const refused = harnessSignInRefusal(options, data, runsAsOwnUser(process.env));
897
+ const refused = harnessSignInRefusal(options, data, ownUser);
859
898
  if (refused)
860
899
  throw new Error(refused);
861
900
  }
901
+ // The Ollama this server asks, and its runner beside it: OLLAMA_HOST, else the default address on one owner's own machine
902
+ // alone (ollamaHostOf). Read once, at the start: a refused one is said once, here, in the base rule's words.
903
+ const ollamaHost = ollamaHostOf(process.env, whyNotOwnMachine(options, data, ownUser).length === 0);
862
904
  const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
863
905
  if (tokenRefused)
864
906
  throw new Error(tokenRefused);
@@ -899,7 +941,7 @@ export async function startServe(options) {
899
941
  // store handle it opened.
900
942
  const stops = [];
901
943
  try {
902
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates }, stops);
944
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, boxAllow, templates, ollamaHost }, stops);
903
945
  }
904
946
  catch (error) {
905
947
  for (const stop of stops)
@@ -929,7 +971,7 @@ async function whileReplaced(take, held, until, waiting) {
929
971
  }
930
972
  }
931
973
  async function startHolding(options, data, checked, stops) {
932
- const { maxRuns, minFreeBytes, learning, boxAllow, templates } = checked;
974
+ const { maxRuns, minFreeBytes, learning, boxAllow, templates, ollamaHost } = checked;
933
975
  /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
934
976
  * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
935
977
  * read (the view never fails for it). */
@@ -951,7 +993,12 @@ async function startHolding(options, data, checked, stops) {
951
993
  // shown nowhere.
952
994
  let secretStores;
953
995
  let triggerSettings = new Map();
954
- 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 }) };
996
+ 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 } : {}) };
997
+ // A refused OLLAMA_HOST lists nothing (ollama-provider.ts baseOf): said once, at the start, in the base rule's words,
998
+ // which never hold the value (a user or password in it stays unsaid).
999
+ const ollamaRefused = ollamaHostRefused(base);
1000
+ if (ollamaRefused)
1001
+ log ? log(logLine("ollama_host_refused", { line: ollamaRefused })) : void process.stderr.write(`agentrun-serve: ${ollamaRefused}\n`);
955
1002
  // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
956
1003
  // the start, in words, before anything else opens.
957
1004
  // The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
@@ -1052,6 +1099,10 @@ async function startHolding(options, data, checked, stops) {
1052
1099
  // call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
1053
1100
  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`)));
1054
1101
  await toolKeys.load();
1102
+ // The keys each plan-billed harness recipe this server names runs on, saved for that harness alone (harness-keys.ts):
1103
+ // sealed rows in the store, loaded once here and kept in step with every save, so its listing reads them at once.
1104
+ const harnessKeys = new HarnessKeysOverStore(store, seal.key, planRecipesOf(base), data);
1105
+ await harnessKeys.load();
1055
1106
  // 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,
1056
1107
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
1057
1108
  const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
@@ -1062,7 +1113,9 @@ async function startHolding(options, data, checked, stops) {
1062
1113
  return fake ? (await import(pathToFileURL(resolve(fake)).href)).default : undefined;
1063
1114
  };
1064
1115
  // Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
1116
+ // A start that fails aborts it too: what began on it (the host-address read's retry) stops with that start.
1065
1117
  const stopping = new AbortController();
1118
+ stops.push(async () => stopping.abort());
1066
1119
  /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
1067
1120
  let schemaSealed = Promise.resolve();
1068
1121
  // The start's sweep of ended runs whose stored cost is unknown (cost-heal.ts), once this server listens; stop drains it.
@@ -1075,16 +1128,22 @@ async function startHolding(options, data, checked, stops) {
1075
1128
  const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
1076
1129
  if (options.githubMcpOrigin)
1077
1130
  mcpServers.appOrigin = options.githubMcpOrigin;
1131
+ if (options.composioMcpOrigin)
1132
+ mcpServers.composioOrigin = options.composioMcpOrigin;
1078
1133
  mcpServers.standIns = options.mcpStandIns === true;
1079
1134
  // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the checks read in step (which
1080
1135
  // servers are saved, a workflow's grants, the template apply): the server is the one writer of these rows (a save,
1081
1136
  // refresh, sign-in or delete), so the snapshot is refreshed after each of those and reads what is saved now. An agent's
1082
1137
  // save lists its granted servers live and pins their tools on its revision (saveable, mcpListingOf); the runner reads
1083
1138
  // that pin and the credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP
1084
- // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on.
1139
+ // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on,
1140
+ // and the variable a Composio server saved with api_key_env reads its key from (`keyEnv`), which a run's start checks.
1085
1141
  let mcpMeta = new Map();
1086
1142
  const refreshMcpMeta = async () => {
1087
- 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) }])));
1143
+ mcpMeta = new Map(await Promise.all((await listMcpServers(store)).map(async (row) => {
1144
+ const keyEnv = await mcpServers.keyEnvOf(row);
1145
+ return [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [], source: await mcpServers.sourceOf(row), ...(keyEnv ? { keyEnv } : {}) }];
1146
+ })));
1088
1147
  };
1089
1148
  await refreshMcpMeta();
1090
1149
  // Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
@@ -1151,6 +1210,9 @@ async function startHolding(options, data, checked, stops) {
1151
1210
  let probes = 0;
1152
1211
  const probe = async (why) => {
1153
1212
  const mine = ++probes;
1213
+ // The Ollama listing the offers are made from is read before they are, so the first capabilities do not remake them.
1214
+ if (asksOllama(env))
1215
+ await ollamaModels(env);
1154
1216
  const from = offersInputs(env);
1155
1217
  const started = performance.now();
1156
1218
  const next = await harnessOffers(offersEnvOf(env));
@@ -1172,6 +1234,8 @@ async function startHolding(options, data, checked, stops) {
1172
1234
  log: (what, error) => log?.(logLine(what, { error: error.message })),
1173
1235
  ...(options.listerIdleMs !== undefined ? { idleMs: options.listerIdleMs } : {}),
1174
1236
  });
1237
+ /** Whether the offers held now were made from `inputs` (offersInputs). */
1238
+ const offersMadeFrom = (inputs) => offersFrom !== undefined && inputs.length === offersFrom.length && inputs.every((value, i) => value === offersFrom[i]);
1175
1239
  const keysChanged = async () => {
1176
1240
  // 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
1177
1241
  // serverSecrets live, store-view), and a list builds a listing cut of other keys again (builtOfNow). A failed run's error words
@@ -1182,12 +1246,27 @@ async function startHolding(options, data, checked, stops) {
1182
1246
  const next = await needsOf(env);
1183
1247
  if (mine === needsAsked)
1184
1248
  needs = next;
1185
- const inputs = offersInputs(env);
1186
- if (offersFrom && inputs.length === offersFrom.length && inputs.every((value, i) => value === offersFrom[i]))
1249
+ if (offersMadeFrom(offersInputs(env)))
1187
1250
  recompose();
1188
1251
  else
1189
1252
  await probe("key");
1190
1253
  };
1254
+ /** The Ollama here, as capabilities read it: its listing asked again behind the answer once stale (ollamaModels), and
1255
+ * the reading made again, as a key's save does, once a listing differs from the one the offers were made from. So a
1256
+ * model pulled, or Ollama started after this server, shows in a later answer with no restart. */
1257
+ const ollamaNow = async () => {
1258
+ if (!asksOllama(env))
1259
+ return;
1260
+ void ollamaModels(env);
1261
+ if (offersFrom && !offersMadeFrom(offersInputs(env)))
1262
+ await keysChanged();
1263
+ };
1264
+ /** After a harness key is saved or removed (harness-keys.ts): the listings built again, cut of it, and the offers probed
1265
+ * again, as a recipe is offered once every key it runs on is saved here (harnessKeysSavedHere). No environment changes. */
1266
+ const harnessKeysChanged = async () => {
1267
+ await lister.keysChanged();
1268
+ await probe("harness-key");
1269
+ };
1191
1270
  /** After the model gateway is saved or removed in the console: the saved gateway read again, then env, as a key's save. */
1192
1271
  const gatewayChanged = async () => {
1193
1272
  savedGateway = await readSavedGateway(store, seal.key);
@@ -1218,7 +1297,9 @@ async function startHolding(options, data, checked, stops) {
1218
1297
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
1219
1298
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
1220
1299
  const fauxDocker = Boolean(options.faux) && options.fauxDocker === true;
1221
- const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker });
1300
+ // 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;
1301
+ // `probeContainer` sets it for a test of a real one.
1302
+ const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker, ...(options.probeContainer ? { container: options.probeContainer } : options.faux ? { container: { inside: false } } : {}) });
1222
1303
  const docker = found.some((offer) => offer.id === "docker" && offer.available);
1223
1304
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
1224
1305
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
@@ -1239,13 +1320,35 @@ async function startHolding(options, data, checked, stops) {
1239
1320
  // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
1240
1321
  // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
1241
1322
  // runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
1323
+ // A read that failed with none known is read again in the background (retryHostAddresses) until one answers and the
1324
+ // helper containers the failed reads left are gone, or this server stops: the boxes are made again from the answer and
1325
+ // said again, so Docker is offered with no restart. Every reader of boxOffers reads it when it is called; capabilities
1326
+ // are composed again.
1327
+ const boxesOf = (hostAddresses) => {
1328
+ if (hostAddresses)
1329
+ log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
1330
+ const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
1331
+ // Each box with what it reaches (place-offers.ts withNetworks).
1332
+ const offers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
1333
+ log?.(logLine("boxes", boxesLog(offers, enabledBoxes(env))));
1334
+ return offers;
1335
+ };
1242
1336
  const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
1243
- if (hostAddresses)
1244
- log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
1245
- const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
1246
- // Each box with what it reaches (place-offers.ts withNetworks).
1247
- const boxOffers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
1248
- log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
1337
+ let boxOffers = boxesOf(hostAddresses);
1338
+ if (hostAddresses?.why !== undefined && hostAddresses.addresses.length === 0) {
1339
+ void retryHostAddresses({
1340
+ env,
1341
+ read: () => hostAddressesOnce(env),
1342
+ found: (read) => {
1343
+ boxOffers = boxesOf(unionOf(read, dockerHostAddressesOf(env)));
1344
+ // Capabilities are first composed at the start's probe, below; before it, there is nothing to compose again.
1345
+ if (caps)
1346
+ recompose();
1347
+ },
1348
+ signal: stopping.signal,
1349
+ ...(options.hostReadWait ? { wait: options.hostReadWait } : {}),
1350
+ });
1351
+ }
1249
1352
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
1250
1353
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
1251
1354
  const sealKey = seal.key;
@@ -1385,10 +1488,8 @@ async function startHolding(options, data, checked, stops) {
1385
1488
  * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
1386
1489
  const shellOfRevision = async (revision) => {
1387
1490
  const body = revision.body;
1388
- return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
1491
+ return shellOf(settingOfDefinition(body)?.computer ?? computerOfPlace(fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : [])));
1389
1492
  };
1390
- /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1391
- const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1392
1493
  /** The run read's costs (A8, store-reads/learning.ts runAllInOverStore): `cost.usd` its own spend, the
1393
1494
  * job's (its compile turn is learning's), null while unknown; what learning spent for it
1394
1495
  * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown.
@@ -1396,12 +1497,26 @@ async function startHolding(options, data, checked, stops) {
1396
1497
  const allInViewOf = async (runId, view) => {
1397
1498
  const cost = (view.cost ?? {});
1398
1499
  const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
1399
- const all = await runAllInOverStore(store, runId, own);
1500
+ // A purge gate that can't be asked (its store read of a writer's row fails) leaves this read without its answer, never
1501
+ // a 500: the revision ledger its `learning_usd` and `all_in_usd` share is read from takes the champion with no record
1502
+ // skipped (as before the purge), so a revision a purged run wrote may be the one it counts as serving, for this read
1503
+ // alone. Figures only: no text is read or shown. Every write that asks the gate still fails closed (decideCheck
1504
+ // throws, so no promote lands; recordPromotion trims nothing). Such a read says so: `cost.degraded`.
1505
+ let degraded = false;
1506
+ const all = await runAllInOverStore(store, runId, own, (agentId, records) => refusedFor(agentId, records).catch((error) => {
1507
+ degraded = true;
1508
+ const line = `learning: run ${runId}: its costs were read without the purge gate's answer: ${error instanceof Error ? error.message : String(error)}`;
1509
+ if (log)
1510
+ log(logLine("learning", { line }));
1511
+ else
1512
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1513
+ return Object.assign(() => false, { unread: true });
1514
+ }));
1400
1515
  if (!all)
1401
1516
  return {};
1402
1517
  // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1403
1518
  // gives): known as it answered even when its compile turn's cost is not; the row's while the run is at work.
1404
- 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 } };
1519
+ 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 } : {}) } };
1405
1520
  };
1406
1521
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1407
1522
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
@@ -1430,6 +1545,9 @@ async function startHolding(options, data, checked, stops) {
1430
1545
  secretStores.add("server", () => tokens.map((entry) => entry.token));
1431
1546
  // The model gateway's key saved in the console (model-gateway.ts): cut from everything shown, as every saved key is.
1432
1547
  secretStores.add("model-gateway", () => (savedGateway?.key ? [savedGateway.key] : []));
1548
+ // Each harness key saved, and each replaced or removed one still kept sealed (harness-keys.ts RETIRED_KEPT): a timeline
1549
+ // written while one was live stays cut after it changes.
1550
+ secretStores.add("harness-keys", () => harnessKeys.values());
1433
1551
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1434
1552
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1435
1553
  const emailPasswords = new Set();
@@ -1724,12 +1842,10 @@ async function startHolding(options, data, checked, stops) {
1724
1842
  return [...serverSecrets(), ...pointers];
1725
1843
  };
1726
1844
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1727
- // Which runs a learning folder's log names are purged, by each one's row (its purge time): the history reads serve none
1728
- // of their merges.
1729
- const purgedOf = async (runIds) => {
1730
- const rows = await Promise.all(runIds.map((runId) => store.runs.get(runId)));
1731
- return new Set(runIds.filter((_, i) => rows[i] !== undefined && rows[i].purgedAt !== null));
1732
- };
1845
+ // What championOf skips of the agent's promotion records (purged-workflow.ts refusedIn): a champion the purge gate
1846
+ // refuses at its commit, so the views name the champion a run's claim serves. A folder whose end() throws after the ask
1847
+ // is logged, never the read's 500.
1848
+ const refusedFor = (agentId, records) => refusedIn(() => learningFolderOf(data, agentId), store, (line) => (log ? log(logLine("learning", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)))(records);
1733
1849
  // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1734
1850
  const auditsOfAgent = async (agentId) => {
1735
1851
  const { workspace, end } = learningFolderOf(data, agentId);
@@ -1747,6 +1863,11 @@ async function startHolding(options, data, checked, stops) {
1747
1863
  // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1748
1864
  const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
1749
1865
  const runReadDepsFor = (origin) => ({ ...viewDepsFor(origin), recordings });
1866
+ /** A run as GET /v2/runs/{run_id} answers it, its links at `origin`. */
1867
+ const runRead = async (runId, origin) => {
1868
+ const view = await viewOverStore(store, runId, runReadDepsFor(origin));
1869
+ return view && { ...view, ...(await runComputerRead(store, runId, view, { context: ctx })), ...(await allInViewOf(runId, view)) };
1870
+ };
1750
1871
  const ownOriginOf = () => options.publicUrl ?? url;
1751
1872
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1752
1873
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
@@ -1786,8 +1907,10 @@ async function startHolding(options, data, checked, stops) {
1786
1907
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1787
1908
  needAgent,
1788
1909
  momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1789
- // A trigger never messages a run on a plan-billed recipe: its turn would run on its owner's own sign-in.
1790
- planRecipe: (harness) => recipeHarness(base, harness) === "plan",
1910
+ // A trigger never messages a run on a plan-billed recipe whose keys are not all saved: its turn would run on its
1911
+ // owner's own sign-in. With them saved, the turn runs on them (harness-keys.ts), and a claim that opens not every one
1912
+ // is refused (cli-run-spec.ts).
1913
+ planRecipe: (harness) => recipeHarness(base, harness) === "plan" && !harnessKeysSavedHere(data, harness),
1791
1914
  // Read when a firing's message is sent (declared below, with the delete turn).
1792
1915
  runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
1793
1916
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
@@ -1912,14 +2035,15 @@ async function startHolding(options, data, checked, stops) {
1912
2035
  const was = options.faux && options.fauxGitHub ? github.view() : undefined;
1913
2036
  if (was && was.slug !== FAUX_GITHUB.slug)
1914
2037
  throw new Error(`--faux-github connects a fake GitHub App, and this data directory has the GitHub App ${was.slug} connected: use a scratch data directory.`);
1915
- const fauxGitHub = options.faux && options.fauxGitHub ? await startFauxGitHub() : undefined;
2038
+ // Its repository as a bare git repository beside the data, so a run's checkout of it (agent-scout's) stays on this machine.
2039
+ const fauxGitHub = options.faux && options.fauxGitHub ? await startFauxGitHub({ webDir: join(data, "faux-github-web") }) : undefined;
1916
2040
  if (fauxGitHub) {
1917
2041
  stops.push(() => fauxGitHub.close());
1918
2042
  if (was)
1919
2043
  await github.remove();
1920
2044
  await github.save(fauxGitHub.app);
1921
2045
  await github.setInstallations([{ id: FAUX_GITHUB.installation, account: FAUX_GITHUB.account }]);
1922
- await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories })}\n`, { mode: 0o600 });
2046
+ await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories, api_url: fauxGitHub.url })}\n`, { mode: 0o600 });
1923
2047
  }
1924
2048
  const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: fauxGitHub?.url ?? options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
1925
2049
  /** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
@@ -1937,6 +2061,42 @@ async function startHolding(options, data, checked, stops) {
1937
2061
  return "token" in minted ? { api, hosts, token: minted.token } : { api, hosts, anonymous: "unusable" in minted ? minted.unusable : minted.failed };
1938
2062
  },
1939
2063
  };
2064
+ // Suggested agents (suggestions.ts): scans run the bundled agent-scout, applied once and reused (one apply at a time
2065
+ // on this server); a create pushes through the App's token for the one repository, then applies the package it pushed
2066
+ // as an imported template, so the agent here is made from the very files the pull request adds.
2067
+ let scouting;
2068
+ const suggestions = new Suggestions({
2069
+ settings: store.settings,
2070
+ github: { view: () => github.view(), settingsUrl: () => github.settingsUrl(), get api() { return githubConnect.api; }, repoInstallation: (repo, signal) => githubConnect.repoInstallation(repo, signal), tokenWith: (installation, repo, permissions, signal) => githubConnect.tokenWith(installation, repo, permissions, signal), revokeToken: (token) => githubConnect.revokeToken(token) },
2071
+ scoutAgent: () => (scouting ??= (async () => {
2072
+ const mine = (await agents.list()).find((one) => one.template?.id === SCOUT_TEMPLATE && !one.agent.archivedAt);
2073
+ if (mine)
2074
+ return mine.agent.id;
2075
+ const pkg = registry.get(SCOUT_TEMPLATE);
2076
+ if (!pkg)
2077
+ throw new ApiError("unavailable", `This server does not ship the ${SCOUT_TEMPLATE} template, which scans a repository.`);
2078
+ return (await applyTemplate(pkg, { parameters: {} })).applied.agent_id;
2079
+ })().finally(() => { scouting = undefined; })),
2080
+ startScan: async (agentId, content) => (await startRunOf(await needRunnableAgent(agentId), { input: { content } })).id,
2081
+ readRun: async (runId) => {
2082
+ const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
2083
+ if (!view)
2084
+ return undefined;
2085
+ const result = isObject(view.result) ? view.result : undefined;
2086
+ const error = isObject(view.error) && typeof view.error.message === "string" ? view.error.message : typeof result?.output_error === "string" ? `Its answer did not meet the scout's schema: ${result.output_error}` : undefined;
2087
+ return { status: String(view.status), ...(result && result.output != null ? { output: result.output } : {}), ...(error ? { error } : {}), ...(typeof view.ended_at === "string" ? { endedAt: Date.parse(view.ended_at) } : {}) };
2088
+ },
2089
+ // Kept, then applied (template-import.ts applyImported): a thrown error means no agent was made. The package has no
2090
+ // trigger, so the apply makes the agent as its last write.
2091
+ cancelScan: async (runId) => { await cancel(store, await needRun(runId)); },
2092
+ agentFrom: async (id, sha) => (await agents.list()).find((one) => one.template?.id === id && one.template.sha === sha && !one.agent.archivedAt)?.agent.id,
2093
+ makeAgent: async (id, origin, files) => {
2094
+ const made = await applyImported({ registry, store, apply: (pkg) => applyTemplate(pkg, { parameters: {} }) }, id, origin, files);
2095
+ return { agentId: made.applied.agent_id, warnings: made.applied.warnings };
2096
+ },
2097
+ ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
2098
+ ...(options.onUsage ? { used: options.onUsage } : {}),
2099
+ });
1940
2100
  // A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
1941
2101
  // with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
1942
2102
  // is a server secret while it may be in use.
@@ -2595,7 +2755,7 @@ async function startHolding(options, data, checked, stops) {
2595
2755
  // purged or kept as the purge had got, and the next DELETE does it again.
2596
2756
  forgetCopies: async (agentId, runId) => {
2597
2757
  await forgetRunCopies(store.settings, agentId, runId);
2598
- await notYetWith(() => forgetRunLearning(data, agentId, runId), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
2758
+ await notYetWith(() => forgetRunLearning(data, agentId, runId, store), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
2599
2759
  },
2600
2760
  // /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
2601
2761
  // learning ended as /stats counts it (its state and reason alone).
@@ -2780,6 +2940,18 @@ async function startHolding(options, data, checked, stops) {
2780
2940
  });
2781
2941
  if (unpinned.length)
2782
2942
  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: {} } });
2943
+ // A granted tool of a Composio server that reads its key from the environment (api_key_env) while that variable is
2944
+ // unset, or whose address is off Composio's origin: refused by its name before the run starts, never launched
2945
+ // without the server's tools, and nothing sent (composioEnvKey).
2946
+ const unset = (revision.body.tools ?? []).flatMap((tool, index) => {
2947
+ const named = mcpToolOf(tool);
2948
+ const saved = named ? mcpMeta.get(named.server) : undefined;
2949
+ const keyEnv = saved?.keyEnv;
2950
+ const got = named && saved && keyEnv ? composioEnvKey(named.server, saved.url, keyEnv, mcpServers.composioOrigin) : undefined;
2951
+ return got && "refused" in got ? [{ field: `definition.tools[${index}]`, reason: got.reason, message: got.refused, tool, keyEnv: keyEnv, unset: got.reason === "missing" }] : [];
2952
+ });
2953
+ if (unset.length)
2954
+ 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]])) } });
2783
2955
  }
2784
2956
  const pinnedTools = (server) => {
2785
2957
  const saved = mcpMeta.get(server);
@@ -3088,11 +3260,15 @@ async function startHolding(options, data, checked, stops) {
3088
3260
  return false;
3089
3261
  throw error;
3090
3262
  };
3263
+ /** A fresh apply's twins: the live agents here made from the package `pkgId` with the parameters `digest` digests. The
3264
+ * apply still makes another and warns of each (applyWith); its plan names them first (planTemplate). None for an
3265
+ * apply onto an agent (`onto`). */
3266
+ 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);
3091
3267
  /** POST /templates/{id}/apply {dry_run: true}: the apply's plan, from the same reads and checks as the apply
3092
3268
  * (prepareApply), with nothing written: whether it makes an agent or revises the one agent_id names (and its current
3093
- * revision), the keys and MCP servers this server lacks (where the apply would refuse with 409, the plan lists them),
3094
- * what becomes of each trigger (made, changed in place, removed, or skipped for a connection this server lacks), and
3095
- * the computer it picks. Any other refusal is the apply's own. */
3269
+ * revision), the agents a fresh one would make a twin of, the keys and MCP servers this server lacks (where the apply
3270
+ * would refuse with 409, the plan lists them), what becomes of each trigger (made, changed in place, removed, or
3271
+ * skipped for a connection this server lacks), and the computer it picks. Any other refusal is the apply's own. */
3096
3272
  async function planTemplate(template, body) {
3097
3273
  const p = await prepareApply(template, body, { plan: true });
3098
3274
  // A monid grant is pinned to monid's listing when the agent is saved (saveable: monidPinOf), read with the monid key:
@@ -3103,6 +3279,8 @@ async function startHolding(options, data, checked, stops) {
3103
3279
  const was = p.onto?.revision?.kind === "agentic" ? p.onto.revision : undefined;
3104
3280
  const unread = !env[MONID_KEY_ENV]?.trim() && (await pinMonid(tools, { key: undefined, ...(was ? { previous: { grants: was.body.tools ?? [], pin: was.monidPin ?? null } } : {}) }));
3105
3281
  const missing = unread && "refused" in unread && !p.missing.includes(MONID_KEY_ENV) ? [...p.missing, MONID_KEY_ENV] : p.missing;
3282
+ // 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
3283
+ // connection, a feed's URLs, a launch hook), not_an_option for one it never makes.
3106
3284
  const planned = [];
3107
3285
  for (const [i, trigger] of p.made.triggers.entries()) {
3108
3286
  const name = String(trigger.name).trim();
@@ -3110,11 +3288,11 @@ async function startHolding(options, data, checked, stops) {
3110
3288
  // On an API-only server, skipped in the apply's own words (prepareApply).
3111
3289
  const hostSkip = p.hostless.get(i);
3112
3290
  if (hostSkip) {
3113
- planned.push({ name, kind, action: "skip", reason: hostSkip.message });
3291
+ planned.push({ name, kind, action: "skip", code: hostSkip.reason, reason: hostSkip.message });
3114
3292
  continue;
3115
3293
  }
3116
3294
  if (p.emptyFeeds.has(i)) {
3117
- 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) });
3295
+ 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) });
3118
3296
  continue;
3119
3297
  }
3120
3298
  const was = p.hadByName.get(name);
@@ -3127,7 +3305,7 @@ async function startHolding(options, data, checked, stops) {
3127
3305
  // (any trigger, on or off), read here; its account and subscription are Composio's to answer, which a plan never asks.
3128
3306
  const refusal = kind === "composio" && !options.publicUrl ? composioNoPublicUrl() : trigger.enabled !== false && !(was && !was.enabled) ? await triggerUnavailable(kind) : undefined;
3129
3307
  if (refusal && notSetUpYet(kind, refusal.code))
3130
- planned.push({ name, kind, action: "skip", reason: refusal.message });
3308
+ planned.push({ name, kind, action: "skip", code: NOT_SET_UP, reason: refusal.message });
3131
3309
  else if (refusal)
3132
3310
  throw refusal;
3133
3311
  else
@@ -3141,6 +3319,7 @@ async function startHolding(options, data, checked, stops) {
3141
3319
  action: p.onto ? "revise" : "create",
3142
3320
  agent_id: p.onto?.agent.id ?? null,
3143
3321
  current_revision_id: p.onto?.revision?.id ?? null,
3322
+ twins: await twinsOf(p.onto, p.pkg.id, p.digest),
3144
3323
  missing_secrets: missing,
3145
3324
  unmatched_mcp: p.unsaved.map((need) => ({ source: need.source, toolkit: need.toolkit, required: need.required })),
3146
3325
  triggers: planned,
@@ -3242,11 +3421,16 @@ async function startHolding(options, data, checked, stops) {
3242
3421
  // A trigger is made only when its firings have somewhere to go: on an API-only server, a schedule or a feed with the
3243
3422
  // launch hook set (api-only.ts); under the run-keys setting, for an agent whose runs owe keys, only with the launch
3244
3423
  // hook, the one way a firing's run carries them (run-keys.ts). Each other is said, and stays listed, so a trigger the
3245
- // agent has by its name is left as it is, never removed.
3424
+ // 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.
3246
3425
  const hooked = options.launchHook !== undefined;
3247
3426
  const hostless = new Map(made.triggers.flatMap((trigger, i) => {
3248
3427
  const skip = (options.apiOnly ? apiOnlyTriggerSkipped(pkg.name, trigger, hooked) : undefined) ?? runKeysTriggerSkipped(pkg.name, trigger, brought, hooked);
3249
- return skip ? [[i, skip]] : [];
3428
+ if (!skip)
3429
+ return [];
3430
+ const keptOn = had.find((row) => row.enabled && row.name === String(trigger.name).trim());
3431
+ // An API-only server serves no trigger route: its archive is what turns the agent's triggers off.
3432
+ const off = options.apiOnly ? "archiving the agent turns it off" : `PATCH /v2/triggers/${keptOn?.id} with {"enabled": false} turns it off`;
3433
+ 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]];
3250
3434
  }));
3251
3435
  const unmade = (i) => emptyFeeds.has(i) || hostless.has(i);
3252
3436
  const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !unmade(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
@@ -3321,9 +3505,8 @@ async function startHolding(options, data, checked, stops) {
3321
3505
  const { pkg, onto, saved, mapped, grants, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned } = await prepareApply(template, body, { plan: false });
3322
3506
  // A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
3323
3507
  // which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
3324
- const twins = onto ? [] : (await agents.list())
3325
- .filter((one) => one.template?.id === pkg.id && one.template.parameters_digest === digest)
3326
- .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}.` }));
3508
+ const twins = (await twinsOf(onto, pkg.id, digest))
3509
+ .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}.` }));
3327
3510
  // An update writes the package as a new revision of the agent, as an edit does (its id, name and description are the
3328
3511
  // agent's own: the package's never replace them), but what the package owns and leaves out is gone (fromPackage); only onto the
3329
3512
  // revision it read, else 412 with nothing changed. A fresh apply makes the agent as POST /agents does.
@@ -3612,7 +3795,7 @@ async function startHolding(options, data, checked, stops) {
3612
3795
  if (undeclared.length)
3613
3796
  throw invalid(undeclared);
3614
3797
  }
3615
- const owed = options.runKeys && revision ? packageKeysOf(revision).filter((name) => !env[name]) : [];
3798
+ const owed = options.runKeys && revision ? keysOwed(revision, env, []) : [];
3616
3799
  const needsKey = handed.model === undefined && serverKeyMissing(env, target);
3617
3800
  if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined && !needsKey && !owed.length)
3618
3801
  return undefined;
@@ -3624,9 +3807,9 @@ async function startHolding(options, data, checked, stops) {
3624
3807
  const keys = handed.keys ?? held.keys;
3625
3808
  if (!model && needsKey)
3626
3809
  throw modelKeyRequired(true);
3627
- const unpaid = revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3628
- if (owed.length && unpaid.length)
3629
- throw new ApiError("agent_not_runnable", unpaid.map((one) => one.message).join(" "), { fields: unpaid });
3810
+ const unpaid = owed.length && revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3811
+ if (unpaid.length)
3812
+ throw keysOwedRefusal(unpaid);
3630
3813
  return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) });
3631
3814
  };
3632
3815
  }
@@ -3634,21 +3817,24 @@ async function startHolding(options, data, checked, stops) {
3634
3817
  const entry = await needRunnableAgent(agentId);
3635
3818
  const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3636
3819
  // 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
3637
- // answers that run), with the trigger, input origin and title a start here would give it, and capped as a trigger's
3638
- // run is. The firing is its key, so it takes no Idempotency-Key, whose check across a restart is the run's origin.
3820
+ // answers that run), started by the trigger's target policy as a firing here starts one (its cap, which the host's may
3821
+ // lower, its effort when it sets one, its previous result, its trigger, origin and title), with the host's body and
3822
+ // 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.
3639
3823
  if (body.trigger_firing !== undefined) {
3640
3824
  if (req.headers["idempotency-key"] !== undefined)
3641
3825
  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." }]);
3826
+ // It starts on its trigger's target as a firing here would: on the agent's current revision, holding no computer.
3827
+ const fixed = HANDED_FIXED.filter((field) => body[field] !== undefined);
3828
+ if (fixed.length)
3829
+ 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}.` })));
3642
3830
  const { trigger_firing: given, ...rest } = body;
3643
- const firing = await triggers.handedStart(given, agentId);
3644
- if ("run_id" in firing)
3645
- return { status: 202, body: await viewOverStore(store, firing.run_id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${firing.run_id}`, "idempotent-replayed": "true" } };
3646
- const secrets = await handed();
3647
- const seal = startSeal(secrets);
3648
- 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) });
3649
- // A host that answered its hook first started this run after: the firing is started with it now.
3650
- await triggers.handedRan(firing.trigger.id, firing.key, run.id);
3651
- return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3831
+ // The firing's room is checked and held as drive's is while its run is written; the firing is started with the run.
3832
+ const run = await triggers.handedStart(given, agentId, async (firing) => {
3833
+ const secrets = await handed();
3834
+ const seal = startSeal(secrets);
3835
+ return targets.start(firing.target, rest.input, firing.trigger, firing.from, firing.title, firing.previous, { body: rest, ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3836
+ });
3837
+ 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" } : {}) } };
3652
3838
  }
3653
3839
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
3654
3840
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -4220,16 +4406,19 @@ async function startHolding(options, data, checked, stops) {
4220
4406
  return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
4221
4407
  }
4222
4408
  // This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
4223
- // cleared; every other browser's session left as it is. A viewer watching with it is cut off.
4409
+ // cleared; every other browser's session left as it is. A viewer watching with it is cut off. Its sessions at this
4410
+ // server's other ports go too (page.ts sessionsAtEveryPort: a browser sends a host's cookies to every port), each
4411
+ // name cleared; a cookie this server did not make (another server's on the same host) is left as it is.
4224
4412
  case "/auth/sign-out": {
4225
4413
  fromPage(req);
4226
4414
  if (!signedIn(req, me))
4227
4415
  throw new ApiError("unauthenticated", "this browser is not signed in");
4228
- for (const value of heldSessions(req))
4229
- if (me.valid(value))
4230
- me.revoke(value);
4416
+ const ended = sessionsAtEveryPort(req).filter(({ value }) => me.valid(value));
4417
+ for (const { value } of ended)
4418
+ me.revoke(value);
4231
4419
  viewers.recheck();
4232
- return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
4420
+ const names = new Set([ownerCookieName(req), ...ended.map(({ name }) => name)]);
4421
+ return send(res, 200, { signed_out: true }, { "set-cookie": [...names].map((name) => ownerCookie(req, "", 0, name)) });
4233
4422
  }
4234
4423
  // Every browser and phone: the sessions' epoch moves on, so every cookie made before is none, this one's too.
4235
4424
  case "/auth/sign-out-everywhere": {
@@ -4323,6 +4512,7 @@ async function startHolding(options, data, checked, stops) {
4323
4512
  // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
4324
4513
  const runnerShell = shellTools(await shellOf({ kind: "none" }));
4325
4514
  await planNow();
4515
+ await ollamaNow();
4326
4516
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
4327
4517
  // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
4328
4518
  // runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
@@ -4332,7 +4522,7 @@ async function startHolding(options, data, checked, stops) {
4332
4522
  // skew check; left out when the store cannot say (a read that failed).
4333
4523
  const state = await store.schemaState?.().catch(() => undefined);
4334
4524
  const storeSchema = state ? { store_schema: { version: state.version, runner_floor: state.runnerFloor, known: state.known } } : {};
4335
- 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) } } });
4525
+ 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 } });
4336
4526
  }
4337
4527
  if (found.name === "getOpenapi")
4338
4528
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -4457,8 +4647,13 @@ async function startHolding(options, data, checked, stops) {
4457
4647
  // non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
4458
4648
  // What a stored predicate read to let the request through (SecretRequest.seen): the operation's write is refused if
4459
4649
  // that changed before it lands, so a write allowed against one stored credential never lands over another.
4650
+ // `byToken`: the gate read this request as the API token's, so an MCP server it saves is recorded as the token's, and
4651
+ // it saves over or removes only one the token saved (mcp-secret-writes.ts tokenWriteOverRefused), compared again in
4652
+ // the statement that writes or removes the row (mcp-servers-store.ts save, remove).
4460
4653
  let secretSeen;
4654
+ let byToken = false;
4461
4655
  if (isSecretWriteOperation(found.name) && req.headers.authorization !== undefined && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4656
+ byToken = true;
4462
4657
  const body = req.method === "DELETE" || req.method === "GET" ? undefined : await bodyOf(req).catch(() => undefined);
4463
4658
  // A segment that is not valid percent-encoding is taken as it came: the request goes on to the token's own check.
4464
4659
  const params = (found.pattern.exec(path) ?? []).slice(1).map((part) => {
@@ -4469,7 +4664,7 @@ async function startHolding(options, data, checked, stops) {
4469
4664
  return part;
4470
4665
  }
4471
4666
  });
4472
- const checked = { params, store };
4667
+ const checked = { params, store, apiOnly: options.apiOnly === true };
4473
4668
  if (await writesSecretFor(found.name, body, checked)) {
4474
4669
  authFailed(`/v2${path}`, "secret_without_session");
4475
4670
  // Where the person finishes it: the operation's console page, filled with what the request held that is no
@@ -5011,10 +5206,10 @@ async function startHolding(options, data, checked, stops) {
5011
5206
  return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
5012
5207
  }
5013
5208
  case "getRun": {
5014
- const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
5015
- if (!view)
5209
+ const run = await runRead(id, linkOrigin(req));
5210
+ if (!run)
5016
5211
  throw new ApiError("not_found", `no run ${id}`);
5017
- return send(res, 200, { ...view, ...(await runComputerOf(id, view)), ...(await allInViewOf(id, view)) });
5212
+ return send(res, 200, run);
5018
5213
  }
5019
5214
  case "getTimeline":
5020
5215
  await needRun(id);
@@ -5073,13 +5268,8 @@ async function startHolding(options, data, checked, stops) {
5073
5268
  const row = ID.test(id) ? await store.runs.get(id) : undefined;
5074
5269
  if (!row)
5075
5270
  throw new ApiError("not_found", `no run ${id}`);
5076
- // API-only (api-only.ts): a run of an agent another system owns alone, for the backend whose inline runs made it,
5077
- // as it deletes that agent; a run of an agent made here is the profile's refusal, in its words, as before.
5078
- if (options.apiOnly) {
5079
- const agent = await store.agents.get(row.agentId);
5080
- if (!agent || !ownedElsewhere(agent))
5081
- throw new ApiError("not_found", apiOnlyRefusal(`/v2${path}`));
5082
- }
5271
+ // API-only (api-only.ts) purges a run wherever its token may delete the run's whole agent, which is any agent:
5272
+ // another system's, and one made here once archived. One run is less than all of them, so it is served alike.
5083
5273
  await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
5084
5274
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
5085
5275
  return void res.end();
@@ -5274,6 +5464,10 @@ async function startHolding(options, data, checked, stops) {
5274
5464
  case "deleteComputer":
5275
5465
  await attach.remove(id);
5276
5466
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5467
+ case "listRunningComputers": {
5468
+ const origin = linkOrigin(req);
5469
+ return send(res, 200, await runningComputers(store, (runId) => runRead(runId, origin)), { "cache-control": "no-store" });
5470
+ }
5277
5471
  case "listComputers":
5278
5472
  case "saveComputerKeys":
5279
5473
  case "testComputer":
@@ -5488,6 +5682,25 @@ async function startHolding(options, data, checked, stops) {
5488
5682
  await toolKeys.remove(id);
5489
5683
  await keysChanged();
5490
5684
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5685
+ case "listHarnessKeys":
5686
+ return send(res, 200, harnessKeys.list());
5687
+ // Never through `idempotent`: its record keeps the body, and this body is the value. The owner's session alone (the
5688
+ // dispatch's secret-write check, harness-keys.ts registerSecretWrite), for a recipe this server names and a key it
5689
+ // runs on; the next claim of a run on that harness opens it, with no restart. Then the listings are built again, cut
5690
+ // of it, and the harness offers probed again: whether the recipe is offered turns on its keys being saved.
5691
+ case "saveHarnessKey": {
5692
+ const recipe = harnessKeys.recipe(id);
5693
+ const body = await bodyOf(req);
5694
+ if (stopping.signal.aborted)
5695
+ throw new ApiError("unavailable", "The server is shutting down: the key was not saved.");
5696
+ await harnessKeys.save(recipe, decodeURIComponent(second), body);
5697
+ await harnessKeysChanged();
5698
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5699
+ }
5700
+ case "deleteHarnessKey":
5701
+ await harnessKeys.remove(harnessKeys.recipe(id), decodeURIComponent(second));
5702
+ await harnessKeysChanged();
5703
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
5491
5704
  // Never through `idempotent`: its record keeps the body, and the body holds the password.
5492
5705
  case "getEmailAccount":
5493
5706
  case "saveEmailAccount":
@@ -5569,7 +5782,7 @@ async function startHolding(options, data, checked, stops) {
5569
5782
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
5570
5783
  case "listMcpServers":
5571
5784
  return send(res, 200, await mcpServers.list());
5572
- // Names only: no URL, auth type, header, tool or Composio record, so a token that may not read the list may read this.
5785
+ // Names only: what the API-only profile serves in place of the list.
5573
5786
  case "listMcpServerNames":
5574
5787
  return send(res, 200, { names: (await listMcpServers(store)).map((row) => row.name).sort() });
5575
5788
  case "getMcpServer":
@@ -5580,7 +5793,7 @@ async function startHolding(options, data, checked, stops) {
5580
5793
  const body = await bodyOf(req);
5581
5794
  // A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
5582
5795
  if (!(await mcpServers.composioPreset(id))) {
5583
- const saved = await mcpServers.save(id, body, stopping.signal, secretSeen);
5796
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, undefined, undefined, byToken);
5584
5797
  await refreshMcpMeta();
5585
5798
  return send(res, 200, saved);
5586
5799
  }
@@ -5598,7 +5811,7 @@ async function startHolding(options, data, checked, stops) {
5598
5811
  }),
5599
5812
  inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS),
5600
5813
  };
5601
- const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard);
5814
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard, byToken);
5602
5815
  await refreshMcpMeta();
5603
5816
  return send(res, 200, over.note ? { ...saved, composio: over.note } : saved);
5604
5817
  }
@@ -5613,11 +5826,14 @@ async function startHolding(options, data, checked, stops) {
5613
5826
  // made and what that save made that this one no longer stands on (an account of another user, an auth config of
5614
5827
  // another toolkit), with the key it was made with, and says so as a delete does; what another saved server uses is
5615
5828
  // that one's now, and said too. A save as another user or auth config is refused while Composio triggers use the
5616
- // server, in the delete's words, checked in its project's turn before the row is written.
5829
+ // server, in the delete's words, checked in its project's turn before the row is written. An API-only server's token
5830
+ // saves one that names its key by api_key_env (the secret-write gate), and over a saved server only one it saved
5831
+ // (mcp-secret-writes.ts tokenWriteOverRefused), landing only while the row still has the credential the gate read
5832
+ // (secretSeen) and the token's mark. The body names no address or headers (composioSave refuses them).
5617
5833
  const answer = await inComposioTurn(async () => {
5618
5834
  const over = {};
5619
5835
  const guard = { turn: (work) => composioTriggers.inTurnOf(id, work), inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS) };
5620
- 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);
5836
+ 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);
5621
5837
  await refreshMcpMeta();
5622
5838
  return over.dropped ? { ...saved, composio: await composioLeft(id, over.dropped) } : saved;
5623
5839
  });
@@ -5659,6 +5875,33 @@ async function startHolding(options, data, checked, stops) {
5659
5875
  const view = githubConnection();
5660
5876
  return send(res, 200, view ? { connected: true, ...view } : { connected: false });
5661
5877
  }
5878
+ case "listGitHubRepositories": {
5879
+ // The installations repaired from GitHub's own first, as getGitHubConnection does (at most once a minute): an
5880
+ // installation whose event was missed is listed, not hidden until a restart.
5881
+ await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
5882
+ const listed = await githubConnect.repositories(stopping.signal);
5883
+ if ("unusable" in listed)
5884
+ throw new ApiError("github_not_connected", listed.unusable);
5885
+ return send(res, 200, listed, { "cache-control": "no-store" });
5886
+ }
5887
+ case "listSuggestions":
5888
+ // The same repair first: the page's Refresh and Check again read installations as GitHub has them.
5889
+ await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
5890
+ return send(res, 200, await suggestions.list({ ...(url.searchParams.has("repo") ? { repo: url.searchParams.get("repo") } : {}), ...(url.searchParams.has("status") ? { status: url.searchParams.get("status") } : {}) }), { "cache-control": "no-store" });
5891
+ case "scanForSuggestions": {
5892
+ const scanned = await suggestions.scan(await bodyOf(req));
5893
+ return send(res, scanned.status, scanned.body, { location: `/v2/runs/${String(scanned.body.run_id)}` });
5894
+ }
5895
+ case "getSuggestion":
5896
+ return send(res, 200, await suggestions.get(id, stopping.signal, url.searchParams.get("name") ?? undefined), { "cache-control": "no-store" });
5897
+ case "discardSuggestion":
5898
+ return send(res, 200, await suggestions.discard(id));
5899
+ case "restoreSuggestion":
5900
+ return send(res, 200, await suggestions.restore(id));
5901
+ case "createSuggestedAgent": {
5902
+ const created = await suggestions.create(id, await bodyOf(req), stopping.signal);
5903
+ return send(res, created.status, created.body);
5904
+ }
5662
5905
  case "disconnectGitHub": {
5663
5906
  const view = githubConnection();
5664
5907
  if (!view)
@@ -5684,7 +5927,7 @@ async function startHolding(options, data, checked, stops) {
5684
5927
  // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting). All of
5685
5928
  // it in the Composio turn, so a Composio save still at work finishes first and its record is counted.
5686
5929
  const forgotten = await inComposioTurn(async () => {
5687
- const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
5930
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen, byToken));
5688
5931
  await refreshMcpMeta();
5689
5932
  return !made ? undefined : "unusable" in made ? composioNote(id, made.cleanup) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal, made.cleanup);
5690
5933
  });
@@ -5724,16 +5967,17 @@ async function startHolding(options, data, checked, stops) {
5724
5967
  // over the same records and the money rule's decision, costStopOverStore), so the view never says a workflow serves
5725
5968
  // that does not run first.
5726
5969
  const records = await promotionsOf(store.settings, id);
5970
+ const refused = await refusedFor(id, records);
5727
5971
  const costStop = await costStopOverStore(store, id);
5728
5972
  const body = entry.revision?.body;
5729
5973
  const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
5730
- 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) });
5974
+ 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) });
5731
5975
  }
5732
5976
  case "getLearningCost": {
5733
5977
  await needAgent(id);
5734
5978
  // The agent's cost per run over the one store (agentCostOverStore): each ended run's figures and path, aggregates only.
5735
5979
  const { limit, csv } = learningCostQuery(url);
5736
- const read = await agentCostOverStore(store, id, limit);
5980
+ const read = await agentCostOverStore(store, id, limit, refusedFor);
5737
5981
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
5738
5982
  const shown = await learningShown(id);
5739
5983
  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) })) } };
@@ -5750,13 +5994,15 @@ async function startHolding(options, data, checked, stops) {
5750
5994
  // (promotionsShown: a reason as well as each workflow's name). Beside what serves, each one's state, its check's
5751
5995
  // numbers and its audit line (learn/audit.ts servingLinesOf), at the agent's numbers.
5752
5996
  const records = await promotionsOf(store.settings, id);
5997
+ // Every champion below skips a record the purge gate refuses at its commit, as a run's claim does (championOf).
5998
+ const refused = await refusedFor(id, records);
5753
5999
  const shown = await learningShown(id);
5754
- const shownRead = promotionsShown(records, shown);
6000
+ const shownRead = promotionsShown(records, shown, refused);
5755
6001
  // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
5756
6002
  const loop = auditLoopOf(entry.revision?.body?.learning);
5757
6003
  // Each one's state with the money rule's decision a run's launch reads (costStopOverStore): a champion it stopped
5758
6004
  // running first reads `stopped`.
5759
- const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop, await costStopOverStore(store, id));
6005
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop, await costStopOverStore(store, id), refused);
5760
6006
  // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
5761
6007
  // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
5762
6008
  const writer = auditWriterOf(entry.revision ?? undefined);
@@ -5765,7 +6011,7 @@ async function startHolding(options, data, checked, stops) {
5765
6011
  // first), then main: never by paging the workflow's history. Its nodes with their tiers and code checks, and the
5766
6012
  // check it was promoted on; nodes null when no commit read holds its text (or the folder can't be read now).
5767
6013
  const championRead = async (workflow, digest) => {
5768
- const champion = championOf(records, workflow);
6014
+ const champion = championOf(records, workflow, refused);
5769
6015
  const record = champion?.digest === digest ? champion : undefined;
5770
6016
  const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
5771
6017
  const read = await workflowAtDigest(data, id, workflow, digest, commits, store).catch(() => undefined);
@@ -5778,7 +6024,7 @@ async function startHolding(options, data, checked, stops) {
5778
6024
  }
5779
6025
  return shownDeep({ digest, commit: read?.commit ?? null, nodes: doc === undefined ? null : workflowNodesOf(doc), check: record?.check ?? null }, shown);
5780
6026
  };
5781
- const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
6027
+ const serving = await Promise.all(servingOf(records, refused).map(async (one, i) => ({
5782
6028
  ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
5783
6029
  not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
5784
6030
  champion: one.digest === null ? null : await championRead(one.workflow, one.digest),
@@ -5814,7 +6060,7 @@ async function startHolding(options, data, checked, stops) {
5814
6060
  }
5815
6061
  case "listLearningLog":
5816
6062
  await needAgent(id);
5817
- return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), purgedOf));
6063
+ return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), store));
5818
6064
  case "getLearningCorrections": {
5819
6065
  await needAgent(id);
5820
6066
  // corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
@@ -5841,7 +6087,7 @@ async function startHolding(options, data, checked, stops) {
5841
6087
  }
5842
6088
  case "listLearnedWorkflowRevisions":
5843
6089
  await needAgent(id);
5844
- return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), purgedOf));
6090
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), store));
5845
6091
  case "readLearningFile":
5846
6092
  await needAgent(id);
5847
6093
  return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id), store));
@@ -5852,7 +6098,7 @@ async function startHolding(options, data, checked, stops) {
5852
6098
  const refuse = await learningValues(id);
5853
6099
  const action = found.name === "approveLearningFile" ? "approve" : found.name === "restoreLearningFile" ? "restore" : "retire";
5854
6100
  // A change to a workflow is a write to the agent's learning: in its delete turn (agentWrite).
5855
- 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) }));
6101
+ 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 }));
5856
6102
  // 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.
5857
6103
  await lister.learningChanged(id);
5858
6104
  return sendText(res, written.status, { ...written, text: secretsShown(refuse).text(written.text) });
@@ -5975,9 +6221,8 @@ async function startHolding(options, data, checked, stops) {
5975
6221
  const done = new AbortController();
5976
6222
  res.once("close", () => done.abort());
5977
6223
  const imported = await importTemplate(importDeps, body, done.signal);
5978
- const pickView = await computerHere([imported.pkg]);
5979
6224
  const uploaded = imported.pkg.id.startsWith(UPLOAD_PREFIX);
5980
- return send(res, imported.status, { template: { ...packageView(imported.pkg), computer_here: pickView(imported.pkg) }, ...(({ instructions, skill_files }) => ({ instructions, skill_files }))(packageDetail(imported.pkg)), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : uploaded ? templatesLink(linkOrigin(req)) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
6225
+ return send(res, imported.status, { ...packageDetail(imported.pkg, await computerHere([imported.pkg])), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : uploaded ? templatesLink(linkOrigin(req)) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
5981
6226
  }
5982
6227
  case "getTemplate": {
5983
6228
  // One package whole, a bundled one's too: as the list shows it, with the files an import's answer shows, for a
@@ -5985,9 +6230,7 @@ async function startHolding(options, data, checked, stops) {
5985
6230
  const pkg = registry.get(id);
5986
6231
  if (!pkg)
5987
6232
  throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
5988
- const pickView = await computerHere([pkg]);
5989
- const { instructions, skill_files } = packageDetail(pkg);
5990
- return send(res, 200, { template: { ...packageView(pkg), computer_here: pickView(pkg) }, instructions, skill_files, console_url: templateLink(linkOrigin(req), pkg.id) });
6233
+ return send(res, 200, { ...packageDetail(pkg, await computerHere([pkg])), console_url: templateLink(linkOrigin(req), pkg.id) });
5991
6234
  }
5992
6235
  case "deleteTemplate":
5993
6236
  await deleteTemplate(importDeps, id);
@@ -6700,7 +6943,9 @@ async function startHolding(options, data, checked, stops) {
6700
6943
  attachHub,
6701
6944
  dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
6702
6945
  localInstall,
6946
+ ollamaHost,
6703
6947
  own: mcpServers.own,
6948
+ ...(fauxGitHub ? { fauxGitHub: { api: fauxGitHub.url, ...(fauxGitHub.web ? { web: fauxGitHub.web } : {}) } } : {}),
6704
6949
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
6705
6950
  // never writes this data root's record again (the next server's, by then).
6706
6951
  close: () => (stopped ??= stop()),