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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
package/dist/model.d.ts CHANGED
@@ -7,11 +7,11 @@ import type { Revision } from "./agent-rows.js";
7
7
  export declare const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
8
8
  /** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_WEB, ...), but the harness table's
9
9
  * (harness-table.ts HARNESS_TABLE_ENV), which withoutFaux drops by name, as it drops the resolved harness modules list
10
- * (HARNESS_MODULES_ENV). */
10
+ * (HARNESS_MODULES_ENV) and recipes list (HARNESS_RECIPES_ENV). */
11
11
  export declare const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
12
- /** `env` without a test hook's name or the resolved harness modules list: serve sets those from startServe's options
13
- * alone, so a name the server's own environment holds (an operator's export, a leftover) never gives its runs fake
14
- * answers or loads a module. */
12
+ /** `env` without a test hook's name or the resolved harness modules or recipes list: serve sets those from startServe's
13
+ * options alone, so a name the server's own environment holds (an operator's export, a leftover) never gives its runs
14
+ * fake answers, loads a module or runs a recipe. */
15
15
  export declare const withoutFaux: (env: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
16
16
  /** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
17
17
  * tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
package/dist/model.js CHANGED
@@ -8,7 +8,7 @@
8
8
  import { isRouter, withLocalModels } from "./local-models.js";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { DEFAULT_HARNESS, PLAN_HARNESSES } from "./harness.js";
11
- import { builtinHarness, factsOf, HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessOf } from "./harness-table.js";
11
+ import { builtinHarness, factsOf, HARNESS_MODULES_ENV, HARNESS_RECIPES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessOf } from "./harness-table.js";
12
12
  import { gatewayBase, modelGatewayBase } from "./provider.js";
13
13
  import { modelFormWhy } from "./model-form.js";
14
14
  // Leaves, which the key rows below read as this module loads, in any import order (wires.ts, adapter-facts.ts).
@@ -21,12 +21,12 @@ import { LOGIN_DEFAULT_MODEL, onClaudeLogin } from "./claude-login.js";
21
21
  export const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
22
22
  /** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_WEB, ...), but the harness table's
23
23
  * (harness-table.ts HARNESS_TABLE_ENV), which withoutFaux drops by name, as it drops the resolved harness modules list
24
- * (HARNESS_MODULES_ENV). */
24
+ * (HARNESS_MODULES_ENV) and recipes list (HARNESS_RECIPES_ENV). */
25
25
  export const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
26
- /** `env` without a test hook's name or the resolved harness modules list: serve sets those from startServe's options
27
- * alone, so a name the server's own environment holds (an operator's export, a leftover) never gives its runs fake
28
- * answers or loads a module. */
29
- export const withoutFaux = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith(FAUX_PREFIX) && name !== HARNESS_TABLE_ENV && name !== HARNESS_MODULES_ENV));
26
+ /** `env` without a test hook's name or the resolved harness modules or recipes list: serve sets those from startServe's
27
+ * options alone, so a name the server's own environment holds (an operator's export, a leftover) never gives its runs
28
+ * fake answers, loads a module or runs a recipe. */
29
+ export const withoutFaux = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith(FAUX_PREFIX) && name !== HARNESS_TABLE_ENV && name !== HARNESS_MODULES_ENV && name !== HARNESS_RECIPES_ENV));
30
30
  /** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
31
31
  * tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
32
32
  * request to the provider the revision's model names (web_search's, hosted-search.ts); the run's turns stay faux. */
@@ -5,11 +5,13 @@ import { defaultData } from '../server-fs.js';
5
5
  import { discoverNative } from './discovery.js';
6
6
  import { nativeEnvironment } from './environment.js';
7
7
  import { secret } from '../secrets.js';
8
+ import { selectedNative } from './connection.js';
9
+ import { sourceLocalConsent } from '../source-sync/local.js';
8
10
  /** Source-machine handoff: discovery never launches a model; connection uses the existing local server credential.
9
11
  * `usage`: the command's own line of the server's USAGE (cli.ts), which names every flag parsed here. */
10
12
  export async function nativeMain(argv, usage) {
11
13
  try {
12
- const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { project: { type: 'string' }, runtime: { type: 'string' }, agent: { type: 'string' }, profile: { type: 'string' }, url: { type: 'string' }, data: { type: 'string' } } });
14
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { project: { type: 'string' }, runtime: { type: 'string' }, agent: { type: 'string' }, profile: { type: 'string' }, url: { type: 'string' }, data: { type: 'string' }, 'no-sync': { type: 'boolean' } } });
13
15
  const operation = positionals[0];
14
16
  if (!values.project || !['discover', 'connect'].includes(operation ?? ''))
15
17
  throw new Error(usage);
@@ -35,7 +37,12 @@ export async function nativeMain(argv, usage) {
35
37
  if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
36
38
  throw new Error('Run AgentRun on this source machine and connect to its loopback URL; hosted native pairing is not available yet.');
37
39
  const token = secret('AGENTRUN_API_KEY') || secret('AGENTRUN_TOKEN') || (await readFile(join(data, '.token'), 'utf8')).trim();
38
- const response = await fetch(new URL('/v2/native/connect', url), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ project: values.project, runtime: values.runtime, selector: values.agent ? { kind: 'agent', name: values.agent } : values.profile ? { kind: 'profile', name: values.profile } : { kind: 'project' } }) });
40
+ const selection = { project: values.project, runtime: values.runtime, selector: values.agent ? { kind: 'agent', name: values.agent } : values.profile ? { kind: 'profile', name: values.profile } : { kind: 'project' } };
41
+ const env = nativeEnvironment();
42
+ const sourceSync = values['no-sync'] ? undefined : await sourceLocalConsent(await selectedNative(selection, env), env);
43
+ if (sourceSync)
44
+ console.error('Setup sync copies this selected project, instructions, authored skills and assets, supported tools/settings and bounded Git history to AgentRun. Credentials stay here; future source changes keep syncing. Use --no-sync to opt out.');
45
+ const response = await fetch(new URL('/v2/native/connect', url), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ ...selection, ...(sourceSync ? { source_sync: sourceSync } : {}) }) });
39
46
  const body = await response.json();
40
47
  if (!response.ok)
41
48
  throw new Error(body.error?.message ?? `Connection failed (${response.status})`);
@@ -1,8 +1,8 @@
1
1
  import { type AgentEntry } from '../agents-store.js';
2
- import type { Store } from '../store/store.js';
2
+ import type { Store, SettingsGuard } from '../store/store.js';
3
3
  import type { NativeBinding, NativeTarget } from './types.js';
4
4
  export declare function selectedNative(input: unknown, env?: NodeJS.ProcessEnv): Promise<NativeTarget>;
5
5
  export declare function connectNative(store: Store, input: unknown, env?: NodeJS.ProcessEnv): Promise<AgentEntry>;
6
- export declare function updateNative(store: Store, entry: AgentEntry, native: NativeBinding): Promise<AgentEntry>;
6
+ export declare function updateNative(store: Store, entry: AgentEntry, native: NativeBinding, settingsGuards?: readonly SettingsGuard[]): Promise<AgentEntry>;
7
7
  export declare function verifyConnection(store: Store, entry: AgentEntry, env?: NodeJS.ProcessEnv): Promise<AgentEntry>;
8
8
  export declare function launchNative(binding: NativeBinding, env?: NodeJS.ProcessEnv): Promise<NativeBinding>;
@@ -1,3 +1,4 @@
1
+ import { sourceSyncOf } from "../source-sync/types.js";
1
2
  import { nativeEnvironment } from "./environment.js";
2
3
  import { basename } from 'node:path';
3
4
  import { ApiError, invalid } from '../errors.js';
@@ -42,7 +43,9 @@ export async function connectNative(store, input, env = nativeEnvironment()) {
42
43
  throw error;
43
44
  }
44
45
  }
45
- export async function updateNative(store, entry, native) {
46
+ export async function updateNative(store, entry, native, settingsGuards) {
47
+ if (sourceSyncOf(entry.revision?.body))
48
+ throw new ApiError("input_invalid", "This agent runs in AgentRun. Its source can sync setup, but reconnecting cannot take execution back.");
46
49
  const before = definitionOf(entry.agent, entry.revision, entry.version);
47
50
  const old = nativeOf(entry.revision?.body), execution = nativeExecutionOverrides(entry.revision?.body);
48
51
  // Disconnect must remain possible, retaining these execution restrictions. Reconnect/conversion must never erase
@@ -59,7 +62,7 @@ export async function updateNative(store, entry, native) {
59
62
  // on disconnect. Reconnect fills an absent legacy harness; managed conversion adopts the selected source harness.
60
63
  const sourceHarness = native.runtime === 'claude-code' ? 'claude-agent' : 'codex';
61
64
  const harness = old ? (entry.revision.body.harness ?? (native.connected ? sourceHarness : undefined)) : sourceHarness;
62
- return commitAgent(store, entry, { definition: { ...definition, ...(harness ? { harness } : {}), native } }, { ifCurrent: entry.revision?.id ?? null });
65
+ return commitAgent(store, entry, { definition: { ...definition, ...(harness ? { harness } : {}), native } }, { ifCurrent: entry.revision?.id ?? null, ...(settingsGuards ? { settingsGuards } : {}) });
63
66
  }
64
67
  export async function verifyConnection(store, entry, env = nativeEnvironment()) {
65
68
  const before = nativeOf(entry.revision?.body);
@@ -12,6 +12,8 @@ export declare function nativeMetadata(binary: string, args: string[], cwd: stri
12
12
  stdout: string;
13
13
  }>;
14
14
  export declare function nativeIdentity(target: Pick<NativeTarget, "runtime" | "project" | "selector" | "machine_id">): string;
15
+ /** The existing native machine identity, shared with explicit source-consent checks before any source scan. */
16
+ export declare function nativeMachineId(): Promise<string>;
15
17
  export declare function discoverNative(options: {
16
18
  project: string;
17
19
  runtime?: NativeRuntime;
@@ -69,6 +69,15 @@ export async function nativeMetadata(binary, args, cwd, env, timeoutMs = 5_000)
69
69
  export function nativeIdentity(target) {
70
70
  return hash(JSON.stringify([target.runtime, target.project, target.selector.kind, target.selector.name ?? null, target.machine_id]));
71
71
  }
72
+ /** The existing native machine identity, shared with explicit source-consent checks before any source scan. */
73
+ export async function nativeMachineId() {
74
+ let machine = hostname();
75
+ try {
76
+ machine = (await readFile("/etc/machine-id", "utf8")).trim();
77
+ }
78
+ catch { /* hostname fallback */ }
79
+ return hash(machine);
80
+ }
72
81
  export async function discoverNative(options) {
73
82
  const env = options.env ?? process.env, home = homeOf(env);
74
83
  let project;
@@ -80,12 +89,7 @@ export async function discoverNative(options) {
80
89
  catch {
81
90
  throw new NativeDiscoveryError();
82
91
  }
83
- let machine = hostname();
84
- try {
85
- machine = (await readFile("/etc/machine-id", "utf8")).trim();
86
- }
87
- catch { /* hostname fallback */ }
88
- const machine_id = hash(machine), targets = [];
92
+ const machine_id = await nativeMachineId(), targets = [];
89
93
  for (const runtime of options.runtime ? [options.runtime] : NATIVE_RUNTIMES) {
90
94
  const binary = await nativeExecutable(runtime, env);
91
95
  const versionResult = binary ? await nativeMetadata(binary, ["--version"], project, env) : null;
@@ -10,6 +10,8 @@ import { discoverNative, nativeIdentity, verifyNative } from './discovery.js';
10
10
  import { nativeEnvironment } from './environment.js';
11
11
  import { openNativeSession } from './runtime.js';
12
12
  import { snapshotNativeInstructions } from './instructions.js';
13
+ import { exportSourceSnapshot, SourceSnapshotError } from './source-snapshot.js';
14
+ import { homedir } from 'node:os';
13
15
  import { exportRemoteHistory } from '../import.js';
14
16
  import { runnerSecrets, secretRedactor } from '../runner/redact.js';
15
17
  import { redactedOutput } from '../key-refusal.js';
@@ -70,10 +72,15 @@ export async function runRemoteWorkerBridge(options = {}) {
70
72
  const output = (value) => {
71
73
  // These identities are generated by the connector, not native payload text. Redacting
72
74
  // a serialized JSON line can erase them (or its braces) when a payload has a long atom.
73
- const safe = 'result' in value ? { id: value.id, result: payload(value.result) }
75
+ // Export refuses secret-bearing content before digesting it. A second redaction pass would silently
76
+ // change authored bytes or content hashes; only this typed, local-only export can use its exact result.
77
+ const safe = 'result' in value ? { id: value.id, result: value.exactSnapshot ?? payload(value.result) }
74
78
  : 'event' in value ? { session_key: value.session_key, event: payload(value.event) }
75
- : { ...(value.id === undefined ? {} : { id: value.id }), error: redact(value.error) };
76
- return process.stdout.write(JSON.stringify(safe) + '\n');
79
+ : { ...(value.id === undefined ? {} : { id: value.id }), error: redact(value.error), ...(value.code ? { code: value.code } : {}) };
80
+ const line = JSON.stringify(safe) + '\n';
81
+ if ('exactSnapshot' in value && value.exactSnapshot && Buffer.byteLength(line) > 128 * 1024 * 1024)
82
+ throw new SourceSnapshotError('limit', 'The complete source snapshot exceeds its transport limit; nothing was truncated.');
83
+ return process.stdout.write(line);
77
84
  };
78
85
  const close = async (sessionKey) => {
79
86
  const held = sessions.get(sessionKey);
@@ -115,6 +122,25 @@ export async function runRemoteWorkerBridge(options = {}) {
115
122
  const payload = message.payload === undefined ? {} : object(message.payload), type = message.type;
116
123
  if (type === 'discover')
117
124
  return discoverNative({ project: text(payload.project, 4096), ...(payload.runtime ? { runtime: runtime(payload.runtime) } : {}), env });
125
+ if (type === 'source-snapshot') {
126
+ // Only a local connector action can send this type; remote command dispatch never admits it.
127
+ const chosen = targetOf(message.target);
128
+ if (!Array.isArray(payload.authorized_roots) || !payload.authorized_roots.length || payload.authorized_roots.length > 32)
129
+ throw new Error('Source export needs locally approved source roots. Enable sync on the source machine.');
130
+ // Private local IPC, never an accepted network command. The connector holds a scoped credential
131
+ // outside this process's environment; include it in refusal without echoing it or rewriting bytes.
132
+ const held = payload.secret_values === undefined ? [] : payload.secret_values;
133
+ if (!Array.isArray(held) || held.length > 16 || held.some(value => typeof value !== 'string' || !value.length || Buffer.byteLength(value) > 8192)
134
+ || held.reduce((bytes, value) => bytes + Buffer.byteLength(value), 0) > 64 * 1024)
135
+ throw new Error('Invalid local held-value envelope.');
136
+ const report = await discoverNative({ project: chosen.project, runtime: chosen.runtime, env });
137
+ const found = report.targets.find(target => nativeIdentity(target) === nativeIdentity(chosen));
138
+ if (!found)
139
+ throw new Error('The locally approved source target changed; discover it again.');
140
+ return exportSourceSnapshot({ target: found, authorizedRoots: payload.authorized_roots.map(root => text(root, 4096)),
141
+ home: env.HOME || homedir(), ...(env.CODEX_HOME ? { codexHome: env.CODEX_HOME } : {}),
142
+ ...(env.CLAUDE_CONFIG_DIR ? { claudeHome: env.CLAUDE_CONFIG_DIR } : {}), secretValues: [...secrets, ...held], environment: env, signal });
143
+ }
118
144
  // Local connector action only: the Python network worker never dispatches these operations.
119
145
  if (type === 'history-preview' || type === 'history-export') {
120
146
  const target = targetOf(message.target);
@@ -223,7 +249,13 @@ export async function runRemoteWorkerBridge(options = {}) {
223
249
  }
224
250
  const abort = new AbortController();
225
251
  operations.set(id, abort);
226
- const task = dispatch(message, abort.signal).then(result => { output({ id, result }); }, error => { output({ id, error: error instanceof Error ? error.message : 'Native operation failed.' }); }).finally(() => { operations.delete(id); pending.delete(task); });
252
+ const task = dispatch(message, abort.signal).then(result => { output({ id, result, ...(message.type === 'source-snapshot' ? { exactSnapshot: result } : {}) }); })
253
+ .catch(error => { if (message.type === 'source-snapshot') {
254
+ const code = error instanceof SourceSnapshotError ? (error.code === 'limit' ? 'snapshot_too_large' : error.code) : 'source_unavailable';
255
+ output({ id, error: 'The approved source snapshot could not be captured.', code });
256
+ }
257
+ else
258
+ output({ id, error: error instanceof Error ? error.message : 'Native operation failed.' }); }).finally(() => { operations.delete(id); pending.delete(task); });
227
259
  pending.add(task);
228
260
  }
229
261
  await shutdown();
@@ -1,3 +1,8 @@
1
+ /** Outbound connector transport. Credentials are scoped to one source; commands use source-approved opaque targets.
2
+ * The ordinary runner owns runs, journals and learning. A leased command is NEVER dispatched again after uncertainty.
3
+ * CAS settings rows keep this contract across API/runner processes and restarts without a second run registry. */
4
+ import type { AdoptionResolver } from "../source-sync/adoption.js";
5
+ import { type SourceAuthority } from "../source-sync/registry.js";
1
6
  import { type AgentEntry } from '../agents-store.js';
2
7
  import type { Store } from '../store/store.js';
3
8
  import type { NativeBinding, NativeEvent, NativeResult, NativeSession } from './types.js';
@@ -7,6 +12,8 @@ export type RemoteCommandType = 'prepare' | 'open' | 'send' | 'close';
7
12
  export declare class RemoteConnectors {
8
13
  readonly store: Store;
9
14
  readonly now: () => number;
15
+ /** One HTTP request's authenticated epoch. Reading its body can await a concurrent owner rotation. */
16
+ private authenticated?;
10
17
  constructor(store: Store, now?: () => number);
11
18
  private connector;
12
19
  private targets;
@@ -23,12 +30,14 @@ export declare class RemoteConnectors {
23
30
  observe: boolean;
24
31
  native_execution: boolean;
25
32
  history_import: boolean;
33
+ config_sync: boolean;
26
34
  };
27
35
  targets: {
28
36
  target_id: string;
29
37
  agent_id: string;
30
38
  name: string;
31
39
  history_only: boolean;
40
+ sync_only: boolean;
32
41
  runtime: "codex" | "claude-code";
33
42
  machine_id: string;
34
43
  state: "ready" | "needs_verification" | "needs_attention";
@@ -60,12 +69,14 @@ export declare class RemoteConnectors {
60
69
  observe: boolean;
61
70
  native_execution: boolean;
62
71
  history_import: boolean;
72
+ config_sync: boolean;
63
73
  };
64
74
  targets: {
65
75
  target_id: string;
66
76
  agent_id: string;
67
77
  name: string;
68
78
  history_only: boolean;
79
+ sync_only: boolean;
69
80
  runtime: "codex" | "claude-code";
70
81
  machine_id: string;
71
82
  state: "ready" | "needs_verification" | "needs_attention";
@@ -95,12 +106,14 @@ export declare class RemoteConnectors {
95
106
  observe: boolean;
96
107
  native_execution: boolean;
97
108
  history_import: boolean;
109
+ config_sync: boolean;
98
110
  };
99
111
  targets: {
100
112
  target_id: string;
101
113
  agent_id: string;
102
114
  name: string;
103
115
  history_only: boolean;
116
+ sync_only: boolean;
104
117
  runtime: "codex" | "claude-code";
105
118
  machine_id: string;
106
119
  state: "ready" | "needs_verification" | "needs_attention";
@@ -117,10 +130,14 @@ export declare class RemoteConnectors {
117
130
  }>;
118
131
  assertReady(binding: NativeBinding): Promise<void>;
119
132
  status(binding: NativeBinding): Promise<NativeBinding>;
120
- importTarget(id: string, input: unknown): Promise<{
133
+ importTarget(id: string, input: unknown, resolveAdoption?: AdoptionResolver): Promise<{
121
134
  agent_id: string;
122
135
  native: NativeBinding;
123
136
  }>;
137
+ syncAuthority(id: string, targetId: string): Promise<{
138
+ agentId: string;
139
+ authority: SourceAuthority;
140
+ }>;
124
141
  disconnectTarget(binding: NativeBinding): Promise<void>;
125
142
  importHistory(id: string, targetId: string, input: unknown, own?: readonly string[]): Promise<{
126
143
  agent_id: string;
@@ -1,6 +1,6 @@
1
- /** Outbound connector transport. Credentials are scoped to one source; commands use source-approved opaque targets.
2
- * The ordinary runner owns runs, journals and learning. A leased command is NEVER dispatched again after uncertainty.
3
- * CAS settings rows keep this contract across API/runner processes and restarts without a second run registry. */
1
+ import { sourceKey } from "../source-sync/registry.js";
2
+ import { sourceSyncOf } from "../source-sync/types.js";
3
+ import { cliCaptureOf } from "../source-sync/capture.js";
4
4
  import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
5
5
  import { setTimeout as delay } from 'node:timers/promises';
6
6
  import { ApiError } from '../errors.js';
@@ -26,12 +26,16 @@ const bounded = (v, max = MAX_COMMAND_BYTES) => { if (Buffer.byteLength(JSON.str
26
26
  export class RemoteConnectors {
27
27
  store;
28
28
  now;
29
+ /** One HTTP request's authenticated epoch. Reading its body can await a concurrent owner rotation. */
30
+ authenticated;
29
31
  constructor(store, now = Date.now) {
30
32
  this.store = store;
31
33
  this.now = now;
32
34
  }
33
35
  async connector(id) {
34
36
  const row = await this.store.settings.get(keyOf('connector', id));
37
+ if (this.authenticated && (!row || this.authenticated.id !== id || this.authenticated.credentialHash !== row.credential_hash || row.revoked || row.expires <= this.now()))
38
+ throw new ApiError('unauthenticated', 'This request belongs to an expired or replaced connector credential.');
35
39
  if (!row)
36
40
  throw new ApiError('not_found', 'This connector does not exist.');
37
41
  return row;
@@ -43,11 +47,11 @@ export class RemoteConnectors {
43
47
  const targets = await this.targets(row.id);
44
48
  return { id: row.id, connector_id: row.id, label: row.label, created_at: row.created_at, last_seen_at: row.last_seen ? new Date(row.last_seen).toISOString() : null,
45
49
  status: row.revoked || row.expires <= this.now() ? 'revoked' : row.last_seen + ONLINE_MS >= this.now() ? 'online' : 'offline',
46
- capabilities: { observe: true, native_execution: row.native_execution, history_import: row.history_import === true },
50
+ capabilities: { observe: true, native_execution: row.native_execution, history_import: row.history_import === true, config_sync: row.config_sync === true },
47
51
  targets: targets.map(t => {
48
- const disconnected = t.owner_disconnected || t.target.connected === false;
49
- const issue = t.owner_disconnected ? 'Disconnected by the owner. Reconnect this target before starting a run.' : t.target.connected === false && !t.history_only ? 'This source target is disconnected. Reconnect it before starting a run.' : null;
50
- return { target_id: t.target_id, agent_id: t.agent_id, name: t.name, history_only: t.history_only === true, runtime: t.target.runtime, machine_id: t.target.machine_id, state: disconnected ? 'needs_attention' : t.target.state, issues: issue ? [...t.target.issues, issue] : t.target.issues, capabilities: disconnected ? { ...t.target.capabilities, launch: false } : t.target.capabilities };
52
+ const disconnected = t.owner_disconnected || t.target.connected === false && !t.sync_only;
53
+ const issue = t.owner_disconnected ? 'Disconnected by the owner. Reconnect this target before starting a run.' : t.target.connected === false && !t.history_only && !t.sync_only ? 'This source target is disconnected. Reconnect it before starting a run.' : null;
54
+ return { target_id: t.target_id, agent_id: t.agent_id, name: t.name, history_only: t.history_only === true, sync_only: t.sync_only === true, runtime: t.target.runtime, machine_id: t.target.machine_id, state: disconnected ? 'needs_attention' : t.target.state, issues: issue ? [...t.target.issues, issue] : t.target.issues, capabilities: disconnected ? { ...t.target.capabilities, launch: false } : t.target.capabilities };
51
55
  }) };
52
56
  }
53
57
  async list() {
@@ -62,14 +66,17 @@ export class RemoteConnectors {
62
66
  if (b.label !== undefined && !text(b.label))
63
67
  throw new ApiError('input_invalid', 'Choose a short name for this source machine.');
64
68
  const requested = object(b.capabilities);
65
- if (b.capabilities !== undefined && (Object.keys(requested).some(key => !['native_execution', 'history_import'].includes(key)) || Object.values(requested).some(value => typeof value !== 'boolean')))
69
+ if (b.capabilities !== undefined && (Object.keys(requested).some(key => !['native_execution', 'history_import', 'config_sync'].includes(key)) || Object.values(requested).some(value => typeof value !== 'boolean')))
66
70
  throw new ApiError('input_invalid', 'Choose live execution, history import, or both.');
67
- const capabilities = { native_execution: requested.native_execution ?? true, history_import: requested.history_import ?? false };
68
- if (!capabilities.native_execution && !capabilities.history_import)
71
+ const capabilities = { native_execution: requested.native_execution ?? true, history_import: requested.history_import ?? false, config_sync: requested.config_sync ?? true };
72
+ if (!capabilities.native_execution && !capabilities.history_import && !capabilities.config_sync)
69
73
  throw new ApiError('input_invalid', 'Choose live execution, history import, or both.');
74
+ const replacing = b.connector_id === undefined ? undefined : validId(b.connector_id) ? await this.connector(b.connector_id) : undefined;
75
+ if (b.connector_id !== undefined && !replacing)
76
+ throw new ApiError('input_invalid', 'Choose the existing connector to authorize.');
70
77
  const token = `ar_enroll_${randomBytes(32).toString('base64url')}`;
71
78
  const expires = this.now() + 10 * 60_000;
72
- await this.store.settings.put(keyOf('enrollment', hash(token)), { expires, label: b.label ?? 'Remote machine', capabilities });
79
+ await this.store.settings.put(keyOf('enrollment', hash(token)), { expires, label: b.label ?? 'Remote machine', capabilities, ...(replacing ? { replace_id: replacing.id, replace_credential_hash: replacing.credential_hash, replace_revoked: replacing.revoked } : {}) });
73
80
  return { enrollment_token: token, expires_at: new Date(expires).toISOString(), workspace_id: 'local' };
74
81
  }
75
82
  async register(token, input) {
@@ -79,24 +86,42 @@ export class RemoteConnectors {
79
86
  throw new ApiError('unauthenticated', 'The connection code expired or is invalid. Create another in the console.');
80
87
  const b = object(input);
81
88
  bounded(b, 4096);
82
- if (!validId(b.installation_id) || !validId(b.operation_id) || (b.label !== undefined && !text(b.label)) || typeof object(b.capabilities).native_execution !== 'boolean' || (object(b.capabilities).history_import !== undefined && typeof object(b.capabilities).history_import !== 'boolean'))
89
+ if (!validId(b.installation_id) || !validId(b.operation_id) || (b.label !== undefined && !text(b.label)) || typeof object(b.capabilities).native_execution !== 'boolean' || (object(b.capabilities).history_import !== undefined && typeof object(b.capabilities).history_import !== 'boolean') || (object(b.capabilities).config_sync !== undefined && typeof object(b.capabilities).config_sync !== 'boolean'))
83
90
  throw new ApiError('input_invalid', 'Remote native execution requires an explicit installation, operation and capability selection.');
84
- const requested = { native_execution: object(b.capabilities).native_execution === true, history_import: object(b.capabilities).history_import === true };
85
- if (!requested.native_execution && !requested.history_import || requested.native_execution && enrollment.capabilities?.native_execution === false || requested.history_import && enrollment.capabilities?.history_import !== true)
91
+ const requested = { native_execution: object(b.capabilities).native_execution === true, history_import: object(b.capabilities).history_import === true, config_sync: object(b.capabilities).config_sync === true };
92
+ if (!requested.native_execution && !requested.history_import && !requested.config_sync || requested.native_execution && enrollment.capabilities?.native_execution === false || requested.history_import && enrollment.capabilities?.history_import !== true || requested.config_sync && enrollment.capabilities?.config_sync !== true)
86
93
  throw new ApiError('forbidden', 'The source requested capabilities not approved by the owner connection code.');
94
+ if (enrollment.replace_id && (await this.connector(enrollment.replace_id)).installation_id !== b.installation_id)
95
+ throw new ApiError("forbidden", "Authorize sync from this connector’s original installation.");
87
96
  const requestHash = hash(JSON.stringify(b));
88
97
  let id = enrollment.connector_id;
89
98
  if (id && enrollment.request_hash !== requestHash)
90
99
  throw new ApiError('idempotency_mismatch', 'This connection code has already been used for another request.');
91
100
  if (!id) {
92
- id = opaque('rc');
101
+ id = enrollment.replace_id ?? opaque('rc');
93
102
  if (!await this.store.settings.replaceIf(key, enrollment, { ...enrollment, connector_id: id, request_hash: requestHash }))
94
103
  throw new ApiError('idempotency_in_progress', 'Connection registration is in progress. Retry the same request.');
95
104
  }
96
105
  // Deterministically recover only this registration's reply after a lost HTTP response; no plaintext credential is stored.
97
106
  const credential = `ar_connector_${createHmac('sha256', token).update(id).digest('base64url')}`;
98
107
  const expires = this.now() + 30 * 24 * 60 * 60_000;
99
- const row = await this.store.settings.putIfAbsent(keyOf('connector', id), { id, installation_id: b.installation_id, label: b.label ?? enrollment.label, created_at: new Date(this.now()).toISOString(), last_seen: 0, credential_hash: hash(credential), expires, revoked: false, ...requested });
108
+ const candidate = { id, installation_id: b.installation_id, label: b.label ?? enrollment.label, created_at: new Date(this.now()).toISOString(), last_seen: 0, credential_hash: hash(credential), expires, revoked: false, ...requested };
109
+ let row;
110
+ if (enrollment.replace_id) {
111
+ row = await this.connector(id);
112
+ if (row.installation_id !== b.installation_id)
113
+ throw new ApiError('forbidden', 'Authorize sync from this connector’s original installation.');
114
+ if (row.credential_hash !== candidate.credential_hash) {
115
+ if (row.credential_hash !== enrollment.replace_credential_hash || row.revoked !== enrollment.replace_revoked)
116
+ throw new ApiError('forbidden', 'This connector changed after the owner issued its authorization. Request a new code.');
117
+ const next = { ...row, ...candidate, created_at: row.created_at };
118
+ if (!await this.store.settings.replaceIf(keyOf('connector', id), row, next, undefined, [{ key, fields: { connector_id: id, request_hash: requestHash, expires: enrollment.expires } }]))
119
+ throw new ApiError('idempotency_in_progress', 'The connector changed while being authorized. Retry the same request.');
120
+ row = next;
121
+ }
122
+ }
123
+ else
124
+ row = await this.store.settings.putIfAbsent(keyOf('connector', id), candidate);
100
125
  if (row.revoked || row.expires <= this.now())
101
126
  throw new ApiError('forbidden', 'This connector is revoked. Create a new connection code.');
102
127
  return { connector: await this.view(row), credential, credential_expires_at: new Date(row.expires).toISOString() };
@@ -106,22 +131,30 @@ export class RemoteConnectors {
106
131
  const row = await this.store.settings.get(keyOf('connector', id));
107
132
  if (!row || !token.startsWith('ar_connector_') || !timingSafeEqual(Buffer.from(hash(token)), Buffer.from(row.credential_hash)) || row.revoked || row.expires <= this.now())
108
133
  throw new ApiError('unauthenticated', 'The connector credential is invalid, expired or revoked.');
134
+ this.authenticated = { id, credentialHash: row.credential_hash };
109
135
  }
110
136
  async revoke(id) {
137
+ let revoked;
111
138
  for (let attempt = 0; attempt < 10; attempt++) {
112
139
  const row = await this.connector(id);
113
- if (row.revoked || await this.store.settings.replaceIf(keyOf('connector', id), row, { ...row, revoked: true }))
140
+ if (row.revoked) {
141
+ revoked = row;
114
142
  break;
143
+ }
144
+ const next = { ...row, revoked: true };
145
+ if (await this.store.settings.replaceIf(keyOf('connector', id), row, next)) {
146
+ revoked = next;
147
+ break;
148
+ }
115
149
  }
116
- const row = await this.connector(id);
117
- if (!row.revoked)
150
+ if (!revoked)
118
151
  throw new ApiError('home_busy', 'The connector changed while it was being revoked; retry.');
119
152
  for (const setting of await this.store.settings.all({ prefix: keyOf('command', ''), connectorId: id })) {
120
153
  const command = setting.value;
121
154
  if (setting.key.startsWith(keyOf('command', '')) && command.connector_id === id && ['queued', 'leased'].includes(command.state))
122
155
  await this.store.settings.replaceIf(setting.key, command, { ...command, state: 'cancelled', error: 'Connector revoked.' });
123
156
  }
124
- return { connector: await this.view(row) };
157
+ return { connector: await this.view(revoked) };
125
158
  }
126
159
  async assertReady(binding) {
127
160
  if (!binding.connected || !binding.remote)
@@ -146,7 +179,7 @@ export class RemoteConnectors {
146
179
  return { ...binding, state: 'needs_attention', capabilities: { ...binding.capabilities, launch: false }, issues: [...binding.issues, error instanceof Error ? error.message : 'The remote source is unavailable.'] };
147
180
  }
148
181
  }
149
- async importTarget(id, input) {
182
+ async importTarget(id, input, resolveAdoption) {
150
183
  const b = object(input);
151
184
  bounded(b, 256_000);
152
185
  if (b.history_only !== undefined && typeof b.history_only !== 'boolean')
@@ -168,26 +201,61 @@ export class RemoteConnectors {
168
201
  const connector = await this.connector(id);
169
202
  if (connector.revoked)
170
203
  throw new ApiError('forbidden', 'Connector revoked.');
171
- const historyOnly = b.history_only === true;
172
- if (historyOnly ? !connector.history_import || connector.native_execution : !connector.native_execution)
204
+ const historyOnly = b.history_only === true, syncOnly = !connector.native_execution && !historyOnly && connector.config_sync === true;
205
+ if (historyOnly ? !connector.history_import || connector.native_execution : !connector.native_execution && !syncOnly)
173
206
  throw new ApiError('forbidden', 'This connection code does not authorize the requested import mode.');
174
207
  if (historyOnly)
175
208
  native = { ...native, connected: false, capabilities: { ...native.capabilities, launch: false }, issues: [...native.issues, 'History only: past sessions are imported; this source has not authorized live execution.'] };
209
+ if (syncOnly)
210
+ native = { ...native, connected: false, capabilities: { ...native.capabilities, launch: false } };
176
211
  native = { ...native, remote: { connector_id: id, target_id: b.target_id } };
177
- const agentId = `remote-${hash(`${id}:${b.target_id}`).slice(0, 40)}`;
212
+ const adoption = b.cli_adoption === undefined ? undefined : resolveAdoption ? await resolveAdoption(id, b.target_id, native, b.cli_adoption) : undefined;
213
+ if (b.cli_adoption !== undefined && !adoption)
214
+ throw new ApiError('forbidden', 'This server cannot verify the existing CLI association.');
215
+ if (syncOnly && !adoption)
216
+ throw new ApiError('input_invalid', 'Enable capture for this source CLI first so sync can keep its existing agent and history.');
178
217
  const targetKey = keyOf('target', `${id}.${b.target_id}`);
179
- const prior = await this.store.settings.get(targetKey);
180
- if (prior && (prior.target.project !== native.project || prior.target.runtime !== native.runtime || prior.target.machine_id !== native.machine_id || JSON.stringify(prior.target.selector) !== JSON.stringify(native.selector)))
218
+ let prior = await this.store.settings.get(targetKey);
219
+ const sameSource = (saved) => saved.target.project === native.project && saved.target.runtime === native.runtime && saved.target.machine_id === native.machine_id && JSON.stringify(saved.target.selector) === JSON.stringify(native.selector);
220
+ if (prior && !sameSource(prior))
181
221
  throw new ApiError('idempotency_mismatch', 'A target id cannot be reused for another source agent.');
222
+ if (prior && adoption && prior.agent_id !== adoption.agentId)
223
+ throw new ApiError('input_invalid', 'This target already has its own durable agent. Its history cannot be replaced by a different profile.');
224
+ const agentId = prior?.agent_id ?? adoption?.agentId ?? `remote-${hash(`${id}:${b.target_id}`).slice(0, 40)}`;
182
225
  const name = b.name ?? `${native.runtime} · ${native.selector.name ?? native.project.split('/').filter(Boolean).at(-1) ?? 'project'}`;
226
+ const connectorGuard = { key: keyOf('connector', id), fields: { revoked: false, credential_hash: connector.credential_hash, expires: connector.expires } };
227
+ // Reserve the identity before creating anything. Concurrent imports cannot create two agents, and a crash after
228
+ // reservation is repairable by the same target's retry. A reservation alone grants no execution or export.
229
+ if (!prior) {
230
+ prior = await this.store.settings.putIfAbsent(targetKey, { target_id: b.target_id, agent_id: agentId, name, target: native, history_only: historyOnly, sync_only: syncOnly, owner_disconnected: false, ...(adoption ? { cli_connection_id: adoption.connectionId } : {}) });
231
+ if (prior.agent_id !== agentId || !sameSource(prior))
232
+ throw new ApiError('idempotency_mismatch', 'Another source association reserved this target.');
233
+ }
183
234
  let entry = await getAgent(this.store, agentId);
235
+ if (prior.owner_disconnected)
236
+ native = { ...native, connected: false };
184
237
  if (entry) {
185
- // A source credential cannot undo an owner disconnect. Re-enrollment is a new explicit owner grant.
186
- if (nativeOf(entry.revision?.body)?.connected === false)
187
- native = { ...native, connected: false };
188
- entry = await updateNative(this.store, entry, native);
238
+ const moved = sourceSyncOf(entry.revision?.body);
239
+ const captured = await cliCaptureOf(this.store, entry);
240
+ if (moved) {
241
+ const source = await this.store.settings.get(sourceKey(agentId));
242
+ if (!source || source.id !== moved.id || source.connection?.connector_id !== id || source.connection.target_id !== b.target_id)
243
+ throw new ApiError('forbidden', 'The managed agent no longer has this source association.');
244
+ // Metadata refresh is allowed after Move; execution never becomes native again.
245
+ }
246
+ else if (prior.cli_connection_id) {
247
+ if (captured?.binding.connection_id !== prior.cli_connection_id)
248
+ throw new ApiError('forbidden', 'The retained CLI profile no longer matches this target.');
249
+ }
250
+ else {
251
+ if (nativeOf(entry.revision?.body)?.connected === false)
252
+ native = { ...native, connected: false };
253
+ entry = await updateNative(this.store, entry, native, [connectorGuard, { key: targetKey, fields: { agent_id: agentId, owner_disconnected: prior.owner_disconnected } }]);
254
+ }
189
255
  }
190
256
  else {
257
+ if (adoption || prior.cli_connection_id)
258
+ throw new ApiError('not_found', 'The existing CLI agent is no longer available.');
191
259
  try {
192
260
  entry = await createAgent(this.store, { definition: { id: agentId, name, instructions: '', harness: native.runtime === 'claude-code' ? 'claude-agent' : 'codex', place: { mode: 'runner' }, tools: [], learning: false, native }, skills: {} });
193
261
  }
@@ -199,15 +267,36 @@ export class RemoteConnectors {
199
267
  throw error;
200
268
  }
201
269
  }
202
- const savedTarget = { target_id: b.target_id, agent_id: agentId, name, target: native, history_only: historyOnly, owner_disconnected: prior?.owner_disconnected ?? false };
203
- if (prior) {
204
- if (!await this.store.settings.replaceIf(targetKey, prior, savedTarget))
205
- throw new ApiError('home_busy', 'The owner changed this target while it was being imported. Retry after reviewing its connection.');
206
- }
207
- else
208
- await this.store.settings.putIfAbsent(targetKey, savedTarget);
270
+ const savedTarget = { ...prior, name, target: native, history_only: historyOnly, sync_only: syncOnly };
271
+ if (!await this.store.settings.replaceIf(targetKey, prior, savedTarget, undefined, [connectorGuard, ...(adoption?.guards ?? [])]))
272
+ throw new ApiError('home_busy', 'The owner changed this target while it was being imported. Retry after reviewing its connection.');
209
273
  return { agent_id: agentId, native };
210
274
  }
275
+ async syncAuthority(id, targetId) {
276
+ const connector = await this.connector(id), targetKey = keyOf('target', `${id}.${targetId}`);
277
+ if (connector.revoked || connector.expires <= this.now() || connector.config_sync !== true)
278
+ throw new ApiError('forbidden', 'Authorize configuration sync on the source machine with a new owner connection code.');
279
+ const target = await this.store.settings.get(targetKey);
280
+ if (!target || target.owner_disconnected)
281
+ throw new ApiError('forbidden', 'This source target is unavailable or disconnected by its owner.');
282
+ const entry = await getAgent(this.store, target.agent_id);
283
+ if (!entry?.revision || entry.agent.archivedAt || entry.agent.purgedAt)
284
+ throw new ApiError('not_found', 'The connected agent is unavailable.');
285
+ const native = nativeOf(entry.revision.body), moved = sourceSyncOf(entry.revision.body), capture = await cliCaptureOf(this.store, entry);
286
+ const record = await this.store.settings.get(sourceKey(entry.agent.id));
287
+ if (moved ? record?.id !== moved.id || record?.connection?.connector_id !== id || record?.connection?.target_id !== targetId : target.cli_connection_id ? capture?.binding.connection_id !== target.cli_connection_id : native?.remote?.connector_id !== id || native.remote.target_id !== targetId)
288
+ throw new ApiError('forbidden', 'This connector no longer owns the agent’s source association.');
289
+ const guards = [{ key: keyOf('connector', id), fields: { revoked: false, config_sync: true, credential_hash: connector.credential_hash, expires: connector.expires } },
290
+ { key: targetKey, fields: { agent_id: target.agent_id, owner_disconnected: target.owner_disconnected, cli_connection_id: target.cli_connection_id } }];
291
+ if (target.cli_connection_id) {
292
+ const row = await this.store.settings.get(`cli-learning-connection:${target.cli_connection_id}`);
293
+ if (!row?.active || row.agent_id !== target.agent_id)
294
+ throw new ApiError('forbidden', 'The source CLI capture connection was revoked.');
295
+ guards.push({ key: `cli-learning-connection:${target.cli_connection_id}`, fields: { active: true, generation: row.generation, agent_id: target.agent_id } });
296
+ }
297
+ const { runtime, machine_id, project, selector } = target.target;
298
+ return { agentId: target.agent_id, authority: { source: { runtime, machine_id, project, selector }, connection: { connector_id: id, target_id: targetId }, captureRevision: record?.capture_revision ?? entry.revision.id, guards } };
299
+ }
211
300
  async disconnectTarget(binding) {
212
301
  if (!binding.remote)
213
302
  return;
@@ -1,3 +1,9 @@
1
+ export declare const SOURCE_LOCAL_CONSENT: {
2
+ type: string;
3
+ additionalProperties: boolean;
4
+ properties: Record<string, unknown>;
5
+ required: string[];
6
+ };
1
7
  export declare const NATIVE_SELECTOR: {
2
8
  type: string;
3
9
  additionalProperties: boolean;