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

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 (261) hide show
  1. package/CHANGELOG.md +122 -1
  2. package/README.md +213 -24
  3. package/dist/agent-delete.d.ts +5 -6
  4. package/dist/agent-delete.js +30 -67
  5. package/dist/agent-package.d.ts +71 -0
  6. package/dist/agent-package.js +345 -0
  7. package/dist/agents-store.d.ts +26 -20
  8. package/dist/agents-store.js +41 -33
  9. package/dist/api-only.d.ts +26 -6
  10. package/dist/api-only.js +35 -13
  11. package/dist/claude-login.d.ts +1 -0
  12. package/dist/claude-login.js +1 -1
  13. package/dist/cli-learning/cli.d.ts +3 -0
  14. package/dist/cli-learning/cli.js +17 -3
  15. package/dist/cli-learning/connections.js +3 -2
  16. package/dist/cli-learning/schema.js +2 -1
  17. package/dist/cli.js +70 -7
  18. package/dist/composio-preset.d.ts +2 -1
  19. package/dist/composio-preset.js +4 -3
  20. package/dist/composio-triggers.d.ts +4 -0
  21. package/dist/composio-triggers.js +4 -1
  22. package/dist/computer-needs.d.ts +32 -0
  23. package/dist/computer-needs.js +80 -0
  24. package/dist/computer-setting.d.ts +1 -0
  25. package/dist/computer-setting.js +8 -1
  26. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  27. package/dist/console/assets/index-DbilxljH.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/console-links.d.ts +1 -0
  30. package/dist/console-links.js +2 -0
  31. package/dist/env-switch.d.ts +14 -0
  32. package/dist/env-switch.js +23 -0
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.js +3 -0
  35. package/dist/eval-previous.js +4 -3
  36. package/dist/fal-price.js +10 -13
  37. package/dist/handed-secret.d.ts +4 -0
  38. package/dist/handed-secret.js +10 -0
  39. package/dist/harness-archive.d.ts +15 -5
  40. package/dist/harness-archive.js +71 -34
  41. package/dist/harness-check.d.ts +2 -1
  42. package/dist/harness-check.js +36 -95
  43. package/dist/harness-egress.d.ts +23 -0
  44. package/dist/harness-egress.js +69 -0
  45. package/dist/harness-recipe-entry.d.ts +71 -0
  46. package/dist/harness-recipe-entry.js +184 -0
  47. package/dist/harness-recipe.d.ts +73 -6
  48. package/dist/harness-recipe.js +185 -31
  49. package/dist/harness-sign-in.d.ts +29 -0
  50. package/dist/harness-sign-in.js +122 -0
  51. package/dist/harness-table.d.ts +21 -0
  52. package/dist/harness-table.js +58 -3
  53. package/dist/harness-zip.d.ts +6 -0
  54. package/dist/harness-zip.js +203 -0
  55. package/dist/ids.d.ts +11 -0
  56. package/dist/ids.js +36 -0
  57. package/dist/learn/commit.d.ts +14 -1
  58. package/dist/learn/commit.js +156 -1
  59. package/dist/learn/compile.js +22 -8
  60. package/dist/learn/folder.d.ts +5 -0
  61. package/dist/learn/folder.js +10 -1
  62. package/dist/learn/learning.sh +15 -3
  63. package/dist/learn/promote.d.ts +2 -2
  64. package/dist/learn/secrets.js +30 -7
  65. package/dist/learning-routes.d.ts +23 -11
  66. package/dist/learning-routes.js +110 -20
  67. package/dist/learning.d.ts +9 -6
  68. package/dist/learning.js +9 -4
  69. package/dist/mcp-gateway.js +15 -2
  70. package/dist/mcp-probe.d.ts +3 -0
  71. package/dist/mcp-probe.js +7 -2
  72. package/dist/mcp-resources.d.ts +44 -0
  73. package/dist/mcp-resources.js +100 -0
  74. package/dist/mcp-servers-store.d.ts +16 -12
  75. package/dist/model.d.ts +4 -4
  76. package/dist/model.js +6 -6
  77. package/dist/native/cli.js +9 -2
  78. package/dist/native/connection.d.ts +2 -2
  79. package/dist/native/connection.js +5 -2
  80. package/dist/native/discovery.d.ts +2 -0
  81. package/dist/native/discovery.js +10 -6
  82. package/dist/native/remote-worker-bridge.js +36 -4
  83. package/dist/native/remote.d.ts +18 -1
  84. package/dist/native/remote.js +126 -37
  85. package/dist/native/schema.d.ts +6 -0
  86. package/dist/native/schema.js +31 -6
  87. package/dist/native/source-account.d.ts +13 -0
  88. package/dist/native/source-account.js +114 -0
  89. package/dist/native/source-capture-hooks.d.ts +5 -0
  90. package/dist/native/source-capture-hooks.js +102 -0
  91. package/dist/native/source-mcp-selection.d.ts +13 -0
  92. package/dist/native/source-mcp-selection.js +72 -0
  93. package/dist/native/source-runtime-tools.d.ts +19 -0
  94. package/dist/native/source-runtime-tools.js +103 -0
  95. package/dist/native/source-snapshot-types.d.ts +138 -0
  96. package/dist/native/source-snapshot-types.js +12 -0
  97. package/dist/native/source-snapshot.d.ts +8 -0
  98. package/dist/native/source-snapshot.js +1201 -0
  99. package/dist/observation/learning.js +3 -2
  100. package/dist/openapi.js +167 -36
  101. package/dist/print.js +1 -1
  102. package/dist/purged-workflow.d.ts +12 -0
  103. package/dist/purged-workflow.js +43 -0
  104. package/dist/run-keys.d.ts +46 -0
  105. package/dist/run-keys.js +109 -0
  106. package/dist/run-launch.d.ts +16 -1
  107. package/dist/run-launch.js +30 -1
  108. package/dist/run-learning-served.d.ts +2 -2
  109. package/dist/run-model-key.d.ts +2 -2
  110. package/dist/run-model-key.js +5 -5
  111. package/dist/run-secrets.d.ts +2 -0
  112. package/dist/run-secrets.js +7 -4
  113. package/dist/run-view.d.ts +17 -0
  114. package/dist/run-view.js +25 -1
  115. package/dist/runner/adapter-loop.d.ts +11 -3
  116. package/dist/runner/adapter-loop.js +138 -22
  117. package/dist/runner/adapter-run-spec.js +25 -12
  118. package/dist/runner/audit.d.ts +2 -0
  119. package/dist/runner/audit.js +9 -1
  120. package/dist/runner/beside.js +2 -1
  121. package/dist/runner/claim-secrets.d.ts +29 -3
  122. package/dist/runner/claim-secrets.js +38 -4
  123. package/dist/runner/cli-run-spec.js +23 -12
  124. package/dist/runner/harness-loops.d.ts +6 -0
  125. package/dist/runner/harness-loops.js +11 -1
  126. package/dist/runner/held.d.ts +4 -0
  127. package/dist/runner/journal-kinds.d.ts +2 -0
  128. package/dist/runner/learned-first.d.ts +2 -0
  129. package/dist/runner/learned-first.js +1 -1
  130. package/dist/runner/learning-end.d.ts +7 -2
  131. package/dist/runner/learning-end.js +22 -10
  132. package/dist/runner/learning-seed.d.ts +9 -3
  133. package/dist/runner/learning-seed.js +2 -2
  134. package/dist/runner/main.d.ts +1 -0
  135. package/dist/runner/main.js +20 -13
  136. package/dist/runner/mcp-claim.js +6 -1
  137. package/dist/runner/mcp-run.d.ts +10 -7
  138. package/dist/runner/mcp-run.js +3 -5
  139. package/dist/runner/monid-run.js +9 -11
  140. package/dist/runner/project-checkpoint.d.ts +35 -0
  141. package/dist/runner/project-checkpoint.js +116 -0
  142. package/dist/runner/project-drain.d.ts +8 -0
  143. package/dist/runner/project-drain.js +25 -0
  144. package/dist/runner/project-host.d.ts +10 -0
  145. package/dist/runner/project-host.js +52 -0
  146. package/dist/runner/promotion.d.ts +14 -6
  147. package/dist/runner/promotion.js +98 -41
  148. package/dist/runner/redact.d.ts +13 -0
  149. package/dist/runner/redact.js +67 -1
  150. package/dist/runner/run-channel.d.ts +9 -0
  151. package/dist/runner/run-channel.js +15 -2
  152. package/dist/runner/run-child-host.d.ts +8 -4
  153. package/dist/runner/run-child-host.js +171 -41
  154. package/dist/runner/run-errors.js +2 -2
  155. package/dist/runner/runner-check.js +5 -2
  156. package/dist/runner/runner.js +26 -9
  157. package/dist/runner/store-secrets.js +7 -3
  158. package/dist/runner/workflow-first.d.ts +4 -0
  159. package/dist/runner/workflow-first.js +13 -0
  160. package/dist/runner/workflow-loop.d.ts +2 -1
  161. package/dist/runner/workflow-loop.js +2 -1
  162. package/dist/runner/workflow-spec.js +1 -1
  163. package/dist/runs-over-store.d.ts +34 -6
  164. package/dist/runs-over-store.js +133 -25
  165. package/dist/sdk/runs.d.ts +11 -1
  166. package/dist/sdk/runs.js +117 -26
  167. package/dist/sdk/schema.js +12 -2
  168. package/dist/sdk/workflows.d.ts +1 -1
  169. package/dist/server.d.ts +68 -32
  170. package/dist/server.js +600 -110
  171. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  172. package/dist/source-sync/adoption.d.ts +15 -0
  173. package/dist/source-sync/adoption.js +36 -0
  174. package/dist/source-sync/auxiliary.d.ts +23 -0
  175. package/dist/source-sync/auxiliary.js +64 -0
  176. package/dist/source-sync/capture-git.d.ts +5 -0
  177. package/dist/source-sync/capture-git.js +272 -0
  178. package/dist/source-sync/capture-project.d.ts +53 -0
  179. package/dist/source-sync/capture-project.js +206 -0
  180. package/dist/source-sync/capture-refusal.d.ts +7 -0
  181. package/dist/source-sync/capture-refusal.js +16 -0
  182. package/dist/source-sync/capture.d.ts +11 -0
  183. package/dist/source-sync/capture.js +22 -0
  184. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  185. package/dist/source-sync/checkpoint-gate.js +52 -0
  186. package/dist/source-sync/checkpoints.d.ts +66 -0
  187. package/dist/source-sync/checkpoints.js +168 -0
  188. package/dist/source-sync/claim.d.ts +11 -0
  189. package/dist/source-sync/claim.js +48 -0
  190. package/dist/source-sync/destination.d.ts +47 -0
  191. package/dist/source-sync/destination.js +239 -0
  192. package/dist/source-sync/io.d.ts +15 -0
  193. package/dist/source-sync/io.js +52 -0
  194. package/dist/source-sync/local.d.ts +43 -0
  195. package/dist/source-sync/local.js +229 -0
  196. package/dist/source-sync/prepare.d.ts +59 -0
  197. package/dist/source-sync/prepare.js +93 -0
  198. package/dist/source-sync/projects.d.ts +61 -0
  199. package/dist/source-sync/projects.js +130 -0
  200. package/dist/source-sync/registry.d.ts +95 -0
  201. package/dist/source-sync/registry.js +226 -0
  202. package/dist/source-sync/service.d.ts +33 -0
  203. package/dist/source-sync/service.js +118 -0
  204. package/dist/source-sync/skill-edits.d.ts +12 -0
  205. package/dist/source-sync/skill-edits.js +122 -0
  206. package/dist/source-sync/snapshots.d.ts +48 -0
  207. package/dist/source-sync/snapshots.js +448 -0
  208. package/dist/source-sync/types.d.ts +9 -0
  209. package/dist/source-sync/types.js +14 -0
  210. package/dist/source-sync/workspace.d.ts +66 -0
  211. package/dist/source-sync/workspace.js +273 -0
  212. package/dist/store/agent-body.d.ts +4 -0
  213. package/dist/store/agent-body.js +16 -5
  214. package/dist/store/index.d.ts +2 -2
  215. package/dist/store/index.js +1 -1
  216. package/dist/store/schema.d.ts +2 -1
  217. package/dist/store/schema.js +2 -1
  218. package/dist/store/seal.d.ts +5 -1
  219. package/dist/store/seal.js +12 -3
  220. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  221. package/dist/store/sqlite/project-checkpoints.js +70 -0
  222. package/dist/store/sqlite/run-launch.d.ts +4 -12
  223. package/dist/store/sqlite/run-launch.js +5 -19
  224. package/dist/store/sqlite/store.js +224 -170
  225. package/dist/store/store.d.ts +116 -39
  226. package/dist/store/store.js +14 -1
  227. package/dist/store-reads/learning.d.ts +2 -2
  228. package/dist/store-view.d.ts +3 -1
  229. package/dist/store-view.js +17 -5
  230. package/dist/template-import.d.ts +10 -2
  231. package/dist/template-import.js +116 -13
  232. package/dist/templates.d.ts +26 -5
  233. package/dist/templates.js +62 -10
  234. package/dist/timeline/index.d.ts +1 -1
  235. package/dist/timeline/index.js +1 -1
  236. package/dist/timeline/timeline.d.ts +5 -0
  237. package/dist/timeline/timeline.js +8 -0
  238. package/dist/tool-plane.d.ts +12 -12
  239. package/dist/tools.d.ts +8 -8
  240. package/dist/trigger-launch-hook.d.ts +47 -0
  241. package/dist/trigger-launch-hook.js +90 -0
  242. package/dist/trigger-targets.d.ts +14 -1
  243. package/dist/trigger-targets.js +20 -0
  244. package/dist/triggers.d.ts +54 -5
  245. package/dist/triggers.js +143 -8
  246. package/dist/uploads-archil.js +1 -1
  247. package/dist/uploads.js +1 -1
  248. package/dist/validate.js +1 -2
  249. package/dist/workspace/computer-for-claim.d.ts +2 -0
  250. package/dist/workspace/computer-for-claim.js +43 -0
  251. package/dist/workspace/paths.d.ts +6 -0
  252. package/dist/workspace/paths.js +6 -0
  253. package/dist/workspace/resolve-computer.d.ts +1 -0
  254. package/dist/workspace/run-tools.d.ts +2 -0
  255. package/dist/workspace/run-tools.js +8 -0
  256. package/launcher/agentrun-serve +1 -1
  257. package/package.json +10 -10
  258. package/skills/agentrun-serve/SKILL.md +2 -1
  259. package/templates/README.md +5 -2
  260. package/dist/console/assets/index-B-D0EM3j.js +0 -733
  261. package/dist/console/assets/index-DlQepP2J.css +0 -1
package/dist/server.js CHANGED
@@ -1,9 +1,20 @@
1
+ import { prepareProjectSkillEdit } from "./source-sync/skill-edits.js";
2
+ import { sourceSyncOf } from "./source-sync/types.js";
3
+ import { sourceService, SOURCE_BODY_BYTES } from "./source-sync/service.js";
4
+ import { destinationPreparation, bindSourceTool } from "./source-sync/destination.js";
5
+ import { prepareSource, SourcePreparationError } from "./source-sync/prepare.js";
6
+ import { SnapshotError, validateSourceSnapshot } from "./source-sync/snapshots.js";
7
+ import { cliAdoptionResolver } from "./source-sync/adoption.js";
8
+ import { projectPlacement } from "./source-sync/projects.js";
9
+ import { auxiliaryAdmitter } from "./source-sync/auxiliary.js";
10
+ import { openRunPlacement, sourceSnapshotReader } from "./source-sync/workspace.js";
11
+ import { SOURCE_FAILURES, configurationDigest } from "./source-sync/registry.js";
1
12
  import { CliLearningConnections } from "./cli-learning/connections.js";
2
13
  import { ObservationLearning } from "./observation/learning.js";
3
14
  import { cliLearningOf } from "./store/agent-body.js";
4
15
  import { maintainObservations, Observations } from './observation/observer.js';
5
16
  import { isObservationRoute, observationHttp } from './observation/http.js';
6
- import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
17
+ import { SDK_MAX_OPEN_MS, SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
7
18
  import { learningModelOf } from "./learning-model.js";
8
19
  import { answerSkill } from './skill-route.js';
9
20
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
@@ -18,7 +29,9 @@ import { createHash, createHmac, randomBytes } from "node:crypto";
18
29
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
19
30
  import { createServer } from "node:http";
20
31
  import proxyaddr from "proxy-addr";
21
- import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
32
+ import { API_ONLY_HOOKED_KINDS, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
33
+ import { RUN_KEYS_ENV } from "./env-switch.js";
34
+ import { declaredKeys, keysOwed, keysOwedRefusal, packageKeysOf, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
22
35
  import { capacityOverStore, capacityWindowOf } from "./capacity.js";
23
36
  import { carriedFields } from "./answer-json.js";
24
37
  import { dirname, join, relative, resolve, sep } from "node:path";
@@ -29,7 +42,9 @@ import { existsSync } from "node:fs";
29
42
  import { rm } from "node:fs/promises";
30
43
  import { homedir, hostname } from "node:os";
31
44
  import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
32
- import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, ownedElsewhere, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
45
+ import { agentPackage } from "./agent-package.js";
46
+ import { uuidv7 } from "./ids.js";
47
+ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, definitionOf, etagOf, externalKey, getAgent, listAgents, makeRevision, ownedElsewhere, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
33
48
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
34
49
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
35
50
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
@@ -43,7 +58,7 @@ import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
43
58
  import { homePath, hostOwnedOf } from "./home-path.js";
44
59
  import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
45
60
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
46
- import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, tableIds } from "./harness-table.js";
61
+ import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_RECIPES_ENV, HARNESS_RECIPES_SETTING, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, harnessRecipesEnv, recipeHarness, tableIds } from "./harness-table.js";
47
62
  import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
48
63
  import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
49
64
  import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
@@ -51,7 +66,8 @@ import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
51
66
  import { answerStoreCall } from "./import-proxy.js";
52
67
  import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf, withAgentRepo } from "./learning.js";
53
68
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
54
- import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
69
+ import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, forgetRunLearning, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
70
+ import { purgedRun } from "./purged-workflow.js";
55
71
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
56
72
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
57
73
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -73,6 +89,10 @@ import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
73
89
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
74
90
  import { builtOfNow, factsOverStore, listedItem, lookingBackEnd, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
75
91
  import { healEndedCosts } from "./cost-heal.js";
92
+ import { reconcileProjectCheckpoints } from "./source-sync/checkpoints.js";
93
+ import { acknowledgeProjects } from "./source-sync/checkpoint-gate.js";
94
+ import { LocalSources } from "./source-sync/local.js";
95
+ import { beginSourceIO } from "./source-sync/io.js";
76
96
  import { createLister } from "./run-listing.js";
77
97
  import { HELD_WAITS } from "./runner/journal-kinds.js";
78
98
  import { servedTimelineRows } from "./run-timeline-served.js";
@@ -119,7 +139,7 @@ import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
119
139
  import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
120
140
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
121
141
  import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
122
- import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
142
+ 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";
123
143
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
124
144
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
125
145
  import { recordDataRoot } from "./runner/disk-free.js";
@@ -139,7 +159,7 @@ import { signInsOverStore } from "./sign-ins-store.js";
139
159
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
140
160
  import { composioMadeKey, composioPerRun } from "./composio-made.js";
141
161
  import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
142
- import { ComposioTriggers } from "./composio-triggers.js";
162
+ import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
143
163
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
144
164
  import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
145
165
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
@@ -167,9 +187,9 @@ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
167
187
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
168
188
  import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
169
189
  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";
170
- import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
171
- import { templateInstallLink, templateLink } from "./console-links.js";
172
- import { GITHUB_HOSTS } from "./template-source.js";
190
+ import { deleteTemplate, dropRemovedUploads, importTemplate, loadImported, UPLOAD_PREFIX } from "./template-import.js";
191
+ import { templateInstallLink, templateLink, templatesLink } from "./console-links.js";
192
+ import { GITHUB_HOSTS, IMPORT_LIMITS } from "./template-source.js";
173
193
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
174
194
  import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
175
195
  import { wakeAnsweredBySetting } from "./settings-wake.js";
@@ -194,12 +214,12 @@ import { noAccount, openAccount } from "./email/account.js";
194
214
  import { emailRoute } from "./email/routes.js";
195
215
  import { addressForms, openCalendar } from "./calendar/address.js";
196
216
  import { calendarRoute } from "./calendar/routes.js";
197
- import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKept, runDiskKey } from "./archil-settings.js";
217
+ import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, loadArchilSettings, runDiskKept, runDiskKey } from "./archil-settings.js";
198
218
  import { computerOfPlace } from "./computer-setting.js";
199
219
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
200
220
  import { fauxComputers } from "./faux-computers.js";
201
221
  import { writesHeld } from "./workspace.js";
202
- import { deleteExternalAgent, oneAtATime, purgeAgent, purgedAgain, purgeRun, purgingKey } from "./agent-delete.js";
222
+ import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
203
223
  import { resetLearning } from "./learning-reset.js";
204
224
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
205
225
  import { sdkRunKey } from "./sdk/runs.js";
@@ -216,6 +236,9 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
216
236
  * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
217
237
  const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
218
238
  const MAX_BODY = 1 << 20;
239
+ /** POST /v2/templates/import's body: an upload's files at the import's own limit, base64 (4/3) with room for the JSON
240
+ * around them. */
241
+ const TEMPLATE_UPLOAD_BODY = Math.ceil((IMPORT_LIMITS.packageBytes * 4) / 3) + MAX_BODY;
219
242
  /** The starts that may begin setup's import without ending it (a worker that failed, a process that ended) before the
220
243
  * owner's yes is dropped: an import that fails the same way each time is not taken up at every start for good. */
221
244
  const IMPORT_STARTS = 3;
@@ -249,7 +272,7 @@ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_E
249
272
  * startInProcessRunner). */
250
273
  export function fauxEnvOf(options) {
251
274
  // The owner's harness modules too (not a test switch): a run's process reads the same table as the server.
252
- const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
275
+ const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...harnessRecipesEnv(options.harnessRecipes ?? [], options.data, { signIn: options.harnessSignIn === true }), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
253
276
  if (!options.faux)
254
277
  return env;
255
278
  env[FAUX_ENV] = resolve(options.faux);
@@ -278,19 +301,6 @@ async function tokenIn(file) {
278
301
  }
279
302
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
280
303
  const SESSION_S = SESSION_MS / 1000;
281
- const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
282
- /** 410 purged for a route of a purged run (Runs.purge): its tombstone, what is kept of it. `tools_usd`: its paid tools'
283
- * meter as /usage read it at its purge (null: unknown, or none read). */
284
- function purgedRun(row) {
285
- const meters = row.metrics?.purged?.meters;
286
- return new ApiError("purged", `The run ${row.id} was purged: what it was given and did is gone, and its cost stays in every total.`, {
287
- details: {
288
- run_id: row.id, agent_id: row.agentId, state: row.state, started_at: isoOrNull(row.startedAt), ended_at: isoOrNull(row.endedAt),
289
- cost_usd: row.costUsd ?? row.costAtMostUsd, cost_upper_bound: row.costUsd === null && row.costAtMostUsd !== null, tools_usd: typeof meters?.tools === "number" ? meters.tools : null,
290
- purged_at: isoOrNull(row.purgedAt),
291
- },
292
- });
293
- }
294
304
  export const ROUTES = [
295
305
  { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
296
306
  { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
@@ -299,6 +309,15 @@ export const ROUTES = [
299
309
  { method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
300
310
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
301
311
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/history$/, name: "importRemoteHistory" },
312
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync\/grant$/, name: "grantSourceSync" },
313
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync$/, name: "publishSourceSync" },
314
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync\/status$/, name: "sourceSyncFailure" },
315
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/source$/, name: "getSourceSync" },
316
+ { method: "PATCH", pattern: /^\/agents\/([^/]+)\/source$/, name: "setSourceSync" },
317
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/source\/move$/, name: "moveSourceAgent" },
318
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/source\/tools$/, name: "bindSourceTool" },
319
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/source\/resolve$/, name: "resolveSourceSync" },
320
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/source\/project-review$/, name: "reviewSourceProject" },
302
321
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
303
322
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
304
323
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
@@ -329,6 +348,7 @@ export const ROUTES = [
329
348
  { method: "DELETE", pattern: /^\/agents\/([^/]+)$/, name: "deleteAgent" },
330
349
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
331
350
  { method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
351
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/package$/, name: "getAgentPackage" },
332
352
  { method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
333
353
  { method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
334
354
  { method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
@@ -438,6 +458,8 @@ export const ROUTES = [
438
458
  { method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
439
459
  { method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
440
460
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
461
+ // The saved servers' names alone, for a host that builds runs from them (served API-only too: api-only.ts).
462
+ { method: "GET", pattern: /^\/settings\/mcp-server-names$/, name: "listMcpServerNames" },
441
463
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
442
464
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
443
465
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
@@ -483,6 +505,7 @@ export const ROUTES = [
483
505
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
484
506
  { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
485
507
  { method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
508
+ { method: "GET", pattern: /^\/templates\/([^/]+)$/, name: "getTemplate" },
486
509
  { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
487
510
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
488
511
  // Answered before the bearer check: the request's signature is its credential.
@@ -736,6 +759,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
736
759
  * URL kept sealed, never shown. */
737
760
  slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
738
761
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
762
+ /** A backend SDK run's start (sdk/runs.ts): the fields it takes, and the most seconds it stays open. */
763
+ sdk_runs: { started_at: true, title: true, labels: true, max_open_s: SDK_MAX_OPEN_MS / 1000 },
739
764
  triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
740
765
  },
741
766
  regions: [{ id: "local", jurisdiction: null, state: "live" }],
@@ -788,6 +813,29 @@ function integerParam(value, name, max) {
788
813
  throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
789
814
  return Number(value);
790
815
  }
816
+ /** A start with --harness-sign-in on a server that is not one owner's own, on their own machine. */
817
+ export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
818
+ /** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
819
+ * it may. One owner's own server on their own machine: it listens on loopback alone, with no public address; its store
820
+ * is the SQLite one in its data directory (no AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside
821
+ * it as its own user (`ownUser`: runIsolationOf's `process`), never under --no-runner or a user of their own; and one
822
+ * person starts them, as Claude Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one
823
+ * API token. A check, a schedule and a shared server run on a key (HARNESS.md#sign-in). */
824
+ export function harnessSignInRefusal(options, data, ownUser) {
825
+ const host = options.host ?? DEFAULT_HOST;
826
+ // Every token the server takes (acceptedTokens): AGENTRUN_TOKEN's as `default` beside the list's, or else DIR/.token's alone.
827
+ const tokens = (options.token === undefined ? 0 : 1) + (options.tokens?.length ?? 0);
828
+ const why = [
829
+ ...(loopback(host) ? [] : [`listens on ${host}, past loopback`]),
830
+ ...(options.publicUrl ? [`has a public address (${options.publicUrl})`] : []),
831
+ ...(options.apiOnly ? ["has no owner (the API-only profile), so anyone with its token starts runs"] : []),
832
+ ...(tokens > 1 ? [`takes ${tokens} API tokens (AGENTRUN_TOKEN and AGENTRUN_TOKENS together), so more than one person starts runs`] : []),
833
+ ...(storeTarget(data).kind === "sqlite" ? [] : ["keeps its store in Postgres (AGENTRUN_STORE_URL), which servers elsewhere share"]),
834
+ ...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
835
+ ...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
836
+ ];
837
+ return why.length ? `${HARNESS_SIGN_IN_NOT_LOCAL}: --harness-sign-in runs a recipe on its owner's own sign-in on one owner's own machine alone, and this server ${why.join("; ")}. Start it without --harness-sign-in: its plan-billed recipes run on keys.` : undefined;
838
+ }
791
839
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
792
840
  // by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
793
841
  export async function startServe(options) {
@@ -800,9 +848,17 @@ export async function startServe(options) {
800
848
  // So is the harness modules list, from `harnessModules` alone (an operator names them with --harness-module or
801
849
  // AGENTRUN_SERVE_HARNESS_MODULES, which the CLI reads into the option).
802
850
  delete process.env[HARNESS_MODULES_ENV];
851
+ // And the recipes, from `harnessRecipes` alone (--harness-recipe or AGENTRUN_SERVE_HARNESS_RECIPES).
852
+ delete process.env[HARNESS_RECIPES_ENV];
803
853
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
804
854
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
805
855
  const data = await realpath(resolve(options.data));
856
+ if (options.harnessSignIn) {
857
+ const { runsAsOwnUser } = await import("./runner/run-child-host.js");
858
+ const refused = harnessSignInRefusal(options, data, runsAsOwnUser(process.env));
859
+ if (refused)
860
+ throw new Error(refused);
861
+ }
806
862
  const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
807
863
  if (tokenRefused)
808
864
  throw new Error(tokenRefused);
@@ -895,7 +951,7 @@ async function startHolding(options, data, checked, stops) {
895
951
  // shown nowhere.
896
952
  let secretStores;
897
953
  let triggerSettings = new Map();
898
- const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data) };
954
+ const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data), ...harnessRecipesEnv(options.harnessRecipes ?? [], data, { signIn: options.harnessSignIn === true }) };
899
955
  // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
900
956
  // the start, in words, before anything else opens.
901
957
  // The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
@@ -971,7 +1027,14 @@ async function startHolding(options, data, checked, stops) {
971
1027
  // runner/runner-check.ts): this data root's id, and the names (never the values) of the run-facing environment this
972
1028
  // server holds, each said in the store at every start, replacing the last start's.
973
1029
  await recordDataRoot(store, data);
974
- await recordRunEnv(store, runFacingNames((name) => secret(name) ?? base[name], Object.keys(base)));
1030
+ // Harness modules and recipes this start was given as options (--harness-module, --harness-recipe) are said under the
1031
+ // setting a runner apart reads them from, as an exported setting is: a runner without them would claim their runs and
1032
+ // have no harness to run them on.
1033
+ const startedWith = {
1034
+ [HARNESS_MODULES_SETTING]: options.harnessModules?.length ? options.harnessModules.join(",") : undefined,
1035
+ [HARNESS_RECIPES_SETTING]: options.harnessRecipes?.length ? options.harnessRecipes.join(",") : undefined,
1036
+ };
1037
+ await recordRunEnv(store, runFacingNames((name) => startedWith[name] ?? secret(name) ?? base[name], Object.keys(base)));
975
1038
  // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
976
1039
  // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled. A hosted machine a runner in a
977
1040
  // process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
@@ -1028,7 +1091,7 @@ async function startHolding(options, data, checked, stops) {
1028
1091
  // with whether each can be granted: a known meta tool can't (mcp-meta.ts).
1029
1092
  const mcpTools = (server) => {
1030
1093
  const saved = mcpMeta.get(server);
1031
- return saved && marked(saved.url, { tools: saved.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) })) }).tools;
1094
+ return saved && marked(saved.url, { tools: saved.tools.map(boundTool) }).tools;
1032
1095
  };
1033
1096
  // The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
1034
1097
  // once here.
@@ -1279,9 +1342,12 @@ async function startHolding(options, data, checked, stops) {
1279
1342
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
1280
1343
  * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
1281
1344
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
1282
- * is no shell), whose shell runs the shell tools; else none, and why. */
1283
- const shellHere = async () => {
1284
- if ((await shellOf({ kind: "none" })) === "local")
1345
+ * is no shell), whose shell runs the shell tools; else none, and why. A package that needs programs (`sandbox`) asks
1346
+ * for a sandbox alone, whose box a run checks for them: Archil's exec is none, so in Mode 2 it is told why no sandbox
1347
+ * answers (the Docker box can't mount Archil's workspaces), never given the exec. */
1348
+ const shellHere = async (wants = {}) => {
1349
+ const exec = (await shellOf({ kind: "none" })) === "local";
1350
+ if (exec && !wants.sandbox)
1285
1351
  return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
1286
1352
  const fresh = newAgentPlace(boxOffers);
1287
1353
  let why = "why" in fresh ? fresh.why : "it is not set up";
@@ -1293,14 +1359,18 @@ async function startHolding(options, data, checked, stops) {
1293
1359
  else if ((await shellOf(computer)) === "computer")
1294
1360
  return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
1295
1361
  }
1362
+ if (exec)
1363
+ return { none: `no sandbox answers here: Archil's serverless exec is no sandbox, and the docker box is unavailable here (${why})` };
1296
1364
  return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
1297
1365
  };
1298
1366
  /** Each package's computer list read against this server now, as a listing shows it (`computer_here`): what an apply
1299
1367
  * here would pick (pickComputer), the shell asked for once for them all. */
1300
1368
  const computerHere = async (packages) => {
1301
- const here = packages.some((one) => one.computer) ? await shellHere() : undefined;
1369
+ const here = packages.some((one) => one.computer && !one.needs) ? await shellHere() : undefined;
1370
+ const sandbox = packages.some((one) => one.computer && one.needs) ? await shellHere({ sandbox: true }) : undefined;
1302
1371
  return (pkg) => {
1303
- const pick = here && pickComputer(pkg, here);
1372
+ const shell = pkg.needs ? sandbox : here;
1373
+ const pick = shell && pickComputer(pkg, shell);
1304
1374
  if (!pick)
1305
1375
  return null;
1306
1376
  if ("refused" in pick)
@@ -1525,7 +1595,65 @@ async function startHolding(options, data, checked, stops) {
1525
1595
  refusedTimer.unref();
1526
1596
  // The runner beside this server, when its run isolation was refused (cli.ts): its word, kept in this store until the stop.
1527
1597
  let refusedBeside;
1598
+ const sourceWorkspaces = { data, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) };
1599
+ const localSources = new LocalSources(store, { secrets: () => [...serverSecrets(), sdkSecret, ...tokens.map(entry => entry.token)] });
1600
+ const sources = sourceService(store, sourceWorkspaces, async (entry, snapshot) => {
1601
+ const prepared = await prepareSource(snapshot, destinationPreparation(store, entry.agent.id, {
1602
+ env: () => env, boxes: () => boxOffers, check: revision => saveable(revision),
1603
+ // Readiness needs a successful probe, not capabilities' display fallback after a failed helper check.
1604
+ // A different runner repeats this prerequisite at claim, before its ownership helper changes any bytes/modes.
1605
+ projectExecution: async () => ({ isolation: runIsolationName(await runIsolationOf(base, 1, () => { })),
1606
+ storage: await loadArchilSettings(store, sourceWorkspaces.env) ? "archil" : "local" }),
1607
+ }));
1608
+ const prior = entry.revision?.body;
1609
+ // Main's corrections/workflow setting remains the owner's choice across the ownership cutover.
1610
+ return prior?.learning === undefined ? prepared : { ...prepared, revision: { ...prepared.revision,
1611
+ body: { ...prepared.revision.body, learning: prior.learning } } };
1612
+ }, async (entry, snapshot, prepared) => {
1613
+ const record = await sources.sync.get(entry.agent.id);
1614
+ if (!record)
1615
+ throw new ApiError("precondition_failed", "The source sync connection changed during preparation.");
1616
+ const revision = { ...prepared.revision, body: { ...prepared.revision.body, sourceSync: {
1617
+ id: record.id, snapshot: snapshot.digest, project: snapshot.digest, configuration: configurationDigest(prepared.revision.body),
1618
+ } } };
1619
+ // This private, unadmitted probe verifies the actual destination's modes, Git and assets before ownership moves.
1620
+ const placed = await sourceProjects.place({ agentId: entry.agent.id, runId: uuidv7(), revision,
1621
+ launch: { input: "", title: "Source preparation", place: resolvePlace(prepared.revision.body.place, { mode: "runner" }) } });
1622
+ await placed?.undo();
1623
+ }, agentId => localSources.authorize(agentId));
1624
+ const sourceProjects = projectPlacement({ snapshots: agentId => sourceSnapshotReader(store, agentId, sourceWorkspaces),
1625
+ hold: ({ agentId }) => beginSourceIO(store, agentId, "placement"),
1626
+ destination: target => openRunPlacement(store, target, sourceWorkspaces),
1627
+ placeUploads: async ({ runId, launch, workspace }) => {
1628
+ const { files, bytesOf } = await uploads.heldFiles(runId, launch.files ?? []);
1629
+ await uploads.copyInto(workspace, files, bytesOf);
1630
+ await uploads.release(runId);
1631
+ } });
1632
+ const localSourcePublisher = localSources.publisher(sources.sync, { agentWrite: (id, call) => agentWrite(id, call) });
1633
+ let localSourceSweep = Promise.resolve(), localSourceBusy = false;
1634
+ const sweepLocalSources = () => {
1635
+ if (localSourceBusy || stopping.signal.aborted)
1636
+ return localSourceSweep;
1637
+ localSourceBusy = true;
1638
+ localSourceSweep = localSourcePublisher.tick(stopping.signal).then(() => undefined).catch(() => {
1639
+ if (!stopping.signal.aborted)
1640
+ process.stderr.write("agentrun-serve: source setup sync could not finish; the last complete snapshot is retained. Check the source status and connection.\n");
1641
+ }).finally(() => { localSourceBusy = false; });
1642
+ return localSourceSweep;
1643
+ };
1644
+ const localSourceTimer = setInterval(() => void sweepLocalSources(), 30_000);
1645
+ localSourceTimer.unref();
1528
1646
  const startDeps = {
1647
+ project: { ...sourceProjects, place: async (given) => {
1648
+ try {
1649
+ return await sourceProjects.place(given);
1650
+ }
1651
+ catch (error) {
1652
+ if (error instanceof SnapshotError)
1653
+ throw new ApiError("agent_not_runnable", error.message);
1654
+ throw error;
1655
+ }
1656
+ } },
1529
1657
  // A start while every runner here refused to claim is refused in their words (runner/presence.ts).
1530
1658
  runnersRefused: refusedNow,
1531
1659
  runBodyIssues,
@@ -1596,6 +1724,12 @@ async function startHolding(options, data, checked, stops) {
1596
1724
  return [...serverSecrets(), ...pointers];
1597
1725
  };
1598
1726
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1727
+ // Which runs a learning folder's log names are purged, by each one's row (its purge time): the history reads serve none
1728
+ // of their merges.
1729
+ const purgedOf = async (runIds) => {
1730
+ const rows = await Promise.all(runIds.map((runId) => store.runs.get(runId)));
1731
+ return new Set(runIds.filter((_, i) => rows[i] !== undefined && rows[i].purgedAt !== null));
1732
+ };
1599
1733
  // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1600
1734
  const auditsOfAgent = async (agentId) => {
1601
1735
  const { workspace, end } = learningFolderOf(data, agentId);
@@ -1652,6 +1786,8 @@ async function startHolding(options, data, checked, stops) {
1652
1786
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1653
1787
  needAgent,
1654
1788
  momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
1789
+ // A trigger never messages a run on a plan-billed recipe: its turn would run on its owner's own sign-in.
1790
+ planRecipe: (harness) => recipeHarness(base, harness) === "plan",
1655
1791
  // Read when a firing's message is sent (declared below, with the delete turn).
1656
1792
  runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
1657
1793
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
@@ -1664,6 +1800,9 @@ async function startHolding(options, data, checked, stops) {
1664
1800
  const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
1665
1801
  return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
1666
1802
  },
1803
+ // Read as the server's environment stands now (a saved key changes it).
1804
+ ...(options.runKeys ? { keysOwed: (revision) => keysOwed(revision, env, []) } : {}),
1805
+ hooked: options.launchHook !== undefined,
1667
1806
  };
1668
1807
  const targets = triggerTargets(store, triggerDeps);
1669
1808
  // Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
@@ -1790,7 +1929,7 @@ async function startHolding(options, data, checked, stops) {
1790
1929
  // A template import reads GitHub's own hosts alone (a test's faux GitHub in their place), with an installation token of
1791
1930
  // the App when GitHub is connected (tokenForListing: metadata read, the least there is), else anonymously, and says why.
1792
1931
  const importDeps = {
1793
- registry, store,
1932
+ registry, store, apiOnly: options.apiOnly === true,
1794
1933
  reach: async (signal) => {
1795
1934
  const api = options.templateImportApi ?? GITHUB_API;
1796
1935
  const hosts = options.templateImportApi ? [new URL(options.templateImportApi).host] : GITHUB_HOSTS;
@@ -1803,6 +1942,9 @@ async function startHolding(options, data, checked, stops) {
1803
1942
  // is a server secret while it may be in use.
1804
1943
  mcpServers.appToken = (signal) => githubConnect.tokenForListing(signal);
1805
1944
  secretStores.add("github-tokens", () => githubConnect.liveTokens());
1945
+ /** Why a trigger of `kind` can't be on here now (its connection), or undefined: what a create of an enabled one is
1946
+ * refused with, and what an apply's plan says of the triggers it would make. */
1947
+ const triggerUnavailable = async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined);
1806
1948
  const triggers = new Triggers({
1807
1949
  // The server's own store (the one it opened) holds the triggers a person writes and reads; a test may inject another
1808
1950
  // (startServe's `store`).
@@ -1810,7 +1952,7 @@ async function startHolding(options, data, checked, stops) {
1810
1952
  clock: options.triggerClock,
1811
1953
  ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1812
1954
  adapters,
1813
- unavailable: async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined),
1955
+ unavailable: triggerUnavailable,
1814
1956
  // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1815
1957
  // A feed trigger's reach: where its reads may go, as an MCP server's requests may (mcp-oauth.ts feedAt), and a test's
1816
1958
  // or an eval's route to its fake feeds (feedsAt).
@@ -1828,6 +1970,7 @@ async function startHolding(options, data, checked, stops) {
1828
1970
  },
1829
1971
  // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1830
1972
  upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1973
+ ...(options.launchHook ? { launchHook: options.launchHook } : {}),
1831
1974
  });
1832
1975
  const composioTriggers = new ComposioTriggers({
1833
1976
  control: options.composioControl ?? {},
@@ -2218,7 +2361,7 @@ async function startHolding(options, data, checked, stops) {
2218
2361
  async function needRunnableAgent(id) {
2219
2362
  const entry = await needAgent(id);
2220
2363
  // Another system's agent is archived only by its delete (its archive route is refused).
2221
- if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2364
+ if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
2222
2365
  throw agentDeleting(id);
2223
2366
  if (entry.agent.archivedAt)
2224
2367
  throw new ApiError("agent_not_runnable", `The agent ${id} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
@@ -2287,7 +2430,7 @@ async function startHolding(options, data, checked, stops) {
2287
2430
  // A purged agent's row stays as its tombstone: a write that waited on its purge is 410, never a folder made again.
2288
2431
  if (entry.agent.purgedAt !== null)
2289
2432
  throw purgedAgent(entry.agent);
2290
- if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2433
+ if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
2291
2434
  throw agentDeleting(id);
2292
2435
  // A purge stopped part way (its mark still there): nothing of the agent is written, nor is it unarchived, until a
2293
2436
  // DELETE finishes it.
@@ -2434,12 +2577,26 @@ async function startHolding(options, data, checked, stops) {
2434
2577
  // The agent's folder (its runs' folders, its home, its learning folder) and its scratch folder.
2435
2578
  await rm(agentFolder(data, agentId), { recursive: true, force: true });
2436
2579
  await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
2580
+ // Private source metadata is owned by this exact agent. Prefix siblings with dotted IDs are left alone.
2581
+ for (const key of [`source-sync.agent.${agentId}`, `source-sync.local.${agentId}`])
2582
+ await store.settings.remove(key);
2583
+ for (const prefix of [`source-sync.tool.${agentId}.`, `source-sync.checkpoint.${agentId}.`]) {
2584
+ for (const row of await store.settings.all({ prefix }))
2585
+ if (/^[a-f0-9]{64}$/.test(row.key.slice(prefix.length)))
2586
+ await store.settings.remove(row.key);
2587
+ }
2437
2588
  await forgetKept("agent", agentId);
2438
2589
  },
2439
2590
  // The replay runs of its input, its audit's shadow run and a learning run it names (the store's), and its audit's shadow
2440
2591
  // run by its id (one whose launch is gone too).
2441
2592
  madeFrom: async (runId) => [...new Set([...(await store.runs.madeFrom(runId)), shadowRunId(runId)])],
2442
- forgetCopies: (agentId, runId) => forgetRunCopies(store.settings, agentId, runId),
2593
+ // Its copies in the agent's promotion records, then its text off the agent's learning folder's current files (its
2594
+ // merges' diff files and feedback lines), in the agent's queue: a folder that can't be written now is 503, the run
2595
+ // purged or kept as the purge had got, and the next DELETE does it again.
2596
+ forgetCopies: async (agentId, runId) => {
2597
+ await forgetRunCopies(store.settings, agentId, runId);
2598
+ await notYetWith(() => forgetRunLearning(data, agentId, runId), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
2599
+ },
2443
2600
  // /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
2444
2601
  // learning ended as /stats counts it (its state and reason alone).
2445
2602
  kept: async (runId) => {
@@ -2575,8 +2732,9 @@ async function startHolding(options, data, checked, stops) {
2575
2732
  /** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
2576
2733
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
2577
2734
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2578
- * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
2579
- async function runnable(revision, place, { capped = false, price = decisionPrice } = {}) {
2735
+ * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice).
2736
+ * `carried`: the names of the tool keys the run carries (run-keys.ts), each read as one this host holds. */
2737
+ async function runnable(revision, place, { capped = false, price = decisionPrice, carried = [] } = {}) {
2580
2738
  if (cliLearningOf(revision.body))
2581
2739
  throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
2582
2740
  if (sdkOf(revision.body))
@@ -2634,8 +2792,13 @@ async function startHolding(options, data, checked, stops) {
2634
2792
  });
2635
2793
  };
2636
2794
  const monid = revision.monidPin ?? undefined;
2795
+ // Under the run-keys setting, a template's tool key this host does not hold is each run's to carry: one that does not
2796
+ // is refused for it alone, before the checks that read the keys it would bring.
2797
+ const owed = options.runKeys ? keysOwed(revision, env, carried) : [];
2798
+ if (owed.length)
2799
+ throw keysOwedRefusal(owed);
2637
2800
  // Claude Code's login on this machine is a runner place's alone: a sandbox run is checked for a key, as it runs.
2638
- const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice: price });
2801
+ const blockers = await blockersOf(withCarried(envAtPlace(env, shape.place), carried), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice: price });
2639
2802
  if (!blockers.length)
2640
2803
  return;
2641
2804
  const message = blockers.map((b) => b.message).join(" ");
@@ -2839,7 +3002,7 @@ async function startHolding(options, data, checked, stops) {
2839
3002
  // Its last read and its commit in the agent's delete turn (agentWrite), the check outside it: an edit or a template
2840
3003
  // update whose commit comes once the agent is purged is 410, and one after a purge stopped part way is 409, nothing
2841
3004
  // written (the store refuses a purged agent's revision too, AgentPurged).
2842
- const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
3005
+ const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, prepare: prepareProjectSkillEdit(store, entry.agent.id, sourceWorkspaces), ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
2843
3006
  reconcileComputer(entry.agent.id);
2844
3007
  return { entry: edited, warnings };
2845
3008
  }
@@ -2863,6 +3026,7 @@ async function startHolding(options, data, checked, stops) {
2863
3026
  * reads it, cut of the host's secrets as the learning reads cut them, and a replay run's launch made as a run's start
2864
3027
  * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
2865
3028
  const replayAskOf = (entry) => ({
3029
+ admitAuxiliary: auxiliaryAdmitter(store, { data, project: startDeps.project }),
2866
3030
  store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
2867
3031
  folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
2868
3032
  launchOf: async (input) => {
@@ -2924,19 +3088,96 @@ async function startHolding(options, data, checked, stops) {
2924
3088
  return false;
2925
3089
  throw error;
2926
3090
  };
2927
- /** applyTemplate's work, in its turn on the agent where it has agent_id. */
2928
- async function applyWith(template, body) {
2929
- const { parameters, grants: asked, servers: picks, model: override, choice, approvals, agentId } = applyBodyOf(template, body);
3091
+ /** POST /templates/{id}/apply {dry_run: true}: the apply's plan, from the same reads and checks as the apply
3092
+ * (prepareApply), with nothing written: whether it makes an agent or revises the one agent_id names (and its current
3093
+ * revision), the keys and MCP servers this server lacks (where the apply would refuse with 409, the plan lists them),
3094
+ * what becomes of each trigger (made, changed in place, removed, or skipped for a connection this server lacks), and
3095
+ * the computer it picks. Any other refusal is the apply's own. */
3096
+ async function planTemplate(template, body) {
3097
+ const p = await prepareApply(template, body, { plan: true });
3098
+ // A monid grant is pinned to monid's listing when the agent is saved (saveable: monidPinOf), read with the monid key:
3099
+ // with none here the apply is refused, so the plan lists the key. A grant the agent's current pin carries reads
3100
+ // nothing (pinMonid with no key answers before any request).
3101
+ const definition = isObject(p.made.agent) && isObject(p.made.agent.definition) ? p.made.agent.definition : {};
3102
+ const tools = Array.isArray(definition.tools) ? definition.tools.filter((tool) => typeof tool === "string") : [];
3103
+ const was = p.onto?.revision?.kind === "agentic" ? p.onto.revision : undefined;
3104
+ const unread = !env[MONID_KEY_ENV]?.trim() && (await pinMonid(tools, { key: undefined, ...(was ? { previous: { grants: was.body.tools ?? [], pin: was.monidPin ?? null } } : {}) }));
3105
+ const missing = unread && "refused" in unread && !p.missing.includes(MONID_KEY_ENV) ? [...p.missing, MONID_KEY_ENV] : p.missing;
3106
+ const planned = [];
3107
+ for (const [i, trigger] of p.made.triggers.entries()) {
3108
+ const name = String(trigger.name).trim();
3109
+ const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
3110
+ // On an API-only server, skipped in the apply's own words (prepareApply).
3111
+ const hostSkip = p.hostless.get(i);
3112
+ if (hostSkip) {
3113
+ planned.push({ name, kind, action: "skip", reason: hostSkip.message });
3114
+ continue;
3115
+ }
3116
+ if (p.emptyFeeds.has(i)) {
3117
+ planned.push({ name, kind, action: "skip", reason: feedTriggerEmpty(p.pkg.name, trigger, isObject(p.pkg.triggers[i]?.source) ? p.pkg.triggers[i].source.urls : undefined) });
3118
+ continue;
3119
+ }
3120
+ const was = p.hadByName.get(name);
3121
+ if (was && isObject(was.source) && was.source.kind === kind && !p.remade.has(i)) {
3122
+ planned.push({ name, kind, action: "update" });
3123
+ continue;
3124
+ }
3125
+ // Made (again), on unless the owner had turned the old one off: a connection this server lacks skips it, as the
3126
+ // apply's create does (notSetUpYet), or refuses the apply. A Composio trigger is skipped for want of a public URL
3127
+ // (any trigger, on or off), read here; its account and subscription are Composio's to answer, which a plan never asks.
3128
+ const refusal = kind === "composio" && !options.publicUrl ? composioNoPublicUrl() : trigger.enabled !== false && !(was && !was.enabled) ? await triggerUnavailable(kind) : undefined;
3129
+ if (refusal && notSetUpYet(kind, refusal.code))
3130
+ planned.push({ name, kind, action: "skip", reason: refusal.message });
3131
+ else if (refusal)
3132
+ throw refusal;
3133
+ else
3134
+ planned.push({ name, kind, action: "create", ...(was ? { reason: `The agent's ${name} trigger is removed and made again: its kind or its Composio server, event or config changed.` } : {}) });
3135
+ }
3136
+ for (const row of p.removing)
3137
+ planned.push({ name: row.name, kind: isObject(row.source) ? String(row.source.kind) : "", action: "remove" });
3138
+ const computer = p.pick && !("refused" in p.pick) ? p.pick.computer : undefined;
3139
+ return {
3140
+ plan: {
3141
+ action: p.onto ? "revise" : "create",
3142
+ agent_id: p.onto?.agent.id ?? null,
3143
+ current_revision_id: p.onto?.revision?.id ?? null,
3144
+ missing_secrets: missing,
3145
+ unmatched_mcp: p.unsaved.map((need) => ({ source: need.source, toolkit: need.toolkit, required: need.required })),
3146
+ triggers: planned,
3147
+ computer: computer ? { kind: computer.kind, provider: computer.provider ?? null } : null,
3148
+ },
3149
+ };
3150
+ }
3151
+ /** What an apply reads and checks before its first write, the same for its plan (`plan`) and itself: the body
3152
+ * (applyBodyOf), the agent agent_id names, the keys and MCP servers, the computer, the model, the agent and triggers it
3153
+ * makes and how they meet the agent's, every refusal but the keys' and MCP servers' (which the plan lists). */
3154
+ async function prepareApply(template, body, { plan }) {
3155
+ const { parameters, grants: asked, servers: picks, model: override, choice, approvals, agentId, revision: expected, sha } = applyBodyOf(template, body);
3156
+ // The package the caller read (its sha): another stored under this id since (an upload of the same name) is not what
3157
+ // they planned or confirmed.
3158
+ if (sha !== undefined && (template.origin?.sha ?? null) !== sha)
3159
+ throw new ApiError("precondition_failed", `The ${template.name} template stored here is not the package of sha ${sha} (another was stored under ${template.id} since): nothing was changed. Read it again (GET /templates), then apply.`);
2930
3160
  // With agent_id, the apply writes a new revision of that agent (one this template made) in place of making another:
2931
- // everything below checks the package as a fresh apply does, through the same code.
3161
+ // everything below checks the package as a fresh apply does, through the same code. With `revision`, only onto the
3162
+ // revision the caller read: the write below is held to the revision read here (ifCurrent), so one written in between
3163
+ // is 412 as well.
2932
3164
  const onto = agentId === undefined ? undefined : await templateAgentOf(agentId, template);
3165
+ if (onto && expected !== undefined && (onto.revision?.id ?? null) !== expected)
3166
+ throw new ApiError("precondition_failed", `The agent ${onto.agent.id}'s current revision is ${onto.revision?.id ?? "none"}, not ${expected} (an edit, or another apply, wrote one since it was read): nothing was changed. Read it again, then apply.`);
2933
3167
  // An update's triggers are reconciled by name with the ones the agent has (below), read with the agent: each write to
2934
3168
  // one is made only while it is still this agent's (TriggerOwn.onAgent), so one a PATCH moves away meanwhile is left.
2935
3169
  const had = onto ? await store.triggers.list(onto.agent.id) : [];
2936
- if (onto && options.templateApplyRead)
3170
+ if (onto && !plan && options.templateApplyRead)
2937
3171
  await options.templateApplyRead(onto.agent.id);
2938
- // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2939
- const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
3172
+ // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made. Under
3173
+ // the run-keys setting, a tool key is each run's to carry (run-keys.ts): its agent is made, the warning says so, and a
3174
+ // run that does not carry it is refused. A model key is still the server's, and so is monid's: the agent's monid tools
3175
+ // are checked with it when the agent is saved (monidPinOf), before any run.
3176
+ const declared = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].sort();
3177
+ const absent = declared.filter((name) => !secret(name, storedKeys));
3178
+ const brought = options.runKeys ? absent.filter((name) => TOOL_FIELDS.includes(name) && name !== MONID_KEY_ENV) : [];
3179
+ const missing = absent.filter((name) => !brought.includes(name));
3180
+ const keyWarnings = brought.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server: it takes it from each run (${RUN_KEYS_ENV}=1), so a run that does not carry it in keys is refused.`, fix: `Send keys.${name} with each run, or add it in Settings → API Keys.` }));
2940
3181
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
2941
3182
  // one: several and no pick is a 422); the package's
2942
3183
  // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
@@ -2949,29 +3190,32 @@ async function startHolding(options, data, checked, stops) {
2949
3190
  // of a saved server that happens to be named as its toolkit.
2950
3191
  const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
2951
3192
  const needed = unsaved.filter((need) => need.required);
2952
- if (missing.length || needed.length) {
3193
+ if (!plan && (missing.length || needed.length)) {
2953
3194
  const fix = "Add it in Settings → API Keys, or set it where AgentRun starts, then apply the template again.";
2954
- throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
3195
+ throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: options.runKeys && name === MONID_KEY_ENV ? `${name} is not set on this server, and a run can't bring it (${RUN_KEYS_ENV}=1): the agent's monid tools are checked with this server's key when it is saved.` : `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
2955
3196
  }
2956
3197
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
2957
3198
  // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
2958
3199
  // whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
2959
- const pick = pickComputer(pkg, await shellHere());
3200
+ const pick = pickComputer(pkg, await shellHere({ sandbox: Boolean(pkg.needs) }));
2960
3201
  if (pick && "refused" in pick)
2961
- throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
3202
+ throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: pick.fix ?? COMPUTER_FIX }] });
2962
3203
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
2963
3204
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
2964
3205
  const skipped = unsaved.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}, so the agent was made without its tools (${need.tools.join(", ")}).`, fix: mcpSetUp(need) }));
2965
3206
  // A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
2966
- // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
2967
- const unrunnable = choice && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
3207
+ // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway. A plan whose keys are
3208
+ // missing lists them and goes on: a model refused for want of one of them is the same lack, and once they are added
3209
+ // the next plan reads the model again.
3210
+ const lacking = plan && missing.length > 0;
3211
+ const unrunnable = choice && !lacking && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
2968
3212
  if (choice && unrunnable) {
2969
3213
  const message = `The ${pkg.name} template's choice ${choice.label} runs ${choice.model} on ${choice.harness}, which this server can't run: ${unrunnable.replace(/\.$/, "")}. Nothing was created.`;
2970
3214
  throw new ApiError("agent_not_runnable", message, { fields: [{ field: "overrides.choice", reason: NOT_SET_UP, message, fix: "Apply with the default or another choice, or, where the model only wants a key, add it in Settings → Model keys." }] });
2971
3215
  }
2972
3216
  const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
2973
3217
  const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2974
- if ("refused" in picked && picked.refused) {
3218
+ if ("refused" in picked && picked.refused && !lacking) {
2975
3219
  const message = `The ${pkg.name} template prefers ${pkg.model?.prefer}, which this server can't run on ${harness ?? DEFAULT_HARNESS}: ${picked.refused.why}. Nothing was created.`;
2976
3220
  throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
2977
3221
  }
@@ -2995,15 +3239,26 @@ async function startHolding(options, data, checked, stops) {
2995
3239
  // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2996
3240
  // A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
2997
3241
  const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
2998
- const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !emptyFeeds.has(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
3242
+ // A trigger is made only when its firings have somewhere to go: on an API-only server, a schedule or a feed with the
3243
+ // launch hook set (api-only.ts); under the run-keys setting, for an agent whose runs owe keys, only with the launch
3244
+ // hook, the one way a firing's run carries them (run-keys.ts). Each other is said, and stays listed, so a trigger the
3245
+ // agent has by its name is left as it is, never removed.
3246
+ const hooked = options.launchHook !== undefined;
3247
+ const hostless = new Map(made.triggers.flatMap((trigger, i) => {
3248
+ const skip = (options.apiOnly ? apiOnlyTriggerSkipped(pkg.name, trigger, hooked) : undefined) ?? runKeysTriggerSkipped(pkg.name, trigger, brought, hooked);
3249
+ return skip ? [[i, skip]] : [];
3250
+ }));
3251
+ const unmade = (i) => emptyFeeds.has(i) || hostless.has(i);
3252
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !unmade(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
2999
3253
  if (refusedTriggers.length)
3000
3254
  throw invalid(refusedTriggers);
3001
3255
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
3002
3256
  for (const one of [made.agent, ...made.triggers])
3003
3257
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
3004
3258
  throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
3005
- // The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either).
3006
- const listed = new Set(made.triggers.flatMap((trigger, i) => (emptyFeeds.has(i) ? [] : [String(trigger.name).trim()])));
3259
+ // The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either,
3260
+ // except one an API-only server does not make, which leaves each the agent has: hostless above).
3261
+ const listed = new Set(made.triggers.flatMap((trigger, i) => (emptyFeeds.has(i) && !hostless.has(i) ? [] : [String(trigger.name).trim()])));
3007
3262
  // The triggers to remove: each of the agent's that an apply of this package marked as its own (TriggerRow.templateId)
3008
3263
  // and whose name the package no longer lists. A trigger the owner made, one a PATCH moved here from another agent (or
3009
3264
  // away and back), and one made before the mark was kept carry none, and are left. One whose removal fails keeps its
@@ -3018,7 +3273,7 @@ async function startHolding(options, data, checked, stops) {
3018
3273
  const resent = new Map();
3019
3274
  const remade = new Set();
3020
3275
  for (const [i, trigger] of made.triggers.entries()) {
3021
- const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
3276
+ const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
3022
3277
  if (!was || !isObject(trigger.source) || trigger.source.kind !== "composio" || !isObject(was.source) || was.source.kind !== "composio")
3023
3278
  continue;
3024
3279
  try {
@@ -3037,7 +3292,7 @@ async function startHolding(options, data, checked, stops) {
3037
3292
  // have to make again without being its own, or another package's, refuses the apply with nothing written (409 under
3038
3293
  // triggers.<i>): the owner renames or deletes it, then applies again.
3039
3294
  const notOurs = made.triggers.flatMap((trigger, i) => {
3040
- const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
3295
+ const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
3041
3296
  if (!was || was.templateId === pkg.id)
3042
3297
  return [];
3043
3298
  const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
@@ -3052,10 +3307,18 @@ async function startHolding(options, data, checked, stops) {
3052
3307
  if (notOurs.length)
3053
3308
  throw new ApiError("name_taken", notOurs.length === 1 ? notOurs[0].message : `${notOurs.length} of the agent's triggers have the names of the ${pkg.name} template's and are not its own. Nothing was changed: rename or delete each, then apply the template again.`, { fields: notOurs });
3054
3309
  // The agent keeps where it came from (the package on the revision the apply writes): the package's id, version and,
3055
- // imported, its SHA; and a keyed digest of the parameters it was given (never the parameters: one may be a credential).
3056
- // Which triggers are the package's is on each trigger (its mark), not here.
3310
+ // imported, its SHA; a keyed digest of the parameters it was given (never the parameters: one may be a credential); and
3311
+ // the names of the keys it declared (never a value), which an export names after the server's copy of the package
3312
+ // changes, and whose tool keys a run may carry (under the run-keys setting, a run that does not is refused). Which
3313
+ // triggers are the package's is on each trigger (its mark), not here.
3057
3314
  const digest = parametersDigest(sealKey, stable(parameters));
3058
- const origin = { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null, parameters_digest: digest };
3315
+ const origin = { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null, parameters_digest: digest, secrets: declared };
3316
+ return { pkg, onto, missing, unsaved, saved, mapped, grants, pick, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned: [...keyWarnings, ...skipped, ...kept, ...modelWarnings, ...computerWarnings] };
3317
+ }
3318
+ /** applyTemplate's work, in its turn on the agent where it has agent_id: prepareApply's reads and checks, then its
3319
+ * writes. */
3320
+ async function applyWith(template, body) {
3321
+ const { pkg, onto, saved, mapped, grants, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned } = await prepareApply(template, body, { plan: false });
3059
3322
  // A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
3060
3323
  // which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
3061
3324
  const twins = onto ? [] : (await agents.list())
@@ -3095,7 +3358,7 @@ async function startHolding(options, data, checked, stops) {
3095
3358
  const leftThere = [];
3096
3359
  try {
3097
3360
  for (const [i, trigger] of made.triggers.entries()) {
3098
- if (emptyFeeds.has(i))
3361
+ if (unmade(i))
3099
3362
  continue;
3100
3363
  const aimed = { ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } };
3101
3364
  let was = hadByName.get(String(trigger.name).trim());
@@ -3180,9 +3443,9 @@ async function startHolding(options, data, checked, stops) {
3180
3443
  const ticked = saved.map((need) => ({ ...need, tools: need.tools.filter((tool) => grants.includes(mcpToolName(need.server, tool))) }));
3181
3444
  const appShort = await appPermissionWarnings({ name: pkg.name, mcp: ticked }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
3182
3445
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
3183
- const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
3446
+ const hooks = made.triggers.flatMap((trigger, i) => (!hostless.has(i) && isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
3184
3447
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
3185
- const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
3448
+ const githubTriggers = made.triggers.flatMap((trigger, i) => (!hostless.has(i) && isObject(trigger.source) && trigger.source.kind === "github"
3186
3449
  ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
3187
3450
  : []));
3188
3451
  // Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
@@ -3191,7 +3454,9 @@ async function startHolding(options, data, checked, stops) {
3191
3454
  return refused && isObject(trigger.source) && trigger.source.kind === "composio" ? [{ field: `triggers.${i}`, reason: NOT_SET_UP, message: composioTriggerSkipped(pkg.name, trigger, refused.message), fix: COMPOSIO_TRIGGER_FIX }] : [];
3192
3455
  });
3193
3456
  // Each feed trigger it skipped for want of a feed: which, and the parameter to set.
3194
- const feedsSkipped = [...emptyFeeds].map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: feedTriggerEmpty(pkg.name, made.triggers[i], isObject(pkg.triggers[i]?.source) ? pkg.triggers[i].source.urls : undefined) }));
3457
+ const feedsSkipped = [...emptyFeeds].filter((i) => !hostless.has(i)).map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: feedTriggerEmpty(pkg.name, made.triggers[i], isObject(pkg.triggers[i]?.source) ? pkg.triggers[i].source.urls : undefined) }));
3458
+ // Each trigger an API-only server does not make: not_set_up_here when the launch hook would make it, else not_an_option.
3459
+ const hostSkipped = [...hostless].map(([i, { reason, message }]) => ({ field: `triggers.${i}`, reason, message }));
3195
3460
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
3196
3461
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
3197
3462
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
@@ -3200,7 +3465,7 @@ async function startHolding(options, data, checked, stops) {
3200
3465
  // What the apply did to the agent: made it, wrote a new revision, or wrote none (an update whose package and
3201
3466
  // parameters the current revision already holds: commitAgent keeps that revision).
3202
3467
  const agentChange = !onto ? "made" : entry.revision?.id === onto.revision?.id ? "unchanged" : "updated";
3203
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, agent_change: agentChange, servers: used, triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
3468
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_id: entry.revision?.id ?? null, revision_version: entry.version, agent_change: agentChange, servers: used, triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...warned, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...hostSkipped, ...leftThere, ...appShort, ...twins] };
3204
3469
  return { applied, minted, updated: onto !== undefined };
3205
3470
  }
3206
3471
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -3259,11 +3524,13 @@ async function startHolding(options, data, checked, stops) {
3259
3524
  * bound to its server's origin then and the model key to the gateway's (AGENT_MODEL_BASE_URL). `handed` is called only
3260
3525
  * for new work, inside the request's idempotent work: there each mcp_auth entry must name a saved per_run server, and
3261
3526
  * the model key must be text, else 422, nothing written. A retry its key already answered replays that answer even
3262
- * when the server has since changed or gone, since it does no new work. */
3527
+ * when the server has since changed or gone, since it does no new work. `keys`, the run's own tool keys (run-keys.ts),
3528
+ * go the same way: each a tool key name to its value as text, else 422 by name, never with the value; whether the
3529
+ * run's revision reads each is its start's check (prepareLaunch), by name alone. */
3263
3530
  function handedLaunchSecrets(body) {
3264
- if (body.mcp_auth === undefined && body.model_key === undefined)
3531
+ if (body.mcp_auth === undefined && body.model_key === undefined && body.keys === undefined)
3265
3532
  return { body, handed: async () => ({}) };
3266
- const { mcp_auth, model_key, ...rest } = body;
3533
+ const { mcp_auth, model_key, keys: given, ...rest } = body;
3267
3534
  const handed = async () => {
3268
3535
  const issues = [];
3269
3536
  const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
@@ -3289,12 +3556,16 @@ async function startHolding(options, data, checked, stops) {
3289
3556
  issues.push({ field, reason: "not_an_option", message: perRunComposio ? `The MCP server ${server} takes a Composio account from each run, not headers: send {"composio_user_id": "<user>", "connected_account_id": "ca_..."} (the account optional).` : `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` });
3290
3557
  }
3291
3558
  const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
3559
+ const keys = given === undefined ? undefined : runKeysOf(given, issues);
3292
3560
  if (issues.length)
3293
3561
  throw invalid(issues);
3294
- return { ...(mcp_auth !== undefined ? { mcp: auth } : {}), ...(model !== undefined ? { model } : {}) };
3562
+ // Empty keys are kept: on a message they replace the run's keys with none (on a start, none is what it has).
3563
+ return { ...(mcp_auth !== undefined ? { mcp: auth } : {}), ...(model !== undefined ? { model } : {}), ...(keys !== undefined ? { keys } : {}) };
3295
3564
  };
3296
3565
  return { body: rest, handed };
3297
3566
  }
3567
+ /** The start option naming the tool keys `handed` carries, by name (runs-over-store StartOptions.keys). */
3568
+ const carriedOf = (handed) => (handed.keys ? { keys: Object.keys(handed.keys) } : {});
3298
3569
  /** The 422 for a model key where the run's model never takes it (run-model-key.ts modelKeyMisfit), at `model_key`. */
3299
3570
  const misfit = (why) => invalid([{ field: "model_key", reason: "not_an_option", message: why }]);
3300
3571
  /** A start's launch seal of `handed` (handedLaunchSecrets), made once the start prepared the run's launch: a model key
@@ -3302,7 +3573,7 @@ async function startHolding(options, data, checked, stops) {
3302
3573
  * is refused where the server holds no key for the run's route (serverKeyMissing). Undefined when nothing is handed:
3303
3574
  * the start's own check (runs-over-store keyedOrRefused) refuses that one where it has no key to spend. */
3304
3575
  function startSeal(handed) {
3305
- if (handed.mcp === undefined && handed.model === undefined)
3576
+ if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined)
3306
3577
  return undefined;
3307
3578
  return (runId, launch, kind) => {
3308
3579
  const target = { kind, model: launch.model, native: Boolean(launch.native) };
@@ -3314,7 +3585,7 @@ async function startHolding(options, data, checked, stops) {
3314
3585
  else if (serverKeyMissing(env, target))
3315
3586
  throw modelKeyRequired(false);
3316
3587
  const origin = runModelOrigin(env);
3317
- return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}) });
3588
+ return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}), ...(handed.keys ? { keys: handed.keys } : {}) });
3318
3589
  };
3319
3590
  }
3320
3591
  /** A message's launch secrets for run `run` (its kind and launch as stored): what it hands replaces that part of the
@@ -3322,7 +3593,10 @@ async function startHolding(options, data, checked, stops) {
3322
3593
  * part it does not hand is kept as the run holds it (none after its turn's end erased it). A model key is refused
3323
3594
  * where the run's model never takes it. One is required where the server holds no key for the run's route and the
3324
3595
  * run holds none when the message is written (its last turn ended): 422 model_key_required from inside that write,
3325
- * which then writes nothing, so a turn never starts with no key to spend. */
3596
+ * which then writes nothing, so a turn never starts with no key to spend. Its `keys` replace the run's whole, each one
3597
+ * its revision reads (else 422 by name); under the run-keys setting, a message that would leave the run without a tool
3598
+ * key its template declared and this host does not hold (its last turn's end erased them) is refused, 409, nothing
3599
+ * written. */
3326
3600
  async function messageSeal(run, handed) {
3327
3601
  const launch = readLaunchBody((await store.runs.launch(run.id)).body);
3328
3602
  const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
@@ -3331,22 +3605,51 @@ async function startHolding(options, data, checked, stops) {
3331
3605
  if (why)
3332
3606
  throw misfit(why);
3333
3607
  }
3608
+ const row = handed.keys || options.runKeys ? await store.runs.get(run.id) : undefined;
3609
+ const revision = row ? await store.agents.revision(row.revisionId) : undefined;
3610
+ if (handed.keys) {
3611
+ const undeclared = undeclaredKeys(Object.keys(handed.keys), revision ? await declaredKeys(revision) : []);
3612
+ if (undeclared.length)
3613
+ throw invalid(undeclared);
3614
+ }
3615
+ const owed = options.runKeys && revision ? packageKeysOf(revision).filter((name) => !env[name]) : [];
3334
3616
  const needsKey = handed.model === undefined && serverKeyMissing(env, target);
3335
- if (handed.mcp === undefined && handed.model === undefined && !needsKey)
3617
+ if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined && !needsKey && !owed.length)
3336
3618
  return undefined;
3337
3619
  const origin = runModelOrigin(env);
3338
3620
  return (current) => {
3339
3621
  const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
3340
3622
  const mcp = handed.mcp ?? held.mcp;
3341
3623
  const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
3624
+ const keys = handed.keys ?? held.keys;
3342
3625
  if (!model && needsKey)
3343
3626
  throw modelKeyRequired(true);
3344
- return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}) });
3627
+ const unpaid = revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
3628
+ if (owed.length && unpaid.length)
3629
+ throw new ApiError("agent_not_runnable", unpaid.map((one) => one.message).join(" "), { fields: unpaid });
3630
+ return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) });
3345
3631
  };
3346
3632
  }
3347
3633
  async function createRun(req, agentId) {
3348
3634
  const entry = await needRunnableAgent(agentId);
3349
3635
  const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3636
+ // The host's run for a firing the launch hook handed it: the firing's own run, under the firing's key (a second start
3637
+ // answers that run), with the trigger, input origin and title a start here would give it, and capped as a trigger's
3638
+ // run is. The firing is its key, so it takes no Idempotency-Key, whose check across a restart is the run's origin.
3639
+ if (body.trigger_firing !== undefined) {
3640
+ if (req.headers["idempotency-key"] !== undefined)
3641
+ throw invalid([{ field: "trigger_firing", reason: "not_allowed", message: "A run for a trigger firing is keyed by the firing, and a second start answers its run: send it without Idempotency-Key." }]);
3642
+ const { trigger_firing: given, ...rest } = body;
3643
+ const firing = await triggers.handedStart(given, agentId);
3644
+ if ("run_id" in firing)
3645
+ return { status: 202, body: await viewOverStore(store, firing.run_id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${firing.run_id}`, "idempotent-replayed": "true" } };
3646
+ const secrets = await handed();
3647
+ const seal = startSeal(secrets);
3648
+ const run = await startRunOf(entry, rest, { origin: { key: firing.key }, trigger: firing.trigger, from: firing.from, title: firing.title, capped: !nativeOf(entry.revision?.body), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3649
+ // A host that answered its hook first started this run after: the firing is started with it now.
3650
+ await triggers.handedRan(firing.trigger.id, firing.key, run.id);
3651
+ return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3652
+ }
3350
3653
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
3351
3654
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
3352
3655
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -3356,8 +3659,9 @@ async function startHolding(options, data, checked, stops) {
3356
3659
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
3357
3660
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
3358
3661
  }
3359
- const seal = startSeal(await handed());
3360
- const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
3662
+ const secrets = await handed();
3663
+ const seal = startSeal(secrets);
3664
+ const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3361
3665
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
3362
3666
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3363
3667
  });
@@ -3413,8 +3717,9 @@ async function startHolding(options, data, checked, stops) {
3413
3717
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
3414
3718
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
3415
3719
  }
3416
- const seal = startSeal(await handed());
3417
- const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
3720
+ const secrets = await handed();
3721
+ const seal = startSeal(secrets);
3722
+ const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
3418
3723
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
3419
3724
  });
3420
3725
  }
@@ -4187,19 +4492,72 @@ async function startHolding(options, data, checked, stops) {
4187
4492
  await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
4188
4493
  return send(res, 200, await broker.revoke(connectorId));
4189
4494
  }
4190
- if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
4495
+ if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand", "grantSourceSync", "publishSourceSync", "sourceSyncFailure"].includes(found.name)) {
4191
4496
  const parts = found.pattern.exec(path);
4192
4497
  const connectorId = decodeURIComponent(parts[1]);
4193
4498
  const broker = new RemoteConnectors(store);
4194
4499
  await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
4195
4500
  // History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
4196
4501
  const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
4197
- : found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : MAX_BODY;
4502
+ : found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : found.name === "publishSourceSync" ? SOURCE_BODY_BYTES : MAX_BODY;
4198
4503
  const body = await bodyOf(req, limit);
4199
4504
  if (found.name === "importRemoteTarget")
4200
- return send(res, 200, await broker.importTarget(connectorId, body));
4505
+ return send(res, 200, await broker.importTarget(connectorId, body, cliAdoptionResolver(store, new CliLearningConnections(store, sdkSecret))));
4201
4506
  if (found.name === "importRemoteHistory")
4202
4507
  return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [...tokens.map((entry) => entry.token), String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
4508
+ if (["grantSourceSync", "publishSourceSync", "sourceSyncFailure"].includes(found.name)) {
4509
+ const targetId = decodeURIComponent(parts[2]), target = await broker.syncAuthority(connectorId, targetId);
4510
+ const scoped = sources.forConnector(broker, connectorId, targetId);
4511
+ if (found.name === "grantSourceSync") {
4512
+ if (Object.keys(body).length)
4513
+ throw new ApiError("input_invalid", "A sync grant takes an empty object; export authority comes from connector enrollment.");
4514
+ const granted = await agentWrite(target.agentId, async () => {
4515
+ const record = await scoped.grant(target.agentId);
4516
+ // Account/environment prerequisites can recover while source bytes stay unchanged.
4517
+ try {
4518
+ await scoped.reconcile(target.agentId);
4519
+ }
4520
+ catch (error) {
4521
+ if (!(error instanceof SourcePreparationError) && !(error instanceof ApiError && error.status < 500))
4522
+ throw error;
4523
+ }
4524
+ return record;
4525
+ });
4526
+ return send(res, 200, granted);
4527
+ }
4528
+ const allowed = found.name === "publishSourceSync" ? ["generation", "sequence", "snapshot"] : ["generation", "sequence", "code"];
4529
+ if (Object.keys(body).some(key => !allowed.includes(key)) || typeof body.generation !== "string" || !Number.isSafeInteger(body.sequence) || Number(body.sequence) < 0)
4530
+ throw new ApiError("input_invalid", "Supply the current sync generation and a non-negative sequence.");
4531
+ if (found.name === "sourceSyncFailure") {
4532
+ if (typeof body.code !== "string" || !Object.hasOwn(SOURCE_FAILURES, body.code))
4533
+ throw new ApiError("input_invalid", "Choose a supported source failure code.");
4534
+ return send(res, 200, await agentWrite(target.agentId, () => scoped.failed(target.agentId, { generation: body.generation, sequence: Number(body.sequence), code: body.code })));
4535
+ }
4536
+ if (!isObject(body.snapshot))
4537
+ throw new ApiError("input_invalid", "Supply a complete source snapshot envelope.");
4538
+ try {
4539
+ // Even an idempotent replay must carry a valid bounded envelope; a matching digest is not validation.
4540
+ validateSourceSnapshot(body.snapshot);
4541
+ const saved = await agentWrite(target.agentId, async () => {
4542
+ const published = await scoped.publish(target.agentId, { generation: body.generation, sequence: Number(body.sequence), snapshot: body.snapshot });
4543
+ // Publication is durable even when a new setup cannot yet be applied; the owner sees its readiness reason.
4544
+ try {
4545
+ await scoped.reconcile(target.agentId);
4546
+ }
4547
+ catch (error) {
4548
+ if (!(error instanceof SourcePreparationError) && !(error instanceof ApiError && error.status < 500))
4549
+ throw error;
4550
+ }
4551
+ return published;
4552
+ });
4553
+ return send(res, 200, saved);
4554
+ }
4555
+ catch (error) {
4556
+ if (error instanceof SnapshotError)
4557
+ throw new ApiError("input_invalid", error.message);
4558
+ throw error;
4559
+ }
4560
+ }
4203
4561
  if (found.name === "pollRemoteConnector")
4204
4562
  return send(res, 200, await broker.poll(connectorId, body));
4205
4563
  const commandId = decodeURIComponent(parts[2]);
@@ -4285,7 +4643,14 @@ async function startHolding(options, data, checked, stops) {
4285
4643
  case "enrollCliLearning": {
4286
4644
  if (!isLoopback(req.socket.remoteAddress ?? ""))
4287
4645
  throw new ApiError("forbidden", "CLI learning enrollment must come from the local source machine.");
4288
- return send(res, 201, await new CliLearningConnections(store, sdkSecret).enroll(await bodyOf(req)));
4646
+ const { source_sync, ...body } = await bodyOf(req);
4647
+ const connection = await new CliLearningConnections(store, sdkSecret).enroll(body);
4648
+ if (source_sync !== undefined) {
4649
+ await localSources.grant(connection.agent_id, source_sync);
4650
+ await sources.sync.grant(connection.agent_id);
4651
+ void sweepLocalSources();
4652
+ }
4653
+ return send(res, 201, connection);
4289
4654
  }
4290
4655
  case "listCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).list());
4291
4656
  case "revokeCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).revoke(id));
@@ -4319,6 +4684,64 @@ async function startHolding(options, data, checked, stops) {
4319
4684
  throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
4320
4685
  return send(res, 200, await new Observations(store, Date.now, new ObservationLearning(store, new CliLearningConnections(store, sdkSecret), learning !== "off")).snapshot(days, url.searchParams.get("session_id") ?? undefined));
4321
4686
  }
4687
+ case "getSourceSync": return send(res, 200, await sources.status(id));
4688
+ case "reviewSourceProject": {
4689
+ const body = await bodyOf(req), entry = await needAgent(id);
4690
+ if (!sourceSyncOf(entry.revision?.body))
4691
+ throw new ApiError("input_invalid", "This agent has no moved project to review.");
4692
+ if (Object.keys(body).length !== 1 || !Object.hasOwn(body, "receipts"))
4693
+ throw new ApiError("input_invalid", "Choose the unresolved run receipts you reviewed.");
4694
+ await reconcileProjectCheckpoints(store, id);
4695
+ await acknowledgeProjects(store, id, body.receipts);
4696
+ return send(res, 200, await sources.status(id));
4697
+ }
4698
+ case "setSourceSync": {
4699
+ const body = await bodyOf(req);
4700
+ if (Object.keys(body).length !== 1 || typeof body.enabled !== "boolean")
4701
+ throw new ApiError("input_invalid", "Set enabled to true or false.");
4702
+ await sources.sync.setEnabled(id, body.enabled);
4703
+ return send(res, 200, await sources.status(id));
4704
+ }
4705
+ case "moveSourceAgent": {
4706
+ const body = await bodyOf(req);
4707
+ if (Object.keys(body).length)
4708
+ throw new ApiError("input_invalid", "Move takes an empty object and uses the latest complete synchronized setup.");
4709
+ try {
4710
+ const entry = await agentWrite(id, () => sources.sync.move(id));
4711
+ return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), source: await sources.status(id) });
4712
+ }
4713
+ catch (error) {
4714
+ if (error instanceof SourcePreparationError || error instanceof SnapshotError)
4715
+ throw new ApiError("agent_not_runnable", error.message);
4716
+ throw error;
4717
+ }
4718
+ }
4719
+ case "resolveSourceSync": {
4720
+ const body = await bodyOf(req);
4721
+ if (Object.keys(body).some(key => !["revision", "snapshot"].includes(key)) || typeof body.revision !== "string" || typeof body.snapshot !== "string")
4722
+ throw new ApiError("input_invalid", "Choose the source snapshot and current agent revision you reviewed.");
4723
+ try {
4724
+ const entry = await agentWrite(id, () => sources.sync.useSource(id, { revision: body.revision, snapshot: body.snapshot }));
4725
+ return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), source: await sources.status(id) });
4726
+ }
4727
+ catch (error) {
4728
+ if (error instanceof SourcePreparationError || error instanceof SnapshotError)
4729
+ throw new ApiError("agent_not_runnable", error.message);
4730
+ throw error;
4731
+ }
4732
+ }
4733
+ case "bindSourceTool": {
4734
+ const body = await bodyOf(req), record = await sources.sync.get(id);
4735
+ if (Object.keys(body).some(key => !["tool", "server"].includes(key)) || typeof body.tool !== "string" || typeof body.server !== "string")
4736
+ throw new ApiError("input_invalid", "Choose a source tool and its destination connection.");
4737
+ if (!record?.snapshot)
4738
+ throw new ApiError("agent_not_runnable", "Sync the complete setup before choosing its tool connections.");
4739
+ const snapshot = await sources.sync.options.read(id, record.snapshot), requirement = snapshot.configuration.tools.find(tool => tool.name === body.tool);
4740
+ if (!requirement)
4741
+ throw new ApiError("input_invalid", "Choose a tool required by this source setup.");
4742
+ await bindSourceTool(store, id, requirement, body.server);
4743
+ return send(res, 200, await sources.status(id));
4744
+ }
4322
4745
  case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
4323
4746
  case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
4324
4747
  case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
@@ -4329,7 +4752,13 @@ async function startHolding(options, data, checked, stops) {
4329
4752
  return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
4330
4753
  }
4331
4754
  case "connectNative": {
4332
- const entry = await connectNative(store, await bodyOf(req));
4755
+ const { source_sync, ...body } = await bodyOf(req);
4756
+ const entry = await connectNative(store, body);
4757
+ if (source_sync !== undefined) {
4758
+ await localSources.grant(entry.agent.id, source_sync);
4759
+ await sources.sync.grant(entry.agent.id);
4760
+ void sweepLocalSources();
4761
+ }
4333
4762
  return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
4334
4763
  }
4335
4764
  case "getNative": {
@@ -4349,6 +4778,7 @@ async function startHolding(options, data, checked, stops) {
4349
4778
  const native = nativeOf(entry.revision?.body);
4350
4779
  if (!native)
4351
4780
  throw new ApiError("not_found", "This agent has no native connection.");
4781
+ await localSources.revoke(id);
4352
4782
  const changed = await updateNative(store, entry, { ...native, connected: false });
4353
4783
  if (native.remote)
4354
4784
  await new RemoteConnectors(store).disconnectTarget(native);
@@ -4439,6 +4869,32 @@ async function startHolding(options, data, checked, stops) {
4439
4869
  const page = all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row));
4440
4870
  return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
4441
4871
  }
4872
+ case "getAgentPackage": {
4873
+ const entry = await needAgent(id);
4874
+ const { agent, revision } = entry;
4875
+ // An agent whose source is somewhere else has no package here: its project or application holds it.
4876
+ const body = (revision?.body ?? {});
4877
+ const elsewhere = ownedElsewhere(agent) ? "another system's agent, which that system defines" : body.native ? "a native agent, which its project on its own machine defines" : body.cli_learning ? "a CLI learning agent, which its CLI's sessions define" : body.sdk ? "an SDK agent, which its application's code defines" : undefined;
4878
+ if (elsewhere)
4879
+ throw new ApiError("not_exportable", `The agent ${id} is ${elsewhere}: export it from there.`);
4880
+ if (!revision || revision.kind !== "agentic")
4881
+ throw new ApiError("not_exportable", `The agent ${id} ${revision ? "is a workflow, and a template package holds an agent" : "has no revision to export"}.`);
4882
+ // Its triggers: those that start its runs and those that message one of them (each row names the agent it runs as).
4883
+ const own = new Set((await store.triggers.list(id)).map((row) => row.id));
4884
+ const views = (await triggers.list()).triggers.filter((view) => own.has(view.id));
4885
+ const answer = agentPackage({
4886
+ agent: { id, name: agent.name, description: agent.description ?? null },
4887
+ definition: definitionOf(agent, revision, entry.version),
4888
+ skills: (isObject(revision.skills) ? revision.skills : {}),
4889
+ template: entry.template ? { id: entry.template.id, version: entry.template.version, ...(entry.template.secrets ? { secrets: entry.template.secrets } : {}) } : null,
4890
+ origin: entry.template ? registry.get(entry.template.id) : undefined,
4891
+ servers: mcpMeta,
4892
+ triggers: views,
4893
+ signIns: await store.signIns.list(id),
4894
+ now: options.triggerClock?.now() ?? Date.now(),
4895
+ });
4896
+ return send(res, 200, answer);
4897
+ }
4442
4898
  case "setCurrent": {
4443
4899
  // The body read first, outside the agent's delete turn; the move made in it (agentWrite), as an edit's revision is:
4444
4900
  // one whose body arrives while the agent is purged is 410 (the store refuses it too, AgentPurged).
@@ -4454,6 +4910,8 @@ async function startHolding(options, data, checked, stops) {
4454
4910
  const candidate = await agents.revision(id, revision);
4455
4911
  if (!candidate)
4456
4912
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
4913
+ if (sourceSyncOf(candidate.revision.body)?.id !== sourceSyncOf(entry.revision?.body)?.id)
4914
+ throw new ApiError("input_invalid", "A revision restore cannot change this agent’s source ownership. Keep a revision from after Move.");
4457
4915
  if (stable(cliLearningOf(candidate.revision.body)) !== stable(cliLearningOf(entry.revision?.body)))
4458
4916
  throw new ApiError("input_invalid", "A revision restore cannot change the enrolled CLI learning connection.");
4459
4917
  if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
@@ -4474,16 +4932,23 @@ async function startHolding(options, data, checked, stops) {
4474
4932
  case "deleteAgent": {
4475
4933
  // Another system's agent deleted whole; one made here purged once archived (agent-delete.ts). One delete of an agent
4476
4934
  // at a time, the agent read in its turn, so a DELETE after one that finished is 404 (deleted) or 204 (purged).
4477
- await deleteInTurn(id, async () => {
4478
- const { agent } = await needAgent(id);
4479
- if (agent.purgedAt !== null)
4480
- return purgedAgain(agentDeleteHost, id);
4481
- if (ownedElsewhere(agent))
4482
- return deleteExternalAgent(agentDeleteHost, id);
4483
- if (agent.archivedAt === null)
4484
- throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
4485
- await purgeAgent(agentDeleteHost, id);
4486
- });
4935
+ try {
4936
+ await deleteInTurn(id, async () => {
4937
+ const { agent } = await needAgent(id);
4938
+ if (agent.purgedAt !== null)
4939
+ return;
4940
+ if (ownedElsewhere(agent))
4941
+ return deleteExternalAgent(agentDeleteHost, id);
4942
+ if (agent.archivedAt === null)
4943
+ throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
4944
+ await purgeAgent(agentDeleteHost, id);
4945
+ });
4946
+ }
4947
+ finally {
4948
+ // An upload its purge took with it is no longer served: also after a purge that committed and then failed, and on
4949
+ // the DELETE sent again. A store that cannot answer leaves it to the next DELETE, or the next start's load.
4950
+ await dropRemovedUploads({ registry, store }).catch(() => undefined);
4951
+ }
4487
4952
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4488
4953
  return void res.end();
4489
4954
  }
@@ -4498,7 +4963,10 @@ async function startHolding(options, data, checked, stops) {
4498
4963
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
4499
4964
  // In the agent's delete turn (agentWrite): an unarchive sent while its purge runs waits for it and is 410, so no
4500
4965
  // run of it starts between the purge's live check and its tombstone.
4501
- const triggersOff = await agentWrite(id, () => (found.name === "archiveAgent" ? triggers.agentArchived(id) : triggers.agentUnarchived(id)));
4966
+ // On an API-only server with the launch hook, which serves no trigger route to turn one on, the unarchive turns its
4967
+ // schedule and feed triggers on again (the ones its apply makes there).
4968
+ const turnOn = options.apiOnly && options.launchHook ? (source) => API_ONLY_HOOKED_KINDS.has(source.kind) : undefined;
4969
+ const triggersOff = await agentWrite(id, () => (found.name === "archiveAgent" ? triggers.agentArchived(id) : triggers.agentUnarchived(id, turnOn)));
4502
4970
  // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
4503
4971
  if (found.name === "archiveAgent")
4504
4972
  reconcileComputer(id);
@@ -4512,7 +4980,7 @@ async function startHolding(options, data, checked, stops) {
4512
4980
  const entry = await needAgent(id);
4513
4981
  const controller = new AbortController();
4514
4982
  req.once("close", () => controller.abort());
4515
- const agent = { id, archived: entry.agent.archivedAt != null, external: entry.agent.externalRef !== null, liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
4983
+ const agent = { id, archived: entry.agent.archivedAt != null, external: ownedElsewhere(entry.agent), liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
4516
4984
  return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
4517
4985
  }
4518
4986
  case "forgetSignIn": {
@@ -4600,7 +5068,8 @@ async function startHolding(options, data, checked, stops) {
4600
5068
  }
4601
5069
  case "deleteRun": {
4602
5070
  // In its agent's delete turn (an agent's delete or purge, or another purge of one of its runs, finishes first), the
4603
- // run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run is no work).
5071
+ // run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run's only work is
5072
+ // its learning folder's scrub, again).
4604
5073
  const row = ID.test(id) ? await store.runs.get(id) : undefined;
4605
5074
  if (!row)
4606
5075
  throw new ApiError("not_found", `no run ${id}`);
@@ -5100,6 +5569,9 @@ async function startHolding(options, data, checked, stops) {
5100
5569
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
5101
5570
  case "listMcpServers":
5102
5571
  return send(res, 200, await mcpServers.list());
5572
+ // Names only: no URL, auth type, header, tool or Composio record, so a token that may not read the list may read this.
5573
+ case "listMcpServerNames":
5574
+ return send(res, 200, { names: (await listMcpServers(store)).map((row) => row.name).sort() });
5103
5575
  case "getMcpServer":
5104
5576
  return send(res, 200, await mcpServers.get(id));
5105
5577
  case "previewMcpServer":
@@ -5255,7 +5727,7 @@ async function startHolding(options, data, checked, stops) {
5255
5727
  const costStop = await costStopOverStore(store, id);
5256
5728
  const body = entry.revision?.body;
5257
5729
  const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
5258
- return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)), learning_model: await learningModelOf(modelEnv, entry.revision) });
5730
+ return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop), purgedOf), learning_model: await learningModelOf(modelEnv, entry.revision) });
5259
5731
  }
5260
5732
  case "getLearningCost": {
5261
5733
  await needAgent(id);
@@ -5296,7 +5768,7 @@ async function startHolding(options, data, checked, stops) {
5296
5768
  const champion = championOf(records, workflow);
5297
5769
  const record = champion?.digest === digest ? champion : undefined;
5298
5770
  const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
5299
- const read = await workflowAtDigest(data, id, workflow, digest, commits).catch(() => undefined);
5771
+ const read = await workflowAtDigest(data, id, workflow, digest, commits, store).catch(() => undefined);
5300
5772
  let doc;
5301
5773
  try {
5302
5774
  doc = read ? JSON.parse(read.text) : undefined;
@@ -5342,7 +5814,7 @@ async function startHolding(options, data, checked, stops) {
5342
5814
  }
5343
5815
  case "listLearningLog":
5344
5816
  await needAgent(id);
5345
- return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
5817
+ return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), purgedOf));
5346
5818
  case "getLearningCorrections": {
5347
5819
  await needAgent(id);
5348
5820
  // corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
@@ -5369,10 +5841,10 @@ async function startHolding(options, data, checked, stops) {
5369
5841
  }
5370
5842
  case "listLearnedWorkflowRevisions":
5371
5843
  await needAgent(id);
5372
- return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
5844
+ return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), purgedOf));
5373
5845
  case "readLearningFile":
5374
5846
  await needAgent(id);
5375
- return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id)));
5847
+ return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id), store));
5376
5848
  case "retireLearningFile":
5377
5849
  case "approveLearningFile":
5378
5850
  case "restoreLearningFile": {
@@ -5495,14 +5967,27 @@ async function startHolding(options, data, checked, stops) {
5495
5967
  return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
5496
5968
  }
5497
5969
  case "importTemplate": {
5498
- // Read from GitHub and checked; a dry run answers it (200), else it is stored and served (201). The answer shows the
5499
- // package whole, its instructions and every skill file, for a person to read before they apply it.
5500
- const body = await bodyOf(req);
5970
+ // Read from GitHub, or uploaded whole ({files}), and checked; a dry run answers it (200), else it is stored and
5971
+ // served (201). The answer shows the package whole, its instructions and every skill file, for a person to read
5972
+ // before they apply it. An upload's body carries the package's bytes (base64 among them), up to the import's own
5973
+ // limit (TEMPLATE_UPLOAD_BODY).
5974
+ const body = await bodyOf(req, TEMPLATE_UPLOAD_BODY);
5501
5975
  const done = new AbortController();
5502
5976
  res.once("close", () => done.abort());
5503
5977
  const imported = await importTemplate(importDeps, body, done.signal);
5504
5978
  const pickView = await computerHere([imported.pkg]);
5505
- return send(res, imported.status, { template: { ...packageView(imported.pkg), computer_here: pickView(imported.pkg) }, ...(({ instructions, skill_files }) => ({ instructions, skill_files }))(packageDetail(imported.pkg)), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
5979
+ const uploaded = imported.pkg.id.startsWith(UPLOAD_PREFIX);
5980
+ return send(res, imported.status, { template: { ...packageView(imported.pkg), computer_here: pickView(imported.pkg) }, ...(({ instructions, skill_files }) => ({ instructions, skill_files }))(packageDetail(imported.pkg)), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : uploaded ? templatesLink(linkOrigin(req)) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
5981
+ }
5982
+ case "getTemplate": {
5983
+ // One package whole, a bundled one's too: as the list shows it, with the files an import's answer shows, for a
5984
+ // person (or a coding agent) to read before they apply it.
5985
+ const pkg = registry.get(id);
5986
+ if (!pkg)
5987
+ throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
5988
+ const pickView = await computerHere([pkg]);
5989
+ const { instructions, skill_files } = packageDetail(pkg);
5990
+ return send(res, 200, { template: { ...packageView(pkg), computer_here: pickView(pkg) }, instructions, skill_files, console_url: templateLink(linkOrigin(req), pkg.id) });
5506
5991
  }
5507
5992
  case "deleteTemplate":
5508
5993
  await deleteTemplate(importDeps, id);
@@ -5512,6 +5997,9 @@ async function startHolding(options, data, checked, stops) {
5512
5997
  if (!pkg)
5513
5998
  throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
5514
5999
  const body = await bodyOf(req);
6000
+ // A dry run writes nothing, so it keeps no Idempotency-Key record either: a retry reads the plan again.
6001
+ if (body.dry_run === true)
6002
+ return send(res, 200, await planTemplate(pkg, body));
5515
6003
  // The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
5516
6004
  // keeps a webhook trigger's secret (below).
5517
6005
  let minted = new Map();
@@ -6145,6 +6633,7 @@ async function startHolding(options, data, checked, stops) {
6145
6633
  // the store closes last.
6146
6634
  closing = true;
6147
6635
  stopping.abort();
6636
+ clearInterval(localSourceTimer);
6148
6637
  // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
6149
6638
  plan.close();
6150
6639
  const observationStopped = stopObservationRetention();
@@ -6167,6 +6656,7 @@ async function startHolding(options, data, checked, stops) {
6167
6656
  await schemaSealed;
6168
6657
  await installStopped;
6169
6658
  await observationStopped;
6659
+ await localSourceSweep;
6170
6660
  // The ends' follower stops before the webhooks it feeds and the store it reads.
6171
6661
  clearTimeout(endsTimer);
6172
6662
  await endsRead;