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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. package/CHANGELOG.md +122 -1
  2. package/README.md +213 -24
  3. package/dist/agent-delete.d.ts +5 -6
  4. package/dist/agent-delete.js +30 -67
  5. package/dist/agent-package.d.ts +71 -0
  6. package/dist/agent-package.js +345 -0
  7. package/dist/agents-store.d.ts +26 -20
  8. package/dist/agents-store.js +41 -33
  9. package/dist/api-only.d.ts +26 -6
  10. package/dist/api-only.js +35 -13
  11. package/dist/claude-login.d.ts +1 -0
  12. package/dist/claude-login.js +1 -1
  13. package/dist/cli-learning/cli.d.ts +3 -0
  14. package/dist/cli-learning/cli.js +17 -3
  15. package/dist/cli-learning/connections.js +3 -2
  16. package/dist/cli-learning/schema.js +2 -1
  17. package/dist/cli.js +70 -7
  18. package/dist/composio-preset.d.ts +2 -1
  19. package/dist/composio-preset.js +4 -3
  20. package/dist/composio-triggers.d.ts +4 -0
  21. package/dist/composio-triggers.js +4 -1
  22. package/dist/computer-needs.d.ts +32 -0
  23. package/dist/computer-needs.js +80 -0
  24. package/dist/computer-setting.d.ts +1 -0
  25. package/dist/computer-setting.js +8 -1
  26. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  27. package/dist/console/assets/index-DbilxljH.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/console-links.d.ts +1 -0
  30. package/dist/console-links.js +2 -0
  31. package/dist/env-switch.d.ts +14 -0
  32. package/dist/env-switch.js +23 -0
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.js +3 -0
  35. package/dist/eval-previous.js +4 -3
  36. package/dist/fal-price.js +10 -13
  37. package/dist/handed-secret.d.ts +4 -0
  38. package/dist/handed-secret.js +10 -0
  39. package/dist/harness-archive.d.ts +15 -5
  40. package/dist/harness-archive.js +71 -34
  41. package/dist/harness-check.d.ts +2 -1
  42. package/dist/harness-check.js +36 -95
  43. package/dist/harness-egress.d.ts +23 -0
  44. package/dist/harness-egress.js +69 -0
  45. package/dist/harness-recipe-entry.d.ts +71 -0
  46. package/dist/harness-recipe-entry.js +184 -0
  47. package/dist/harness-recipe.d.ts +73 -6
  48. package/dist/harness-recipe.js +185 -31
  49. package/dist/harness-sign-in.d.ts +29 -0
  50. package/dist/harness-sign-in.js +122 -0
  51. package/dist/harness-table.d.ts +21 -0
  52. package/dist/harness-table.js +58 -3
  53. package/dist/harness-zip.d.ts +6 -0
  54. package/dist/harness-zip.js +203 -0
  55. package/dist/ids.d.ts +11 -0
  56. package/dist/ids.js +36 -0
  57. package/dist/learn/commit.d.ts +14 -1
  58. package/dist/learn/commit.js +156 -1
  59. package/dist/learn/compile.js +22 -8
  60. package/dist/learn/folder.d.ts +5 -0
  61. package/dist/learn/folder.js +10 -1
  62. package/dist/learn/learning.sh +15 -3
  63. package/dist/learn/promote.d.ts +2 -2
  64. package/dist/learn/secrets.js +30 -7
  65. package/dist/learning-routes.d.ts +23 -11
  66. package/dist/learning-routes.js +110 -20
  67. package/dist/learning.d.ts +9 -6
  68. package/dist/learning.js +9 -4
  69. package/dist/mcp-gateway.js +15 -2
  70. package/dist/mcp-probe.d.ts +3 -0
  71. package/dist/mcp-probe.js +7 -2
  72. package/dist/mcp-resources.d.ts +44 -0
  73. package/dist/mcp-resources.js +100 -0
  74. package/dist/mcp-servers-store.d.ts +16 -12
  75. package/dist/model.d.ts +4 -4
  76. package/dist/model.js +6 -6
  77. package/dist/native/cli.js +9 -2
  78. package/dist/native/connection.d.ts +2 -2
  79. package/dist/native/connection.js +5 -2
  80. package/dist/native/discovery.d.ts +2 -0
  81. package/dist/native/discovery.js +10 -6
  82. package/dist/native/remote-worker-bridge.js +36 -4
  83. package/dist/native/remote.d.ts +18 -1
  84. package/dist/native/remote.js +126 -37
  85. package/dist/native/schema.d.ts +6 -0
  86. package/dist/native/schema.js +31 -6
  87. package/dist/native/source-account.d.ts +13 -0
  88. package/dist/native/source-account.js +114 -0
  89. package/dist/native/source-capture-hooks.d.ts +5 -0
  90. package/dist/native/source-capture-hooks.js +102 -0
  91. package/dist/native/source-mcp-selection.d.ts +13 -0
  92. package/dist/native/source-mcp-selection.js +72 -0
  93. package/dist/native/source-runtime-tools.d.ts +19 -0
  94. package/dist/native/source-runtime-tools.js +103 -0
  95. package/dist/native/source-snapshot-types.d.ts +138 -0
  96. package/dist/native/source-snapshot-types.js +12 -0
  97. package/dist/native/source-snapshot.d.ts +8 -0
  98. package/dist/native/source-snapshot.js +1201 -0
  99. package/dist/observation/learning.js +3 -2
  100. package/dist/openapi.js +167 -36
  101. package/dist/print.js +1 -1
  102. package/dist/purged-workflow.d.ts +12 -0
  103. package/dist/purged-workflow.js +43 -0
  104. package/dist/run-keys.d.ts +46 -0
  105. package/dist/run-keys.js +109 -0
  106. package/dist/run-launch.d.ts +16 -1
  107. package/dist/run-launch.js +30 -1
  108. package/dist/run-learning-served.d.ts +2 -2
  109. package/dist/run-model-key.d.ts +2 -2
  110. package/dist/run-model-key.js +5 -5
  111. package/dist/run-secrets.d.ts +2 -0
  112. package/dist/run-secrets.js +7 -4
  113. package/dist/run-view.d.ts +17 -0
  114. package/dist/run-view.js +25 -1
  115. package/dist/runner/adapter-loop.d.ts +11 -3
  116. package/dist/runner/adapter-loop.js +138 -22
  117. package/dist/runner/adapter-run-spec.js +25 -12
  118. package/dist/runner/audit.d.ts +2 -0
  119. package/dist/runner/audit.js +9 -1
  120. package/dist/runner/beside.js +2 -1
  121. package/dist/runner/claim-secrets.d.ts +29 -3
  122. package/dist/runner/claim-secrets.js +38 -4
  123. package/dist/runner/cli-run-spec.js +23 -12
  124. package/dist/runner/harness-loops.d.ts +6 -0
  125. package/dist/runner/harness-loops.js +11 -1
  126. package/dist/runner/held.d.ts +4 -0
  127. package/dist/runner/journal-kinds.d.ts +2 -0
  128. package/dist/runner/learned-first.d.ts +2 -0
  129. package/dist/runner/learned-first.js +1 -1
  130. package/dist/runner/learning-end.d.ts +7 -2
  131. package/dist/runner/learning-end.js +22 -10
  132. package/dist/runner/learning-seed.d.ts +9 -3
  133. package/dist/runner/learning-seed.js +2 -2
  134. package/dist/runner/main.d.ts +1 -0
  135. package/dist/runner/main.js +20 -13
  136. package/dist/runner/mcp-claim.js +6 -1
  137. package/dist/runner/mcp-run.d.ts +10 -7
  138. package/dist/runner/mcp-run.js +3 -5
  139. package/dist/runner/monid-run.js +9 -11
  140. package/dist/runner/project-checkpoint.d.ts +35 -0
  141. package/dist/runner/project-checkpoint.js +116 -0
  142. package/dist/runner/project-drain.d.ts +8 -0
  143. package/dist/runner/project-drain.js +25 -0
  144. package/dist/runner/project-host.d.ts +10 -0
  145. package/dist/runner/project-host.js +52 -0
  146. package/dist/runner/promotion.d.ts +14 -6
  147. package/dist/runner/promotion.js +98 -41
  148. package/dist/runner/redact.d.ts +13 -0
  149. package/dist/runner/redact.js +67 -1
  150. package/dist/runner/run-channel.d.ts +9 -0
  151. package/dist/runner/run-channel.js +15 -2
  152. package/dist/runner/run-child-host.d.ts +8 -4
  153. package/dist/runner/run-child-host.js +171 -41
  154. package/dist/runner/run-errors.js +2 -2
  155. package/dist/runner/runner-check.js +5 -2
  156. package/dist/runner/runner.js +26 -9
  157. package/dist/runner/store-secrets.js +7 -3
  158. package/dist/runner/workflow-first.d.ts +4 -0
  159. package/dist/runner/workflow-first.js +13 -0
  160. package/dist/runner/workflow-loop.d.ts +2 -1
  161. package/dist/runner/workflow-loop.js +2 -1
  162. package/dist/runner/workflow-spec.js +1 -1
  163. package/dist/runs-over-store.d.ts +34 -6
  164. package/dist/runs-over-store.js +133 -25
  165. package/dist/sdk/runs.d.ts +11 -1
  166. package/dist/sdk/runs.js +117 -26
  167. package/dist/sdk/schema.js +12 -2
  168. package/dist/sdk/workflows.d.ts +1 -1
  169. package/dist/server.d.ts +68 -32
  170. package/dist/server.js +600 -110
  171. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  172. package/dist/source-sync/adoption.d.ts +15 -0
  173. package/dist/source-sync/adoption.js +36 -0
  174. package/dist/source-sync/auxiliary.d.ts +23 -0
  175. package/dist/source-sync/auxiliary.js +64 -0
  176. package/dist/source-sync/capture-git.d.ts +5 -0
  177. package/dist/source-sync/capture-git.js +272 -0
  178. package/dist/source-sync/capture-project.d.ts +53 -0
  179. package/dist/source-sync/capture-project.js +206 -0
  180. package/dist/source-sync/capture-refusal.d.ts +7 -0
  181. package/dist/source-sync/capture-refusal.js +16 -0
  182. package/dist/source-sync/capture.d.ts +11 -0
  183. package/dist/source-sync/capture.js +22 -0
  184. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  185. package/dist/source-sync/checkpoint-gate.js +52 -0
  186. package/dist/source-sync/checkpoints.d.ts +66 -0
  187. package/dist/source-sync/checkpoints.js +168 -0
  188. package/dist/source-sync/claim.d.ts +11 -0
  189. package/dist/source-sync/claim.js +48 -0
  190. package/dist/source-sync/destination.d.ts +47 -0
  191. package/dist/source-sync/destination.js +239 -0
  192. package/dist/source-sync/io.d.ts +15 -0
  193. package/dist/source-sync/io.js +52 -0
  194. package/dist/source-sync/local.d.ts +43 -0
  195. package/dist/source-sync/local.js +229 -0
  196. package/dist/source-sync/prepare.d.ts +59 -0
  197. package/dist/source-sync/prepare.js +93 -0
  198. package/dist/source-sync/projects.d.ts +61 -0
  199. package/dist/source-sync/projects.js +130 -0
  200. package/dist/source-sync/registry.d.ts +95 -0
  201. package/dist/source-sync/registry.js +226 -0
  202. package/dist/source-sync/service.d.ts +33 -0
  203. package/dist/source-sync/service.js +118 -0
  204. package/dist/source-sync/skill-edits.d.ts +12 -0
  205. package/dist/source-sync/skill-edits.js +122 -0
  206. package/dist/source-sync/snapshots.d.ts +48 -0
  207. package/dist/source-sync/snapshots.js +448 -0
  208. package/dist/source-sync/types.d.ts +9 -0
  209. package/dist/source-sync/types.js +14 -0
  210. package/dist/source-sync/workspace.d.ts +66 -0
  211. package/dist/source-sync/workspace.js +273 -0
  212. package/dist/store/agent-body.d.ts +4 -0
  213. package/dist/store/agent-body.js +16 -5
  214. package/dist/store/index.d.ts +2 -2
  215. package/dist/store/index.js +1 -1
  216. package/dist/store/schema.d.ts +2 -1
  217. package/dist/store/schema.js +2 -1
  218. package/dist/store/seal.d.ts +5 -1
  219. package/dist/store/seal.js +12 -3
  220. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  221. package/dist/store/sqlite/project-checkpoints.js +70 -0
  222. package/dist/store/sqlite/run-launch.d.ts +4 -12
  223. package/dist/store/sqlite/run-launch.js +5 -19
  224. package/dist/store/sqlite/store.js +224 -170
  225. package/dist/store/store.d.ts +116 -39
  226. package/dist/store/store.js +14 -1
  227. package/dist/store-reads/learning.d.ts +2 -2
  228. package/dist/store-view.d.ts +3 -1
  229. package/dist/store-view.js +17 -5
  230. package/dist/template-import.d.ts +10 -2
  231. package/dist/template-import.js +116 -13
  232. package/dist/templates.d.ts +26 -5
  233. package/dist/templates.js +62 -10
  234. package/dist/timeline/index.d.ts +1 -1
  235. package/dist/timeline/index.js +1 -1
  236. package/dist/timeline/timeline.d.ts +5 -0
  237. package/dist/timeline/timeline.js +8 -0
  238. package/dist/tool-plane.d.ts +12 -12
  239. package/dist/tools.d.ts +8 -8
  240. package/dist/trigger-launch-hook.d.ts +47 -0
  241. package/dist/trigger-launch-hook.js +90 -0
  242. package/dist/trigger-targets.d.ts +14 -1
  243. package/dist/trigger-targets.js +20 -0
  244. package/dist/triggers.d.ts +54 -5
  245. package/dist/triggers.js +143 -8
  246. package/dist/uploads-archil.js +1 -1
  247. package/dist/uploads.js +1 -1
  248. package/dist/validate.js +1 -2
  249. package/dist/workspace/computer-for-claim.d.ts +2 -0
  250. package/dist/workspace/computer-for-claim.js +43 -0
  251. package/dist/workspace/paths.d.ts +6 -0
  252. package/dist/workspace/paths.js +6 -0
  253. package/dist/workspace/resolve-computer.d.ts +1 -0
  254. package/dist/workspace/run-tools.d.ts +2 -0
  255. package/dist/workspace/run-tools.js +8 -0
  256. package/launcher/agentrun-serve +1 -1
  257. package/package.json +10 -10
  258. package/skills/agentrun-serve/SKILL.md +2 -1
  259. package/templates/README.md +5 -2
  260. package/dist/console/assets/index-B-D0EM3j.js +0 -733
  261. package/dist/console/assets/index-DlQepP2J.css +0 -1
@@ -0,0 +1,95 @@
1
+ import { type AgentEntry } from "../agents-store.js";
2
+ import type { SourceSnapshot, SourceSnapshotBlocker } from "../native/source-snapshot-types.js";
3
+ import { type McpGuard, type NewRevision, type SettingsGuard, type Store } from "../store/store.js";
4
+ export declare const sourceKey: (agentId: string) => string;
5
+ export type SourceIdentity = SourceSnapshot["source"];
6
+ export interface SourceRecord {
7
+ readonly version: 1;
8
+ readonly id: string;
9
+ readonly agent_id: string;
10
+ readonly source: SourceIdentity;
11
+ readonly connection?: {
12
+ readonly connector_id: string;
13
+ readonly target_id: string;
14
+ };
15
+ readonly capture_revision: string;
16
+ readonly generation: string;
17
+ readonly enabled: boolean;
18
+ readonly sequence: number;
19
+ readonly snapshot?: string;
20
+ readonly attempt?: {
21
+ readonly digest: string;
22
+ readonly code?: SourceFailureCode;
23
+ readonly blockers: readonly SourceSnapshotBlocker[];
24
+ };
25
+ }
26
+ export interface SourceAuthority {
27
+ readonly source: SourceIdentity;
28
+ readonly connection?: SourceRecord["connection"];
29
+ /** The actual source credential/target rows, including generation and owner disconnect predicates. */
30
+ readonly guards: readonly SettingsGuard[];
31
+ readonly captureRevision: string;
32
+ }
33
+ export interface SourcePreparation {
34
+ readonly revision: NewRevision;
35
+ /** Destination credential/tool generations checked again in the cutover transaction. */
36
+ readonly guards?: readonly SettingsGuard[];
37
+ readonly mcpGuards?: readonly McpGuard[];
38
+ }
39
+ export interface SourceSyncOptions {
40
+ /** Authority is checked on every operation, also after Move. It must never be inferred from a path or title. */
41
+ authorize(agentId: string, operation: "grant" | "push" | "move"): Promise<SourceAuthority>;
42
+ /** Validates all bytes/paths/digests and commits an immutable complete manifest before returning. */
43
+ persist(agentId: string, snapshot: SourceSnapshot): Promise<void>;
44
+ read(agentId: string, digest: string): Promise<SourceSnapshot>;
45
+ /** Resolves the actual managed tools, policies, model access and workspace. Refusal leaves execution at its source. */
46
+ prepare(entry: AgentEntry, snapshot: SourceSnapshot): Promise<SourcePreparation>;
47
+ /** Exercise real destination file/Git/mode preparation before cutover, without admitting or running a task. */
48
+ verifyDestination?(entry: AgentEntry, snapshot: SourceSnapshot, prepared: SourcePreparation): Promise<void>;
49
+ }
50
+ export declare const SOURCE_FAILURES: {
51
+ readonly unsupported_platform: "This source needs a supported snapshot reader for its operating system.";
52
+ readonly source_changed: "The source changed while it was being read. Sync will retry a complete version.";
53
+ readonly source_unavailable: "The source setup could not be read. Check the source connection and its approved folders.";
54
+ readonly snapshot_too_large: "This project exceeds the supported snapshot size. Select a smaller complete project.";
55
+ };
56
+ export type SourceFailureCode = keyof typeof SOURCE_FAILURES;
57
+ /** The coupled settings group: a source update never combines new tool policy with unrelated managed settings. */
58
+ export declare function configurationDigest(body: unknown): string;
59
+ export declare class SourceSync {
60
+ readonly store: Store;
61
+ readonly options: SourceSyncOptions;
62
+ constructor(store: Store, options: SourceSyncOptions);
63
+ get(agentId: string): Promise<SourceRecord | undefined>;
64
+ private entry;
65
+ private authorized;
66
+ /** Called only after the source explicitly grants configuration/project export. A new grant defaults to on. */
67
+ grant(agentId: string): Promise<SourceRecord>;
68
+ /** The signed-in owner's switch. The record is retained so disconnect can never turn a moved agent native again. */
69
+ setEnabled(agentId: string, enabled: boolean): Promise<SourceRecord>;
70
+ publish(agentId: string, input: {
71
+ generation: string;
72
+ sequence: number;
73
+ snapshot: SourceSnapshot;
74
+ }): Promise<SourceRecord>;
75
+ private guard;
76
+ /** A source failure is a fixed server-owned message, never a path, exception dump or credential-bearing text. */
77
+ failed(agentId: string, input: {
78
+ generation: string;
79
+ sequence: number;
80
+ code: SourceFailureCode;
81
+ }): Promise<SourceRecord>;
82
+ /** One atomic ownership cutover. Retrying after an uncertain response returns the same managed agent. */
83
+ move(agentId: string): Promise<AgentEntry>;
84
+ /** A source push only changes an already moved agent when its managed configuration still matches our baseline. */
85
+ reconcile(agentId: string): Promise<"unchanged" | "applied" | "conflict">;
86
+ /** Project edits and their authored skill closure form one group. A source update cannot publish new skill metadata
87
+ * while silently retaining older script bytes, nor replace the files a managed run changed. */
88
+ conflicts(entry: AgentEntry, record: SourceRecord): Promise<boolean>;
89
+ /** Explicit owner resolution, pinned to the version shown. Old managed files remain in immutable history. */
90
+ useSource(agentId: string, expected: {
91
+ revision: string;
92
+ snapshot: string;
93
+ }): Promise<AgentEntry>;
94
+ private apply;
95
+ }
@@ -0,0 +1,226 @@
1
+ /** Source ownership survives Move. Snapshot bytes commit first; these small rows publish their digests under the
2
+ * connector's revocation guards. Managed revisions carry the cutover receipt, so a crash cannot restore native work. */
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { getAgent } from "../agents-store.js";
5
+ import { uuidv7 } from "../ids.js";
6
+ import { ApiError } from "../errors.js";
7
+ import { canonical, isObject } from "../store/agent-body.js";
8
+ import { ActiveRuns, RevisionMoved } from "../store/store.js";
9
+ import { sourceSyncOf } from "./types.js";
10
+ export const sourceKey = (agentId) => `source-sync.agent.${agentId}`;
11
+ const hash = (value) => createHash("sha256").update(canonical(value)).digest("hex");
12
+ const generation = () => randomBytes(24).toString("base64url");
13
+ const busy = () => new ApiError("precondition_failed", "The source or agent changed while syncing. Read its current status and try again.");
14
+ const matches = (a, b) => canonical(a) === canonical(b);
15
+ export const SOURCE_FAILURES = {
16
+ unsupported_platform: "This source needs a supported snapshot reader for its operating system.",
17
+ source_changed: "The source changed while it was being read. Sync will retry a complete version.",
18
+ source_unavailable: "The source setup could not be read. Check the source connection and its approved folders.",
19
+ snapshot_too_large: "This project exceeds the supported snapshot size. Select a smaller complete project.",
20
+ };
21
+ /** The coupled settings group: a source update never combines new tool policy with unrelated managed settings. */
22
+ export function configurationDigest(body) {
23
+ if (!isObject(body))
24
+ throw new TypeError("a configuration is a revision body");
25
+ const { sourceSync: _source, ...configuration } = body;
26
+ return hash(configuration);
27
+ }
28
+ const projectDigest = (snapshot) => hash({ project: snapshot.project, skills: snapshot.skills,
29
+ entries: snapshot.entries.filter(entry => entry.role === "project" || entry.role === "skill").sort((a, b) => a.path.localeCompare(b.path)) });
30
+ export class SourceSync {
31
+ store;
32
+ options;
33
+ constructor(store, options) {
34
+ this.store = store;
35
+ this.options = options;
36
+ }
37
+ async get(agentId) {
38
+ return await this.store.settings.get(sourceKey(agentId));
39
+ }
40
+ async entry(agentId) {
41
+ const entry = await getAgent(this.store, agentId);
42
+ if (!entry?.revision || entry.agent.purgedAt || entry.agent.archivedAt || entry.agent.externalRef)
43
+ throw new ApiError("not_found", "Choose an active connected agent owned by this server.");
44
+ return entry;
45
+ }
46
+ async authorized(agentId, operation, record) {
47
+ const authority = await this.options.authorize(agentId, operation);
48
+ if (record && !matches(record.source, authority.source))
49
+ throw new ApiError("forbidden", "This source does not own the agent's sync connection.");
50
+ if (record && canonical(record.connection ?? null) !== canonical(authority.connection ?? null))
51
+ throw new ApiError("forbidden", "A different connector owns this agent's sync connection.");
52
+ if (!authority.guards.length)
53
+ throw new TypeError("source authority requires a durable revocation guard");
54
+ const capture = await this.store.agents.revision(authority.captureRevision);
55
+ if (!capture || capture.agentId !== agentId)
56
+ throw new ApiError("forbidden", "The source capture revision does not belong to this agent.");
57
+ return authority;
58
+ }
59
+ /** Called only after the source explicitly grants configuration/project export. A new grant defaults to on. */
60
+ async grant(agentId) {
61
+ await this.entry(agentId);
62
+ const authority = await this.authorized(agentId, "grant");
63
+ const candidate = { version: 1, id: hash({ agentId, source: authority.source }), agent_id: agentId,
64
+ source: authority.source, ...(authority.connection ? { connection: authority.connection } : {}), capture_revision: authority.captureRevision, generation: generation(), enabled: true, sequence: -1 };
65
+ const record = await this.store.settings.putIfAbsent(sourceKey(agentId), candidate);
66
+ if (!matches(record.source, authority.source) || canonical(record.connection ?? null) !== canonical(authority.connection ?? null))
67
+ throw new ApiError("forbidden", "This agent already has a different authorized source.");
68
+ // Merely inserting an unpublished grant cannot move execution. Every publish and cutover rechecks authority in
69
+ // its write transaction, including a revocation which raced this first registration.
70
+ return record;
71
+ }
72
+ /** The signed-in owner's switch. The record is retained so disconnect can never turn a moved agent native again. */
73
+ async setEnabled(agentId, enabled) {
74
+ await this.entry(agentId);
75
+ for (let tries = 0; tries < 8; tries++) {
76
+ const record = await this.get(agentId);
77
+ if (!record)
78
+ throw new ApiError("not_found", "Connect this agent's source before enabling sync.");
79
+ if (record.enabled === enabled)
80
+ return record;
81
+ // Re-enabling needs a fresh source grant. Owner disable is always available, including while its source is offline.
82
+ const authority = enabled ? await this.authorized(agentId, "grant", record) : undefined;
83
+ const next = { ...record, enabled, generation: generation(), sequence: -1 };
84
+ if (await this.store.settings.replaceIf(sourceKey(agentId), record, next, undefined, authority?.guards))
85
+ return next;
86
+ }
87
+ throw busy();
88
+ }
89
+ async publish(agentId, input) {
90
+ if (!Number.isSafeInteger(input.sequence) || input.sequence < 0)
91
+ throw new ApiError("input_invalid", "A source snapshot needs a non-negative sequence.");
92
+ let record = await this.get(agentId);
93
+ if (!record)
94
+ throw new ApiError("forbidden", "This source has no configuration sync grant.");
95
+ const authority = await this.authorized(agentId, "push", record);
96
+ const check = (row) => {
97
+ if (!row.enabled || row.generation !== input.generation)
98
+ throw new ApiError("forbidden", "Source sync is off or its grant changed.");
99
+ if (!matches(row.source, input.snapshot.source))
100
+ throw new ApiError("forbidden", "The snapshot belongs to a different source target.");
101
+ if (input.sequence < row.sequence)
102
+ throw busy();
103
+ if (input.sequence === row.sequence && row.attempt?.digest !== input.snapshot.digest)
104
+ throw busy();
105
+ };
106
+ check(record);
107
+ if (input.sequence === record.sequence)
108
+ return record;
109
+ // The persistence boundary validates even an incomplete manifest; it never makes an incomplete version movable.
110
+ await this.options.persist(agentId, input.snapshot);
111
+ for (let tries = 0; tries < 8; tries++) {
112
+ check(record);
113
+ if (input.sequence === record.sequence)
114
+ return record;
115
+ const next = { ...record, sequence: input.sequence,
116
+ ...(input.snapshot.complete && !input.snapshot.blockers.length ? { snapshot: input.snapshot.digest } : {}),
117
+ attempt: { digest: input.snapshot.digest, blockers: input.snapshot.blockers } };
118
+ if (await this.store.settings.replaceIf(sourceKey(agentId), record, next, undefined, authority.guards))
119
+ return next;
120
+ record = await this.get(agentId) ?? (() => { throw busy(); })();
121
+ }
122
+ throw busy();
123
+ }
124
+ guard(record) {
125
+ return { key: sourceKey(record.agent_id), fields: { id: record.id, generation: record.generation,
126
+ enabled: true, snapshot: record.snapshot, sequence: record.sequence } };
127
+ }
128
+ /** A source failure is a fixed server-owned message, never a path, exception dump or credential-bearing text. */
129
+ async failed(agentId, input) {
130
+ if (!Object.hasOwn(SOURCE_FAILURES, input.code) || !Number.isSafeInteger(input.sequence) || input.sequence < 0)
131
+ throw new ApiError("input_invalid", "Supply a supported source failure code and sequence.");
132
+ for (let tries = 0; tries < 8; tries++) {
133
+ const record = await this.get(agentId);
134
+ if (!record || !record.enabled || record.generation !== input.generation)
135
+ throw new ApiError("forbidden", "Source sync is off or its grant changed.");
136
+ const authority = await this.authorized(agentId, "push", record);
137
+ if (input.sequence < record.sequence || input.sequence === record.sequence && record.attempt?.code !== input.code)
138
+ throw busy();
139
+ if (input.sequence === record.sequence)
140
+ return record;
141
+ const next = { ...record, sequence: input.sequence, attempt: { digest: hash(input), code: input.code,
142
+ blockers: [{ code: input.code, message: SOURCE_FAILURES[input.code] }] } };
143
+ if (await this.store.settings.replaceIf(sourceKey(agentId), record, next, undefined, authority.guards))
144
+ return next;
145
+ }
146
+ throw busy();
147
+ }
148
+ /** One atomic ownership cutover. Retrying after an uncertain response returns the same managed agent. */
149
+ async move(agentId) {
150
+ const entry = await this.entry(agentId);
151
+ const record = await this.get(agentId);
152
+ if (!record)
153
+ throw new ApiError("agent_not_runnable", "Connect this agent's source and sync its setup first.");
154
+ const moved = sourceSyncOf(entry.revision.body);
155
+ if (moved?.id === record.id)
156
+ return entry;
157
+ const authority = await this.authorized(agentId, "move", record);
158
+ return await this.apply(entry, record, authority, true);
159
+ }
160
+ /** A source push only changes an already moved agent when its managed configuration still matches our baseline. */
161
+ async reconcile(agentId) {
162
+ const entry = await this.entry(agentId), record = await this.get(agentId), binding = sourceSyncOf(entry.revision.body);
163
+ if (!record?.enabled || !binding || binding.id !== record.id || !record.snapshot || binding.snapshot === record.snapshot)
164
+ return "unchanged";
165
+ if (await this.conflicts(entry, record))
166
+ return "conflict";
167
+ const authority = await this.authorized(agentId, "move", record);
168
+ await this.apply(entry, record, authority, false);
169
+ return "applied";
170
+ }
171
+ /** Project edits and their authored skill closure form one group. A source update cannot publish new skill metadata
172
+ * while silently retaining older script bytes, nor replace the files a managed run changed. */
173
+ async conflicts(entry, record) {
174
+ const binding = sourceSyncOf(entry.revision?.body);
175
+ if (!binding || !record.snapshot || binding.snapshot === record.snapshot)
176
+ return false;
177
+ if (configurationDigest(entry.revision.body) !== binding.configuration)
178
+ return true;
179
+ if (binding.project === binding.snapshot)
180
+ return false;
181
+ const [before, after] = await Promise.all([this.options.read(entry.agent.id, binding.snapshot), this.options.read(entry.agent.id, record.snapshot)]);
182
+ return projectDigest(before) !== projectDigest(after);
183
+ }
184
+ /** Explicit owner resolution, pinned to the version shown. Old managed files remain in immutable history. */
185
+ async useSource(agentId, expected) {
186
+ const entry = await this.entry(agentId), record = await this.get(agentId);
187
+ if (!record || entry.revision.id !== expected.revision || record.snapshot !== expected.snapshot)
188
+ throw busy();
189
+ if (!sourceSyncOf(entry.revision.body))
190
+ throw new ApiError("input_invalid", "Move this agent before resolving source updates.");
191
+ return this.apply(entry, record, await this.authorized(agentId, "move", record), true);
192
+ }
193
+ async apply(entry, record, authority, moving) {
194
+ if (!record.enabled || !record.snapshot)
195
+ throw new ApiError("agent_not_runnable", "Sync a complete setup before moving this agent.");
196
+ if (record.attempt?.blockers.length)
197
+ throw new ApiError("agent_not_runnable", record.attempt.blockers.map(item => item.message).join(" "));
198
+ const snapshot = await this.options.read(entry.agent.id, record.snapshot);
199
+ if (!snapshot.complete || snapshot.blockers.length || snapshot.digest !== record.snapshot || !matches(snapshot.source, record.source))
200
+ throw new ApiError("agent_not_runnable", "The source snapshot is incomplete or does not match its published manifest. Sync again.");
201
+ const prepared = await this.options.prepare(entry, snapshot);
202
+ await this.options.verifyDestination?.(entry, snapshot, prepared);
203
+ const body = prepared.revision.body;
204
+ if (prepared.revision.kind !== "agentic" || !isObject(body) || body.native || body.sdk || body.cli_learning)
205
+ throw new TypeError("Move prepares an independent managed agentic revision");
206
+ const previous = sourceSyncOf(entry.revision.body);
207
+ const next = { ...prepared.revision, id: uuidv7(), body: { ...body, sourceSync: {
208
+ id: record.id, snapshot: record.snapshot,
209
+ // A separately published managed project checkpoint is a server edit. Configuration sync must not reset it.
210
+ project: !moving && previous?.project !== previous?.snapshot ? previous.project : record.snapshot,
211
+ configuration: configurationDigest(body),
212
+ } } };
213
+ try {
214
+ await this.store.agents.addRevision({ ...next, agentId: entry.agent.id, ifCurrent: entry.revision.id,
215
+ ...(moving ? { ifNoActiveRuns: true } : {}), settingsGuards: [this.guard(record), ...authority.guards, ...(prepared.guards ?? [])], mcpGuards: prepared.mcpGuards });
216
+ }
217
+ catch (error) {
218
+ if (error instanceof ActiveRuns)
219
+ throw new ApiError("agent_not_runnable", "Finish this agent's active runs before moving it to AgentRun.");
220
+ if (error instanceof RevisionMoved)
221
+ throw busy();
222
+ throw error;
223
+ }
224
+ return (await this.entry(entry.agent.id));
225
+ }
226
+ }
@@ -0,0 +1,33 @@
1
+ /** Source HTTP operations share one registry and the same private storage as managed run placement. */
2
+ import { type AgentEntry } from "../agents-store.js";
3
+ import { RemoteConnectors } from "../native/remote.js";
4
+ import type { SourceSnapshot, SourceSnapshotBlocker } from "../native/source-snapshot-types.js";
5
+ import type { Store } from "../store/store.js";
6
+ import { sourceToolConnections } from "./destination.js";
7
+ import { SourceSync, type SourcePreparation, type SourceSyncOptions } from "./registry.js";
8
+ import { type SourceWorkspaceOptions } from "./workspace.js";
9
+ import { type ProjectIssue } from "./checkpoint-gate.js";
10
+ export declare const SOURCE_BODY_BYTES: number;
11
+ export interface SourceStatus {
12
+ readonly enabled: boolean;
13
+ readonly moved: boolean;
14
+ readonly state: "needs_connection" | "paused" | "syncing" | "needs_attention" | "ready" | "moved" | "conflict";
15
+ readonly blockers: readonly SourceSnapshotBlocker[];
16
+ readonly snapshot?: string;
17
+ readonly current_snapshot?: string;
18
+ readonly connection?: {
19
+ readonly connector_id: string;
20
+ readonly target_id: string;
21
+ };
22
+ readonly files?: number;
23
+ readonly bytes?: number;
24
+ readonly skills?: number;
25
+ readonly tools?: number;
26
+ readonly tool_connections?: Awaited<ReturnType<typeof sourceToolConnections>>;
27
+ readonly project_issues?: readonly ProjectIssue[];
28
+ }
29
+ export declare function sourceService(store: Store, workspace: SourceWorkspaceOptions, prepare: (entry: AgentEntry, snapshot: SourceSnapshot) => Promise<SourcePreparation>, verifyDestination?: SourceSyncOptions["verifyDestination"], localAuthorize?: SourceSyncOptions["authorize"]): {
30
+ sync: SourceSync;
31
+ forConnector(broker: RemoteConnectors, connectorId: string, targetId: string): SourceSync;
32
+ status(agentId: string): Promise<SourceStatus>;
33
+ };
@@ -0,0 +1,118 @@
1
+ /** Source HTTP operations share one registry and the same private storage as managed run placement. */
2
+ import { getAgent } from "../agents-store.js";
3
+ import { ApiError } from "../errors.js";
4
+ import { nativeOf } from "../native/binding.js";
5
+ import { RemoteConnectors } from "../native/remote.js";
6
+ import { SourcePreparationError } from "./prepare.js";
7
+ import { sourceToolConnections } from "./destination.js";
8
+ import { SourceSync } from "./registry.js";
9
+ import { commitSourceSnapshot, readSourceSnapshot, validateSourceSnapshot, SnapshotError } from "./snapshots.js";
10
+ import { sourceSyncOf } from "./types.js";
11
+ import { sourceSnapshotReader, sourceWorkspace } from "./workspace.js";
12
+ import { unresolvedProjects } from "./checkpoint-gate.js";
13
+ import { withSourceIO } from "./io.js";
14
+ export const SOURCE_BODY_BYTES = 128 * 1024 * 1024;
15
+ export function sourceService(store, workspace, prepare, verifyDestination, localAuthorize) {
16
+ const withWorkspace = async (agentId, call) => {
17
+ const opened = await sourceWorkspace(store, agentId, workspace);
18
+ try {
19
+ return await call(opened.workspace);
20
+ }
21
+ finally {
22
+ await opened.end();
23
+ }
24
+ };
25
+ const sync = new SourceSync(store, {
26
+ authorize: async (agentId) => {
27
+ const record = await sync.get(agentId), entry = await getAgent(store, agentId);
28
+ const connection = record?.connection ?? nativeOf(entry?.revision?.body)?.remote;
29
+ if (!connection) {
30
+ if (localAuthorize)
31
+ return localAuthorize(agentId, "move");
32
+ throw new ApiError("agent_not_runnable", "Enable source sync from this agent's connector before moving it.");
33
+ }
34
+ const found = await new RemoteConnectors(store).syncAuthority(connection.connector_id, connection.target_id);
35
+ if (found.agentId !== agentId)
36
+ throw new ApiError("forbidden", "This connector belongs to another agent.");
37
+ return found.authority;
38
+ },
39
+ persist: async (agentId, snapshot) => {
40
+ validateSourceSnapshot(snapshot);
41
+ if (snapshot.complete && !snapshot.blockers.length)
42
+ await withSourceIO(store, agentId, "snapshot", () => withWorkspace(agentId, async (work) => { await commitSourceSnapshot(work, snapshot); }));
43
+ },
44
+ read: async (agentId, digest) => {
45
+ const opened = await sourceSnapshotReader(store, agentId, workspace);
46
+ try {
47
+ return await readSourceSnapshot(opened.workspace, digest);
48
+ }
49
+ finally {
50
+ await opened.end();
51
+ }
52
+ },
53
+ prepare,
54
+ verifyDestination,
55
+ });
56
+ return {
57
+ sync,
58
+ forConnector(broker, connectorId, targetId) {
59
+ // An adopted CLI profile has no native binding. Its first grant uses the signed, durable target association;
60
+ // subsequent operations resolve the same connection from the stored source row.
61
+ return new SourceSync(store, { ...sync.options, authorize: async (agentId) => {
62
+ const current = await broker.syncAuthority(connectorId, targetId);
63
+ if (current.agentId !== agentId)
64
+ throw new ApiError("forbidden", "This source target changed its agent association.");
65
+ return current.authority;
66
+ } });
67
+ },
68
+ async status(agentId) {
69
+ const entry = await getAgent(store, agentId);
70
+ if (!entry?.revision || entry.agent.purgedAt || entry.agent.archivedAt)
71
+ throw new ApiError("not_found", "Choose an active connected agent.");
72
+ const record = await sync.get(agentId), binding = sourceSyncOf(entry.revision.body);
73
+ if (!record)
74
+ return { enabled: false, moved: false, state: "needs_connection", ...(nativeOf(entry.revision.body)?.remote ? { connection: nativeOf(entry.revision.body).remote } : {}), blockers: [{ code: "source_consent", message: "Enable sync on this agent's source connection to bring its setup to AgentRun." }] };
75
+ const moved = binding?.id === record.id;
76
+ const common = { enabled: record.enabled, moved, ...(record.snapshot ? { snapshot: record.snapshot } : {}),
77
+ ...(binding ? { current_snapshot: binding.snapshot } : {}), ...(record.connection ? { connection: record.connection } : {}) };
78
+ const projectIssues = moved ? await unresolvedProjects(store, agentId) : [];
79
+ if (projectIssues.length)
80
+ return { ...common, state: "needs_attention", project_issues: projectIssues,
81
+ blockers: [{ code: "project_not_saved", message: "A run’s project changes need review before another run can start. Its files and receipts are retained." }] };
82
+ if (!record.enabled)
83
+ return { ...common, state: "paused", blockers: [] };
84
+ if (record.attempt?.blockers.length)
85
+ return { ...common, state: "needs_attention", blockers: record.attempt.blockers };
86
+ if (!record.snapshot)
87
+ return { ...common, state: "syncing", blockers: [] };
88
+ if (moved && await sync.conflicts(entry, record)) {
89
+ return { ...common, state: "conflict", blockers: [{ code: "managed_changes", message: "Files or settings changed on both the source and AgentRun. Choose which version to keep before applying this update." }] };
90
+ }
91
+ let snapshot;
92
+ try {
93
+ snapshot = await sync.options.read(agentId, record.snapshot);
94
+ }
95
+ catch (error) {
96
+ if (error instanceof SnapshotError)
97
+ return { ...common, state: "needs_attention", blockers: [{ code: `snapshot_${error.code}`, message: error.message }] };
98
+ throw error;
99
+ }
100
+ const sizes = { files: snapshot.entries.filter(item => item.type === "file").length, bytes: snapshot.entries.reduce((sum, item) => sum + item.bytes, 0), skills: snapshot.skills.length, tools: snapshot.configuration.tools.length,
101
+ tool_connections: await sourceToolConnections(store, agentId, snapshot) };
102
+ try {
103
+ await sync.options.authorize(agentId, "move");
104
+ if (moved && binding.snapshot === record.snapshot)
105
+ return { ...common, ...sizes, state: "moved", blockers: [] };
106
+ await prepare(entry, snapshot);
107
+ return { ...common, ...sizes, state: moved ? "moved" : "ready", blockers: [] };
108
+ }
109
+ catch (error) {
110
+ if (error instanceof SourcePreparationError)
111
+ return { ...common, ...sizes, state: "needs_attention", blockers: error.blockers };
112
+ if (error instanceof ApiError && error.status < 500)
113
+ return { ...common, ...sizes, state: "needs_attention", blockers: [{ code: error.code, message: error.message }] };
114
+ throw error;
115
+ }
116
+ },
117
+ };
118
+ }
@@ -0,0 +1,12 @@
1
+ import type { SavePrepare } from "../agents-store.js";
2
+ import { type SourceSnapshot } from "../native/source-snapshot-types.js";
3
+ import type { Store } from "../store/store.js";
4
+ import { type SourceWorkspaceOptions } from "./workspace.js";
5
+ /** Compare against the last owner-authored file set, not current task-edited bytes. An unchanged file in an editor
6
+ * round trip keeps those task edits; a changed file is explicit owner intent. Removing SKILL.md removes that skill's
7
+ * complete asset directory, so native discovery cannot keep offering deleted guidance. Other removals are per-file. */
8
+ export declare function projectWithSkillEdits(snapshot: SourceSnapshot, previous: Readonly<Record<string, string>>, next: Readonly<Record<string, string>>): SourceSnapshot;
9
+ /** Called inside the agent's delete turn after validation. The durable I/O receipt also fences other server processes
10
+ * until the revision CAS settles. Failed/unknown storage operations retain it; a stale revision leaves only unreferenced
11
+ * immutable bytes, and the next commit attempt rebuilds against its new current project. */
12
+ export declare function prepareProjectSkillEdit(store: Store, agentId: string, options: SourceWorkspaceOptions): SavePrepare;
@@ -0,0 +1,122 @@
1
+ /** Explicit owner skill edits make a new immutable project. Current run folders are never touched. */
2
+ import { createHash } from "node:crypto";
3
+ import { sourceSnapshotDigest } from "../native/source-snapshot-types.js";
4
+ import { canonical, isSkillPath } from "../store/agent-body.js";
5
+ import { beginSourceIO } from "./io.js";
6
+ import { commitSourceSnapshot, readSourceSnapshot, seedEntries, SnapshotError, validateSourceSnapshot } from "./snapshots.js";
7
+ import { sourceSyncOf } from "./types.js";
8
+ import { sourceSnapshotReader, sourceWorkspace } from "./workspace.js";
9
+ const within = (root, path) => path === root || path.startsWith(`${root}/`);
10
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
11
+ function destination(snapshot, entry) {
12
+ if (entry.role === "project")
13
+ return entry.path === "project" ? "" : entry.path.slice(8);
14
+ if (entry.role === "skill") {
15
+ const skill = snapshot.skills.find(skill => within(skill.path, entry.path));
16
+ if (skill)
17
+ return `.agents/skills/${skill.name}${entry.path.slice(skill.path.length)}`;
18
+ }
19
+ return undefined;
20
+ }
21
+ /** Compare against the last owner-authored file set, not current task-edited bytes. An unchanged file in an editor
22
+ * round trip keeps those task edits; a changed file is explicit owner intent. Removing SKILL.md removes that skill's
23
+ * complete asset directory, so native discovery cannot keep offering deleted guidance. Other removals are per-file. */
24
+ export function projectWithSkillEdits(snapshot, previous, next) {
25
+ validateSourceSnapshot(snapshot);
26
+ for (const files of [previous, next])
27
+ for (const [path, text] of Object.entries(files)) {
28
+ if (!isSkillPath(path) || typeof text !== "string")
29
+ throw new SnapshotError("invalid", "Owner skill files must be relative paths and text.");
30
+ }
31
+ if (canonical(previous) === canonical(next))
32
+ return snapshot;
33
+ const removedRoots = Object.keys(previous).filter(path => path.endsWith("/SKILL.md") && !Object.hasOwn(next, path))
34
+ .map(path => `.agents/skills/${path.slice(0, -9)}`);
35
+ const removedFiles = new Set(Object.keys(previous).filter(path => !Object.hasOwn(next, path)).map(path => `.agents/skills/${path}`));
36
+ const removed = (path) => removedFiles.has(path) || removedRoots.some(root => within(root, path));
37
+ const discarded = snapshot.entries.filter(entry => entry.type === "file" && removed(destination(snapshot, entry) ?? ""))
38
+ .map(entry => destination(snapshot, entry));
39
+ const entries = snapshot.entries.filter(entry => !removed(destination(snapshot, entry) ?? "")).map(entry => ({ ...entry }));
40
+ const skills = snapshot.skills.filter(skill => !removedRoots.some(root => within(root, `.agents/skills/${skill.name}`)));
41
+ const blobs = { ...snapshot.blobs };
42
+ for (const [path, text] of Object.entries(next)) {
43
+ const target = `.agents/skills/${path}`, unchanged = Object.hasOwn(previous, path) && previous[path] === text;
44
+ if (unchanged && !removed(target))
45
+ continue;
46
+ const prior = snapshot.entries.find(entry => destination(snapshot, entry) === target && entry.type === "file");
47
+ // A caller may remove SKILL.md while retaining an explicitly owned companion. Preserve its current bytes/mode,
48
+ // but do not restore a task-deleted unchanged file merely because its old text remains on the revision.
49
+ if (unchanged && !prior)
50
+ continue;
51
+ const bytes = unchanged ? Buffer.from(snapshot.blobs[prior.sha256], "base64") : Buffer.from(text), sha256 = hash(bytes);
52
+ const matches = entries.filter(entry => destination(snapshot, entry) === target);
53
+ if (matches.some(entry => entry.type !== "file"))
54
+ throw new SnapshotError("conflict", "An owner skill file conflicts with a current project directory.");
55
+ blobs[sha256] = bytes.toString("base64");
56
+ if (matches.length)
57
+ for (const entry of matches) {
58
+ entry.bytes = bytes.length;
59
+ entry.sha256 = sha256;
60
+ }
61
+ else {
62
+ const skill = skills.find(skill => within(`.agents/skills/${skill.name}`, target));
63
+ const root = skill?.path ?? "project", role = skill ? "skill" : "project";
64
+ const stored = skill ? `${skill.path}${target.slice(`.agents/skills/${skill.name}`.length)}` : `project/${target}`;
65
+ const parts = stored.split("/");
66
+ for (let n = root.split("/").length; n < parts.length; n++) {
67
+ const parent = parts.slice(0, n).join("/"), exists = entries.find(entry => entry.path === parent);
68
+ if (exists?.type === "file")
69
+ throw new SnapshotError("conflict", "An owner skill path has a current project file as its parent.");
70
+ if (!exists) {
71
+ const targetParent = skill ? `.agents/skills/${skill.name}${parent.slice(skill.path.length)}` : parent === "project" ? "" : parent.slice(8);
72
+ const previousParent = snapshot.entries.find(entry => entry.type === "directory" && destination(snapshot, entry) === targetParent);
73
+ entries.push({ path: parent, role, type: "directory", mode: previousParent?.mode ?? 0o755, bytes: 0 });
74
+ }
75
+ }
76
+ entries.push({ path: stored, role, type: "file", mode: prior?.mode ?? 0o644, bytes: bytes.length, sha256 });
77
+ }
78
+ }
79
+ // Retain only referenced content. Immutable old manifests/blobs are retained separately for pinned runs/revisions.
80
+ const retained = new Set(entries.flatMap(entry => entry.sha256 ? [entry.sha256] : []));
81
+ if (snapshot.project.git?.bundle)
82
+ retained.add(snapshot.project.git.bundle.sha256);
83
+ for (const transform of snapshot.transforms ?? [])
84
+ retained.add(transform.destination_sha256);
85
+ const currentPaths = new Set(entries.map(entry => destination({ ...snapshot, skills }, entry)));
86
+ const project = snapshot.project.git ? { git: { ...snapshot.project.git, dirty: true,
87
+ deleted: [...new Set([...snapshot.project.git.deleted, ...discarded])].filter(path => !currentPaths.has(path)).sort() } } : snapshot.project;
88
+ const value = { ...snapshot, entries: entries.sort((a, b) => a.path.localeCompare(b.path)), skills, project,
89
+ blobs: Object.fromEntries([...retained].map(sha => [sha, blobs[sha]])) };
90
+ const result = { ...value, digest: sourceSnapshotDigest(value) };
91
+ validateSourceSnapshot(result);
92
+ seedEntries(result); // The saved project must be placeable: skill/project aliases cannot disagree.
93
+ return result;
94
+ }
95
+ /** Called inside the agent's delete turn after validation. The durable I/O receipt also fences other server processes
96
+ * until the revision CAS settles. Failed/unknown storage operations retain it; a stale revision leaves only unreferenced
97
+ * immutable bytes, and the next commit attempt rebuilds against its new current project. */
98
+ export function prepareProjectSkillEdit(store, agentId, options) {
99
+ return async (revision, current) => {
100
+ const binding = sourceSyncOf(current?.body), previous = (current?.skills ?? {}), next = (revision.skills ?? {});
101
+ if (!binding || canonical(previous) === canonical(next))
102
+ return { revision, settled: async () => { } };
103
+ const reader = await sourceSnapshotReader(store, agentId, options);
104
+ let snapshot;
105
+ try {
106
+ snapshot = await readSourceSnapshot(reader.workspace, binding.project);
107
+ }
108
+ finally {
109
+ await reader.end();
110
+ }
111
+ const successor = projectWithSkillEdits(snapshot, previous, next);
112
+ const receipt = await beginSourceIO(store, agentId, "snapshot");
113
+ const opened = await sourceWorkspace(store, agentId, options);
114
+ try {
115
+ await commitSourceSnapshot(opened.workspace, successor);
116
+ }
117
+ finally {
118
+ await opened.end();
119
+ }
120
+ return { revision: { ...revision, body: { ...revision.body, sourceSync: { ...binding, project: successor.digest } } }, settled: () => receipt.settled() };
121
+ };
122
+ }