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

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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
package/dist/server.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { modelsInFlight } from "./in-flight.js";
2
+ import { CALLS_PAGE_ROWS } from "./timeline/index.js";
1
3
  import { prepareProjectSkillEdit } from "./source-sync/skill-edits.js";
2
4
  import { sourceSyncOf } from "./source-sync/types.js";
3
5
  import { sourceService, SOURCE_BODY_BYTES } from "./source-sync/service.js";
@@ -29,8 +31,9 @@ import { createHash, createHmac, randomBytes } from "node:crypto";
29
31
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
30
32
  import { createServer } from "node:http";
31
33
  import proxyaddr from "proxy-addr";
32
- import { API_ONLY_HOOKED_KINDS, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
33
- import { RUN_KEYS_ENV } from "./env-switch.js";
34
+ import { API_ONLY_HOOKED_KINDS, apiOnlyMcpSave, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
35
+ import { API_ONLY_MCP_ORIGINS_ENV, apiOnlyMcpOriginsFrom, RUN_KEYS_ENV } from "./env-switch.js";
36
+ import { holdApiOnlyMcpOrigins, offApiOnlyMcpServers } from "./mcp-api-only-origins.js";
34
37
  import { declaredKeys, keysOwed, keysOwedRefusal, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
35
38
  import { capacityOverStore, capacityWindowOf } from "./capacity.js";
36
39
  import { carriedFields } from "./answer-json.js";
@@ -47,17 +50,15 @@ import { uuidv7 } from "./ids.js";
47
50
  import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, definitionOf, etagOf, externalKey, getAgent, listAgents, makeRevision, ownedElsewhere, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
48
51
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
49
52
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
50
- import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
53
+ import { FAUX_EXA_ENV, FAUX_FIRECRAWL_ENV, FAUX_WEB_ENV } from "./web-run.js";
51
54
  import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid, PRICED_BY_USAGE } from "./monid.js";
52
- import { FAUX_EXA_ENV } from "./exa-keyless.js";
53
- import { FAUX_FIRECRAWL_ENV } from "./firecrawl-keyless.js";
54
55
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
55
56
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
56
57
  import { deref, explain } from "./explain.js";
57
58
  import { HOME_HOST_OWNED } from "./files.js";
58
59
  import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
59
60
  import { homePath, hostOwnedOf } from "./home-path.js";
60
- import { asksOllama, chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
61
+ import { asksOllama, chooseModel, EFFORTS, FAUX_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
61
62
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
62
63
  import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_RECIPES_ENV, HARNESS_RECIPES_SETTING, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, harnessRecipesEnv, planRecipesOf, recipeHarness, tableIds } from "./harness-table.js";
63
64
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
@@ -75,9 +76,10 @@ import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPl
75
76
  import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
76
77
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
77
78
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
79
+ import { API_KEYS_LIMIT, ApiKeys } from "./api-keys.js";
78
80
  import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
79
81
  import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownerCookieName, ownOrigin, sessionsAtEveryPort, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
80
- import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
82
+ import { hostFix, hostName, isLoopbackName, loopbackNames, movedFix } from "./host-check.js";
81
83
  import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
82
84
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
83
85
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
@@ -100,7 +102,7 @@ import { servedTimelineRows } from "./run-timeline-served.js";
100
102
  import { servedRunTrace } from "./run-trace.js";
101
103
  import { servedRunUsage } from "./run-usage.js";
102
104
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
103
- import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
105
+ import { agentPointers, cutHanded, handedSecretValues, launchValuesOf, RETIRED_MAX, retiredValues, WITHHELD_LEARNING, WITHHELD_MESSAGE } from "./handed-values.js";
104
106
  import { runCutValues } from "./run-cut.js";
105
107
  import { readLaunchBody } from "./run-launch.js";
106
108
  import { modelKeyMisfit, modelKeyOf, modelKeyRequired, noServerKeyFor, runModelOrigin, serverKeyMissing } from "./run-model-key.js";
@@ -126,7 +128,7 @@ import { championOf, forgetRunCopies, GRADE_SOURCES, gradeView, LABEL_MAX, promo
126
128
  import { workflowNodesOf } from "./learn/workflow-nodes.js";
127
129
  import { deleteLearning } from "./learn/delete.js";
128
130
  import { runModelRef } from "./model.js";
129
- import { ollamaHostOf, ollamaHostRefused, ollamaListing, ollamaModels } from "./ollama-provider.js";
131
+ import { ollamaHostOf, ollamaHostRefused, ollamaListing, ollamaModels, ollamaReading } from "./ollama-provider.js";
130
132
  import { REDACTED } from "./secret-cut.js";
131
133
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
132
134
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
@@ -136,18 +138,21 @@ import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerO
136
138
  import { dockerDaemonCheck } from "./docker-daemon.js";
137
139
  import { hostAddressesOnce, noHostAddresses, retryHostAddresses, unionOf } from "./docker-host-addresses.js";
138
140
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
139
- import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
141
+ import { blockersOf, CODE_NODES_ENV, deniedComputer, issueOf, NOT_SET_UP } from "./runnable.js";
142
+ import { computerDeniedWords } from "./refusal-words.js";
140
143
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
141
144
  import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
142
145
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
143
146
  import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
144
- import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, loopback, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
147
+ import { CLAUDE_LOGIN_ROUTES, LOGIN_REFUSES_API_KEYS, oneOwnerDeps, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, loopback, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, withClaudeLogin } from "./claude-login.js";
148
+ import { ClaudeSignIns } from "./claude-sign-in.js";
145
149
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
146
150
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
147
151
  import { recordDataRoot } from "./runner/disk-free.js";
148
152
  import { recordRunEnv, runFacingNames } from "./runner/runner-check.js";
149
153
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
150
154
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
155
+ import { keptReads, within, WRAPPED_WAIT_MS, wrappedView } from "./wrapped.js";
151
156
  import { joinedBasis } from "./runner/metrics.js";
152
157
  import { unifiedUsage } from "./unified-usage.js";
153
158
  import { agentLoopOverStore } from "./store-reads/loop.js";
@@ -161,7 +166,7 @@ import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
161
166
  import { signInsOverStore } from "./sign-ins-store.js";
162
167
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
163
168
  import { composioEnvKey, composioMadeKey, composioPerRun } from "./composio-made.js";
164
- import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
169
+ import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioToolkits, composioTools } from "./composio-preset.js";
165
170
  import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
166
171
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
167
172
  import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
@@ -188,10 +193,11 @@ import { webhook } from "./trigger-webhook.js";
188
193
  import { SCHEME_NAMES } from "./trigger-signatures.js";
189
194
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
190
195
  import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
191
- import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
196
+ import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, RELEASE_WORDS_MAX, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
192
197
  import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
193
198
  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";
194
199
  import { applyImported, deleteTemplate, dropRemovedUploads, importTemplate, loadImported, UPLOAD_PREFIX } from "./template-import.js";
200
+ import { hereOf, Marketplace, marketplaceUrlOf } from "./marketplace.js";
195
201
  import { templateInstallLink, templateLink, templatesLink } from "./console-links.js";
196
202
  import { GITHUB_HOSTS, IMPORT_LIMITS } from "./template-source.js";
197
203
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
@@ -229,8 +235,10 @@ import { resetLearning } from "./learning-reset.js";
229
235
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
230
236
  import { sdkRunKey } from "./sdk/runs.js";
231
237
  import { waitEndedKey } from "./browser-wait-ended.js";
238
+ import { browserHoldKey } from "./browser-hold.js";
232
239
  import { agentComputerOf, agentComputerView, agentDirName, agentFolder, agentHomeFolder, claimKinds, runFolder, scratchFolder, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
233
240
  import { keyReader } from "./key-meta.js";
241
+ import { redacted } from "./key-refusal.js";
234
242
  export const CONTRACT = "agentrun.v2/0";
235
243
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
236
244
  const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
@@ -274,7 +282,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
274
282
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
275
283
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
276
284
  * harness's, which scripts the harnesses with or without it. */
277
- const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV]];
285
+ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxExa", FAUX_EXA_ENV]];
278
286
  /** The switches a run's process gets, each module path resolved: the owner's harness modules (harnessModules), and the test
279
287
  * switches, which are empty outside tests. A test's in-process runner takes the same (test/support.mjs
280
288
  * startInProcessRunner). */
@@ -442,6 +450,8 @@ export const ROUTES = [
442
450
  { method: "GET", pattern: /^\/stats$/, name: "getStats" },
443
451
  // The runs waiting and held, the live runners and their free slots, and the recent hand-backs (capacity.ts).
444
452
  { method: "GET", pattern: /^\/capacity$/, name: "getCapacity" },
453
+ // A year of the work under this machine's home (wrapped.ts), on a server on the person's own machine alone.
454
+ { method: "GET", pattern: /^\/wrapped$/, name: "getWrapped" },
445
455
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
446
456
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
447
457
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
@@ -477,6 +487,7 @@ export const ROUTES = [
477
487
  { method: "GET", pattern: /^\/settings\/mcp-server-names$/, name: "listMcpServerNames" },
478
488
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
479
489
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
490
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/toolkits$/, name: "listComposioToolkits" },
480
491
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
481
492
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
482
493
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
@@ -497,6 +508,11 @@ export const ROUTES = [
497
508
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/oauth\/private-hosts$/, name: "putMcpPrivateHosts" },
498
509
  { method: "GET", pattern: /^\/settings\/tools$/, name: "getToolSettings" },
499
510
  { method: "PUT", pattern: /^\/settings\/tools$/, name: "putToolSettings" },
511
+ // The API keys a person makes for their apps (api-keys.ts): a read with any token; making and revoking one are secret
512
+ // writes, so the one secret-write check takes them from the owner's session alone.
513
+ { method: "GET", pattern: /^\/settings\/api-keys$/, name: "listApiKeys" },
514
+ { method: "POST", pattern: /^\/settings\/api-keys$/, name: "createApiKey" },
515
+ { method: "DELETE", pattern: /^\/settings\/api-keys\/([^/]+)$/, name: "revokeApiKey" },
500
516
  { method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
501
517
  { method: "PUT", pattern: /^\/settings\/webhook$/, name: "saveWebhook" },
502
518
  { method: "DELETE", pattern: /^\/settings\/webhook$/, name: "deleteWebhook" },
@@ -517,9 +533,11 @@ export const ROUTES = [
517
533
  { method: "DELETE", pattern: /^\/triggers\/([^/]+)$/, name: "deleteTrigger" },
518
534
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/fire$/, name: "fireTrigger" },
519
535
  { method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
536
+ { method: "POST", pattern: /^\/triggers\/([^/]+)\/firings\/([^/]+)\/release$/, name: "releaseTriggerFiring" },
520
537
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
521
538
  { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
522
539
  { method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
540
+ { method: "GET", pattern: /^\/marketplace\/templates$/, name: "listMarketplaceTemplates" },
523
541
  { method: "GET", pattern: /^\/templates\/([^/]+)$/, name: "getTemplate" },
524
542
  { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
525
543
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
@@ -648,11 +666,14 @@ async function planStep(step) {
648
666
  }
649
667
  }
650
668
  async function needsOf(env) {
651
- const chosen = await chooseModel(env, undefined);
652
- const learning_model = await learningModelOf(env);
653
- if ("why" in chosen)
654
- return { needs: chosen.needs, priced: null, learning_model };
655
- return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0, learning_model };
669
+ // A reading no run waits on, as the offers are (ollamaReading): a key's save never waits on a stuck Ollama's /api/show.
670
+ return ollamaReading(async () => {
671
+ const chosen = await chooseModel(env, undefined);
672
+ const learning_model = await learningModelOf(env);
673
+ if ("why" in chosen)
674
+ return { needs: chosen.needs, priced: null, learning_model };
675
+ return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0, learning_model };
676
+ });
656
677
  }
657
678
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
658
679
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
@@ -774,18 +795,25 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
774
795
  * (tool-keys-store.ts), never in the clear. */
775
796
  tool_keys: { routes: true, at_rest: "sealed" },
776
797
  /** 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) },
798
+ * (harness-keys.ts); `harnesses` its ids here, and `kept` each id with keys saved whose recipe it no longer names
799
+ * (a running server's, from its store: HarnessKeysOverStore.unnamed), so the console offers the page only where
800
+ * there is one or a key to remove. */
801
+ harness_keys: { routes: true, at_rest: "sealed", harnesses: planRecipesOf(env).map((recipe) => recipe.id), kept: [] },
779
802
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
780
803
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. Every harness of the table runs a
781
- * grant (runnable.ts takes one on any), a module's among them. */
782
- mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...harnessIds(env)] },
804
+ * grant (runnable.ts takes one on any), a module's among them. `composio_per_run`: a per-run Composio server takes
805
+ * each run's own Composio account (mcp_auth's ComposioRunBinding, composioperrun/1), said here so a backend in
806
+ * front learns it from this answer, which an API-only server serves, not from the API document, which it refuses. */
807
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...harnessIds(env)], composio_per_run: true },
783
808
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
784
809
  learning,
785
810
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
786
811
  * ends (webhooks.ts); its secret kept sealed under the same seal key. */
787
812
  // Always sealed: the server starts with its seal key (seal-key.ts bootSealKey), so nothing is kept in the clear.
788
813
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
814
+ /** /settings/api-keys: the keys a person makes in the console for their apps (api-keys.ts), each shown once and
815
+ * kept as a keyed hash alone; `limit`, the most a server keeps. */
816
+ api_keys: { routes: true, limit: API_KEYS_LIMIT, at_rest: "hashed" },
789
817
  /** /settings/slack: one Slack incoming-webhook URL each of `events` is posted to as a readable message (slack.ts); the
790
818
  * URL kept sealed, never shown. */
791
819
  slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
@@ -844,6 +872,8 @@ function integerParam(value, name, max) {
844
872
  throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
845
873
  return Number(value);
846
874
  }
875
+ /** Why a server started on its owner's own sign-in makes no API key for an app, in one line. */
876
+ export const HARNESS_SIGN_IN_REFUSES_API_KEYS = "This server runs on its owner's own sign-in (--harness-sign-in), which is one person's: it creates no API key for an app, and a key created before opens nothing here. Revoke the ones listed that you no longer want.";
847
877
  /** A start with --harness-sign-in on a server that is not one owner's own, on their own machine. */
848
878
  export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
849
879
  /** Why `options` on `data` is not one owner's own server on their own machine, each reason in words; none when it is. One
@@ -854,6 +884,16 @@ export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
854
884
  * starts under (harnessSignInRefusal), and where the Ollama at this machine's default address is a model of the person
855
885
  * who starts runs (ollama-provider.ts ollamaHostOf). */
856
886
  export function whyNotOwnMachine(options, data, ownUser) {
887
+ return [
888
+ ...whyNotOwnersServer(options, data),
889
+ ...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
890
+ ...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
891
+ ];
892
+ }
893
+ /** Why `options` on `data` is not one owner's server on their own machine as far as who reaches it goes, each reason in
894
+ * words: whyNotOwnMachine's facts but its runner's. What may read this machine's own files for whoever asks (GET
895
+ * /v2/wrapped). */
896
+ export function whyNotOwnersServer(options, data) {
857
897
  const host = options.host ?? DEFAULT_HOST;
858
898
  // Every token the server takes (acceptedTokens): AGENTRUN_TOKEN's as `default` beside the list's, or else DIR/.token's alone.
859
899
  const tokens = (options.token === undefined ? 0 : 1) + (options.tokens?.length ?? 0);
@@ -863,8 +903,6 @@ export function whyNotOwnMachine(options, data, ownUser) {
863
903
  ...(options.apiOnly ? ["has no owner (the API-only profile), so anyone with its token starts runs"] : []),
864
904
  ...(tokens > 1 ? [`takes ${tokens} API tokens (AGENTRUN_TOKEN and AGENTRUN_TOKENS together), so more than one person starts runs`] : []),
865
905
  ...(storeTarget(data).kind === "sqlite" ? [] : ["keeps its store in Postgres (AGENTRUN_STORE_URL), which servers elsewhere share"]),
866
- ...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
867
- ...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
868
906
  ];
869
907
  }
870
908
  /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
@@ -1035,6 +1073,8 @@ async function startHolding(options, data, checked, stops) {
1035
1073
  // The packages served: the bundled ones, read and checked before the start, and those imported here, which the store
1036
1074
  // keeps and are checked again as they load (template-import.ts). One that no longer checks is left out, said in the log.
1037
1075
  const registry = new TemplateRegistry(templates);
1076
+ // The marketplace's list (marketplace.ts), read when the console or a caller asks for it, never at the start.
1077
+ const marketplace = new Marketplace(options.marketplace !== undefined ? options.marketplace : marketplaceUrlOf(process.env, Boolean(options.faux)));
1038
1078
  await loadImported({ registry, store }, (id, why) => log?.(logLine("template_import_skipped", { template: id, why })));
1039
1079
  stopObservationRetention = await maintainObservations(new Observations(store), {
1040
1080
  onError: () => { process.stderr.write("agentrun-serve: observation retention failed; retrying on the next sweep\n"); },
@@ -1125,6 +1165,18 @@ async function startHolding(options, data, checked, stops) {
1125
1165
  const storedKeys = (name) => toolKeys.value(name);
1126
1166
  // A stored key that does not open is said once at the start, never a refusal to start.
1127
1167
  toolKeys.view();
1168
+ // The API-only profile's MCP origins, normalized as the environment's are (a list passed in code included), and held in
1169
+ // the store for every reader of a saved server there (mcp-api-only-origins.ts); removed when the profile is off.
1170
+ const apiOnlyMcpOrigins = options.apiOnly ? apiOnlyMcpOriginsFrom((options.apiOnlyMcpOrigins ?? []).join(",")) : [];
1171
+ await holdApiOnlyMcpOrigins(store, options.apiOnly === true, apiOnlyMcpOrigins);
1172
+ // Said once at an API-only start: the per_run servers the token saved whose origin is off that list (with the setting
1173
+ // unset, every one, as on an upgrade whose operator has not listed them), whose runs are refused until it lists them.
1174
+ // Their names alone, never an address. Nothing is said when there are none.
1175
+ const offList = options.apiOnly ? await offApiOnlyMcpServers(store) : [];
1176
+ if (offList.length) {
1177
+ const fields = { count: offList.length, servers: offList.join(","), line: `runs that grant these per_run MCP servers the API token saved are refused, nothing sent, until ${API_ONLY_MCP_ORIGINS_ENV} lists their origin` };
1178
+ log ? log(logLine("api_only_mcp_off_list", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("api_only_mcp_off_list", fields)}\n`);
1179
+ }
1128
1180
  const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
1129
1181
  if (options.githubMcpOrigin)
1130
1182
  mcpServers.appOrigin = options.githubMcpOrigin;
@@ -1171,13 +1223,44 @@ async function startHolding(options, data, checked, stops) {
1171
1223
  // where it is signed in. A sign-in, a sign-out or an expiry it sees makes the reading again, as a key's save does.
1172
1224
  const plan = new ChatGPTPlan({ store, sealKey: seal.key, log: (fields) => (log ? log(logLine("chatgpt", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("chatgpt", fields)}\n`)), changed: () => keysChanged() });
1173
1225
  await plan.load();
1174
- stops.push(async () => plan.close());
1226
+ stops.push(async () => void plan.close());
1175
1227
  // Claude Code's login on this machine (claude-login.ts): env carries where it is while the owner has it on, so
1176
1228
  // claude-agent's model checks see a model without a key. Unset, its switch follows the listen address: there on
1177
1229
  // loopback, off past it. A setting kept where the mode is now off or refused goes first.
1178
1230
  const loginOff = claudeLoginSwitchedOff(base, options.host ?? DEFAULT_HOST);
1179
- const loginRefused = whyNotOneOwner({ apiOnly: options.apiOnly === true, tokens: tokens.length });
1180
- await dropRefusedLogin(store.settings, loginOff ?? loginRefused, (line) => (log ? log(logLine("claude_login", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)));
1231
+ // The API keys made in the console (api-keys.ts), read once here: this process is the store's one server, so the keys
1232
+ // it holds are the store's. No value is kept, so none joins the server's secrets: a key in a text is cut by its shape
1233
+ // (redact/match.ts).
1234
+ // On two servers the keys are dormant, so a key made on this store before opens nothing there and their tokens are the
1235
+ // ones they were started with: an API-only server (api-only.ts), which has no owner and serves none of the keys'
1236
+ // routes, and one started on its owner's own sign-in (--harness-sign-in), which is one person's. Dormant keys are
1237
+ // still read: the owner of the second sees and revokes them, and they count for the one-owner rule below, so none
1238
+ // waits unseen for a start that takes keys again.
1239
+ const apiKeys = new ApiKeys(store, seal.key, {
1240
+ say: (fields) => (log ? log(logLine("api_key", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("api_key", fields)}\n`)),
1241
+ dormant: options.apiOnly === true || options.harnessSignIn === true,
1242
+ });
1243
+ stops.push(() => apiKeys.close());
1244
+ await apiKeys.load();
1245
+ // A key is one more caller that starts runs, as a second token is: counted each time the login's refusal is asked,
1246
+ // since keys are made and revoked while the server runs, and the login's turn-on takes the keys' turn (oneOwnerDeps).
1247
+ const oneOwner = oneOwnerDeps({ apiOnly: options.apiOnly === true, tokens: tokens.length, keysDormant: options.harnessSignIn === true }, apiKeys);
1248
+ /** Why this server makes no API key now, in words; undefined when it does. The one-owner rule from its other side: a
1249
+ * recipe on the owner's own sign-in, and Claude Code's login on this machine while it is on, are one person's. */
1250
+ const apiKeysRefused = async () => options.harnessSignIn ? HARNESS_SIGN_IN_REFUSES_API_KEYS : (await claudeLoginSetting(store.settings)) ? LOGIN_REFUSES_API_KEYS : undefined;
1251
+ // Making a key, revoking one and turning the login on each take a turn (ApiKeys.inTurn; the login's is taken in
1252
+ // turnOnClaudeLogin, through oneOwnerDeps' `turn`), one at a time: each decides by what the others left once their writes
1253
+ // landed or were undone, never by a key taken out for a removal that then fails.
1254
+ // The sign-in this server starts, kept for this process (claude-sign-in.ts). Its queue is the one way the login's
1255
+ // setting changes, the drop here included.
1256
+ const claudeSignIns = new ClaudeSignIns({ limitMs: options.claudeSignInLimitMs });
1257
+ await dropRefusedLogin(claudeSignIns, store.settings, loginOff ?? oneOwner.refused(), (line) => (log ? log(logLine("claude_login", { line })) : void process.stderr.write(`agentrun-serve: ${line}\n`)));
1258
+ // The status checks' folders a server killed mid-check left in the temporary folder, each with a copy of the account
1259
+ // file (the harness's sweepClaudeStatusFolders): this user's alone, and only once the check has ended by the end it
1260
+ // wrote in its folder, so a check another server on this host runs now stays. Where the mode is there, as status
1261
+ // checks are; a sweep that fails never stops the start.
1262
+ if (loginOff === undefined)
1263
+ await import("@parcha/agentrun-harness-claude").then((claude) => claude.sweepClaudeStatusFolders()).catch(() => []);
1181
1264
  let claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
1182
1265
  // The model gateway saved in the console (model-gateway.ts), its key opened: laid over every reading of env, where the
1183
1266
  // environment names no gateway of its own. Read again at each save or removal (gatewayChanged).
@@ -1203,25 +1286,38 @@ async function startHolding(options, data, checked, stops) {
1203
1286
  // The start-time switches as this server was started: its options, else the CLI's variables. mcpLoopback is the
1204
1287
  // option alone, as everywhere it is read here (localInstall): the CLI sets it from AGENTRUN_MCP_ALLOW_LOOPBACK.
1205
1288
  const switched = { mcpLoopback: options.mcpLoopback === true, webhookPrivateTargets: switchedOnBy(process.env, options).webhookPrivateTargets };
1206
- const compose = (runnerShell) => askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation, switched));
1289
+ // harness_keys.kept from the store's snapshot, made again at each key's save or removal (harnessKeysChanged's probe).
1290
+ const compose = (runnerShell) => {
1291
+ const made = askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, toolKeys.refused(), runnerShell, isolation, switched));
1292
+ return { ...made, features: { ...made.features, harness_keys: { ...made.features.harness_keys, kept: harnessKeys.unnamed() } } };
1293
+ };
1207
1294
  const recompose = () => void (caps = compose());
1208
1295
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
1209
1296
  let offersFrom;
1210
1297
  let probes = 0;
1298
+ // What the latest probe is made from, once it has read it, until it lands: none while no probe is out. A probe that
1299
+ // failed never lands and leaves this at the inputs it read: a later change with those inputs reuses the offers held
1300
+ // when they are made from them, and a change with any other inputs probes again.
1301
+ let probing;
1211
1302
  const probe = async (why) => {
1212
1303
  const mine = ++probes;
1304
+ probing = undefined;
1213
1305
  // The Ollama listing the offers are made from is read before they are, so the first capabilities do not remake them.
1214
1306
  if (asksOllama(env))
1215
1307
  await ollamaModels(env);
1216
1308
  const from = offersInputs(env);
1309
+ if (mine === probes)
1310
+ probing = from;
1217
1311
  const started = performance.now();
1218
1312
  const next = await harnessOffers(offersEnvOf(env));
1219
1313
  log?.(logLine("harness_offers", { why, ms: Math.round(performance.now() - started) }));
1220
1314
  if (mine !== probes)
1221
1315
  return;
1222
- [offers, offersFrom] = [next, from];
1316
+ [offers, offersFrom, probing] = [next, from, undefined];
1223
1317
  recompose();
1224
1318
  };
1319
+ /** Whether `a` and `b` are the same offers' inputs (offersInputs). */
1320
+ const sameInputs = (a, b) => a.length === b.length && a.every((value, i) => value === b[i]);
1225
1321
  /** After a save or delete of a key, the one writer of its file: env again, then what reads it. Writes can overlap
1226
1322
  * (needsOf may wait, and another write lands meanwhile): the latest write's `needs` stands, an earlier one's that
1227
1323
  * finishes after it is dropped. */
@@ -1235,7 +1331,7 @@ async function startHolding(options, data, checked, stops) {
1235
1331
  ...(options.listerIdleMs !== undefined ? { idleMs: options.listerIdleMs } : {}),
1236
1332
  });
1237
1333
  /** 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]);
1334
+ const offersMadeFrom = (inputs) => offersFrom !== undefined && sameInputs(inputs, offersFrom);
1239
1335
  const keysChanged = async () => {
1240
1336
  // 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
1241
1337
  // serverSecrets live, store-view), and a list builds a listing cut of other keys again (builtOfNow). A failed run's error words
@@ -1246,7 +1342,12 @@ async function startHolding(options, data, checked, stops) {
1246
1342
  const next = await needsOf(env);
1247
1343
  if (mine === needsAsked)
1248
1344
  needs = next;
1249
- if (offersMadeFrom(offersInputs(env)))
1345
+ const inputs = offersInputs(env);
1346
+ // A probe still out from other inputs (a turn-on's, after its turn-off) would put back offers made from them as it
1347
+ // lands: a probe of these overtakes it. Only a change starts one, one per change, so nothing loops. A change that
1348
+ // leaves the inputs as they are (a tool key's) starts no probe only when the offers held are current: while they are
1349
+ // behind the inputs, it probes too and drops the probe out, and the offers still end made from the inputs read now.
1350
+ if (offersMadeFrom(inputs) && (probing === undefined || sameInputs(probing, inputs)))
1250
1351
  recompose();
1251
1352
  else
1252
1353
  await probe("key");
@@ -1272,26 +1373,27 @@ async function startHolding(options, data, checked, stops) {
1272
1373
  savedGateway = await readSavedGateway(store, seal.key);
1273
1374
  await keysChanged();
1274
1375
  };
1275
- /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
1276
- const planNow = async () => {
1277
- const was = plan.state;
1278
- if ((await plan.load()).state !== was)
1279
- await keysChanged();
1280
- };
1281
- /** What Claude Code's login routes use: a turn on or off reads the setting again, then env, as a key's save does. A
1282
- * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here. */
1376
+ /** The sign-in as the store holds it now (ChatGPTPlan.refresh): a change reads env again, and so does one this server
1377
+ * failed to take (changed_failed), until it takes. */
1378
+ const planNow = () => plan.refresh();
1379
+ /** What Claude Code's login routes use: a turn on or off hands over the login it saved, then env is read again, as a
1380
+ * key's save does. A sign-in this server starts opens a browser on its machine, so only where the console is on
1381
+ * loopback here; it is kept for this process (claudeSignIns, above), and one still waiting is ended at the stop. */
1382
+ stops.push(async () => claudeSignIns.close());
1283
1383
  const loginDeps = () => ({
1384
+ signIns: claudeSignIns,
1284
1385
  settings: store.settings,
1285
1386
  data,
1286
1387
  env: base,
1287
1388
  pinned: async () => claudeCliIn(installDirOf(data, LOGIN_HARNESS), (await import("@parcha/agentrun-harness-claude")).claudeAgentPlatform()),
1288
- refused: loginRefused,
1389
+ // `refused` and `turn`: the keys are counted when the refusal is asked (inside the turn-on's turn, the keys' own).
1390
+ ...oneOwner,
1289
1391
  sameMachine: isLoopback(host) && !options.publicUrl,
1290
1392
  claude: () => import("@parcha/agentrun-harness-claude"),
1291
- changed: async () => {
1292
- claudeLogin = loginOf(await claudeLoginSetting(store.settings), data, base);
1293
- await keysChanged();
1393
+ saved: (login) => {
1394
+ claudeLogin = login;
1294
1395
  },
1396
+ changed: keysChanged,
1295
1397
  });
1296
1398
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
1297
1399
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
@@ -1323,7 +1425,9 @@ async function startHolding(options, data, checked, stops) {
1323
1425
  // A read that failed with none known is read again in the background (retryHostAddresses) until one answers and the
1324
1426
  // helper containers the failed reads left are gone, or this server stops: the boxes are made again from the answer and
1325
1427
  // said again, so Docker is offered with no restart. Every reader of boxOffers reads it when it is called; capabilities
1326
- // are composed again.
1428
+ // are composed again. One that failed with the operator's addresses known changes no box: the retry only removes the
1429
+ // containers it left. The close cuts a read in flight (its client killed) and stop() awaits the retry last, so the
1430
+ // read's container is removed within the stop's deadline (docker-host-addresses.ts REMOVE_MS).
1327
1431
  const boxesOf = (hostAddresses) => {
1328
1432
  if (hostAddresses)
1329
1433
  log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
@@ -1335,20 +1439,24 @@ async function startHolding(options, data, checked, stops) {
1335
1439
  };
1336
1440
  const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
1337
1441
  let boxOffers = boxesOf(hostAddresses);
1338
- if (hostAddresses?.why !== undefined && hostAddresses.addresses.length === 0) {
1339
- void retryHostAddresses({
1442
+ const hostRetried = hostAddresses === undefined || hostAddresses.why === undefined
1443
+ ? Promise.resolve()
1444
+ : retryHostAddresses({
1340
1445
  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
- },
1446
+ ...(hostAddresses.addresses.length === 0
1447
+ ? {
1448
+ read: () => hostAddressesOnce(env, stopping.signal),
1449
+ found: (read) => {
1450
+ boxOffers = boxesOf(unionOf(read, dockerHostAddressesOf(env)));
1451
+ // Capabilities are first composed at the start's probe, below; before it, there is nothing to compose again.
1452
+ if (caps)
1453
+ recompose();
1454
+ },
1455
+ }
1456
+ : {}),
1348
1457
  signal: stopping.signal,
1349
1458
  ...(options.hostReadWait ? { wait: options.hostReadWait } : {}),
1350
- });
1351
- }
1459
+ }).catch(() => undefined);
1352
1460
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
1353
1461
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
1354
1462
  const sealKey = seal.key;
@@ -1858,7 +1966,7 @@ async function startHolding(options, data, checked, stops) {
1858
1966
  };
1859
1967
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1860
1968
  const statuses = (agentId) => statusesOf(data, agentId);
1861
- const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses });
1969
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, sealKey, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses });
1862
1970
  // A run read as a whole (its own read, its archive) lists its recordings too, from its recordings folder on this machine
1863
1971
  // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1864
1972
  const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
@@ -1883,14 +1991,15 @@ async function startHolding(options, data, checked, stops) {
1883
1991
  env,
1884
1992
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1885
1993
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1886
- cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1994
+ cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns, sealKey }, store, runId),
1887
1995
  context: ctx,
1996
+ sealKey,
1888
1997
  liveViewer: (runId) => liveViewerLink(store, sealKey, runId, answers(runId)),
1889
1998
  };
1890
1999
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1891
2000
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
1892
2001
  // The route frames the SSE around its `page`, which long-polls the journal, byte-identical to the old live run's page.
1893
- const servedTimelineDeps = { serverSecrets, signIns, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses };
2002
+ const servedTimelineDeps = { serverSecrets, signIns, sealKey, keyEnv: () => withSavedGateway(own(withSecrets(process.env, "all", storedKeys)), savedGateway), statuses };
1894
2003
  const timelines = runTimelines({
1895
2004
  context: ctx,
1896
2005
  // The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
@@ -1900,7 +2009,24 @@ async function startHolding(options, data, checked, stops) {
1900
2009
  // from its journal, which keeps what the run said whole.
1901
2010
  timelineRows: (forStore, runId, context, calls) => servedTimelineRows(servedTimelineDeps, forStore, runId, context, calls),
1902
2011
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
2012
+ // A live run's model requests sent and not answered (in-flight.ts), from its booking's records in its journal.
2013
+ inFlight: async (forStore, runId, context) => modelsInFlight(await runEntries(forStore, runId, context)),
1903
2014
  });
2015
+ /** `text` as a message to run `runId` is written: cut of `handed` (what the message itself hands) and of what the run
2016
+ * holds now (its turn's end erases those, and a read after it could no longer cut them). A run whose seal doesn't
2017
+ * open here (its seal key changed or is missing, or what was sealed is damaged or lost) takes no message: 409
2018
+ * not_continuable, reason withheld (WITHHELD_MESSAGE), and nothing is written, since what it can't read it can't
2019
+ * cut, and a message written uncut would show those values once the run's end lets its reads go uncut-withheld.
2020
+ * Read inside the turn that writes the message (runWrite), never before it: a message written first in that turn
2021
+ * (one that hands a new key) is in the seal read here, so a message that says that key without handing it is cut of
2022
+ * it too. Both writers of a message read it: a person's (sendMessage) and a trigger's (trigger-targets.ts
2023
+ * message_run, which skips with those words). */
2024
+ async function cutHeld(runId, text, handed = []) {
2025
+ const held = launchValuesOf(sealKey, runId, (await store.runs.launch(runId)).sealed);
2026
+ if (held === "unreadable")
2027
+ throw new ApiError("not_continuable", WITHHELD_MESSAGE, { details: { reason: "withheld" } });
2028
+ return cutHanded(text, [...handed, ...held]);
2029
+ }
1904
2030
  const triggerDeps = {
1905
2031
  ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}),
1906
2032
  start: startDeps,
@@ -1913,6 +2039,7 @@ async function startHolding(options, data, checked, stops) {
1913
2039
  planRecipe: (harness) => recipeHarness(base, harness) === "plan" && !harnessKeysSavedHere(data, harness),
1914
2040
  // Read when a firing's message is sent (declared below, with the delete turn).
1915
2041
  runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
2042
+ cutHeld: (runId, text) => cutHeld(runId, text),
1916
2043
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
1917
2044
  completedOutput: async (runId) => {
1918
2045
  const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
@@ -1932,12 +2059,24 @@ async function startHolding(options, data, checked, stops) {
1932
2059
  // of the one that opened a request is kept with it for its log line (tokenUsed), never the secret.
1933
2060
  const bearerOf = bearerCheck(tokens);
1934
2061
  const tokenUsed = new WeakMap();
1935
- const bearer = (header, req) => {
2062
+ /** Whether `header` carries a token this server was started with: the one credential that stands in for the setup
2063
+ * code (ownerRoute). A key made in the console never does. */
2064
+ const startToken = (header, req) => {
1936
2065
  const id = bearerOf(header);
1937
2066
  if (id !== undefined && req)
1938
2067
  tokenUsed.set(req, id);
1939
2068
  return id !== undefined;
1940
2069
  };
2070
+ // A key made in the console (api-keys.ts) opens what a token opens, but for setup. Its id is kept for the log line too.
2071
+ const keyUsed = new WeakMap();
2072
+ const bearer = (header, req) => {
2073
+ // Both are checked whatever the first says, so the time taken does not say which kind was presented.
2074
+ const started = startToken(header, req);
2075
+ const key = apiKeys.used(header);
2076
+ if (key !== undefined && req)
2077
+ keyUsed.set(req, key);
2078
+ return started || key !== undefined;
2079
+ };
1941
2080
  // Answered keys are kept in the data directory for the retention capabilities state, and written before the answer
1942
2081
  // is sent, so a client that retries after a restart gets the first answer back.
1943
2082
  // A key's fingerprint is an HMAC of its request's body (stable JSON) under a key derived from the server's seal key:
@@ -2303,13 +2442,14 @@ async function startHolding(options, data, checked, stops) {
2303
2442
  let closing = false;
2304
2443
  const workers = new Map();
2305
2444
  // Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
2306
- const onWorker = (task, projects) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
2445
+ const onWorker = (task, projects, year) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
2307
2446
  const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
2308
2447
  // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
2309
2448
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
2310
2449
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
2311
2450
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
2312
- workerData: { task, data, ...(projects ? { projects } : {}), home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = name === SEAL_KEY_ENV ? seal.text : secret(name); return value === undefined ? [] : [[name, value]]; })) },
2451
+ // A Wrapped read (`year`) writes nothing, so it is handed no secret.
2452
+ workerData: { task, data, ...(projects ? { projects } : {}), ...(year !== undefined ? { year } : {}), home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), ...(task === "wrapped" ? {} : { secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = name === SEAL_KEY_ENV ? seal.text : secret(name); return value === undefined ? [] : [[name, value]]; })) }) },
2313
2453
  // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
2314
2454
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
2315
2455
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
@@ -2335,12 +2475,15 @@ async function startHolding(options, data, checked, stops) {
2335
2475
  if (answer)
2336
2476
  answered(answer);
2337
2477
  // A count the close ended: stopped, not failed (the next start counts again).
2338
- else if (closing && task === "plan")
2478
+ else if (closing && task !== "import")
2339
2479
  answered({ stopped: true });
2340
2480
  else
2341
2481
  failed(new Error(`the import's worker ended (${code}) with no answer`));
2342
2482
  });
2343
2483
  });
2484
+ // GET /v2/wrapped's reads of this machine's home (wrapped.ts), each year's on the import worker, so its parsing never holds
2485
+ // up a request; shared and kept as keptReads says. A read the close ended answers `stopped`: a failed read, not kept.
2486
+ const readWrapped = keptReads((year) => onWorker("wrapped", undefined, year).then((answer) => ("wrapped" in answer ? answer : Promise.reject(new Error("the server stopped before this machine's session history was read")))));
2344
2487
  // The count of what setup would import: started once (at start, or by the page's first read), read as it stands. One
2345
2488
  // stopped (by close, or by setup) starts again on the next read; one that failed stays failed.
2346
2489
  let count;
@@ -2725,11 +2868,12 @@ async function startHolding(options, data, checked, stops) {
2725
2868
  // The run's folder (its work and what sits beside it), its scratch and its native context, on this machine.
2726
2869
  for (const folder of [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId), join(data, "native-context", runId)])
2727
2870
  await rm(folder, { recursive: true, force: true });
2728
- // Its settings: an SDK run's row, its browser wait's end, the Archil disk it resolved to. Its kept computer's row
2871
+ // Its settings: an SDK run's row, its browser wait's end and take, the Archil disk it resolved to. Its kept computer's row
2729
2872
  // (workspace/computer-kept.ts) is left to the janitor, which deletes the computer of a run no longer there and then
2730
2873
  // the row: removed here, the computer would have nothing left to reach it.
2731
2874
  await store.settings.remove(sdkRunKey(runId));
2732
2875
  await store.settings.remove(waitEndedKey(runId));
2876
+ await store.settings.remove(browserHoldKey(runId));
2733
2877
  await store.settings.remove(runDiskKey(runId));
2734
2878
  await forgetKept("run", runId);
2735
2879
  },
@@ -2893,8 +3037,10 @@ async function startHolding(options, data, checked, stops) {
2893
3037
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
2894
3038
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2895
3039
  * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice).
2896
- * `carried`: the names of the tool keys the run carries (run-keys.ts), each read as one this host holds. */
2897
- async function runnable(revision, place, { capped = false, price = decisionPrice, carried = [] } = {}) {
3040
+ * `carried`: the names of the tool keys the run carries (run-keys.ts), each read as one this host holds. `held`: the
3041
+ * run holds its computer (hold: true): kept from running by its model alone, it is not refused, and the refusal is
3042
+ * returned for its launch, its start to answer it (computer-held.ts). */
3043
+ async function runnable(revision, place, { capped = false, price = decisionPrice, carried = [], held = false } = {}) {
2898
3044
  if (cliLearningOf(revision.body))
2899
3045
  throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
2900
3046
  if (sdkOf(revision.body))
@@ -2983,8 +3129,15 @@ async function startHolding(options, data, checked, stops) {
2983
3129
  const harness = blockers.find((b) => b.harness)?.harness;
2984
3130
  const box = blockers.find((b) => b.box)?.box;
2985
3131
  const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}), ...(notGrantable.length ? { not_grantable: notGrantable } : {}) };
2986
- if (revision.kind === "agentic")
2987
- throw new ApiError("agent_not_runnable", message, { fields, details: { unbound, missing, ...named } });
3132
+ if (revision.kind === "agentic") {
3133
+ const details = { unbound, missing, ...named };
3134
+ // A held run kept from running by its model alone opens (runnable.ts Blocker.model: a CLI harness that lacks only a
3135
+ // model key here among them): its computer is its owner's to call, and these words are its start's refusal
3136
+ // (computer-held.ts). Any other blocker refuses it here, as any run.
3137
+ if (held && blockers.every((b) => b.model))
3138
+ return { message, fields, details };
3139
+ throw new ApiError("agent_not_runnable", message, { fields, details });
3140
+ }
2988
3141
  const tier = blockers.find((b) => b.tier)?.tier;
2989
3142
  const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
2990
3143
  const denied = blockers.flatMap((b) => (b.denied ? [b.denied] : []));
@@ -3081,6 +3234,16 @@ async function startHolding(options, data, checked, stops) {
3081
3234
  }
3082
3235
  if (cliLearningOf(body) || sdkOf(body))
3083
3236
  return { warnings: [], stamp: {} };
3237
+ // A workflow's own issues, as POST /workflows/validate lists them (workflowIssues: the DSL's checks, the durable
3238
+ // runner's refusal), refuse its save before anything is written, each at its path under definition.workflow. Asked
3239
+ // with no tools list: its run binds every tool its call nodes name whether `tools` lists it or not (tools.ts
3240
+ // grantedTools), so a call node's unlisted tool is validate's hint, never a reason to refuse a runnable workflow.
3241
+ if (revision.kind === "workflow") {
3242
+ const { workflowIssues } = await import("./workflow-run.js");
3243
+ const { issues } = await workflowIssues(body.workflow);
3244
+ if (issues.length)
3245
+ throw invalid(issues.map(({ path, code, message }) => ({ field: `definition.workflow${path}`, reason: "invalid", code, message })));
3246
+ }
3084
3247
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
3085
3248
  const harnessId = revision.kind === "agentic" ? harnessOfBody(body) : undefined;
3086
3249
  const install = harnessId !== undefined && Object.hasOwn(installs, harnessId) ? installs[harnessId] : undefined;
@@ -3112,7 +3275,10 @@ async function startHolding(options, data, checked, stops) {
3112
3275
  if (never.length)
3113
3276
  throw invalid(never.map(issueOf));
3114
3277
  const mcpPin = listing.pin();
3115
- return { warnings: [...blockers.map(issueOf), ...usage], stamp: { ...(mcpPin ? { mcpPin } : {}), ...(monid ? { monidPin: monid } : {}) } };
3278
+ // A computer every tool of which is set to deny, here or in the agent's own settings: its runs never start it.
3279
+ const denied = await deniedComputer(shape, settings.get(), shellOf);
3280
+ const off = denied ? [{ field: "definition.computer", reason: "not_allowed", message: computerDeniedWords(denied) }] : [];
3281
+ return { warnings: [...blockers.map(issueOf), ...off, ...usage], stamp: { ...(mcpPin ? { mcpPin } : {}), ...(monid ? { monidPin: monid } : {}) } };
3116
3282
  }
3117
3283
  /** An agentic `revision`'s monid pin (monid.ts pinMonid) and a warning per endpoint priced by usage; a grant that
3118
3284
  * cannot be pinned refuses the save (422). Undefined when it grants none. */
@@ -3758,8 +3924,7 @@ async function startHolding(options, data, checked, stops) {
3758
3924
  function startSeal(handed) {
3759
3925
  if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined)
3760
3926
  return undefined;
3761
- return (runId, launch, kind) => {
3762
- const target = { kind, model: launch.model, native: Boolean(launch.native) };
3927
+ return (runId, _launch, target) => {
3763
3928
  if (handed.model !== undefined) {
3764
3929
  const why = modelKeyMisfit(env, target);
3765
3930
  if (why)
@@ -3779,9 +3944,15 @@ async function startHolding(options, data, checked, stops) {
3779
3944
  * which then writes nothing, so a turn never starts with no key to spend. Its `keys` replace the run's whole, each one
3780
3945
  * its revision reads (else 422 by name); under the run-keys setting, a message that would leave the run without a tool
3781
3946
  * key its template declared and this host does not hold (its last turn's end erased them) is refused, 409, nothing
3782
- * written. */
3947
+ * written. A value the run held that the message replaces is kept sealed as `retired`, only to be cut, until the turn's
3948
+ * end erases the seal; where what the run holds does not open here, or past RETIRED_MAX values replaced, the seal says
3949
+ * so (`lost`), and the run is withheld until its end, which counts nothing (handed-values.ts launchValuesOf). */
3783
3950
  async function messageSeal(run, handed) {
3784
3951
  const launch = readLaunchBody((await store.runs.launch(run.id)).body);
3952
+ // A held run its model kept from running takes no message (runs-over-store.ts message refuses it in its create's
3953
+ // words): nothing to seal, and no key check answers before that refusal (its launch pins no model to check).
3954
+ if (launch?.hold?.refused)
3955
+ return undefined;
3785
3956
  const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
3786
3957
  if (handed.model !== undefined) {
3787
3958
  const why = modelKeyMisfit(env, target);
@@ -3801,7 +3972,8 @@ async function startHolding(options, data, checked, stops) {
3801
3972
  return undefined;
3802
3973
  const origin = runModelOrigin(env);
3803
3974
  return (current) => {
3804
- const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
3975
+ const opened = openRunLaunch(sealKey, run.id, current);
3976
+ const held = opened ?? {};
3805
3977
  const mcp = handed.mcp ?? held.mcp;
3806
3978
  const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
3807
3979
  const keys = handed.keys ?? held.keys;
@@ -3810,7 +3982,10 @@ async function startHolding(options, data, checked, stops) {
3810
3982
  const unpaid = owed.length && revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3811
3983
  if (unpaid.length)
3812
3984
  throw keysOwedRefusal(unpaid);
3813
- return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) });
3985
+ const next = { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) };
3986
+ const retired = retiredValues(held, next);
3987
+ const lost = opened === undefined || held.lost === true || retired.length > RETIRED_MAX;
3988
+ return sealRunLaunch(sealKey, run.id, { ...next, ...(lost ? { lost: true } : { retired }) });
3814
3989
  };
3815
3990
  }
3816
3991
  async function createRun(req, agentId) {
@@ -3832,7 +4007,9 @@ async function startHolding(options, data, checked, stops) {
3832
4007
  const run = await triggers.handedStart(given, agentId, async (firing) => {
3833
4008
  const secrets = await handed();
3834
4009
  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) });
4010
+ // What the server writes of the start (its input, which the run's title is read from) is cut of what it hands.
4011
+ const cut = cutHanded(rest, handedSecretValues(secrets));
4012
+ return targets.start(firing.target, cut.input, firing.trigger, firing.from, firing.title, firing.previous, { body: cut, ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3836
4013
  });
3837
4014
  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" } : {}) } };
3838
4015
  }
@@ -3847,7 +4024,9 @@ async function startHolding(options, data, checked, stops) {
3847
4024
  }
3848
4025
  const secrets = await handed();
3849
4026
  const seal = startSeal(secrets);
3850
- const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
4027
+ // What the server writes of the start (its input, which the run's title is read from) is cut of what it hands; the
4028
+ // idempotency fingerprint stays the body's as sent.
4029
+ const run = await startRunOf(entry, cutHanded(body, handedSecretValues(secrets)), { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3851
4030
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
3852
4031
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3853
4032
  });
@@ -3905,7 +4084,8 @@ async function startHolding(options, data, checked, stops) {
3905
4084
  }
3906
4085
  const secrets = await handed();
3907
4086
  const seal = startSeal(secrets);
3908
- const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
4087
+ // What the server writes of the start (its input, which the run's title is read from) is cut of what it hands.
4088
+ const started = await startInline(store, startDeps, inline, cutHanded(run, handedSecretValues(secrets)), { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3909
4089
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
3910
4090
  });
3911
4091
  }
@@ -4066,16 +4246,18 @@ async function startHolding(options, data, checked, stops) {
4066
4246
  async function timeline(req, res, url, runId) {
4067
4247
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
4068
4248
  const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
4069
- // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
4070
- const asked = url.searchParams.get("limit");
4071
- if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
4072
- throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
4073
- const limit = asked === null ? PAGE_ROWS : Number(asked);
4074
- // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
4249
+ // `calls=whole`: each call's arguments and its output too, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), for a grader.
4075
4250
  const shape = url.searchParams.get("calls");
4076
4251
  if (shape !== null && shape !== "whole")
4077
4252
  throw new ApiError("bad_request", "calls is whole, or absent");
4078
4253
  const calls = shape === "whole";
4254
+ // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's). A
4255
+ // calls=whole page holds at most CALLS_PAGE_ROWS, as each row's result may be CALL_RESULT_CHARS long.
4256
+ const most = calls ? CALLS_PAGE_ROWS : PAGE_ROWS;
4257
+ const asked = url.searchParams.get("limit");
4258
+ if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= most))
4259
+ throw new ApiError("bad_request", `limit is an integer from 1 to ${most}${calls ? " with calls=whole" : ""}`);
4260
+ const limit = asked === null ? most : Number(asked);
4079
4261
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
4080
4262
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
4081
4263
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
@@ -4301,7 +4483,7 @@ async function startHolding(options, data, checked, stops) {
4301
4483
  switch (path) {
4302
4484
  case "/setup": {
4303
4485
  const byToken = req.headers.authorization !== undefined;
4304
- if (byToken && !bearer(req.headers.authorization, req))
4486
+ if (byToken && !startToken(req.headers.authorization, req))
4305
4487
  throw new ApiError("unauthenticated", "the Bearer here is the server's token, or none", {}, { "www-authenticate": "Bearer" });
4306
4488
  if (!byToken)
4307
4489
  fromPage(req);
@@ -4320,7 +4502,7 @@ async function startHolding(options, data, checked, stops) {
4320
4502
  const along = takes ? { keep: () => writeDurable(importAsked, chosen ? JSON.stringify({ projects: chosen }) : ""), drop: () => rm(importAsked, { force: true }) } : undefined;
4321
4503
  // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
4322
4504
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
4323
- const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
4505
+ const tokenAsCode = typeof body.code === "string" && body.code !== "" && startToken(`Bearer ${body.code}`, req);
4324
4506
  const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
4325
4507
  if (made === "exists")
4326
4508
  throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
@@ -4522,10 +4704,15 @@ async function startHolding(options, data, checked, stops) {
4522
4704
  // skew check; left out when the store cannot say (a read that failed).
4523
4705
  const state = await store.schemaState?.().catch(() => undefined);
4524
4706
  const storeSchema = state ? { store_schema: { version: state.version, runner_floor: state.runnerFloor, known: state.known } } : {};
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 } });
4707
+ // features.harness_keys.kept names which harness ids still have keys stored: the owner's session or a holder of
4708
+ // the server's token reads it; a caller with neither (this route answers before any bearer check) reads none.
4709
+ const keptShown = byOwnerSession(req) || bearer(req.headers.authorization, req);
4710
+ const keptCap = { ...answer.features.harness_keys, kept: keptShown ? answer.features.harness_keys.kept : [] };
4711
+ // features.api_keys.routes: false on an API-only server, which serves none of the keys' routes and reads no key.
4712
+ return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, harness_keys: keptCap, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) }, claude_login: !loginOff && !options.apiOnly, api_keys: { ...answer.features.api_keys, routes: !options.apiOnly } } });
4526
4713
  }
4527
4714
  if (found.name === "getOpenapi")
4528
- return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
4715
+ return send(res, 200, servedOpenapi(openapi, ownerCookieName(req)));
4529
4716
  // With accounts off there is no owner, and the console still asks whether it may save a secret: secret-writes.ts'
4530
4717
  // verdict over the request the page just marked, never a signed-in user it doesn't have.
4531
4718
  if (found.name === "getAuthSession")
@@ -4798,7 +4985,7 @@ async function startHolding(options, data, checked, stops) {
4798
4985
  await new CliLearningConnections(store, sdkSecret).recordWindow(connection.connection_id, connection.generation, runId, launch.cli_learning.session_id);
4799
4986
  return send(res, 200, result);
4800
4987
  }
4801
- return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
4988
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, sealKey, statuses }, store, runId) });
4802
4989
  }
4803
4990
  if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
4804
4991
  const runId = decodeURIComponent(found.pattern.exec(path)[1]);
@@ -4808,7 +4995,7 @@ async function startHolding(options, data, checked, stops) {
4808
4995
  return send(res, 200, await sdk.events(runId, await bodyOf(req)));
4809
4996
  if (found.name === "completeSdkRun")
4810
4997
  return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
4811
- return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
4998
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, sealKey, statuses }, store, runId) });
4812
4999
  }
4813
5000
  if (!bearer(req.headers.authorization, req)) {
4814
5001
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
@@ -5222,18 +5409,23 @@ async function startHolding(options, data, checked, stops) {
5222
5409
  throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
5223
5410
  const { body, handed } = handedLaunchSecrets(await bodyOf(req));
5224
5411
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
5225
- const seal = await messageSeal(run, await handed());
5412
+ const secrets = await handed();
5413
+ const seal = await messageSeal(run, secrets);
5226
5414
  const extra = unknownFields(body, ["content"]);
5227
5415
  if (extra.length)
5228
5416
  throw invalid(extra);
5229
- const content = body.content;
5230
- if (typeof content !== "string" || !/\S/.test(content))
5231
- throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
5232
- if (content.length > MAX_MESSAGE)
5417
+ const given = body.content;
5418
+ if (typeof given !== "string" || !/\S/.test(given))
5419
+ throw invalid([{ field: "content", reason: given === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
5420
+ if (given.length > MAX_MESSAGE)
5233
5421
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
5234
5422
  // Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
5235
5423
  // In its agent's delete turn (runWrite): a message that may open the run again never lands under its purge.
5236
- const { mode, messageId } = await runWrite(run.agentId, run.id, () => message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) }));
5424
+ // Its text is cut of what it hands and of what the run holds, read in that turn (cutHeld).
5425
+ const { mode, messageId } = await runWrite(run.agentId, run.id, async () => {
5426
+ const content = await cutHeld(run.id, given, handedSecretValues(secrets));
5427
+ return message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
5428
+ });
5237
5429
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
5238
5430
  const { status, state } = await runStatusState(run.id);
5239
5431
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -5493,7 +5685,8 @@ async function startHolding(options, data, checked, stops) {
5493
5685
  await needRun(id);
5494
5686
  // A run's files through the server's read-only Workspace of its folder (serverRunWorkspace); a run with no folder
5495
5687
  // lists none, a withheld run refuses (403), as the base did (filesShown). Same shape and cap the file route answered.
5496
- return send(res, 200, await listRunFilesOverStore(store, id, runReadsDeps));
5688
+ // With ?cut=run, each file's name under the run's cut too.
5689
+ return send(res, 200, await listRunFilesOverStore(store, id, runReadsDeps, url.searchParams.get("cut")));
5497
5690
  }
5498
5691
  // An archived agent's home is read and written as any other's: as its definition is.
5499
5692
  case "listHomeFiles": {
@@ -5582,7 +5775,7 @@ async function startHolding(options, data, checked, stops) {
5582
5775
  // The run's lines from its booking (run-usage.ts), the figures its cost.usd joins: none, with why, while it is at work
5583
5776
  // or where its figure is not its booking's.
5584
5777
  // Names through the run's cut, and a withheld run refused (403), as its trace is.
5585
- return send(res, 200, await servedRunUsage({ serverSecrets, signIns }, store, id));
5778
+ return send(res, 200, await servedRunUsage({ serverSecrets, signIns, sealKey }, store, id));
5586
5779
  case "getRunTrace":
5587
5780
  await needRun(id);
5588
5781
  // The run's spans over its served Timeline rows and its journal (run-trace.ts): cut by the run's one cut, as its
@@ -5646,6 +5839,29 @@ async function startHolding(options, data, checked, stops) {
5646
5839
  return send(res, 200, await usage(url));
5647
5840
  case "getCapacity":
5648
5841
  return send(res, 200, await capacityOverStore(store.runners, capacityWindowOf(url)));
5842
+ case "getWrapped": {
5843
+ // The session files of the machine this server runs on, read for whoever holds a token: only one owner's server on
5844
+ // their own machine answers (whyNotOwnersServer: loopback, no public URL, an owner, one API token, its own SQLite
5845
+ // store). A name an operator allowed (--allow-host) passes the server's Host check for its other routes, but a page
5846
+ // that rebound one to this address must not read the machine's files: here the Host is a loopback name or address.
5847
+ const notOwn = whyNotOwnersServer(options, data);
5848
+ if (!isLoopbackName(hostName(req.headers.host)))
5849
+ notOwn.push("was reached at a name that is not this machine's own");
5850
+ if (notOwn.length)
5851
+ throw new ApiError("forbidden", `wrapped reads this machine's own session files, so only one owner's server on their own machine, reached by a loopback name, answers it. This one ${notOwn.join("; ")}.`);
5852
+ const given = url.searchParams.get("year");
5853
+ const year = given === null ? new Date().getFullYear() : Number(given);
5854
+ if (given !== null && !/^[1-9]\d{3}$/.test(given))
5855
+ throw new ApiError("bad_request", "year is a four-digit year");
5856
+ if (year > new Date().getFullYear())
5857
+ throw new ApiError("bad_request", "year is this year or an earlier one");
5858
+ // A long home is read on, shared, past the wait: the answer says when to ask again rather than hold the request.
5859
+ const read = await within(readWrapped(year), options.wrappedWaitMs ?? WRAPPED_WAIT_MS);
5860
+ if (!read)
5861
+ throw new ApiError("unavailable", `This machine's session history for ${year} is still being read: ask again in a few seconds.`, { retry_after_ms: 5_000 });
5862
+ const analytics = await analyticsOverStore(store, { from: new Date(year, 0, 1).toISOString(), to: new Date(year + 1, 0, 1).toISOString() });
5863
+ return send(res, 200, wrappedView(read.wrapped, analytics.bySource.filter((g) => g.source !== "live").map((g) => ({ source: g.source, runs: g.runs })), read.unread));
5864
+ }
5649
5865
  case "getStats": {
5650
5866
  const filter = analyticsFilter(url);
5651
5867
  // The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
@@ -5697,8 +5913,9 @@ async function startHolding(options, data, checked, stops) {
5697
5913
  await harnessKeysChanged();
5698
5914
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5699
5915
  }
5916
+ // A recipe this server names, or an id whose recipe it no longer names that still has keys kept: removed all the same.
5700
5917
  case "deleteHarnessKey":
5701
- await harnessKeys.remove(harnessKeys.recipe(id), decodeURIComponent(second));
5918
+ await harnessKeys.remove(harnessKeys.held(id), decodeURIComponent(second));
5702
5919
  await harnessKeysChanged();
5703
5920
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
5704
5921
  // Never through `idempotent`: its record keeps the body, and the body holds the password.
@@ -5791,8 +6008,15 @@ async function startHolding(options, data, checked, stops) {
5791
6008
  return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
5792
6009
  case "saveMcpServer": {
5793
6010
  const body = await bodyOf(req);
6011
+ const preset = await mcpServers.composioPreset(id);
6012
+ // API-only, where this route is served only with the operator's MCP origins: a per_run server at one of them alone,
6013
+ // under a name no Composio preset has (api-only.ts apiOnlyMcpSave). Anything else is the refused route's own 404,
6014
+ // before anything reaches the address. The secret-write gate has already refused a credential, and a save over a
6015
+ // server the token did not save or one that seals a credential (403).
6016
+ if (options.apiOnly && !apiOnlyMcpSave(body, preset, apiOnlyMcpOrigins))
6017
+ throw new ApiError("not_found", apiOnlyRefusal(`/v2${path}`));
5794
6018
  // A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
5795
- if (!(await mcpServers.composioPreset(id))) {
6019
+ if (!preset) {
5796
6020
  const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, undefined, undefined, byToken);
5797
6021
  await refreshMcpMeta();
5798
6022
  return send(res, 200, saved);
@@ -5818,6 +6042,8 @@ async function startHolding(options, data, checked, stops) {
5818
6042
  // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
5819
6043
  case "listComposioTools":
5820
6044
  return send(res, 200, await composioTools(await bodyOf(req), options.composioControl ?? {}, stopping.signal), { "cache-control": "no-store" });
6045
+ case "listComposioToolkits":
6046
+ return send(res, 200, await composioToolkits(await bodyOf(req), options.composioControl ?? {}, stopping.signal), { "cache-control": "no-store" });
5821
6047
  case "saveComposioServer": {
5822
6048
  // The name is checked before Composio is called: a refused name leaves nothing made there.
5823
6049
  mcpNameOf(id);
@@ -5848,7 +6074,7 @@ async function startHolding(options, data, checked, stops) {
5848
6074
  case "deleteComposioSubscription":
5849
6075
  return send(res, 200, await composioTriggers.forget(id), { "cache-control": "no-store" });
5850
6076
  case "refreshMcpServer": {
5851
- const refreshed = await mcpServers.refresh(id, stopping.signal);
6077
+ const refreshed = await mcpServers.refresh(id, stopping.signal, options.composioControl ?? {});
5852
6078
  await refreshMcpMeta();
5853
6079
  return send(res, 200, refreshed);
5854
6080
  }
@@ -6048,7 +6274,7 @@ async function startHolding(options, data, checked, stops) {
6048
6274
  const values = await learningValues(id);
6049
6275
  const read = await agentLoopOverStore(store, id);
6050
6276
  const compiles = await Promise.all(read.compiles.map(async (one) => {
6051
- const cut = await runCutValues({ serverSecrets, signIns }, store, one.run_id).catch(() => "unreadable");
6277
+ const cut = await runCutValues({ serverSecrets, signIns, sealKey }, store, one.run_id).catch(() => "unreadable");
6052
6278
  const workflow = one.workflow === null ? null : shown.name(one.workflow);
6053
6279
  if (cut === "unreadable")
6054
6280
  return { ...one, workflow, attempts: one.attempts.map(({ ok }) => ({ ok, errors: [] })), draft_errors: [], withheld: true };
@@ -6136,15 +6362,26 @@ async function startHolding(options, data, checked, stops) {
6136
6362
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
6137
6363
  // from its launch, what it holds for the owner's OK as the store's run view reads it (on its folder's main), as main.
6138
6364
  // Cut by the run's one cut, and refused for a withheld run (run-learning-served.ts).
6139
- return send(res, 200, await servedRunLearning({ serverSecrets, signIns, statuses }, store, run.id));
6365
+ return send(res, 200, await servedRunLearning({ serverSecrets, signIns, sealKey, statuses }, store, run.id));
6140
6366
  }
6141
6367
  case "getRunLearningDiff": {
6142
6368
  const run = await needRun(id);
6143
6369
  // The run's learning diff over the store (learning-routes.ts runDiffOverStore): its merge from its agent's learning
6144
6370
  // folder, else its kept proposal's notes against its seed, else no file against the seed its launch names. Cut by the
6145
6371
  // run's one cut, and refused for a withheld run, as its learning is (run-learning-served.ts).
6146
- return send(res, 200, await servedRunDiff({ serverSecrets, signIns }, store, data, run.id));
6147
- }
6372
+ return send(res, 200, await servedRunDiff({ serverSecrets, signIns, sealKey }, store, data, run.id));
6373
+ }
6374
+ case "listApiKeys":
6375
+ return send(res, 200, apiKeys.list(await apiKeysRefused()));
6376
+ case "createApiKey": {
6377
+ // A secret write: the dispatch's one check let only the owner's session this far (api-keys.ts). Never through
6378
+ // `idempotent`, whose record would keep the answer, and the answer holds the key. Refused, in words, where the
6379
+ // server is one person's (apiKeysRefused), asked in the create's own turn.
6380
+ return send(res, 201, await apiKeys.create(await bodyOf(req), apiKeysRefused));
6381
+ }
6382
+ case "revokeApiKey":
6383
+ await apiKeys.revoke(id);
6384
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
6148
6385
  case "getWebhook":
6149
6386
  return send(res, 200, webhooks.view());
6150
6387
  case "saveWebhook": {
@@ -6212,6 +6449,12 @@ async function startHolding(options, data, checked, stops) {
6212
6449
  const pickView = await computerHere(listed);
6213
6450
  return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
6214
6451
  }
6452
+ case "listMarketplaceTemplates": {
6453
+ // The marketplace's list as read (or kept), each entry with the package here that it is, when one is.
6454
+ const read = await marketplace.list();
6455
+ const here = registry.list();
6456
+ return send(res, 200, { ...read, templates: read.templates.map((entry) => { const id = hereOf(entry, here); return id ? { ...entry, here: id } : entry; }) });
6457
+ }
6215
6458
  case "importTemplate": {
6216
6459
  // Read from GitHub, or uploaded whole ({files}), and checked; a dry run answers it (200), else it is stored and
6217
6460
  // served (201). The answer shows the package whole, its instructions and every skill file, for a person to read
@@ -6291,6 +6534,10 @@ async function startHolding(options, data, checked, stops) {
6291
6534
  }
6292
6535
  case "listTriggerFirings":
6293
6536
  return send(res, 200, await triggers.firings(id));
6537
+ case "releaseTriggerFiring":
6538
+ // The launch hook's host took the firing and will start no run for it: failed now, its trigger's room free. Its
6539
+ // words are kept and sent on (trigger.failed) as any stored string is, cut of every secret the server holds.
6540
+ return send(res, 200, await triggers.release(id, decodeURIComponent(second), await bodyOf(req), (text) => redacted(text, serverSecrets(), RELEASE_WORDS_MAX)));
6294
6541
  }
6295
6542
  throw new ApiError("not_found", `no route ${path}`);
6296
6543
  }
@@ -6380,10 +6627,11 @@ async function startHolding(options, data, checked, stops) {
6380
6627
  const started = performance.now();
6381
6628
  const method = req.method ?? "GET";
6382
6629
  const path = (req.url ?? "/").split("?")[0];
6383
- // Who the request was answered for: the owner's or the console's session, or the id of the API token it carried
6384
- // (api-token.ts), never a secret. A request opened by neither has no such field.
6630
+ // Who the request was answered for: the owner's or the console's session, the id of the API token it carried
6631
+ // (api-token.ts), or the id of the key made in the console (api-keys.ts): never a secret. A request opened by none
6632
+ // has no such field.
6385
6633
  res.once("finish", () => {
6386
- const by = byOwnerSession(req) ? { session: "owner" } : byConsoleSession(req) ? { session: "console" } : tokenUsed.has(req) ? { token: tokenUsed.get(req) } : {};
6634
+ const by = byOwnerSession(req) ? { session: "owner" } : byConsoleSession(req) ? { session: "console" } : tokenUsed.has(req) ? { token: tokenUsed.get(req) } : keyUsed.has(req) ? { api_key: keyUsed.get(req) } : {};
6387
6635
  log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started), ...by }));
6388
6636
  });
6389
6637
  }
@@ -6429,7 +6677,7 @@ async function startHolding(options, data, checked, stops) {
6429
6677
  const raw = (req.url ?? "/").split("?")[0];
6430
6678
  // API-only (api-only.ts): any address but the run routes is refused here, before the page, the owner's routes, the
6431
6679
  // MCP endpoint, the token-less hooks or the token check read anything of the request.
6432
- if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
6680
+ if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw, apiOnlyMcpOrigins.length > 0))
6433
6681
  return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
6434
6682
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
6435
6683
  if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw === "/v2/setup/code" || raw.startsWith("/v2/auth/")))
@@ -6877,8 +7125,11 @@ async function startHolding(options, data, checked, stops) {
6877
7125
  closing = true;
6878
7126
  stopping.abort();
6879
7127
  clearInterval(localSourceTimer);
6880
- // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
6881
- plan.close();
7128
+ // Cancel a pending ChatGPT callback without signing out or changing the saved credential (not waited for).
7129
+ void plan.close();
7130
+ // The CLI's sign-in still waiting for its browser ends with the server, which forgets it: left running, its CLI would
7131
+ // keep the browser's callback port from the next server's sign-in. Awaited until its process is gone.
7132
+ const signInStopped = claudeSignIns.close();
6882
7133
  const observationStopped = stopObservationRetention();
6883
7134
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
6884
7135
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
@@ -6888,16 +7139,18 @@ async function startHolding(options, data, checked, stops) {
6888
7139
  // triggers close, so it never turns one off into a closed file.
6889
7140
  const githubStopped = githubConnect.close();
6890
7141
  triggers.close();
7142
+ // A count and a Wrapped read write nothing: ended outright. An import stops between two files and keeps what it wrote.
6891
7143
  for (const [worker, { task }] of workers) {
6892
- if (task === "plan")
6893
- void worker.terminate();
6894
- else
7144
+ if (task === "import")
6895
7145
  worker.postMessage("stop");
7146
+ else
7147
+ void worker.terminate();
6896
7148
  }
6897
7149
  await Promise.all([...workers.values()].map((w) => w.exit));
6898
7150
  await importing;
6899
7151
  await schemaSealed;
6900
7152
  await installStopped;
7153
+ await signInStopped;
6901
7154
  await observationStopped;
6902
7155
  await localSourceSweep;
6903
7156
  // The ends' follower stops before the webhooks it feeds and the store it reads.
@@ -6909,6 +7162,8 @@ async function startHolding(options, data, checked, stops) {
6909
7162
  viewers.close();
6910
7163
  await attach.close();
6911
7164
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
7165
+ // No request is left to use a key: its last-use writes end before the store they write to closes.
7166
+ await apiKeys.close();
6912
7167
  await mcpStopped;
6913
7168
  await githubStopped;
6914
7169
  // --faux-github's fake GitHub API, once nothing asks it anything.
@@ -6928,6 +7183,9 @@ async function startHolding(options, data, checked, stops) {
6928
7183
  await store.close();
6929
7184
  dataLock.release();
6930
7185
  seal.release();
7186
+ // Last, so a stop cut at its deadline has closed the rest: the host-address retry, aborted above, its read in flight
7187
+ // cut then and its container's removal running since, within two REMOVE_MS.
7188
+ await hostRetried;
6931
7189
  }
6932
7190
  return {
6933
7191
  url,