@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,10 +1,5 @@
1
- import { type AgentRow, type NewRevision, type RevisionPlace, type RevisionRow, type Store, type TemplatePackage } from "./store/index.js";
1
+ import { type AgentRow, type NewRevision, type SettingsGuard, type RevisionPlace, type RevisionRow, type Store, type TemplatePackage } from "./store/index.js";
2
2
  import { type DefinitionBody, type Json } from "./validate.js";
3
- /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision and per minted agent. Two
4
- * minted in one millisecond keep their order: the 12 bits after the time count them up (RFC 9562's monotonic counter),
5
- * and a clock that steps back keeps the last millisecond, so each id sorts after the one before it. Without that, two
6
- * edits in one millisecond tie on created_at and their random ids could number the newer revision first. */
7
- export declare function uuidv7(now?: number): string;
8
3
  /** The store slice this module needs (its agents accessor). */
9
4
  export type AgentsStore = Pick<Store, "agents">;
10
5
  /** One agent as the routes show it: its row, its current revision and that revision's number (the oldest is 1), how many
@@ -16,10 +11,15 @@ export type AgentEntry = {
16
11
  version: number;
17
12
  revisions: number;
18
13
  sizes: Map<string, number>;
19
- /** The template package it was last applied from, as the newest revision an apply wrote keeps it (its first, until an
20
- * apply with agent_id updates it); absent or null for one made otherwise. */
14
+ /** The template package its current revision came from (packageOf): as the apply that wrote that revision, or the
15
+ * nearest one before it in its line, kept it; absent or null for one made otherwise. */
21
16
  template?: TemplatePackage | null;
22
17
  };
18
+ /** Whether another system owns `agent`: an inline run with `external` made it (its `externalRef` set), so the system that
19
+ * sent it sends its deletes, the agent's whole (DELETE /agents/{id}) and, on an API-only server, a run's purge. */
20
+ export declare const ownedElsewhere: (agent: AgentRow) => agent is AgentRow & {
21
+ externalRef: string;
22
+ };
23
23
  /** Refuses a write to an externally owned agent: one that mirrors an agent in another system (its `externalRef` set) is
24
24
  * read-only here — its source is the truth, which writes a new version by running it. Edits, set-current and archive are
25
25
  * refused (403 forbidden); reads work as for any agent. */
@@ -46,6 +46,11 @@ export type SaveStamp = Pick<NewRevision, "mcpPin" | "monidPin">;
46
46
  * to stamp on it. `on`: the revision this save is built on (an edit's: the agent's current one as this try read it, so a
47
47
  * retry on a newer one sees that one; null for a new agent), whose pins carry what the save's grants did not change. */
48
48
  export type SaveCheck = (revision: NewRevision, on: RevisionRow | null) => Promise<SaveStamp | void>;
49
+ /** Immutable assets prepared inside the delete turn; keep their I/O ownership until the revision CAS settles. */
50
+ export type SavePrepare = (revision: NewRevision, on: RevisionRow | null) => Promise<{
51
+ revision: NewRevision;
52
+ settled(): Promise<void>;
53
+ }>;
49
54
  /** The agent `id` as an entry, or null when there is no such agent: its row, its current revision (by the agent row's
50
55
  * current_revision), that revision's number (newest is the count), and the skill sizes. */
51
56
  export declare function getAgent(store: AgentsStore, id: string): Promise<AgentEntry | null>;
@@ -87,9 +92,11 @@ export type InTurn = <T>(work: () => Promise<T>) => Promise<T>;
87
92
  * `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
88
93
  * (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
89
94
  * purged agent, or one whose purge stopped part way); the check runs outside it. */
90
- export declare function commitAgent(store: AgentsStore, read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract, template, fromPackage, inTurn }?: {
95
+ export declare function commitAgent(store: AgentsStore, read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, settingsGuards, check, prepare, contract, template, fromPackage, inTurn }?: {
91
96
  ifCurrent?: string | null;
97
+ settingsGuards?: readonly SettingsGuard[];
92
98
  check?: SaveCheck;
99
+ prepare?: SavePrepare;
93
100
  contract?: boolean;
94
101
  template?: TemplatePackage;
95
102
  fromPackage?: boolean;
@@ -133,15 +140,6 @@ export declare function agentView(entry: AgentEntry, origin: string, extra?: {
133
140
  learning?: {
134
141
  pending: number;
135
142
  } | undefined;
136
- definition: Json | null;
137
- kind: string | null;
138
- mcp_pin: Record<string, {
139
- tools: Record<string, unknown>[];
140
- prices?: Record<string, number>;
141
- }> | null;
142
- revision: string | null;
143
- revisions: number;
144
- source: null;
145
143
  template: {
146
144
  id: string;
147
145
  version: string;
@@ -162,6 +160,18 @@ export declare function agentView(entry: AgentEntry, origin: string, extra?: {
162
160
  home_etag: string;
163
161
  archived_at: string | null;
164
162
  console_url: string;
163
+ source_sync?: {
164
+ moved: true;
165
+ } | undefined;
166
+ definition: Json | null;
167
+ kind: string | null;
168
+ mcp_pin: Record<string, {
169
+ tools: Record<string, unknown>[];
170
+ prices?: Record<string, number>;
171
+ }> | null;
172
+ revision: string | null;
173
+ revisions: number;
174
+ source: null;
165
175
  external?: (ExternalRef & {
166
176
  version: string | null;
167
177
  }) | undefined;
@@ -5,8 +5,9 @@
5
5
  // racing another writer; the store's own transactions make each write atomic.
6
6
  //
7
7
  // The run counts an agent view shows (runs.count, runs.live) are E3's run reads, not this module's; agentView takes them.
8
- import { randomBytes } from "node:crypto";
8
+ import { sourceSyncOf } from "./source-sync/types.js";
9
9
  import { purgedAgent } from "./agents.js";
10
+ import { uuidv7 } from "./ids.js";
10
11
  import { agentLink } from "./console-links.js";
11
12
  import { approvalsOf } from "./approvals.js";
12
13
  import { ApiError, invalid } from "./errors.js";
@@ -18,30 +19,6 @@ import { AgentBodyInvalid, RevisionMoved, bodyOf, canonical, isObject, StoreCons
18
19
  import { canonicalToolSettings, settingsIssues } from "./tool-plane.js";
19
20
  import { computerOfPlace, settingOfDefinition } from "./computer-setting.js";
20
21
  import { skillIssues, skillNames } from "./validate.js";
21
- /** The last millisecond a UUIDv7 was minted in, and how many were minted in it. */
22
- let mintedMs = -1;
23
- let mintedInMs = 0;
24
- /** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision and per minted agent. Two
25
- * minted in one millisecond keep their order: the 12 bits after the time count them up (RFC 9562's monotonic counter),
26
- * and a clock that steps back keeps the last millisecond, so each id sorts after the one before it. Without that, two
27
- * edits in one millisecond tie on created_at and their random ids could number the newer revision first. */
28
- export function uuidv7(now = Date.now()) {
29
- if (now > mintedMs) {
30
- mintedMs = now;
31
- mintedInMs = 0;
32
- }
33
- else if (++mintedInMs > 0xfff) {
34
- mintedMs += 1;
35
- mintedInMs = 0;
36
- }
37
- const bytes = randomBytes(16);
38
- bytes.writeUIntBE(mintedMs, 0, 6);
39
- bytes[6] = 0x70 | (mintedInMs >> 8);
40
- bytes[7] = mintedInMs & 0xff;
41
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
42
- const hex = bytes.toString("hex");
43
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
44
- }
45
22
  const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
46
23
  /** A store refusal as the request's answer: a duplicate name (agent exists) and a constraint map the right way. */
47
24
  function storeError(error) {
@@ -51,11 +28,14 @@ function storeError(error) {
51
28
  throw invalid([{ field: "definition", reason: "invalid", message: error.message }]);
52
29
  throw error;
53
30
  }
31
+ /** Whether another system owns `agent`: an inline run with `external` made it (its `externalRef` set), so the system that
32
+ * sent it sends its deletes, the agent's whole (DELETE /agents/{id}) and, on an API-only server, a run's purge. */
33
+ export const ownedElsewhere = (agent) => agent.externalRef !== null;
54
34
  /** Refuses a write to an externally owned agent: one that mirrors an agent in another system (its `externalRef` set) is
55
35
  * read-only here — its source is the truth, which writes a new version by running it. Edits, set-current and archive are
56
36
  * refused (403 forbidden); reads work as for any agent. */
57
37
  export function refuseExternal(agent) {
58
- if (agent.externalRef !== null)
38
+ if (ownedElsewhere(agent))
59
39
  throw new ApiError("forbidden", `The agent ${agent.id} is managed by its source and is read-only here; change it there and run it again.`);
60
40
  }
61
41
  /** The store's one key of an external reference, "<source>:<kind>:<id>": source and kind hold no colon (POST /runs checks
@@ -64,7 +44,7 @@ export const externalKey = ({ source, kind, id }) => `${source}:${kind}:${id}`;
64
44
  /** The agent's reference in its source and the version its current revision maps there, or null for an agent of this
65
45
  * server's own. */
66
46
  export function externalOf(agent, revision) {
67
- if (agent.externalRef === null)
47
+ if (!ownedElsewhere(agent))
68
48
  return null;
69
49
  const [source = "", kind = "", ...id] = agent.externalRef.split(":");
70
50
  return { source, kind, id: id.join(":"), version: revision?.externalVersion ?? null };
@@ -100,7 +80,7 @@ function revisionInputOf(definition, files) {
100
80
  // pin's arguments sorted) so two revisions that say the same are one body. The store never reimplements it.
101
81
  const set = toolSettingsOf(definition.tool_settings);
102
82
  const common = { skills: files, tools: definition.tools ?? [], ...harness, ...place, ...set };
103
- const capped = typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {};
83
+ const capped = { ...(typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {}), ...(typeof definition.max_requests === "number" && definition.max_requests > 0 ? { maxRequests: definition.max_requests } : {}) };
104
84
  // A workflow keeps its approvals too ("never": it runs unattended), so its call nodes are checked with them (runnable.ts,
105
85
  // permissionOf with the revision's approvals): a call node on a tool set to ask runs under never, as on main.
106
86
  if (isObject(definition.workflow))
@@ -177,7 +157,19 @@ export async function getAgent(store, id) {
177
157
  const revisions = await store.agents.revisions(id); // oldest first (created_at, id)
178
158
  const at = agent.currentRevision === null ? -1 : revisions.findIndex((r) => r.id === agent.currentRevision);
179
159
  const revision = at < 0 ? null : revisions[at];
180
- return { agent, revision, version: at < 0 ? 0 : at + 1, revisions: revisions.length, sizes: sizesOf(revision), template: revisions.findLast((r) => r.package)?.package ?? null };
160
+ return { agent, revision, version: at < 0 ? 0 : at + 1, revisions: revisions.length, sizes: sizesOf(revision), template: packageOf(revision, revisions) };
161
+ }
162
+ /** The package `revision` came from: its own, else that of the nearest revision before it in its line (each one's parent,
163
+ * the revision current when it was committed) that an apply wrote. An edit carries the package it was made on, and a
164
+ * restore of an older revision reads that revision's, never a later apply's. Null for a line no apply wrote. */
165
+ function packageOf(revision, revisions) {
166
+ const byId = new Map(revisions.map((one) => [one.id, one]));
167
+ // Bounded by the count: a line is never longer than the revisions there are.
168
+ for (let at = revision, steps = 0; at && steps < revisions.length; at = at.parent === null ? null : byId.get(at.parent) ?? null, steps++) {
169
+ if (at.package)
170
+ return at.package;
171
+ }
172
+ return null;
181
173
  }
182
174
  /** Every agent here, newest first (its creation, then its id). Archived agents are left out by default. */
183
175
  export async function listAgents(store, options = {}) {
@@ -246,7 +238,7 @@ const EDIT_TRIES = 5;
246
238
  * `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
247
239
  * (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
248
240
  * purged agent, or one whose purge stopped part way); the check runs outside it. */
249
- export async function commitAgent(store, read, { definition, skills, note }, { ifCurrent, check, contract = false, template, fromPackage = false, inTurn } = {}) {
241
+ export async function commitAgent(store, read, { definition, skills, note }, { ifCurrent, settingsGuards, check, prepare, contract = false, template, fromPackage = false, inTurn } = {}) {
250
242
  const stale = () => new ApiError("precondition_failed", "the agent's current revision moved since the If-Match it was read at: read the agent again");
251
243
  const held = (entry) => {
252
244
  if (ifCurrent !== undefined && (entry.revision?.id ?? null) !== ifCurrent)
@@ -296,8 +288,9 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
296
288
  checkPast(definition, now.version);
297
289
  else
298
290
  checkVersion(definition, now.revisions + 1);
291
+ const prepared = await prepare?.(revision, now.revision);
299
292
  try {
300
- await store.agents.addRevision({ agentId: agent.id, ifCurrent: base, ...revision, ...(described ? { description } : {}) });
293
+ await store.agents.addRevision({ agentId: agent.id, ifCurrent: base, ...(settingsGuards ? { settingsGuards } : {}), ...(prepared?.revision ?? revision), ...(described ? { description } : {}) });
301
294
  return (await getAgent(store, agent.id));
302
295
  }
303
296
  catch (error) {
@@ -305,6 +298,9 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
305
298
  storeError(error);
306
299
  return undefined;
307
300
  }
301
+ finally {
302
+ await prepared?.settled();
303
+ }
308
304
  });
309
305
  if (landed)
310
306
  return landed;
@@ -342,6 +338,8 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
342
338
  // No approvals here: an edit that leaves them out asks (openapi.ts DefinitionInput.approvals),
343
339
  // so no edit makes an agent unattended by saying nothing. The console's edit sends back the approvals it read.
344
340
  ...(definition.max_cost_usd === undefined && currentBody.maxCostUsd !== undefined ? { max_cost_usd: currentBody.maxCostUsd } : {}),
341
+ // So does its free-model request limit: see DefinitionInput.max_requests (openapi.ts).
342
+ ...(definition.max_requests === undefined && currentBody.maxRequests !== undefined ? { max_requests: currentBody.maxRequests } : {}),
345
343
  // Its input's and its structured answer's schemas are the agent's contract with its callers: an edit that leaves
346
344
  // one out keeps it.
347
345
  ...(definition.input_schema === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody.inputSchema !== undefined ? { input_schema: currentBody.inputSchema } : {}),
@@ -350,7 +348,22 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
350
348
  ...(definition.checkout === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody.checkout !== undefined ? { checkout: currentBody.checkout } : {}),
351
349
  }
352
350
  : {};
353
- return makeRevision({ ...definition, ...carried, ...owned }, files, note);
351
+ const made = makeRevision({ ...definition, ...carried, ...owned }, files, note);
352
+ const sourceSync = sourceSyncOf(currentBody);
353
+ if (sourceSync) {
354
+ if (made.kind !== "agentic")
355
+ throw new ApiError("input_invalid", "A synced agent keeps its agentic execution. Create a workflow separately.");
356
+ const body = made.body;
357
+ if (body.native || body.sdk || body.cli_learning)
358
+ throw new ApiError("input_invalid", "A moved agent keeps managed execution. Its source connection only syncs setup and captures source runs.");
359
+ if (body.harness !== currentBody.harness) {
360
+ const missing = (currentBody.tools ?? []).filter(tool => !body.tools?.includes(tool));
361
+ if (missing.length)
362
+ throw new ApiError("input_invalid", `Changing harness must preserve this agent's required tools: ${missing.join(", ")}. Choose a compatible harness.`);
363
+ }
364
+ return { ...made, body: { ...made.body, sourceSync } };
365
+ }
366
+ return made;
354
367
  }
355
368
  /** Makes `revisionId`, one of the agent's own, its current one (POST /agents/{id}/current). */
356
369
  export async function setCurrentRevision(store, entry, revisionId) {
@@ -386,7 +399,7 @@ export const etagOf = (entry) => `"${entry.revision?.id ?? "none"}"`;
386
399
  /** A revision as a definition, as POST /agents takes one, numbered. */
387
400
  export function definitionOf(agent, revision, version) {
388
401
  const body = revision.body;
389
- const common = body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {};
402
+ const common = { ...(body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {}), ...(body.maxRequests !== undefined ? { max_requests: body.maxRequests } : {}) };
390
403
  const kindBody = revision.kind === "agentic"
391
404
  ? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(learningSettingForBody(body) !== undefined ? { learning: learningSettingForBody(body) } : {}), ...(body.inputSchema !== undefined ? { input_schema: body.inputSchema } : {}), ...(body.outputSchema !== undefined ? { output_schema: body.outputSchema } : {}), ...(body.checkout !== undefined ? { checkout: body.checkout } : {}), ...common }
392
405
  : { workflow: body.workflow, ...common };
@@ -428,6 +441,7 @@ export function agentView(entry, origin, extra = {}) {
428
441
  revision: revision?.id ?? null,
429
442
  revisions: entry.revisions,
430
443
  source: null,
444
+ ...(sourceSyncOf(body) ? { source_sync: { moved: true } } : {}),
431
445
  // The template package it was applied from (its first revision keeps it): the package's id, version and the commit an
432
446
  // imported one was read at (null for a bundled one). Null for an agent made otherwise.
433
447
  template: entry.template ? { id: entry.template.id, version: entry.template.version, sha: entry.template.sha ?? null } : null,
@@ -469,7 +483,7 @@ export function pinView(pin) {
469
483
  const out = {};
470
484
  for (const [server, pinned] of Object.entries(pin)) {
471
485
  out[server] = {
472
- tools: (pinned.tools ?? []).map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), input_schema: tool.inputSchema ?? {}, ...(tool.annotations ? { annotations: tool.annotations } : {}) })),
486
+ tools: (pinned.tools ?? []).map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), input_schema: tool.inputSchema ?? {}, ...(tool.annotations ? { annotations: tool.annotations } : {}), ...(tool.resource !== undefined ? { resource: tool.resource } : {}) })),
473
487
  ...(pinned.prices && Object.keys(pinned.prices).length ? { prices: { ...pinned.prices } } : {}),
474
488
  };
475
489
  }
@@ -1,18 +1,40 @@
1
+ import { NOT_SET_UP } from "./runnable.js";
1
2
  import type { Route } from "./server.js";
2
- /** The variable that turns the profile on. */
3
- export declare const API_ONLY_ENV = "AGENTRUN_API_ONLY";
4
3
  /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
5
4
  * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
6
5
  * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
7
- * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
6
+ * - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
7
+ * of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
8
8
  * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
9
- * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
9
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
10
+ * and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
10
11
  * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
11
- * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
12
+ * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart;
13
+ * - a backend that builds runs from the MCP servers saved here reads their names (listMcpServerNames), never a URL or a
14
+ * credential, to hold back a job whose server isn't saved before its launch is refused for it;
15
+ * - a backend uploads an agent's package (importTemplate, as {files} alone: a GitHub source is refused in this profile's
16
+ * words, template-import.ts), which an apply then makes into its agent;
17
+ * - a backend that deploys agents here applies their template, reads the agent and its revisions, moves its current
18
+ * revision back, and archives it before its delete (or unarchives it, the schedule and feed triggers its archive
19
+ * turned off on again when the server has the launch hook): its token already makes agents through inline runs, so it
20
+ * gains no new power. A trigger the apply can't make here is skipped, and said (apiOnlyTriggerSkipped). */
12
21
  export declare const API_ONLY_ROUTES: ReadonlySet<string>;
13
- /** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
14
- * words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
15
- export declare function apiOnlyFrom(env?: NodeJS.ProcessEnv): boolean;
22
+ /** The trigger sources an apply on an API-only server makes once the server has the launch hook: the ones that fire on
23
+ * its own clock and need nothing a refused route sets up. Each firing goes to the backend in front of it
24
+ * (trigger-launch-hook.ts), which starts the run through the API on its own keys and budget, never on this server's
25
+ * model key. A webhook, GitHub or Composio trigger is delivered to a hook this profile refuses, and an email trigger
26
+ * reads the account Settings → Email saves: none of them is made here, hook or not. */
27
+ export declare const API_ONLY_HOOKED_KINDS: ReadonlySet<string>;
28
+ /** Why an apply on an API-only server (and its dry run's plan) does not make `trigger` of the `packageName` template, or
29
+ * undefined for one it makes: a schedule or a feed when the server has the launch hook (`hooked`). Without it, those two
30
+ * are not_set_up_here (set the hook and apply again); any other source is not_an_option, hook or not. */
31
+ export declare function apiOnlyTriggerSkipped(packageName: string, trigger: {
32
+ name?: unknown;
33
+ source?: unknown;
34
+ }, hooked: boolean): {
35
+ reason: typeof NOT_SET_UP | "not_an_option";
36
+ message: string;
37
+ } | undefined;
16
38
  /** Whether an API-only server serves `method` on `raw` (the path as sent, its query cut): a /v2 path one of
17
39
  * API_ONLY_ROUTES matches for that method (HEAD as GET), or a GET of a run's computer live view. */
18
40
  export declare function servedApiOnly(routes: readonly Route[], method: string | undefined, raw: string): boolean;
package/dist/api-only.js CHANGED
@@ -1,34 +1,58 @@
1
- /** The variable that turns the profile on. */
2
- export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
1
+ // The API-only profile (AGENTRUN_API_ONLY=1): a server that runs behind its caller's backend serves the run routes and a
2
+ // deploy's routes alone, and refuses every other address before anything else reads the request: the console at "/" and
3
+ // its assets, sign-in and setup, settings, MCP, triggers and their webhook hooks, the rest of agents and templates.
4
+ // Off by default.
5
+ import { API_ONLY_ENV } from "./env-switch.js";
6
+ import { NOT_SET_UP } from "./runnable.js";
7
+ import { LAUNCH_HOOK_SECRET_ENV, LAUNCH_HOOK_URL_ENV } from "./trigger-launch-hook.js";
3
8
  /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
4
9
  * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
5
10
  * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
6
- * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
11
+ * - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
12
+ * of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
7
13
  * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
8
- * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
14
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
15
+ * and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
9
16
  * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
10
- * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
17
+ * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart;
18
+ * - a backend that builds runs from the MCP servers saved here reads their names (listMcpServerNames), never a URL or a
19
+ * credential, to hold back a job whose server isn't saved before its launch is refused for it;
20
+ * - a backend uploads an agent's package (importTemplate, as {files} alone: a GitHub source is refused in this profile's
21
+ * words, template-import.ts), which an apply then makes into its agent;
22
+ * - a backend that deploys agents here applies their template, reads the agent and its revisions, moves its current
23
+ * revision back, and archives it before its delete (or unarchives it, the schedule and feed triggers its archive
24
+ * turned off on again when the server has the launch hook): its token already makes agents through inline runs, so it
25
+ * gains no new power. A trigger the apply can't make here is skipped, and said (apiOnlyTriggerSkipped). */
11
26
  export const API_ONLY_ROUTES = new Set([
12
27
  "createRun", "createInlineRun", "getComputerDaemon",
13
28
  "getRunComputer", "takeOverRunComputer", "handBackRunComputer", "createRunComputerViewer",
14
29
  "listComputers", "getWorkspaceArchil",
15
- "getAgentArchil", "deleteAgentArchil", "deleteAgent",
30
+ "getAgentArchil", "deleteAgentArchil", "deleteAgent", "deleteAgentLearning", "deleteRun",
16
31
  "getLearningLoop", "listLearningPromotions", "getLearningCost", "getRunLearning",
17
32
  "getRun", "getRunUsage", "listRuns", "listAllRuns", "getTimeline",
18
33
  "sendMessage", "stopRun", "cancelRun", "raiseRunCap", "gradeRun",
19
34
  "listRunFiles", "readRunFile",
20
35
  "createFile", "listFiles", "getFile", "uploadFile", "deleteFile",
21
- "getCapabilities", "getHealth", "getUsage", "getCapacity",
36
+ "getCapabilities", "getHealth", "getUsage", "getCapacity", "listMcpServerNames",
37
+ "importTemplate", "applyTemplate", "getAgent", "listRevisions", "setCurrent", "archiveAgent", "unarchiveAgent",
22
38
  ]);
23
- /** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
24
- * words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
25
- export function apiOnlyFrom(env = process.env) {
26
- const given = env[API_ONLY_ENV]?.trim().toLowerCase() ?? "";
27
- if (given === "1" || given === "true")
28
- return true;
29
- if (given === "" || given === "0" || given === "false")
30
- return false;
31
- throw new TypeError(`${API_ONLY_ENV} is 1 (serve the run API only) or 0 (the whole server), not ${JSON.stringify(env[API_ONLY_ENV])}`);
39
+ /** The trigger sources an apply on an API-only server makes once the server has the launch hook: the ones that fire on
40
+ * its own clock and need nothing a refused route sets up. Each firing goes to the backend in front of it
41
+ * (trigger-launch-hook.ts), which starts the run through the API on its own keys and budget, never on this server's
42
+ * model key. A webhook, GitHub or Composio trigger is delivered to a hook this profile refuses, and an email trigger
43
+ * reads the account Settings → Email saves: none of them is made here, hook or not. */
44
+ export const API_ONLY_HOOKED_KINDS = new Set(["schedule", "feed"]);
45
+ /** Why an apply on an API-only server (and its dry run's plan) does not make `trigger` of the `packageName` template, or
46
+ * undefined for one it makes: a schedule or a feed when the server has the launch hook (`hooked`). Without it, those two
47
+ * are not_set_up_here (set the hook and apply again); any other source is not_an_option, hook or not. */
48
+ export function apiOnlyTriggerSkipped(packageName, trigger, hooked) {
49
+ const kind = trigger.source !== null && typeof trigger.source === "object" ? String(trigger.source.kind) : "";
50
+ const named = `The ${packageName} template's trigger ${String(trigger.name).trim()} (${kind}) was not made: this server serves the run API only (${API_ONLY_ENV}=1)`;
51
+ if (!API_ONLY_HOOKED_KINDS.has(kind))
52
+ return { reason: "not_an_option", message: `${named}, which serves no route or setting a ${kind} trigger needs. Start its runs through the API instead.` };
53
+ if (hooked)
54
+ return undefined;
55
+ return { reason: NOT_SET_UP, message: `${named} and has no launch hook, so its firings have nowhere to go. Start its runs through the API, or set the launch hook (${LAUNCH_HOOK_URL_ENV} and ${LAUNCH_HOOK_SECRET_ENV}) and apply again: each firing then goes to your backend, which starts its run.` };
32
56
  }
33
57
  /** A run's computer live view: its page, files and socket, which take the viewer credential alone here (server.ts). */
34
58
  const COMPUTER_LIVE = /^\/v2\/runs\/[^/]+\/computer\/live\//;
@@ -71,6 +71,7 @@ export declare function createArchilRoutes(options: ArchilRoutesOptions): {
71
71
  }>;
72
72
  checkLaunchDisk: (diskId: string, signal?: AbortSignal) => Promise<void>;
73
73
  removeRunFolder: (agentId: string, runId: string, diskId: string, whose?: "launch" | "agent") => Promise<void>;
74
+ removeLearningFolder: (agentId: string, diskId: string) => Promise<void>;
74
75
  };
75
76
  export type ArchilRoutes = ReturnType<typeof createArchilRoutes>;
76
77
  /** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
@@ -30,7 +30,7 @@ import { unknownFields } from "./validate.js";
30
30
  import { ArchilClaimRefused } from "./workspace/archil-claim.js";
31
31
  import { archilDisk } from "./workspace/archil-disk.js";
32
32
  import { deleteDisk, getDisk, listOneDisk } from "./workspace/archil-disks.js";
33
- import { archilWorkspace } from "./workspace/archil.js";
33
+ import { archilWorkspace, spillFolderOf } from "./workspace/archil.js";
34
34
  import { agentDirName } from "./workspace/paths.js";
35
35
  import { WorkspaceError } from "./workspace/workspace.js";
36
36
  import { ARCHIL_API_KEY_ENV, archilApiKey } from "./workspace/archil-key.js";
@@ -285,6 +285,32 @@ export function createArchilRoutes(options) {
285
285
  throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
286
286
  }
287
287
  }
288
+ /** Agent `agentId`'s learning folder on disk `diskId` deleted over the disk's file API: agents/<agent>/learning and
289
+ * everything under it (paths.ts learningKey), which a Mode 2 run's end writes on the disk its claim mounted, the
290
+ * agent's own or one its launch named (the caller's: never made, renamed or removed here), and the folder a learning
291
+ * exec spills beside it (workspace/archil.ts spillFolderOf: a write's input text, left by a failed cleanup). Nothing
292
+ * else on the disk is touched: the agent's runs' folders stay. Done again, it does nothing: a folder not there is gone, and so is the
293
+ * folder of a disk Archil says is gone. Archil off, or no account key, is 503 unavailable; a delete Archil refuses
294
+ * (a computer that still holds the folder, Archil not reached) is 424 upstream_failed, what was not deleted left for
295
+ * the next call. */
296
+ async function removeLearningFolder(agentId, diskId) {
297
+ const what = `The agent ${agentId}'s learning folder on the Archil disk ${diskId}`;
298
+ const settings = await loadArchilSettings(store, env);
299
+ if (settings === undefined)
300
+ throw new ApiError("unavailable", `${what} is not deleted yet: Archil is off on this server, so it can't be reached. Turn Archil on again (PUT /v2/workspace/archil)`);
301
+ const key = await keyOr("unavailable", `${what} can't be deleted`);
302
+ const disk = (options.control?.makeDisk ?? archilDisk)({ disk: diskId, region: settings.region, s3BaseUrl: settings.s3Url, key: () => key });
303
+ try {
304
+ const agent = archilWorkspace(disk, `agents/${agentDirName(agentId)}`, { queueMs: 5_000 });
305
+ for (const name of ["learning", spillFolderOf("learning")])
306
+ await agent.remove(name, { recursive: true, force: true });
307
+ }
308
+ catch (error) {
309
+ if (await diskGone(settings, key, diskId))
310
+ return;
311
+ throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
312
+ }
313
+ }
288
314
  /** Whether Archil's control plane says disk `diskId` is gone: its read answers that the account has no such disk (404,
289
315
  * getDisk's undefined) or reads it as deleted. Only Archil's word counts: a read that fails (not reached, a 5xx, the key
290
316
  * refused) says nothing, so the disk is taken as still there. */
@@ -297,7 +323,7 @@ export function createArchilRoutes(options) {
297
323
  return false;
298
324
  }
299
325
  }
300
- return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder };
326
+ return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder, removeLearningFolder };
301
327
  }
302
328
  /** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
303
329
  * agent's route takes the agent as the dispatch read it. */
@@ -4,6 +4,7 @@ import type { Settings } from "./store/index.js";
4
4
  * loopback; unset, the listen address decides (claudeLoginSwitchedOff). */
5
5
  export declare const CLAUDE_LOGIN_ENV = "AGENTRUN_CLAUDE_CODE_LOGIN";
6
6
  export declare const claudeLoginOff: (env: Readonly<Record<string, string | undefined>>) => boolean;
7
+ export declare const loopback: (host: string) => boolean;
7
8
  /** Why the mode is off on a server listening on `listen`, or undefined where it is there: the switch's `off`, or, unset,
8
9
  * a listen address past loopback. */
9
10
  export declare function claudeLoginSwitchedOff(env: Readonly<Record<string, string | undefined>>, listen: string): string | undefined;
@@ -24,7 +24,7 @@ for (const operation of ["getClaudeLogin", "turnOnClaudeLogin", "turnOffClaudeLo
24
24
  export const CLAUDE_LOGIN_ENV = "AGENTRUN_CLAUDE_CODE_LOGIN";
25
25
  export const claudeLoginOff = (env) => /^(off|0|false|no)$/i.test((env[CLAUDE_LOGIN_ENV] ?? "").trim());
26
26
  const claudeLoginOn = (env) => /^(on|1|true|yes)$/i.test((env[CLAUDE_LOGIN_ENV] ?? "").trim());
27
- const loopback = (host) => host === "localhost" || host === "::1" || /^127\./.test(host); // key-gate: loopback-rule the default follows a loopback listen address
27
+ export const loopback = (host) => host === "localhost" || host === "::1" || /^127\./.test(host); // key-gate: loopback-rule the default follows a loopback listen address
28
28
  /** Why the mode is off on a server listening on `listen`, or undefined where it is there: the switch's `off`, or, unset,
29
29
  * a listen address past loopback. */
30
30
  export function claudeLoginSwitchedOff(env, listen) {
@@ -1,3 +1,5 @@
1
+ import { type CliLearningRuntime } from './install.js';
2
+ import { type SourceLocalConsent } from '../source-sync/local.js';
1
3
  type CliIO = {
2
4
  stdout?: (text: string) => void;
3
5
  stderr?: (text: string) => void;
@@ -5,6 +7,7 @@ type CliIO = {
5
7
  fetch?: typeof fetch;
6
8
  /** Test/packaging boundary: executable plus arguments, never evaluated while installing. */
7
9
  command?: string[];
10
+ sourceConsent?: (runtime: CliLearningRuntime, project: string) => Promise<SourceLocalConsent>;
8
11
  };
9
12
  /** Installer/status command plus the bounded stdin worker invoked by ordinary CLI hooks. */
10
13
  export declare function learningMain(argv: string[], io?: CliIO): Promise<number>;
@@ -6,7 +6,10 @@ import { defaultData } from '../server-fs.js';
6
6
  import { takeHold, releaseHold } from '../harness-install.js';
7
7
  import { cliLearningUrl, installCliLearning, removeCliLearning, statusCliLearning } from './install.js';
8
8
  import { connectionFile, readConnection, saveConnection } from './state.js';
9
- const USAGE = 'usage: agentrun-serve learning connect|status|disconnect|retry --runtime codex|claude-code [--project PATH] [--url LOOPBACK_URL] [--data SERVER_DATA]';
9
+ import { sourceLocalConsent } from '../source-sync/local.js';
10
+ import { selectedNative } from '../native/connection.js';
11
+ import { nativeEnvironment } from '../native/environment.js';
12
+ const USAGE = 'usage: agentrun-serve learning connect|status|disconnect|retry --runtime codex|claude-code [--project PATH] [--url LOOPBACK_URL] [--data SERVER_DATA] [--no-sync]';
10
13
  async function ownerToken(data) {
11
14
  const fromEnvironment = secret('AGENTRUN_API_KEY') || secret('AGENTRUN_TOKEN');
12
15
  if (fromEnvironment)
@@ -82,7 +85,7 @@ export async function learningMain(argv, io = {}) {
82
85
  try {
83
86
  const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
84
87
  project: { type: 'string' }, runtime: { type: 'string' }, data: { type: 'string' }, url: { type: 'string' },
85
- json: { type: 'boolean' }, help: { type: 'boolean' },
88
+ json: { type: 'boolean' }, help: { type: 'boolean' }, 'no-sync': { type: 'boolean' },
86
89
  } });
87
90
  if (values.help) {
88
91
  output(USAGE);
@@ -166,6 +169,12 @@ export async function learningMain(argv, io = {}) {
166
169
  return 0;
167
170
  }
168
171
  const url = await serverUrl(values.url, dataDir);
172
+ const sourceSync = values['no-sync'] ? undefined : await (io.sourceConsent ?? (async (runtime, project) => {
173
+ const env = nativeEnvironment();
174
+ return sourceLocalConsent(await selectedNative({ runtime, project }, env), env);
175
+ }))(runtime, project);
176
+ if (sourceSync)
177
+ errorOutput('Setup sync copies this project’s instructions, authored skills and assets, supported tools/settings, project files and bounded Git history to AgentRun. Native credentials stay here. Future changes keep syncing until disabled; use --no-sync to connect capture only.');
169
178
  const before = await statusCliLearning(options);
170
179
  if (before.state === 'partial')
171
180
  throw new Error('AgentRun hooks were changed or disabled. Run learning disconnect before reconnecting.');
@@ -192,11 +201,16 @@ export async function learningMain(argv, io = {}) {
192
201
  if (!active)
193
202
  throw new Error('This learning connection is inactive. Run learning disconnect, then learning connect to enroll again.');
194
203
  const installation = await installCliLearning({ ...options, url, command: io.command });
204
+ if (sourceSync) {
205
+ const synced = await request(fetcher, url, '/v2/cli-learning/connections', await ownerToken(dataDir), 'POST', { project, runtime, source_sync: sourceSync });
206
+ if (!synced.ok)
207
+ throw new Error(`Capture is connected, but setup sync was refused (HTTP ${synced.status}). Check the source and server are on the same machine, then retry connect.`);
208
+ }
195
209
  output(JSON.stringify({ ...installation, connection_id: existing.connection_id, agent_id: existing.agent_id }, null, 2));
196
210
  return 0;
197
211
  }
198
212
  const token = await ownerToken(dataDir);
199
- const response = await request(fetcher, url, '/v2/cli-learning/connections', token, 'POST', { project, runtime });
213
+ const response = await request(fetcher, url, '/v2/cli-learning/connections', token, 'POST', { project, runtime, ...(sourceSync ? { source_sync: sourceSync } : {}) });
200
214
  if (!response.ok)
201
215
  throw new Error(`Server refused the learning connection (HTTP ${response.status}).`);
202
216
  const body = await response.json();
@@ -1,10 +1,11 @@
1
1
  // A local owner enrolls one installed CLI. Its hook credential can only submit prompt windows for this agent.
2
+ import { cliCaptureOf } from "../source-sync/capture.js";
2
3
  import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
3
4
  import { basename } from 'node:path';
4
5
  import { createAgent, getAgent } from '../agents-store.js';
5
6
  import { ApiError } from '../errors.js';
6
7
  import { selectedNative, launchNative } from '../native/connection.js';
7
- import { cliLearningOf, isObject } from '../store/agent-body.js';
8
+ import { isObject } from '../store/agent-body.js';
8
9
  const key = (id) => `cli-learning-connection:${id}`;
9
10
  const hash = (text) => createHash('sha256').update(text).digest();
10
11
  export class CliLearningConnections {
@@ -69,7 +70,7 @@ export class CliLearningConnections {
69
70
  throw new ApiError("home_busy", "The connection changed concurrently; retry this prompt-window acknowledgement.");
70
71
  }
71
72
  async list() { const result = []; for (const agent of await this.store.agents.list()) {
72
- const entry = await getAgent(this.store, agent.id), binding = cliLearningOf(entry?.revision?.body);
73
+ const entry = await getAgent(this.store, agent.id), binding = entry ? (await cliCaptureOf(this.store, entry))?.binding : undefined;
73
74
  if (binding) {
74
75
  const row = await this.get(binding.connection_id).catch(() => undefined);
75
76
  if (row)
@@ -1,3 +1,4 @@
1
+ import { SOURCE_LOCAL_CONSENT } from '../native/schema.js';
1
2
  import { SDK_PATHS, SDK_RUN } from '../sdk/schema.js';
2
3
  const text = { type: 'string' };
3
4
  const object = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
@@ -16,7 +17,7 @@ const completionSchema = completion.requestBody.content['application/json'].sche
16
17
  const receipt = SDK_PATHS['/agents/{agent_id}/sdk-runs'].post.responses[201];
17
18
  export const CLI_LEARNING_PATHS = {
18
19
  '/cli-learning/connections': {
19
- post: { ...owner, operationId: 'enrollCliLearning', summary: 'Enable learning for an existing local CLI without launching it', description: 'Owner authenticated, source server bound to loopback without a public URL. Verifies native sign-in without a model call. Repeated enrollment preserves the same agent and learned files, and keeps its current Learning Off setting. Store the returned connection token privately, never give it to a model.', requestBody: body(object({ runtime: { enum: ['codex', 'claude-code'] }, project: text, name: text }, ['runtime', 'project'])), responses: { 201: response(object({ ...connection.properties, token: text }, [...connection.required, "token"])) } },
20
+ post: { ...owner, operationId: 'enrollCliLearning', summary: 'Enable learning for an existing local CLI without launching it', description: 'Owner authenticated, source server bound to loopback without a public URL. Verifies native sign-in without a model call. Repeated enrollment preserves the same agent and learned files, and keeps its current Learning Off setting. Store the returned connection token privately, never give it to a model.', requestBody: body(object({ runtime: { enum: ['codex', 'claude-code'] }, project: text, name: text, source_sync: SOURCE_LOCAL_CONSENT }, ['runtime', 'project'])), responses: { 201: response(object({ ...connection.properties, token: text }, [...connection.required, "token"])) } },
20
21
  get: { ...owner, operationId: 'listCliLearning', summary: 'Read enrolled CLI learning connections', responses: { 200: response(object({ connections: { type: 'array', items: connection } })) } }
21
22
  },
22
23
  '/cli-learning/connections/{connection_id}': { delete: { ...owner, operationId: 'revokeCliLearning', summary: 'Revoke CLI capture and guidance delivery, retaining history and learned files', parameters: [id('connection_id')], responses: { 200: response(connection) } } },