@parcha/agentrun-serve 0.1.0-beta.51 → 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 (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.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, 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,15 +58,16 @@ 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";
50
65
  import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
51
66
  import { answerStoreCall } from "./import-proxy.js";
52
- import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
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";
@@ -97,6 +117,7 @@ import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned
97
117
  import { agentDeleting, answerOf, logged, purgedAgent } from "./agents.js";
98
118
  import { keepGrade } from "./runner/feedback-round.js";
99
119
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
120
+ import { namedDisksOf } from "./learn/learning-of.js";
100
121
  import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf, shadowRunId } from "./learn/audit.js";
101
122
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
102
123
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
@@ -118,7 +139,7 @@ import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
118
139
  import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
119
140
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
120
141
  import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
121
- 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";
122
143
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
123
144
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
124
145
  import { recordDataRoot } from "./runner/disk-free.js";
@@ -138,7 +159,7 @@ import { signInsOverStore } from "./sign-ins-store.js";
138
159
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
139
160
  import { composioMadeKey, composioPerRun } from "./composio-made.js";
140
161
  import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
141
- import { ComposioTriggers } from "./composio-triggers.js";
162
+ import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
142
163
  import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
143
164
  import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
144
165
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
@@ -166,9 +187,9 @@ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
166
187
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
167
188
  import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
168
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";
169
- import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
170
- import { templateInstallLink, templateLink } from "./console-links.js";
171
- 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";
172
193
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
173
194
  import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
174
195
  import { wakeAnsweredBySetting } from "./settings-wake.js";
@@ -193,12 +214,13 @@ import { noAccount, openAccount } from "./email/account.js";
193
214
  import { emailRoute } from "./email/routes.js";
194
215
  import { addressForms, openCalendar } from "./calendar/address.js";
195
216
  import { calendarRoute } from "./calendar/routes.js";
196
- 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";
197
218
  import { computerOfPlace } from "./computer-setting.js";
198
219
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
199
220
  import { fauxComputers } from "./faux-computers.js";
200
221
  import { writesHeld } from "./workspace.js";
201
222
  import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
223
+ import { resetLearning } from "./learning-reset.js";
202
224
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
203
225
  import { sdkRunKey } from "./sdk/runs.js";
204
226
  import { waitEndedKey } from "./browser-wait-ended.js";
@@ -214,6 +236,9 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
214
236
  * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
215
237
  const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
216
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;
217
242
  /** The starts that may begin setup's import without ending it (a worker that failed, a process that ended) before the
218
243
  * owner's yes is dropped: an import that fails the same way each time is not taken up at every start for good. */
219
244
  const IMPORT_STARTS = 3;
@@ -247,7 +272,7 @@ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_E
247
272
  * startInProcessRunner). */
248
273
  export function fauxEnvOf(options) {
249
274
  // The owner's harness modules too (not a test switch): a run's process reads the same table as the server.
250
- 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) } : {}) };
251
276
  if (!options.faux)
252
277
  return env;
253
278
  env[FAUX_ENV] = resolve(options.faux);
@@ -276,19 +301,6 @@ async function tokenIn(file) {
276
301
  }
277
302
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
278
303
  const SESSION_S = SESSION_MS / 1000;
279
- const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
280
- /** 410 purged for a route of a purged run (Runs.purge): its tombstone, what is kept of it. `tools_usd`: its paid tools'
281
- * meter as /usage read it at its purge (null: unknown, or none read). */
282
- function purgedRun(row) {
283
- const meters = row.metrics?.purged?.meters;
284
- 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.`, {
285
- details: {
286
- run_id: row.id, agent_id: row.agentId, state: row.state, started_at: isoOrNull(row.startedAt), ended_at: isoOrNull(row.endedAt),
287
- cost_usd: row.costUsd ?? row.costAtMostUsd, cost_upper_bound: row.costUsd === null && row.costAtMostUsd !== null, tools_usd: typeof meters?.tools === "number" ? meters.tools : null,
288
- purged_at: isoOrNull(row.purgedAt),
289
- },
290
- });
291
- }
292
304
  export const ROUTES = [
293
305
  { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
294
306
  { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
@@ -297,6 +309,15 @@ export const ROUTES = [
297
309
  { method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
298
310
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
299
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" },
300
321
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
301
322
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
302
323
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
@@ -327,6 +348,7 @@ export const ROUTES = [
327
348
  { method: "DELETE", pattern: /^\/agents\/([^/]+)$/, name: "deleteAgent" },
328
349
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
329
350
  { method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
351
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/package$/, name: "getAgentPackage" },
330
352
  { method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
331
353
  { method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
332
354
  { method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
@@ -436,6 +458,8 @@ export const ROUTES = [
436
458
  { method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
437
459
  { method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
438
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" },
439
463
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
440
464
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
441
465
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
@@ -481,6 +505,7 @@ export const ROUTES = [
481
505
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
482
506
  { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
483
507
  { method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
508
+ { method: "GET", pattern: /^\/templates\/([^/]+)$/, name: "getTemplate" },
484
509
  { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
485
510
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
486
511
  // Answered before the bearer check: the request's signature is its credential.
@@ -494,6 +519,8 @@ export const ROUTES = [
494
519
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
495
520
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
496
521
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
522
+ // The agent's learning reset, the agent and its runs kept (learning-reset.ts).
523
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)\/learning$/, name: "deleteAgentLearning" },
497
524
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
498
525
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
499
526
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
@@ -732,6 +759,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
732
759
  * URL kept sealed, never shown. */
733
760
  slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
734
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 },
735
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" } },
736
765
  },
737
766
  regions: [{ id: "local", jurisdiction: null, state: "live" }],
@@ -784,6 +813,29 @@ function integerParam(value, name, max) {
784
813
  throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
785
814
  return Number(value);
786
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
+ }
787
839
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
788
840
  // by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
789
841
  export async function startServe(options) {
@@ -796,9 +848,17 @@ export async function startServe(options) {
796
848
  // So is the harness modules list, from `harnessModules` alone (an operator names them with --harness-module or
797
849
  // AGENTRUN_SERVE_HARNESS_MODULES, which the CLI reads into the option).
798
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];
799
853
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
800
854
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
801
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
+ }
802
862
  const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
803
863
  if (tokenRefused)
804
864
  throw new Error(tokenRefused);
@@ -891,7 +951,7 @@ async function startHolding(options, data, checked, stops) {
891
951
  // shown nowhere.
892
952
  let secretStores;
893
953
  let triggerSettings = new Map();
894
- 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 }) };
895
955
  // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
896
956
  // the start, in words, before anything else opens.
897
957
  // The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
@@ -967,7 +1027,14 @@ async function startHolding(options, data, checked, stops) {
967
1027
  // runner/runner-check.ts): this data root's id, and the names (never the values) of the run-facing environment this
968
1028
  // server holds, each said in the store at every start, replacing the last start's.
969
1029
  await recordDataRoot(store, data);
970
- 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)));
971
1038
  // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
972
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
973
1040
  // process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
@@ -1024,7 +1091,7 @@ async function startHolding(options, data, checked, stops) {
1024
1091
  // with whether each can be granted: a known meta tool can't (mcp-meta.ts).
1025
1092
  const mcpTools = (server) => {
1026
1093
  const saved = mcpMeta.get(server);
1027
- 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;
1028
1095
  };
1029
1096
  // The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
1030
1097
  // once here.
@@ -1275,9 +1342,12 @@ async function startHolding(options, data, checked, stops) {
1275
1342
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
1276
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
1277
1344
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
1278
- * is no shell), whose shell runs the shell tools; else none, and why. */
1279
- const shellHere = async () => {
1280
- 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)
1281
1351
  return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
1282
1352
  const fresh = newAgentPlace(boxOffers);
1283
1353
  let why = "why" in fresh ? fresh.why : "it is not set up";
@@ -1289,14 +1359,18 @@ async function startHolding(options, data, checked, stops) {
1289
1359
  else if ((await shellOf(computer)) === "computer")
1290
1360
  return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
1291
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})` };
1292
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})` };
1293
1365
  };
1294
1366
  /** Each package's computer list read against this server now, as a listing shows it (`computer_here`): what an apply
1295
1367
  * here would pick (pickComputer), the shell asked for once for them all. */
1296
1368
  const computerHere = async (packages) => {
1297
- 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;
1298
1371
  return (pkg) => {
1299
- const pick = here && pickComputer(pkg, here);
1372
+ const shell = pkg.needs ? sandbox : here;
1373
+ const pick = shell && pickComputer(pkg, shell);
1300
1374
  if (!pick)
1301
1375
  return null;
1302
1376
  if ("refused" in pick)
@@ -1521,7 +1595,65 @@ async function startHolding(options, data, checked, stops) {
1521
1595
  refusedTimer.unref();
1522
1596
  // The runner beside this server, when its run isolation was refused (cli.ts): its word, kept in this store until the stop.
1523
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();
1524
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
+ } },
1525
1657
  // A start while every runner here refused to claim is refused in their words (runner/presence.ts).
1526
1658
  runnersRefused: refusedNow,
1527
1659
  runBodyIssues,
@@ -1592,6 +1724,12 @@ async function startHolding(options, data, checked, stops) {
1592
1724
  return [...serverSecrets(), ...pointers];
1593
1725
  };
1594
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
+ };
1595
1733
  // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1596
1734
  const auditsOfAgent = async (agentId) => {
1597
1735
  const { workspace, end } = learningFolderOf(data, agentId);
@@ -1648,6 +1786,8 @@ async function startHolding(options, data, checked, stops) {
1648
1786
  getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
1649
1787
  needAgent,
1650
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",
1651
1791
  // Read when a firing's message is sent (declared below, with the delete turn).
1652
1792
  runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
1653
1793
  runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
@@ -1660,6 +1800,9 @@ async function startHolding(options, data, checked, stops) {
1660
1800
  const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
1661
1801
  return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
1662
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,
1663
1806
  };
1664
1807
  const targets = triggerTargets(store, triggerDeps);
1665
1808
  // Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
@@ -1786,7 +1929,7 @@ async function startHolding(options, data, checked, stops) {
1786
1929
  // A template import reads GitHub's own hosts alone (a test's faux GitHub in their place), with an installation token of
1787
1930
  // the App when GitHub is connected (tokenForListing: metadata read, the least there is), else anonymously, and says why.
1788
1931
  const importDeps = {
1789
- registry, store,
1932
+ registry, store, apiOnly: options.apiOnly === true,
1790
1933
  reach: async (signal) => {
1791
1934
  const api = options.templateImportApi ?? GITHUB_API;
1792
1935
  const hosts = options.templateImportApi ? [new URL(options.templateImportApi).host] : GITHUB_HOSTS;
@@ -1799,6 +1942,9 @@ async function startHolding(options, data, checked, stops) {
1799
1942
  // is a server secret while it may be in use.
1800
1943
  mcpServers.appToken = (signal) => githubConnect.tokenForListing(signal);
1801
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);
1802
1948
  const triggers = new Triggers({
1803
1949
  // The server's own store (the one it opened) holds the triggers a person writes and reads; a test may inject another
1804
1950
  // (startServe's `store`).
@@ -1806,7 +1952,7 @@ async function startHolding(options, data, checked, stops) {
1806
1952
  clock: options.triggerClock,
1807
1953
  ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1808
1954
  adapters,
1809
- 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,
1810
1956
  // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1811
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
1812
1958
  // or an eval's route to its fake feeds (feedsAt).
@@ -1824,6 +1970,7 @@ async function startHolding(options, data, checked, stops) {
1824
1970
  },
1825
1971
  // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1826
1972
  upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1973
+ ...(options.launchHook ? { launchHook: options.launchHook } : {}),
1827
1974
  });
1828
1975
  const composioTriggers = new ComposioTriggers({
1829
1976
  control: options.composioControl ?? {},
@@ -2214,7 +2361,7 @@ async function startHolding(options, data, checked, stops) {
2214
2361
  async function needRunnableAgent(id) {
2215
2362
  const entry = await needAgent(id);
2216
2363
  // Another system's agent is archived only by its delete (its archive route is refused).
2217
- if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2364
+ if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
2218
2365
  throw agentDeleting(id);
2219
2366
  if (entry.agent.archivedAt)
2220
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() } });
@@ -2283,7 +2430,7 @@ async function startHolding(options, data, checked, stops) {
2283
2430
  // A purged agent's row stays as its tombstone: a write that waited on its purge is 410, never a folder made again.
2284
2431
  if (entry.agent.purgedAt !== null)
2285
2432
  throw purgedAgent(entry.agent);
2286
- if (entry.agent.archivedAt && entry.agent.externalRef !== null)
2433
+ if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
2287
2434
  throw agentDeleting(id);
2288
2435
  // A purge stopped part way (its mark still there): nothing of the agent is written, nor is it unarchived, until a
2289
2436
  // DELETE finishes it.
@@ -2318,11 +2465,42 @@ async function startHolding(options, data, checked, stops) {
2318
2465
  throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${again}`, { retry_after_ms: 5_000 });
2319
2466
  }
2320
2467
  };
2468
+ /** The Archil disks agent `agentId`'s learning folder may be on: a Mode 2 run's end writes it on the disk its claim
2469
+ * mounted (workspace/learning-workspace.ts, at learningKey), the agent's stored disk (named here only for
2470
+ * `agentDisk`) or one a launch named (kind "launch", a customer's: each run's disk, learn/learning-of.ts namedDisksOf,
2471
+ * read off its row, so a purged run whose launch is gone still names it). A run's kept disk, or a launch's kind
2472
+ * "agent", is the agent's own disk, mounted only while it is still the stored one (workspace/run-disk.ts runDiskOf):
2473
+ * one no longer stored was removed at Archil, its folder with it. */
2474
+ const learningDisksOf = async (agentId, agentDisk) => {
2475
+ const disks = new Set();
2476
+ const stored = agentDisk ? await agentDiskOf(store, agentId) : undefined;
2477
+ if (stored)
2478
+ disks.add(stored.diskId);
2479
+ for (const disk of await namedDisksOf(store, agentId))
2480
+ disks.add(disk);
2481
+ return [...disks];
2482
+ };
2483
+ /** Step 2 of DELETE /agents/{id}, and DELETE /agents/{id}/learning: the learning module's delete over the agent's
2484
+ * learning folder on this server's disk, as the learning routes open it (learningFolderOf), which deleteLearning ends
2485
+ * in its finally, and over its folder on each Archil disk a launch of its runs named and, for a reset (`agentDisk`),
2486
+ * on its own disk, which the agent's delete removes whole in step 3 (archil-routes.ts removeLearningFolder; Archil
2487
+ * off or refusing is 503 unavailable, nothing here deleted, for the next call). */
2488
+ const learningDelete = options.deleteLearning ?? ((given, agentId, { keepResetLedger = false, agentDisk = false } = {}) => deleteLearning(given, agentId, learningFolderOf(data, agentId), {
2489
+ keepResetLedger,
2490
+ elsewhere: async () => {
2491
+ for (const diskId of await learningDisksOf(agentId, agentDisk)) {
2492
+ try {
2493
+ await archil.removeLearningFolder(agentId, diskId);
2494
+ }
2495
+ catch (error) {
2496
+ if (!(error instanceof ApiError && ["unavailable", "upstream_failed"].includes(error.code)))
2497
+ throw error;
2498
+ throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. The agent's learning folder on this server and its learning records are kept: send the DELETE again once it can be reached.`, { retry_after_ms: 5_000 });
2499
+ }
2500
+ }
2501
+ },
2502
+ }));
2321
2503
  /** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
2322
- /** Step 2 of DELETE /agents/{id}: the learning module's delete over the agent's learning folder on this server's disk,
2323
- * as the learning routes open it (learningFolderOf), which deleteLearning ends in its finally. A learning folder on
2324
- * the agent's Archil disk goes with that disk in step 3. */
2325
- const learningDelete = options.deleteLearning ?? ((given, agentId) => deleteLearning(given, agentId, learningFolderOf(data, agentId)));
2326
2504
  const agentDeleteHost = {
2327
2505
  store,
2328
2506
  deleteLearning: learningDelete,
@@ -2374,8 +2552,11 @@ async function startHolding(options, data, checked, stops) {
2374
2552
  // DELETE. A run on its agent's own disk: with its agent's delete that disk went whole (removeDisk), its folder with
2375
2553
  // it; deleted alone, its folder there is deleted, the disk kept, read from its disk setting, which goes after.
2376
2554
  const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
2377
- if (launched?.kind === "launch")
2555
+ // The agent's learning folder there too: a Mode 2 end wrote the run's diff and correction in it, and nothing reads it.
2556
+ if (launched?.kind === "launch") {
2378
2557
  await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"], again);
2558
+ await notYetWith(() => archil.removeLearningFolder(agentId, launched.diskId), ["unavailable", "upstream_failed"], again);
2559
+ }
2379
2560
  else if (alone) {
2380
2561
  const own = launched?.diskId ?? (await runDiskKept(store, runId));
2381
2562
  if (own)
@@ -2396,12 +2577,26 @@ async function startHolding(options, data, checked, stops) {
2396
2577
  // The agent's folder (its runs' folders, its home, its learning folder) and its scratch folder.
2397
2578
  await rm(agentFolder(data, agentId), { recursive: true, force: true });
2398
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
+ }
2399
2588
  await forgetKept("agent", agentId);
2400
2589
  },
2401
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
2402
2591
  // run by its id (one whose launch is gone too).
2403
2592
  madeFrom: async (runId) => [...new Set([...(await store.runs.madeFrom(runId)), shadowRunId(runId)])],
2404
- 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
+ },
2405
2600
  // /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
2406
2601
  // learning ended as /stats counts it (its state and reason alone).
2407
2602
  kept: async (runId) => {
@@ -2421,6 +2616,16 @@ async function startHolding(options, data, checked, stops) {
2421
2616
  pollMs: 200,
2422
2617
  ...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
2423
2618
  };
2619
+ /** What DELETE /agents/{id}/learning does outside the learning module (learning-reset.ts): the agent delete's learning
2620
+ * step, cancel path and wait, and the agent's learning queue, where a run's start reads its seed. */
2621
+ const learningResetHost = {
2622
+ store,
2623
+ deleteLearning: learningDelete,
2624
+ cancel: agentDeleteHost.cancel,
2625
+ inQueue: (agentId, work) => withAgentRepo(data, agentId, work),
2626
+ waitMs: agentDeleteHost.waitMs,
2627
+ pollMs: agentDeleteHost.pollMs,
2628
+ };
2424
2629
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
2425
2630
  // routes read from the store + the run view now, not a live Run.
2426
2631
  async function needRun(id) {
@@ -2527,8 +2732,9 @@ async function startHolding(options, data, checked, stops) {
2527
2732
  /** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
2528
2733
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
2529
2734
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2530
- * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
2531
- 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 = [] } = {}) {
2532
2738
  if (cliLearningOf(revision.body))
2533
2739
  throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
2534
2740
  if (sdkOf(revision.body))
@@ -2586,8 +2792,13 @@ async function startHolding(options, data, checked, stops) {
2586
2792
  });
2587
2793
  };
2588
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);
2589
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.
2590
- 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 });
2591
2802
  if (!blockers.length)
2592
2803
  return;
2593
2804
  const message = blockers.map((b) => b.message).join(" ");
@@ -2663,7 +2874,7 @@ async function startHolding(options, data, checked, stops) {
2663
2874
  return undefined;
2664
2875
  try {
2665
2876
  return mcpPinOf(granted, { server: (name) => { const kept = carried.get(name); if (kept)
2666
- return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices }; } });
2877
+ return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices, toolkit: listing.toolkit }; } });
2667
2878
  }
2668
2879
  catch (error) {
2669
2880
  throw invalid([{ field: "definition.tools", reason: "not_an_option", message: error.message }]);
@@ -2791,7 +3002,7 @@ async function startHolding(options, data, checked, stops) {
2791
3002
  // Its last read and its commit in the agent's delete turn (agentWrite), the check outside it: an edit or a template
2792
3003
  // update whose commit comes once the agent is purged is 410, and one after a purge stopped part way is 409, nothing
2793
3004
  // written (the store refuses a purged agent's revision too, AgentPurged).
2794
- 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) });
2795
3006
  reconcileComputer(entry.agent.id);
2796
3007
  return { entry: edited, warnings };
2797
3008
  }
@@ -2815,6 +3026,7 @@ async function startHolding(options, data, checked, stops) {
2815
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
2816
3027
  * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
2817
3028
  const replayAskOf = (entry) => ({
3029
+ admitAuxiliary: auxiliaryAdmitter(store, { data, project: startDeps.project }),
2818
3030
  store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
2819
3031
  folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
2820
3032
  launchOf: async (input) => {
@@ -2876,19 +3088,96 @@ async function startHolding(options, data, checked, stops) {
2876
3088
  return false;
2877
3089
  throw error;
2878
3090
  };
2879
- /** applyTemplate's work, in its turn on the agent where it has agent_id. */
2880
- async function applyWith(template, body) {
2881
- 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.`);
2882
3160
  // With agent_id, the apply writes a new revision of that agent (one this template made) in place of making another:
2883
- // 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.
2884
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.`);
2885
3167
  // An update's triggers are reconciled by name with the ones the agent has (below), read with the agent: each write to
2886
3168
  // one is made only while it is still this agent's (TriggerOwn.onAgent), so one a PATCH moves away meanwhile is left.
2887
3169
  const had = onto ? await store.triggers.list(onto.agent.id) : [];
2888
- if (onto && options.templateApplyRead)
3170
+ if (onto && !plan && options.templateApplyRead)
2889
3171
  await options.templateApplyRead(onto.agent.id);
2890
- // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2891
- 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.` }));
2892
3181
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
2893
3182
  // one: several and no pick is a 422); the package's
2894
3183
  // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
@@ -2901,29 +3190,32 @@ async function startHolding(options, data, checked, stops) {
2901
3190
  // of a saved server that happens to be named as its toolkit.
2902
3191
  const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
2903
3192
  const needed = unsaved.filter((need) => need.required);
2904
- if (missing.length || needed.length) {
3193
+ if (!plan && (missing.length || needed.length)) {
2905
3194
  const fix = "Add it in Settings → API Keys, or set it where AgentRun starts, then apply the template again.";
2906
- 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) }))] });
2907
3196
  }
2908
3197
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
2909
3198
  // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
2910
3199
  // whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
2911
- const pick = pickComputer(pkg, await shellHere());
3200
+ const pick = pickComputer(pkg, await shellHere({ sandbox: Boolean(pkg.needs) }));
2912
3201
  if (pick && "refused" in pick)
2913
- 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 }] });
2914
3203
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
2915
3204
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
2916
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) }));
2917
3206
  // A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
2918
- // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
2919
- 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)));
2920
3212
  if (choice && unrunnable) {
2921
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.`;
2922
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." }] });
2923
3215
  }
2924
3216
  const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
2925
3217
  const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2926
- if ("refused" in picked && picked.refused) {
3218
+ if ("refused" in picked && picked.refused && !lacking) {
2927
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.`;
2928
3220
  throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
2929
3221
  }
@@ -2947,15 +3239,26 @@ async function startHolding(options, data, checked, stops) {
2947
3239
  // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2948
3240
  // A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
2949
3241
  const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
2950
- 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])));
2951
3253
  if (refusedTriggers.length)
2952
3254
  throw invalid(refusedTriggers);
2953
3255
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
2954
3256
  for (const one of [made.agent, ...made.triggers])
2955
3257
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
2956
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" } });
2957
- // The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either).
2958
- 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()])));
2959
3262
  // The triggers to remove: each of the agent's that an apply of this package marked as its own (TriggerRow.templateId)
2960
3263
  // and whose name the package no longer lists. A trigger the owner made, one a PATCH moved here from another agent (or
2961
3264
  // away and back), and one made before the mark was kept carry none, and are left. One whose removal fails keeps its
@@ -2970,7 +3273,7 @@ async function startHolding(options, data, checked, stops) {
2970
3273
  const resent = new Map();
2971
3274
  const remade = new Set();
2972
3275
  for (const [i, trigger] of made.triggers.entries()) {
2973
- const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
3276
+ const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
2974
3277
  if (!was || !isObject(trigger.source) || trigger.source.kind !== "composio" || !isObject(was.source) || was.source.kind !== "composio")
2975
3278
  continue;
2976
3279
  try {
@@ -2989,7 +3292,7 @@ async function startHolding(options, data, checked, stops) {
2989
3292
  // have to make again without being its own, or another package's, refuses the apply with nothing written (409 under
2990
3293
  // triggers.<i>): the owner renames or deletes it, then applies again.
2991
3294
  const notOurs = made.triggers.flatMap((trigger, i) => {
2992
- const was = emptyFeeds.has(i) ? undefined : hadByName.get(String(trigger.name).trim());
3295
+ const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
2993
3296
  if (!was || was.templateId === pkg.id)
2994
3297
  return [];
2995
3298
  const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
@@ -3004,10 +3307,18 @@ async function startHolding(options, data, checked, stops) {
3004
3307
  if (notOurs.length)
3005
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 });
3006
3309
  // The agent keeps where it came from (the package on the revision the apply writes): the package's id, version and,
3007
- // imported, its SHA; and a keyed digest of the parameters it was given (never the parameters: one may be a credential).
3008
- // 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.
3009
3314
  const digest = parametersDigest(sealKey, stable(parameters));
3010
- 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 });
3011
3322
  // A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
3012
3323
  // which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
3013
3324
  const twins = onto ? [] : (await agents.list())
@@ -3029,8 +3340,8 @@ async function startHolding(options, data, checked, stops) {
3029
3340
  // (catchup_window_s and max_active_runs the package leaves out back to their defaults, as a fresh apply makes them); a new name is made; one the package
3030
3341
  // marked and no longer lists is removed (`removing`). Each trigger the apply makes or keeps is marked as the package's; each write to one the agent had is made only while it
3031
3342
  // is still the agent's: one a PATCH moved away meanwhile is neither changed nor removed, and its name is made anew.
3032
- // Each trigger it made or kept, in the package's order, as it stands after its write: the answer's trigger_ids and
3033
- // triggers (its name, its kind, and whether it is on).
3343
+ // Each trigger it made or kept, in the package's order, as it stands after its write: the answer's triggers (its id,
3344
+ // its name, its kind, and whether it is on).
3034
3345
  const answered = [];
3035
3346
  const list = (view) => answered.push({ trigger_id: view.id, name: view.name, kind: view.source.kind, enabled: view.enabled });
3036
3347
  // The triggers this apply made (never one it changed in place): what a refusal's undo removes.
@@ -3047,7 +3358,7 @@ async function startHolding(options, data, checked, stops) {
3047
3358
  const leftThere = [];
3048
3359
  try {
3049
3360
  for (const [i, trigger] of made.triggers.entries()) {
3050
- if (emptyFeeds.has(i))
3361
+ if (unmade(i))
3051
3362
  continue;
3052
3363
  const aimed = { ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } };
3053
3364
  let was = hadByName.get(String(trigger.name).trim());
@@ -3132,9 +3443,9 @@ async function startHolding(options, data, checked, stops) {
3132
3443
  const ticked = saved.map((need) => ({ ...need, tools: need.tools.filter((tool) => grants.includes(mcpToolName(need.server, tool))) }));
3133
3444
  const appShort = await appPermissionWarnings({ name: pkg.name, mcp: ticked }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
3134
3445
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
3135
- 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)] : []));
3136
3447
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
3137
- 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"
3138
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) }]
3139
3450
  : []));
3140
3451
  // Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
@@ -3143,7 +3454,9 @@ async function startHolding(options, data, checked, stops) {
3143
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 }] : [];
3144
3455
  });
3145
3456
  // Each feed trigger it skipped for want of a feed: which, and the parameter to set.
3146
- 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 }));
3147
3460
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
3148
3461
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
3149
3462
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
@@ -3152,7 +3465,7 @@ async function startHolding(options, data, checked, stops) {
3152
3465
  // What the apply did to the agent: made it, wrote a new revision, or wrote none (an update whose package and
3153
3466
  // parameters the current revision already holds: commitAgent keeps that revision).
3154
3467
  const agentChange = !onto ? "made" : entry.revision?.id === onto.revision?.id ? "unchanged" : "updated";
3155
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, agent_change: agentChange, servers: used, trigger_ids: answered.map((one) => one.trigger_id), 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] };
3156
3469
  return { applied, minted, updated: onto !== undefined };
3157
3470
  }
3158
3471
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -3211,11 +3524,13 @@ async function startHolding(options, data, checked, stops) {
3211
3524
  * bound to its server's origin then and the model key to the gateway's (AGENT_MODEL_BASE_URL). `handed` is called only
3212
3525
  * for new work, inside the request's idempotent work: there each mcp_auth entry must name a saved per_run server, and
3213
3526
  * the model key must be text, else 422, nothing written. A retry its key already answered replays that answer even
3214
- * 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. */
3215
3530
  function handedLaunchSecrets(body) {
3216
- if (body.mcp_auth === undefined && body.model_key === undefined)
3531
+ if (body.mcp_auth === undefined && body.model_key === undefined && body.keys === undefined)
3217
3532
  return { body, handed: async () => ({}) };
3218
- const { mcp_auth, model_key, ...rest } = body;
3533
+ const { mcp_auth, model_key, keys: given, ...rest } = body;
3219
3534
  const handed = async () => {
3220
3535
  const issues = [];
3221
3536
  const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
@@ -3241,12 +3556,16 @@ async function startHolding(options, data, checked, stops) {
3241
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.` });
3242
3557
  }
3243
3558
  const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
3559
+ const keys = given === undefined ? undefined : runKeysOf(given, issues);
3244
3560
  if (issues.length)
3245
3561
  throw invalid(issues);
3246
- 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 } : {}) };
3247
3564
  };
3248
3565
  return { body: rest, handed };
3249
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) } : {});
3250
3569
  /** The 422 for a model key where the run's model never takes it (run-model-key.ts modelKeyMisfit), at `model_key`. */
3251
3570
  const misfit = (why) => invalid([{ field: "model_key", reason: "not_an_option", message: why }]);
3252
3571
  /** A start's launch seal of `handed` (handedLaunchSecrets), made once the start prepared the run's launch: a model key
@@ -3254,7 +3573,7 @@ async function startHolding(options, data, checked, stops) {
3254
3573
  * is refused where the server holds no key for the run's route (serverKeyMissing). Undefined when nothing is handed:
3255
3574
  * the start's own check (runs-over-store keyedOrRefused) refuses that one where it has no key to spend. */
3256
3575
  function startSeal(handed) {
3257
- if (handed.mcp === undefined && handed.model === undefined)
3576
+ if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined)
3258
3577
  return undefined;
3259
3578
  return (runId, launch, kind) => {
3260
3579
  const target = { kind, model: launch.model, native: Boolean(launch.native) };
@@ -3266,7 +3585,7 @@ async function startHolding(options, data, checked, stops) {
3266
3585
  else if (serverKeyMissing(env, target))
3267
3586
  throw modelKeyRequired(false);
3268
3587
  const origin = runModelOrigin(env);
3269
- 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 } : {}) });
3270
3589
  };
3271
3590
  }
3272
3591
  /** A message's launch secrets for run `run` (its kind and launch as stored): what it hands replaces that part of the
@@ -3274,7 +3593,10 @@ async function startHolding(options, data, checked, stops) {
3274
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
3275
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
3276
3595
  * run holds none when the message is written (its last turn ended): 422 model_key_required from inside that write,
3277
- * 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. */
3278
3600
  async function messageSeal(run, handed) {
3279
3601
  const launch = readLaunchBody((await store.runs.launch(run.id)).body);
3280
3602
  const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
@@ -3283,22 +3605,51 @@ async function startHolding(options, data, checked, stops) {
3283
3605
  if (why)
3284
3606
  throw misfit(why);
3285
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]) : [];
3286
3616
  const needsKey = handed.model === undefined && serverKeyMissing(env, target);
3287
- if (handed.mcp === undefined && handed.model === undefined && !needsKey)
3617
+ if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined && !needsKey && !owed.length)
3288
3618
  return undefined;
3289
3619
  const origin = runModelOrigin(env);
3290
3620
  return (current) => {
3291
3621
  const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
3292
3622
  const mcp = handed.mcp ?? held.mcp;
3293
3623
  const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
3624
+ const keys = handed.keys ?? held.keys;
3294
3625
  if (!model && needsKey)
3295
3626
  throw modelKeyRequired(true);
3296
- 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 } : {}) });
3297
3631
  };
3298
3632
  }
3299
3633
  async function createRun(req, agentId) {
3300
3634
  const entry = await needRunnableAgent(agentId);
3301
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
+ }
3302
3653
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
3303
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.
3304
3655
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -3308,8 +3659,9 @@ async function startHolding(options, data, checked, stops) {
3308
3659
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
3309
3660
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
3310
3661
  }
3311
- const seal = startSeal(await handed());
3312
- 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) });
3313
3665
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
3314
3666
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
3315
3667
  });
@@ -3365,8 +3717,9 @@ async function startHolding(options, data, checked, stops) {
3365
3717
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
3366
3718
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
3367
3719
  }
3368
- const seal = startSeal(await handed());
3369
- 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) });
3370
3723
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
3371
3724
  });
3372
3725
  }
@@ -4091,13 +4444,13 @@ async function startHolding(options, data, checked, stops) {
4091
4444
  authFailed(`/v2${path}`, "approve_without_session");
4092
4445
  throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
4093
4446
  }
4094
- // Purging a run or an agent, or deleting another system's agent, cannot be undone: the owner's session or the API
4095
- // token. A console session counts as the owner's only where it does for a secret (secret-writes.ts: accounts off on a
4096
- // loopback-bound server); bound off loopback with accounts off, whoever opened the console is no owner. With no
4097
- // credential at all it is 401, as every route is.
4098
- if ((found.name === "deleteRun" || found.name === "deleteAgent") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4447
+ // Purging a run or an agent, deleting another system's agent, or resetting an agent's learning cannot be undone: the
4448
+ // owner's session or the API token. A console session counts as the owner's only where it does for a secret
4449
+ // (secret-writes.ts: accounts off on a loopback-bound server); bound off loopback with accounts off, whoever opened the
4450
+ // console is no owner. With no credential at all it is 401, as every route is.
4451
+ if ((found.name === "deleteRun" || found.name === "deleteAgent" || found.name === "deleteAgentLearning") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4099
4452
  authFailed(`/v2${path}`, "delete_without_owner");
4100
- throw new ApiError("forbidden", "Deleting a run or an agent takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
4453
+ throw new ApiError("forbidden", "Deleting a run or an agent, or resetting an agent's learning, takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
4101
4454
  }
4102
4455
  // Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
4103
4456
  // owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
@@ -4139,19 +4492,72 @@ async function startHolding(options, data, checked, stops) {
4139
4492
  await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
4140
4493
  return send(res, 200, await broker.revoke(connectorId));
4141
4494
  }
4142
- if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
4495
+ if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand", "grantSourceSync", "publishSourceSync", "sourceSyncFailure"].includes(found.name)) {
4143
4496
  const parts = found.pattern.exec(path);
4144
4497
  const connectorId = decodeURIComponent(parts[1]);
4145
4498
  const broker = new RemoteConnectors(store);
4146
4499
  await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
4147
4500
  // History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
4148
4501
  const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
4149
- : 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;
4150
4503
  const body = await bodyOf(req, limit);
4151
4504
  if (found.name === "importRemoteTarget")
4152
- 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))));
4153
4506
  if (found.name === "importRemoteHistory")
4154
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
+ }
4155
4561
  if (found.name === "pollRemoteConnector")
4156
4562
  return send(res, 200, await broker.poll(connectorId, body));
4157
4563
  const commandId = decodeURIComponent(parts[2]);
@@ -4237,7 +4643,14 @@ async function startHolding(options, data, checked, stops) {
4237
4643
  case "enrollCliLearning": {
4238
4644
  if (!isLoopback(req.socket.remoteAddress ?? ""))
4239
4645
  throw new ApiError("forbidden", "CLI learning enrollment must come from the local source machine.");
4240
- 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);
4241
4654
  }
4242
4655
  case "listCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).list());
4243
4656
  case "revokeCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).revoke(id));
@@ -4271,6 +4684,64 @@ async function startHolding(options, data, checked, stops) {
4271
4684
  throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
4272
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));
4273
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
+ }
4274
4745
  case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
4275
4746
  case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
4276
4747
  case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
@@ -4281,7 +4752,13 @@ async function startHolding(options, data, checked, stops) {
4281
4752
  return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
4282
4753
  }
4283
4754
  case "connectNative": {
4284
- 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
+ }
4285
4762
  return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
4286
4763
  }
4287
4764
  case "getNative": {
@@ -4301,6 +4778,7 @@ async function startHolding(options, data, checked, stops) {
4301
4778
  const native = nativeOf(entry.revision?.body);
4302
4779
  if (!native)
4303
4780
  throw new ApiError("not_found", "This agent has no native connection.");
4781
+ await localSources.revoke(id);
4304
4782
  const changed = await updateNative(store, entry, { ...native, connected: false });
4305
4783
  if (native.remote)
4306
4784
  await new RemoteConnectors(store).disconnectTarget(native);
@@ -4391,6 +4869,32 @@ async function startHolding(options, data, checked, stops) {
4391
4869
  const page = all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row));
4392
4870
  return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
4393
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
+ }
4394
4898
  case "setCurrent": {
4395
4899
  // The body read first, outside the agent's delete turn; the move made in it (agentWrite), as an edit's revision is:
4396
4900
  // one whose body arrives while the agent is purged is 410 (the store refuses it too, AgentPurged).
@@ -4406,6 +4910,8 @@ async function startHolding(options, data, checked, stops) {
4406
4910
  const candidate = await agents.revision(id, revision);
4407
4911
  if (!candidate)
4408
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.");
4409
4915
  if (stable(cliLearningOf(candidate.revision.body)) !== stable(cliLearningOf(entry.revision?.body)))
4410
4916
  throw new ApiError("input_invalid", "A revision restore cannot change the enrolled CLI learning connection.");
4411
4917
  if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
@@ -4426,16 +4932,23 @@ async function startHolding(options, data, checked, stops) {
4426
4932
  case "deleteAgent": {
4427
4933
  // Another system's agent deleted whole; one made here purged once archived (agent-delete.ts). One delete of an agent
4428
4934
  // at a time, the agent read in its turn, so a DELETE after one that finished is 404 (deleted) or 204 (purged).
4429
- await deleteInTurn(id, async () => {
4430
- const { agent } = await needAgent(id);
4431
- if (agent.purgedAt !== null)
4432
- return;
4433
- if (agent.externalRef !== null)
4434
- return deleteExternalAgent(agentDeleteHost, id);
4435
- if (agent.archivedAt === null)
4436
- 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.`);
4437
- await purgeAgent(agentDeleteHost, id);
4438
- });
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
+ }
4439
4952
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4440
4953
  return void res.end();
4441
4954
  }
@@ -4450,7 +4963,10 @@ async function startHolding(options, data, checked, stops) {
4450
4963
  // the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
4451
4964
  // In the agent's delete turn (agentWrite): an unarchive sent while its purge runs waits for it and is 410, so no
4452
4965
  // run of it starts between the purge's live check and its tombstone.
4453
- 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)));
4454
4970
  // An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
4455
4971
  if (found.name === "archiveAgent")
4456
4972
  reconcileComputer(id);
@@ -4464,7 +4980,7 @@ async function startHolding(options, data, checked, stops) {
4464
4980
  const entry = await needAgent(id);
4465
4981
  const controller = new AbortController();
4466
4982
  req.once("close", () => controller.abort());
4467
- 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) };
4468
4984
  return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
4469
4985
  }
4470
4986
  case "forgetSignIn": {
@@ -4552,10 +5068,18 @@ async function startHolding(options, data, checked, stops) {
4552
5068
  }
4553
5069
  case "deleteRun": {
4554
5070
  // In its agent's delete turn (an agent's delete or purge, or another purge of one of its runs, finishes first), the
4555
- // 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).
4556
5073
  const row = ID.test(id) ? await store.runs.get(id) : undefined;
4557
5074
  if (!row)
4558
5075
  throw new ApiError("not_found", `no run ${id}`);
5076
+ // API-only (api-only.ts): a run of an agent another system owns alone, for the backend whose inline runs made it,
5077
+ // as it deletes that agent; a run of an agent made here is the profile's refusal, in its words, as before.
5078
+ if (options.apiOnly) {
5079
+ const agent = await store.agents.get(row.agentId);
5080
+ if (!agent || !ownedElsewhere(agent))
5081
+ throw new ApiError("not_found", apiOnlyRefusal(`/v2${path}`));
5082
+ }
4559
5083
  await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
4560
5084
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4561
5085
  return void res.end();
@@ -5045,6 +5569,9 @@ async function startHolding(options, data, checked, stops) {
5045
5569
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
5046
5570
  case "listMcpServers":
5047
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() });
5048
5575
  case "getMcpServer":
5049
5576
  return send(res, 200, await mcpServers.get(id));
5050
5577
  case "previewMcpServer":
@@ -5200,7 +5727,7 @@ async function startHolding(options, data, checked, stops) {
5200
5727
  const costStop = await costStopOverStore(store, id);
5201
5728
  const body = entry.revision?.body;
5202
5729
  const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
5203
- 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) });
5204
5731
  }
5205
5732
  case "getLearningCost": {
5206
5733
  await needAgent(id);
@@ -5241,7 +5768,7 @@ async function startHolding(options, data, checked, stops) {
5241
5768
  const champion = championOf(records, workflow);
5242
5769
  const record = champion?.digest === digest ? champion : undefined;
5243
5770
  const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
5244
- const read = await workflowAtDigest(data, id, workflow, digest, commits).catch(() => undefined);
5771
+ const read = await workflowAtDigest(data, id, workflow, digest, commits, store).catch(() => undefined);
5245
5772
  let doc;
5246
5773
  try {
5247
5774
  doc = read ? JSON.parse(read.text) : undefined;
@@ -5287,7 +5814,7 @@ async function startHolding(options, data, checked, stops) {
5287
5814
  }
5288
5815
  case "listLearningLog":
5289
5816
  await needAgent(id);
5290
- 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));
5291
5818
  case "getLearningCorrections": {
5292
5819
  await needAgent(id);
5293
5820
  // corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
@@ -5303,12 +5830,21 @@ async function startHolding(options, data, checked, stops) {
5303
5830
  const written = await agentWrite(id, () => correctionsWrite(data, id, { text, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse }));
5304
5831
  return send(res, 200, written, { etag: written.etag });
5305
5832
  }
5833
+ case "deleteAgentLearning": {
5834
+ // The agent's learning reset (learning-reset.ts), a write to its learning: in its delete turn (agentWrite), which
5835
+ // reads the agent there (404 unknown) and refuses one being deleted.
5836
+ await agentWrite(id, () => resetLearning(learningResetHost, id));
5837
+ // A run's list row that read a workflow of the agent's says what the folder says now, at the next list.
5838
+ await lister.learningChanged(id);
5839
+ res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
5840
+ return void res.end();
5841
+ }
5306
5842
  case "listLearnedWorkflowRevisions":
5307
5843
  await needAgent(id);
5308
- 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));
5309
5845
  case "readLearningFile":
5310
5846
  await needAgent(id);
5311
- 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));
5312
5848
  case "retireLearningFile":
5313
5849
  case "approveLearningFile":
5314
5850
  case "restoreLearningFile": {
@@ -5431,14 +5967,27 @@ async function startHolding(options, data, checked, stops) {
5431
5967
  return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
5432
5968
  }
5433
5969
  case "importTemplate": {
5434
- // Read from GitHub and checked; a dry run answers it (200), else it is stored and served (201). The answer shows the
5435
- // package whole, its instructions and every skill file, for a person to read before they apply it.
5436
- 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);
5437
5975
  const done = new AbortController();
5438
5976
  res.once("close", () => done.abort());
5439
5977
  const imported = await importTemplate(importDeps, body, done.signal);
5440
5978
  const pickView = await computerHere([imported.pkg]);
5441
- 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) });
5442
5991
  }
5443
5992
  case "deleteTemplate":
5444
5993
  await deleteTemplate(importDeps, id);
@@ -5448,6 +5997,9 @@ async function startHolding(options, data, checked, stops) {
5448
5997
  if (!pkg)
5449
5998
  throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
5450
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));
5451
6003
  // The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
5452
6004
  // keeps a webhook trigger's secret (below).
5453
6005
  let minted = new Map();
@@ -6081,6 +6633,7 @@ async function startHolding(options, data, checked, stops) {
6081
6633
  // the store closes last.
6082
6634
  closing = true;
6083
6635
  stopping.abort();
6636
+ clearInterval(localSourceTimer);
6084
6637
  // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
6085
6638
  plan.close();
6086
6639
  const observationStopped = stopObservationRetention();
@@ -6103,6 +6656,7 @@ async function startHolding(options, data, checked, stops) {
6103
6656
  await schemaSealed;
6104
6657
  await installStopped;
6105
6658
  await observationStopped;
6659
+ await localSourceSweep;
6106
6660
  // The ends' follower stops before the webhooks it feeds and the store it reads.
6107
6661
  clearTimeout(endsTimer);
6108
6662
  await endsRead;