@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
@@ -1,58 +1,27 @@
1
- // DELETE /v2/agents/{agent_id}: an agent another system owns (made by an inline run, POST /runs with `external`) deleted
2
- // whole, for a host that must delete what it sent (deleteExternalAgent). An agent made here is purged once it is archived
3
- // (purgeAgent; 409 agent_not_archived before). DELETE /v2/runs/{run_id}: one run purged (purgeRun), with the runs made
4
- // from it. An owner must be able to delete what a run read; what it cost stays in every total. So a purge keeps each
5
- // run's row, and an agent's, as a tombstone, and removes everything else of it.
1
+ // DELETE /v2/agents/{agent_id} deletes an agent another system owns whole (deleteExternalAgent), for a host that must
2
+ // delete what it sent, and purges an archived agent made here (purgeAgent). DELETE /v2/runs/{run_id} purges one run with
3
+ // the runs made from it (purgeRun). An owner must be able to delete what a run read, and what it cost stays in every
4
+ // total, so a purge keeps each run's row, and an agent's, as a tombstone and removes everything else of it.
6
5
  //
7
- // A run's purge (purgeRun), only once it is not live (409 run_not_final otherwise, nothing purged: live is not final, or
8
- // held by a runner; a run that ended and can take a follow-up is not live), nor any run made from it: first each run made
9
- // from it (the replay runs of its input, its audit's shadow run, a learning run its kept learning names; each one's own
10
- // such runs before it), then the grades its agent keeps of it and the content its promotion records copied from it (each
11
- // disagreement's input and answers, learn/promote.ts forgetRunCopies), then the run, each by purgeOne: the figures its spend's
12
- // readers read from its journal (kept on the tombstone, PurgeKept), its folders (its own folder on the agent's Archil disk
13
- // it resolved to, and on a disk its launch named), settings and kept answers, then its rows (store runs.purge, which sets
14
- // its purge time last). A replay of its input or an audit's shadow made by a claim (in a runner, maybe another process)
15
- // after the DELETE read the runs made from it is found by the store's purge, under the run's row lock: 409 run_not_final
16
- // naming it, the run kept for the next DELETE, which purges it first (RunsMadeFromLeft); one made once the run is purged
17
- // is refused at its create, nothing written (RunPurged). A DELETE stopped part way finds the run not purged yet and the
18
- // next DELETE finishes it; a DELETE of a purged run is 204 again, and every other route of it is 410 purged with its
19
- // tombstone.
6
+ // Every step is idempotent and ordered so that a DELETE stopped part way leaves the row there, for the next DELETE to
7
+ // finish; a DELETE of a purged run is 204 again. A live run (not final, or held by a runner) refuses its purge with 409
8
+ // run_not_final and nothing purged. The runs made from a run are purged before it: one a claim made after the DELETE read
9
+ // them is found by the store's purge under the run's row lock (RunsMadeFromLeft, 409 naming it), and one made once the run
10
+ // is purged is refused at its create (RunPurged). A run's purge takes its text off its agent's learning folder's current
11
+ // files (its merges' diff files and feedback lines, forgetCopies) and the folder's history reads serve none of its
12
+ // merges, while the folder's git keeps their bytes until a learning reset or the agent's purge deletes it.
20
13
  //
21
- // An archived agent made here (purgeAgent), by the same rule: 409 run_not_final while a run of it is live. Then its
22
- // learning, its things (triggers, sign-ins, its own computer, its disk), each of its runs by purgeOne (the runs made from
23
- // it first, as a run's purge does them), its folders, settings and kept answers, and its rows (store agents.purge: its
24
- // revisions' content, its name and description blanked, its purge time last). Each step is idempotent, so a DELETE stopped part way is finished by the next. Archived, the agent
25
- // takes no new run and no trigger fires it; a run that reached it anyway keeps it unpurged (the store refuses), for the
26
- // next DELETE.
27
- //
28
- // Another system's agent (deleteExternalAgent), in order, each step finished before the next:
29
- // 1. The agent refuses new runs, as a mark in the store that outlives a restart: its archive time, which only this
30
- // delete writes on an agent another system owns (its archive route is refused), set by the trigger engine with its
31
- // triggers off in the same commit. From that commit a person's run, an inline run, a trigger's firing, an SDK run and
32
- // a follow-up that would open one of its runs again are refused (store AgentDeleting / AgentArchived, each read in
33
- // the transaction that would start the run). Then each of its runs not yet final, its learning runs included, is
34
- // cancelled through the cancel path, and waited for until it is final.
35
- // 2. Its learning, by the learning module's deleteLearning (learn/delete.ts: its learning folder's files, then its
36
- // promotions and grades; idempotent; it refuses with LearningInFlight while learning work
37
- // is in flight, which answers 409 learning_busy with the agent left refusing runs).
38
- // 3. Its things: its triggers through the trigger engine (each one's registration upstream first, then its adapter
39
- // settings, then its row), its saved sign-ins (each vendor object too), its own computer, its Archil disk; then each
40
- // run's folders (on a disk its launch named, the caller's, too: the run's own folder there, never the disk), settings
41
- // and kept answers, and its rows (store runs.remove); then the agent's folders, settings and kept answers, and its
42
- // rows (store agents.remove, which commits last).
43
- // A DELETE stopped at any step finds the agent still there, marked, and does every step again: each is idempotent, so the
44
- // next DELETE finishes it. Once the agent's row is gone the agent is unknown: 404. Nothing the agent owns elsewhere (a
45
- // trigger's registration upstream, a saved sign-in at its vendor, its own computer, its Archil disk, a run's folder on a
46
- // disk its launch named) is left with the agent's row gone: the record here that names it (for a run's folder, its launch
47
- // record) is removed only once it is deleted there, and while it is not, the
48
- // delete stops with 503 unavailable, the agent kept and refusing runs, for the next DELETE to finish. From step 1's mark
49
- // the agent takes no new trigger, off or on (the trigger engine and the store refuse it), and no write to its home or its
50
- // learning (the server's, in the delete's turn); a trigger that reached it anyway keeps its row (store TriggersLeft): the
51
- // same 503, and the next DELETE removes that trigger as it removes the others.
14
+ // Another system's agent is first marked refusing new runs (its archive time, set with its triggers off in one commit, read
15
+ // by every path that would start a run), then its runs are cancelled and waited for, then its learning goes, then its
16
+ // things and rows, the agent's row last. Nothing it owns elsewhere (a trigger's registration upstream, a saved sign-in at
17
+ // its vendor, its own computer, its Archil disk, a run's folder on a disk its launch named) is left with no record here
18
+ // naming it: each record goes only once its thing is deleted there, and until then the DELETE is 503 unavailable, the
19
+ // agent kept and refusing runs. A trigger that reached it anyway keeps its row (store TriggersLeft): the same 503.
52
20
  import { ApiError } from "./errors.js";
53
21
  import { LearningInFlight } from "./learn/delete.js";
54
22
  import { FINAL_STATES, RunsMadeFromLeft, StoreConstraint, TriggersLeft } from "./store/index.js";
55
23
  import { forgetServed } from "./store-view.js";
24
+ import { requireSourceIOIdle } from "./source-sync/io.js";
56
25
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
57
26
  const isFinal = (state) => FINAL_STATES.includes(state);
58
27
  /** Deletes agent `agentId` (another system's, as the route checked) in the three steps above. Throws ApiError
@@ -62,6 +31,7 @@ export async function deleteExternalAgent(host, agentId) {
62
31
  await host.refuse(agentId);
63
32
  await stopRuns(host, agentId);
64
33
  await host.at?.("after_step_1", agentId);
34
+ await requireSourceIOIdle(host.store, agentId);
65
35
  // 2. Its learning.
66
36
  await learningGone(host, agentId);
67
37
  await host.at?.("after_step_2", agentId);
@@ -93,6 +63,7 @@ export async function purgeAgent(host, agentId) {
93
63
  // Marked before anything goes, and kept until its tombstone is written: a purge stopped part way leaves the agent
94
64
  // refusing an unarchive and every write (server.ts agentWrite) until a DELETE finishes it.
95
65
  await host.store.settings.put(purgingKey(agentId), true);
66
+ await requireSourceIOIdle(host.store, agentId);
96
67
  await learningGone(host, agentId);
97
68
  await host.at?.("after_step_2", agentId);
98
69
  await thingsGone(host, agentId);
@@ -128,13 +99,15 @@ export async function purgeAgent(host, agentId) {
128
99
  /** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
129
100
  export const purgingKey = (agentId) => `agent.purging.${agentId}`;
130
101
  /** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
131
- * run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
102
+ * run_not_final, nothing purged, while it or a run made from it is live. A purged run's only work is forgetCopies again,
103
+ * which finds nothing left once a purge finished it; its store scrub was marked before the purge changed a row
104
+ * (sqlite/store.ts #purging). */
132
105
  export async function purgeRun(host, runId) {
133
106
  const run = await host.store.runs.get(runId);
134
107
  if (!run)
135
108
  throw new ApiError("not_found", `no run ${runId}`);
136
109
  if (run.purgedAt !== null)
137
- return;
110
+ return host.forgetCopies(run.agentId, runId);
138
111
  const made = await madeFromAll(host, runId);
139
112
  const live = await liveOf(host, [run, ...made]);
140
113
  if (live.length)
@@ -162,15 +135,14 @@ async function purgeOneOrRefuse(host, agentId, runId, purged, alone) {
162
135
  throw notFinal(purged, error.runs);
163
136
  if (error instanceof StoreConstraint)
164
137
  throw notFinal(purged, [runId]);
138
+ // A purge can commit and still throw (a Postgres commit unanswered), and a retried DELETE skips a purged run: what
139
+ // the process served of it goes now unless the store reads it not purged.
140
+ if ((await host.store.runs.get(runId).catch(() => undefined))?.purgedAt !== null)
141
+ forgetServed(host.store, runId);
165
142
  throw error;
166
143
  }
167
- finally {
168
- // Its answer and input as this process last served them, dropped whatever the purge answered: every route of it is 410
169
- // once it committed, so none is read again. A purge can commit and still throw (its checkpoint held back and the
170
- // scrub's marker not written, sqlite/store.ts #purged), and no later DELETE comes back here (purgeRun: a purged run is
171
- // no work). One that did not commit loses a cache its next read fills again.
172
- forgetServed(host.store, runId);
173
- }
144
+ // Its answer and input as this process last served them: every route of it is 410 from here, so none is read again.
145
+ forgetServed(host.store, runId);
174
146
  }
175
147
  /** Every run made from run `runId` that is there and not purged, each one's own before it (deepest first), never `runId`. */
176
148
  async function madeFromAll(host, runId, seen = new Set([runId])) {
@@ -0,0 +1,71 @@
1
+ import { type Package } from "./templates.js";
2
+ import { type Json } from "./validate.js";
3
+ /** A package's file as the API carries it: text as itself, anything else base64. */
4
+ export type PackageFile = {
5
+ path: string;
6
+ encoding: "utf8" | "base64";
7
+ content: string;
8
+ };
9
+ /** What an export's note can be about: the document's enum of them (openapi.ts), so a note of a kind not here fails the
10
+ * build, and an answer the document does not list fails its schema check. */
11
+ export declare const EXPORT_NOTE_KINDS: readonly ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "secrets", "input_schema", "budget", "package"];
12
+ /** One thing an export could not carry as it is here: what it is, which one, and why, in words. */
13
+ export type ExportNote = {
14
+ kind: (typeof EXPORT_NOTE_KINDS)[number];
15
+ name: string;
16
+ reason: string;
17
+ };
18
+ export type AgentPackage = {
19
+ name: string;
20
+ files: PackageFile[];
21
+ sha256: string;
22
+ report: {
23
+ blocked: ExportNote[];
24
+ remade: ExportNote[];
25
+ };
26
+ };
27
+ /** A saved MCP server as an export reads it: its address, its auth type, what it is (mcp-sources.ts) and its tools. */
28
+ export type SavedServer = {
29
+ url: string;
30
+ auth: string;
31
+ source: {
32
+ source: string;
33
+ toolkit: string | null;
34
+ };
35
+ tools: readonly {
36
+ name: string;
37
+ }[];
38
+ };
39
+ export type ExportInput = {
40
+ agent: {
41
+ id: string;
42
+ name: string;
43
+ description: string | null;
44
+ };
45
+ /** The current revision as GET /agents shows it (agents-store.ts definitionOf). */
46
+ definition: Json;
47
+ /** The revision's skill files, by path under the agent's skills folder. */
48
+ skills: Readonly<Record<string, string>>;
49
+ /** The package the agent was applied from (agentView's `template`) with the key names its apply kept (absent on a
50
+ * revision applied before they were kept), and that package as this server holds it now. */
51
+ template: {
52
+ id: string;
53
+ version: string;
54
+ secrets?: readonly string[];
55
+ } | null;
56
+ origin: Package | undefined;
57
+ servers: ReadonlyMap<string, SavedServer>;
58
+ /** The agent's triggers as GET /triggers shows them: those that start its runs, and those that message one of them. */
59
+ triggers: readonly Json[];
60
+ /** The agent's saved browser sign-ins. */
61
+ signIns: readonly {
62
+ provider: string;
63
+ name: string;
64
+ }[];
65
+ /** The time by the triggers' clock, in epoch milliseconds. */
66
+ now: number;
67
+ };
68
+ /** The package's digest: sha256, in hex, over its files sorted by path, each written as `path NUL bytes NUL`. */
69
+ export declare function packageSha256(files: readonly PackageFile[]): string;
70
+ /** The agent as a package (see the head of this file). */
71
+ export declare function agentPackage(input: ExportInput): AgentPackage;
@@ -0,0 +1,345 @@
1
+ // An agent's current revision written as a template package (GET /v2/agents/{id}/package): the reverse of an apply. Its
2
+ // grants of saved MCP servers become needs by source and toolkit, its triggers bodies with no agent and no secret, and
3
+ // what names this host (its box, its computer's provider, its pins of this server's listings, its place) is left out.
4
+ // What can't travel is said in two lists: `blocked` (the agent would not work elsewhere, or a field it copies holds a
5
+ // credential in the clear, so `agentrun export` writes nothing) and `remade` (the target sets it up again: a webhook's
6
+ // secret, a sign-in, a paired computer, learned state).
7
+ // The answer's files are read back with readPackage before they are answered, so what is answered is a package.
8
+ import { createHash } from "node:crypto";
9
+ import { stringify } from "yaml";
10
+ import { LOOPBACK } from "./mcp-oauth.js";
11
+ import { MANIFEST, memoryFiles, onServerNames, PackageError, readPackage } from "./templates.js";
12
+ import { isMcpName, isMonidName, mcpToolName, parseToolName } from "./tool-names.js";
13
+ import { isPinKeys, permissionKeys, SHELL_FAMILY } from "./tool-gate.js";
14
+ import { toolOf } from "./tools.js";
15
+ import { configSecrets, SEALED_FIELD, SEALED_MASK } from "./trigger-composio.js";
16
+ import { CATCHUP_WINDOW_S } from "./triggers.js";
17
+ import { isObject, MODEL_TIER_NAMES, stable } from "./validate.js";
18
+ import { PAIRED_ID_PREFIX } from "./workspace/attached-computers.js";
19
+ /** What an export's note can be about: the document's enum of them (openapi.ts), so a note of a kind not here fails the
20
+ * build, and an answer the document does not list fails its schema check. */
21
+ export const EXPORT_NOTE_KINDS = ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "secrets", "input_schema", "budget", "package"];
22
+ /** The package's digest: sha256, in hex, over its files sorted by path, each written as `path NUL bytes NUL`. */
23
+ export function packageSha256(files) {
24
+ const hash = createHash("sha256");
25
+ for (const file of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
26
+ hash.update(file.path).update(NUL).update(Buffer.from(file.content, file.encoding)).update(NUL);
27
+ }
28
+ return hash.digest("hex");
29
+ }
30
+ const NUL = Buffer.from([0]);
31
+ /** A package name (lowercase letters, digits and single dashes, at most 64) made of `text`, or "" when nothing of it fits. */
32
+ const slug = (text) => text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 64).replace(/-+$/, "");
33
+ /** The trigger kinds whose setup the target makes again, and what the owner does there. */
34
+ const REMADE_TRIGGERS = {
35
+ webhook: "A webhook trigger gets its own signing secret on the target: give the sender the new one.",
36
+ github: "A github trigger takes events through the target's GitHub App: connect GitHub there (it is skipped until then).",
37
+ composio: "A composio trigger is made again on the target's Composio project.",
38
+ email: "An email trigger receives at an address the target gives it: point the sender at the new one.",
39
+ };
40
+ /** The input fields' keys in the order a package writes them (templates.ts INPUT_KEYS), and a list's items'. */
41
+ const FIELD_KEYS = ["type", "title", "description", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum", "examples", "default"];
42
+ const ITEM_KEYS = ["type", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum"];
43
+ const pick = (from, keys) => Object.fromEntries(keys.flatMap((key) => (from[key] !== undefined ? [[key, from[key]]] : [])));
44
+ /** Each field of `value`, a part of the agent an export copies as it is, that holds a credential in the clear, as its
45
+ * path from `at` (source.urls.0, target.input.api_key): by the walk a composio trigger's config is sealed by
46
+ * (trigger-composio.ts configSecrets: a field named like a credential, at any depth, and an address that carries one,
47
+ * such as a query's token). The field, never the value. */
48
+ const clearIn = (value, at) => configSecrets(value).map((secret) => [at, ...secret.path].join("."));
49
+ const IN_THE_CLEAR = "It holds a credential in the clear, and a package carries no credential: take it out of this field here, then export again.";
50
+ /** `schema`, a compiled input schema, as the manifest's `inputs` that compile to it again; undefined for one that is not a
51
+ * closed object of fields. Whether it compiles back the same is checked once the package is read. */
52
+ function inputsOf(schema) {
53
+ if (!isObject(schema) || schema.type !== "object" || !isObject(schema.properties) || !Object.keys(schema.properties).length)
54
+ return undefined;
55
+ const required = Array.isArray(schema.required) ? schema.required : [];
56
+ const inputs = {};
57
+ for (const [key, property] of Object.entries(schema.properties)) {
58
+ if (!isObject(property))
59
+ return undefined;
60
+ const field = pick(property, FIELD_KEYS);
61
+ inputs[key] = { ...field, ...(isObject(property.items) ? { items: pick(property.items, ITEM_KEYS) } : {}), ...(required.includes(key) ? {} : { required: false }) };
62
+ }
63
+ return inputs;
64
+ }
65
+ /** An input schema as a package compiles one: an empty `required` is left out. */
66
+ const compiledForm = (schema) => (Array.isArray(schema.required) && !schema.required.length ? (({ required: _none, ...rest }) => rest)(schema) : schema);
67
+ /** The agent as a package (see the head of this file). */
68
+ export function agentPackage(input) {
69
+ const { agent, definition, origin, template } = input;
70
+ const blocked = [];
71
+ const remade = [];
72
+ // Its name: the template's it was applied from, else the agent's own as a package name.
73
+ const pkgName = origin?.name || (template ? slug(template.id.split(/[/:]/).at(-1) ?? "") : "") || slug(agent.name) || slug(agent.id) || "agent";
74
+ const sameVersion = !!origin && !!template && origin.version === template.version;
75
+ const settings = (isObject(definition.tool_settings) ? definition.tool_settings : {});
76
+ // Denied as the gate reads the agent's own settings: a shell tool by bash's, then the most specific key set (the tool's
77
+ // own, else its MCP server's or monid provider's wildcard).
78
+ const denied = (tool) => permissionKeys(Object.hasOwn(SHELL_FAMILY, tool) ? SHELL_FAMILY[tool] : tool).map((key) => settings[key]).find((setting) => setting?.permission !== undefined)?.permission === "deny";
79
+ // Its tools: plain and monid ones as they are; MCP ones by server, a wildcard read as the tools its server lists.
80
+ // A tool denied here is left out, so no target grants it.
81
+ const tools = Array.isArray(definition.tools) ? definition.tools : undefined;
82
+ const plain = tools?.filter((tool) => !isMcpName(tool) && !denied(tool));
83
+ const byServer = new Map();
84
+ for (const tool of tools?.filter(isMcpName) ?? []) {
85
+ const parsed = parseToolName(tool);
86
+ if (!parsed || (parsed.kind !== "mcp" && parsed.kind !== "mcp-server"))
87
+ continue;
88
+ const named = parsed.kind === "mcp" ? [parsed.tool] : (input.servers.get(parsed.server)?.tools ?? []).map((one) => one.name);
89
+ const list = byServer.get(parsed.server) ?? [];
90
+ for (const one of named)
91
+ if (!list.includes(one) && !denied(mcpToolName(parsed.server, one)))
92
+ list.push(one);
93
+ byServer.set(parsed.server, list);
94
+ }
95
+ // A trigger that messages one of its runs names a run of this server's, which no package can.
96
+ const starts = input.triggers.filter((view) => !(isObject(view.target) && view.target.kind === "message_run"));
97
+ for (const view of input.triggers.filter((one) => !starts.includes(one)))
98
+ remade.push({ kind: "trigger", name: String(view.name), reason: "It sends a message to a run on this server, which a package can't name: make it again on the target, aimed at a run there." });
99
+ const composioServers = new Set(starts.flatMap((trigger) => (isObject(trigger.source) && trigger.source.kind === "composio" && typeof trigger.source.server === "string" ? [trigger.source.server] : [])));
100
+ // Each saved server the agent is granted tools of, by source and toolkit; one saved nowhere here, on this machine's
101
+ // loopback, or with its own credential in a header is blocked; one the owner signed in to is remade.
102
+ const mcp = [];
103
+ const toolkits = {};
104
+ for (const [server, granted] of byServer) {
105
+ const saved = input.servers.get(server);
106
+ if (!saved) {
107
+ blocked.push({ kind: "mcp_server", name: server, reason: "It is not a saved MCP server here: a local (stdio) server the agent was given on its own machine stays there. Save it as a remote MCP server, or take its tools out of the agent." });
108
+ continue;
109
+ }
110
+ if (saved.source.source === "url") {
111
+ const why = [];
112
+ let host = "";
113
+ try {
114
+ host = new URL(saved.url).hostname;
115
+ }
116
+ catch {
117
+ why.push("its address does not read as a URL");
118
+ }
119
+ if (LOOPBACK.test(host))
120
+ why.push(`it is on this machine (${host}), which the target can't reach`);
121
+ if (saved.auth === "bearer" || saved.auth === "headers")
122
+ why.push("it sends its own auth header, a credential saved on this server that a package never carries");
123
+ if (why.length) {
124
+ blocked.push({ kind: "mcp_server", name: server, reason: `${why.map((one) => `${one.charAt(0).toUpperCase()}${one.slice(1)}`).join(". ")}. Save a server the target reaches, with its own credential there, and grant its tools.` });
125
+ continue;
126
+ }
127
+ if (saved.auth === "oauth")
128
+ remade.push({ kind: "mcp_server", name: server, reason: "It signs in with OAuth: sign in to it again on the target." });
129
+ if (saved.auth === "per_run")
130
+ remade.push({ kind: "mcp_server", name: server, reason: "It takes its credential with each run: the target's runs pass their own." });
131
+ }
132
+ if (!granted.length)
133
+ continue;
134
+ const toolkit = saved.source.toolkit ?? server;
135
+ toolkits[server] = toolkit;
136
+ const pin = {};
137
+ // A pin travels as it is, so one that holds a credential in the clear is blocked, and left out. Its values are read
138
+ // (a scalar, a one-of list); a keys pin holds the names of the fields a call may give, never a value, so it is not.
139
+ for (const tool of granted) {
140
+ const held = settings[mcpToolName(server, tool)]?.pin;
141
+ if (held === undefined)
142
+ continue;
143
+ const values = isObject(held) ? Object.fromEntries(Object.entries(held).filter(([, value]) => !isPinKeys(value))) : held;
144
+ const clear = clearIn(values, `pin.${tool}`);
145
+ for (const field of clear)
146
+ blocked.push({ kind: "pin", name: `${server}: ${field}`, reason: IN_THE_CLEAR });
147
+ if (!clear.length)
148
+ pin[tool] = held;
149
+ }
150
+ const reason = origin?.mcp.find((need) => need.source === saved.source.source && need.toolkit === toolkit)?.reason;
151
+ // Required where a composio trigger runs on it (as a package's composio trigger must); else skipped where none matches.
152
+ mcp.push({ source: saved.source.source, toolkit, tools: granted, ...(composioServers.has(server) ? { required: true } : {}), ...(reason ? { reason } : {}), ...(Object.keys(pin).length ? { pin } : {}) });
153
+ }
154
+ // What the tool settings hold beyond a pin of a granted MCP tool and bash's policy is this server's.
155
+ for (const [tool, setting] of Object.entries(settings)) {
156
+ if (!isObject(setting) || setting.permission === "deny")
157
+ continue;
158
+ const parsed = parseToolName(tool);
159
+ const ofNeed = parsed?.kind === "mcp" && mcp.some((need) => toolkits[parsed.server] === need.toolkit && need.tools.includes(parsed.tool));
160
+ if (setting.pin !== undefined && !ofNeed) {
161
+ if (parsed?.kind === "mcp" || parsed?.kind === "mcp-server")
162
+ remade.push({ kind: "pin", name: tool, reason: "A pin on a tool the agent is not granted: pin it again on the target if the tool is granted there." });
163
+ else
164
+ blocked.push({ kind: "tool_setting", name: tool, reason: "Its arguments are pinned, and a package pins MCP tools alone: without the pin the agent would get more than it has here." });
165
+ }
166
+ if (setting.permission === "allow")
167
+ remade.push({ kind: "tool_setting", name: tool, reason: "It runs without asking here: allow it again on the target." });
168
+ const own = ["provider", "scope"].filter((key) => setting[key] !== undefined);
169
+ if (own.length)
170
+ remade.push({ kind: "tool_setting", name: tool, reason: `Its ${own.join(" and ")} is set on this server: set it again on the target.` });
171
+ }
172
+ // The computer it needs, read down to what any server gives: a shell, or none. The box, the provider, a paired
173
+ // computer and a sandbox's own setup are this server's.
174
+ const computer = isObject(definition.computer) ? definition.computer : undefined;
175
+ const shellTools = (plain ?? []).filter((tool) => toolOf(tool)?.sandboxOnly);
176
+ let computers;
177
+ // The programs its sandbox must have (computer.needs), which a package names beside [shell] alone.
178
+ let needs;
179
+ if (computer?.kind === "none")
180
+ computers = shellTools.length ? ["shell", "none"] : ["none"];
181
+ else if (computer?.kind === "sandbox") {
182
+ computers = ["shell"];
183
+ if (Array.isArray(computer.needs) && computer.needs.length)
184
+ needs = computer.needs.map(String);
185
+ if (computer.image !== undefined || computer.gpu !== undefined || computer.persistent !== undefined)
186
+ remade.push({ kind: "computer", name: "sandbox", reason: "Its sandbox's image, GPUs or persistence are set on this server: set them again on the target." });
187
+ }
188
+ else if (computer)
189
+ remade.push({ kind: "computer", name: String(computer.kind), reason: `A ${String(computer.kind)} computer is this server's: give the agent one again on the target.` });
190
+ if (typeof computer?.provider === "string" && computer.provider.startsWith(PAIRED_ID_PREFIX))
191
+ remade.push({ kind: "paired_computer", name: computer.provider, reason: "A computer paired with this server: pair one with the target." });
192
+ // Its model: the agent's own, and the tier whose model it is (that tier's entry then left out), else balanced; with no
193
+ // model, the tier the package it came from names, so the target picks its own model for it.
194
+ const model = typeof definition.model === "string" ? definition.model : undefined;
195
+ const tiers = (isObject(definition.model_tiers) ? definition.model_tiers : {});
196
+ const ownTier = model ? MODEL_TIER_NAMES.find((tier) => tiers[tier] === model) : undefined;
197
+ const tier = ownTier ?? (model ? "balanced" : origin?.model?.tier ?? "balanced");
198
+ const modelEntry = { tier, ...(model ? { prefer: model } : {}), ...Object.fromEntries(MODEL_TIER_NAMES.flatMap((one) => (one !== ownTier && typeof tiers[one] === "string" ? [[one, tiers[one]]] : []))) };
199
+ // Its triggers, as POST /triggers bodies with no agent: a composio one's server read as its need's toolkit, and what
200
+ // this server set on it (its instance, its hook, its sealed values) left out.
201
+ const triggers = [];
202
+ for (const view of starts) {
203
+ const target = isObject(view.target) ? view.target : {};
204
+ const triggerName = String(view.name);
205
+ let source = isObject(view.source) ? { ...view.source } : {};
206
+ const kind = String(source.kind);
207
+ // A one-shot schedule whose time has passed fired here (or was missed): an apply refuses a time in the past.
208
+ if (kind === "schedule" && typeof source.at === "string" && Date.parse(source.at) <= input.now) {
209
+ remade.push({ kind: "trigger", name: triggerName, reason: `It fired once, at ${source.at}, which has passed: give it a new time on the target.` });
210
+ continue;
211
+ }
212
+ let sealed = [];
213
+ if (kind === "composio") {
214
+ const { instance_id: _instance, hook: _hook, [SEALED_FIELD]: _sealed, ...rest } = source;
215
+ const config = isObject(rest.config) ? rest.config : undefined;
216
+ sealed = config ? Object.keys(config).filter((key) => config[key] === SEALED_MASK) : [];
217
+ source = { ...rest, ...(config ? { config: Object.fromEntries(Object.entries(config).filter(([key]) => !sealed.includes(key))) } : {}) };
218
+ if (typeof source.server !== "string" || !Object.hasOwn(toolkits, source.server)) {
219
+ blocked.push({ kind: "trigger", name: triggerName, reason: `Its Composio server ${String(source.server)} is not one whose tools the agent is granted, and a package's composio trigger runs on one of its MCP needs.` });
220
+ continue;
221
+ }
222
+ source.server = toolkits[source.server];
223
+ }
224
+ // Its source and input travel as they are, so one that holds a credential in the clear (a feed URL's ?token=, an
225
+ // input's api_key) is blocked, and left out.
226
+ const runInput = target.input ?? {};
227
+ const clear = [...clearIn(source, "source"), ...clearIn(runInput, "target.input")];
228
+ if (clear.length) {
229
+ for (const field of clear)
230
+ blocked.push({ kind: "trigger", name: `${triggerName}: ${field}`, reason: IN_THE_CLEAR });
231
+ continue;
232
+ }
233
+ triggers.push({
234
+ name: triggerName, ...(view.enabled === false ? { enabled: false } : {}), source,
235
+ ...(typeof view.catchup_window_s === "number" && view.catchup_window_s !== CATCHUP_WINDOW_S ? { catchup_window_s: view.catchup_window_s } : {}),
236
+ ...(typeof view.max_active_runs === "number" ? { max_active_runs: view.max_active_runs } : {}),
237
+ target: { kind: "start_run", input: runInput, ...(target.max_cost_usd !== undefined ? { max_cost_usd: target.max_cost_usd } : {}), ...(target.effort !== undefined ? { effort: target.effort } : {}) },
238
+ });
239
+ if (Object.hasOwn(REMADE_TRIGGERS, kind))
240
+ remade.push({ kind: "trigger", name: triggerName, reason: `${REMADE_TRIGGERS[kind]}${sealed.length ? ` Its sealed config (${sealed.join(", ")}) is set again there.` : ""}` });
241
+ }
242
+ for (const signIn of input.signIns)
243
+ remade.push({ kind: "sign_in", name: signIn.provider, reason: `The browser sign-in ${signIn.name} is saved on this server: sign in again on the target.` });
244
+ const learning = definition.learning;
245
+ if (learning === true || isObject(learning))
246
+ remade.push({ kind: "learning", name: "learning", reason: "What the agent learned here stays here: its learning starts fresh on the target." });
247
+ // Its texts with each saved server's name read as its toolkit's, as the package names its tools.
248
+ const renamed = Object.fromEntries(Object.entries(toolkits).filter(([server, toolkit]) => server !== toolkit));
249
+ const instructions = onServerNames(String(definition.instructions ?? ""), renamed).trim();
250
+ const skills = Object.fromEntries(Object.entries(input.skills).map(([path, text]) => [path, onServerNames(text, renamed)]));
251
+ // A rule the package it came from ships beside each SKILL.md, the same text beside each, is its rules/ file again.
252
+ const folders = Object.keys(skills).filter((path) => /^[^/]+\/SKILL\.md$/.test(path)).map((path) => path.slice(0, -"/SKILL.md".length));
253
+ const rules = {};
254
+ for (const rule of origin?.rules ?? []) {
255
+ const texts = new Set(folders.map((folder) => skills[`${folder}/${rule}`]));
256
+ const [text] = texts;
257
+ if (!folders.length || texts.size !== 1 || typeof text !== "string")
258
+ continue;
259
+ rules[rule] = text;
260
+ for (const folder of folders)
261
+ delete skills[`${folder}/${rule}`];
262
+ }
263
+ const files = new Map();
264
+ for (const [path, text] of Object.entries(skills))
265
+ files.set(`skills/${path}`, text);
266
+ for (const [rule, text] of Object.entries(rules))
267
+ files.set(`rules/${rule}`, text);
268
+ // The answer's schema: a skill file that is it, else a file of its own at the package's root.
269
+ const outputSchema = isObject(definition.output_schema) ? definition.output_schema : undefined;
270
+ let output;
271
+ if (outputSchema) {
272
+ output = [...files.keys()].sort().find((path) => {
273
+ try {
274
+ return stable(JSON.parse(files.get(path))) === stable(outputSchema);
275
+ }
276
+ catch {
277
+ return false;
278
+ }
279
+ });
280
+ if (!output) {
281
+ const given = origin?.output?.schema;
282
+ output = given && !given.includes("/") && given !== MANIFEST ? given : "output.schema.json";
283
+ files.set(output, `${JSON.stringify(outputSchema, null, 2)}\n`);
284
+ }
285
+ }
286
+ const inputSchema = isObject(definition.input_schema) ? definition.input_schema : undefined;
287
+ const inputs = inputSchema && inputsOf(inputSchema);
288
+ if (inputSchema && !inputs)
289
+ blocked.push({ kind: "input_schema", name: "inputs", reason: "Its input schema is not a closed object of fields, which is what a package's inputs are." });
290
+ // The keys its package declared, as its apply kept them; for a revision applied before they were kept, the package as
291
+ // this server holds it, which names them only while it is the same version.
292
+ const declared = template?.secrets ?? (sameVersion ? origin.secrets : []);
293
+ const secrets = [...new Set([...declared, ...((plain ?? []).some(isMonidName) ? ["MONID_API_KEY"] : [])])].sort();
294
+ // Such a revision of a package updated or removed since its apply: the keys it was applied with are unknown here.
295
+ if (template && !template.secrets && !sameVersion)
296
+ remade.push({ kind: "secrets", name: template.id, reason: `The keys version ${template.version} of ${template.id} names are not known here: ${origin ? `this server holds version ${origin.version}` : "this server no longer holds it"}. Save the keys the agent uses on the target, and name them under secrets in ${MANIFEST}.` });
297
+ const bash = settings.bash?.policy;
298
+ // Bash's policy holds every shell tool, and a package writes it only beside bash: a shell tool kept without bash would
299
+ // run there what the policy refuses here.
300
+ const shellKept = (plain ?? []).filter((tool) => Object.hasOwn(SHELL_FAMILY, tool));
301
+ if (typeof bash === "string" && shellKept.length && !shellKept.includes("bash"))
302
+ blocked.push({ kind: "tool_policy", name: "bash", reason: `Its bash policy (${bash}) holds ${shellKept.join(", ")}, and a package writes that policy only beside bash: grant bash too, or take ${shellKept.length === 1 ? "it" : "them"} out of the agent.` });
303
+ const description = (agent.description?.trim() || agent.name).slice(0, 1024);
304
+ // A package's budget is a spend cap per run first, and one with triggers has one: what fires runs nobody watches.
305
+ const cost = typeof definition.max_cost_usd === "number" ? definition.max_cost_usd : undefined;
306
+ const requests = typeof definition.max_requests === "number" ? definition.max_requests : undefined;
307
+ if (cost === undefined && requests !== undefined)
308
+ blocked.push({ kind: "budget", name: "max_requests", reason: "It caps each run's requests and not its spend, and a package's budget is a spend cap per run: set the agent's max_cost_usd." });
309
+ if (cost === undefined && triggers.length) {
310
+ blocked.push({ kind: "budget", name: "max_cost_usd", reason: "It has triggers and no spend cap per run, and a package with triggers caps what each run they fire may spend: set the agent's max_cost_usd." });
311
+ triggers.length = 0;
312
+ remade.splice(0, remade.length, ...remade.filter((note) => note.kind !== "trigger"));
313
+ }
314
+ // The manifest, in the order templates.ts reads its fields.
315
+ const manifest = {
316
+ name: pkgName, display_name: agent.name, version: template?.version ?? "1.0.0", description,
317
+ harness: [definition.harness], model: modelEntry,
318
+ ...(typeof definition.thinking === "string" ? { effort: definition.thinking } : {}),
319
+ ...(plain ? { tools: plain } : {}), ...(mcp.length ? { mcp } : {}),
320
+ ...(typeof bash === "string" && plain?.includes("bash") ? { tool_policy: { bash } } : {}),
321
+ ...(computers ? { computer: computers } : {}), ...(needs ? { needs } : {}),
322
+ ...(definition.checkout === "pull_request" ? { checkout: "pull_request" } : {}),
323
+ ...(inputs ? { inputs } : {}), ...(secrets.length ? { secrets } : {}),
324
+ ...(cost !== undefined ? { budget: { per_run_usd: cost, ...(requests !== undefined ? { max_requests: requests } : {}) } } : {}),
325
+ ...(learning !== undefined ? { learning } : {}),
326
+ approvals: definition.approvals === "never" ? "never" : "ask",
327
+ ...(triggers.length ? { triggers } : {}),
328
+ ...(output ? { output: { schema: output } } : {}),
329
+ };
330
+ files.set(MANIFEST, `---\n${stringify(manifest, { lineWidth: 0, aliasDuplicateObjects: false })}---\n\n${instructions}\n`);
331
+ const answer = [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, content]) => ({ path, encoding: "utf8", content }));
332
+ // Read back as any package is: each problem is a reason the export would not apply anywhere.
333
+ try {
334
+ const pkg = readPackage(memoryFiles(pkgName, `the export of ${agent.id}`, new Map(answer.map((file) => [file.path, Buffer.from(file.content, "utf8")]))));
335
+ if (inputs && stable(pkg.inputSchema) !== stable(compiledForm(inputSchema)))
336
+ blocked.push({ kind: "input_schema", name: "inputs", reason: "Its input schema uses JSON Schema a package's inputs can't say, so the target's agent would take other input." });
337
+ }
338
+ catch (error) {
339
+ if (!(error instanceof PackageError))
340
+ throw error;
341
+ for (const problem of error.problems)
342
+ blocked.push({ kind: "package", name: pkgName, reason: problem });
343
+ }
344
+ return { name: pkgName, files: answer, sha256: packageSha256(answer), report: { blocked, remade } };
345
+ }