@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,273 @@
1
+ // Server-owned source bundles and exclusive pre-admission placement, on the same storage the runner will use.
2
+ // A claim only verifies the completed receipt. It never invokes this preparer or re-seeds a running project.
3
+ import { constants } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { agentDiskOf, loadArchilSettings, DEFAULT_ARCHIL_EXEC_IMAGE } from "../archil-settings.js";
6
+ import { archilDisk } from "../workspace/archil-disk.js";
7
+ import { archilApiKey } from "../workspace/archil-key.js";
8
+ import { archilWorkspace } from "../workspace/archil.js";
9
+ import { openBeneath } from "../workspace/beneath.js";
10
+ import { localWorkspace } from "../workspace/local.js";
11
+ import { DISK_DIR, relativeSegments, runKey, sourceSnapshotsKey, sourceRunControlKey } from "../workspace/paths.js";
12
+ import { launchDiskProblem, runDiskOf } from "../workspace/run-disk.js";
13
+ import { readOnlyWorkspace } from "../workspace/server-run-workspace.js";
14
+ import { WorkspaceError } from "../workspace/workspace.js";
15
+ import { SnapshotError } from "./snapshots.js";
16
+ import { captureProject } from "./capture-project.js";
17
+ import { captureGit } from "./capture-git.js";
18
+ const noProcess = async () => { throw new WorkspaceError("REFUSED", "Source preparation starts no background programs."); };
19
+ /** Prefix every file operation through LocalWorkspace's descriptor-based walk from the trusted data root. Checking
20
+ * an absolute child root once would let a later parent-link swap redirect its writes. Reads never make folders. */
21
+ function localFolder(data, key) {
22
+ const base = localWorkspace(data), prefix = `${DISK_DIR}/${key}`;
23
+ const at = (path = "") => [prefix, ...relativeSegments(path)].join("/");
24
+ const ensure = async () => {
25
+ const parts = relativeSegments(prefix);
26
+ for (let n = 1; n <= parts.length; n++) {
27
+ const part = parts.slice(0, n).join("/"), stat = await base.stat(part);
28
+ if (stat?.kind === "link")
29
+ throw new WorkspaceError("ESCAPE", "A source folder cannot be reached through a symbolic link.");
30
+ if (stat && stat.kind !== "dir")
31
+ throw new WorkspaceError("REFUSED", "A source folder has a file in its path.");
32
+ if (!stat) {
33
+ await base.mkdir(part);
34
+ const held = await openBeneath(data, part, constants.O_RDONLY | constants.O_DIRECTORY);
35
+ try {
36
+ await held.chmod(0o700);
37
+ await held.sync();
38
+ }
39
+ finally {
40
+ await held.close();
41
+ }
42
+ }
43
+ }
44
+ };
45
+ return {
46
+ read: (path, range) => base.read(at(path), range),
47
+ stat: path => base.stat(at(path)),
48
+ list: path => base.list(at(path)),
49
+ write: async (path, bytes) => { await ensure(); await base.write(at(path), bytes); },
50
+ append: async (path, bytes) => { await ensure(); await base.append(at(path), bytes); },
51
+ mkdir: async (path) => { await ensure(); await base.mkdir(at(path)); },
52
+ remove: (path, options) => base.remove(at(path), options),
53
+ grep: async (pattern, options) => {
54
+ const result = await base.grep(pattern, { ...options, path: at(options?.path) });
55
+ return { ...result, matches: result.matches.map(match => ({ ...match, path: match.path.slice(prefix.length + 1) })) };
56
+ },
57
+ exec: async (argv, options) => { await ensure(); return base.exec(argv, { ...options, cwd: at(options.cwd) }); },
58
+ // Only the runner's separately fenced workspace mounts a computer. Preparation never mints a mount credential.
59
+ mountSpec: noProcess, attach: noProcess,
60
+ process: { start: noProcess, read: noProcess, write: noProcess, signal: noProcess, wait: noProcess, list: noProcess },
61
+ };
62
+ }
63
+ async function backend(store, agentId, options, target) {
64
+ // Validate IDs even when no filesystem call is made (including a malformed Mode 2 target).
65
+ sourceSnapshotsKey(agentId);
66
+ if (target.runId !== undefined)
67
+ runKey(agentId, target.runId);
68
+ const settings = await loadArchilSettings(store, options.env);
69
+ if (!settings) {
70
+ if (target.launch?.archilDisk)
71
+ throw new SnapshotError("prerequisite", "Restore this run's Archil configuration before opening its pinned project.");
72
+ return { mode: "local", open: (key) => localFolder(options.data, key), end: async () => { }, launchDisk: undefined };
73
+ }
74
+ if (target.requirePinned && !target.launch?.archilDisk)
75
+ throw new SnapshotError("prerequisite", "An admitted source project must name its original Archil disk.");
76
+ const { value } = await archilApiKey({ env: options.env ?? {}, keys: store.sealedKeys, sealKey: options.sealKey });
77
+ const control = { region: settings.region, key: () => value, ...options.control };
78
+ let launchDisk;
79
+ if (target.readOnly) {
80
+ // Source status and placement's snapshot reads are not writers. In particular, a concurrent purge may have
81
+ // removed the stored disk after their first metadata read; never allocate a replacement or clear pending here.
82
+ const stored = await agentDiskOf(store, agentId), pinned = target.launch?.archilDisk;
83
+ if (pinned?.kind !== "launch" && (!stored || stored.removing || stored.pending || pinned && pinned.diskId !== stored.diskId))
84
+ throw new SnapshotError("prerequisite", "The retained source disk is unavailable or being removed; a read cannot create or replace it.");
85
+ launchDisk = pinned ?? { diskId: stored.diskId, kind: "agent" };
86
+ const problem = await launchDiskProblem(control, launchDisk.diskId, options.signal ? { signal: options.signal } : {});
87
+ if (problem)
88
+ throw new SnapshotError("prerequisite", problem);
89
+ }
90
+ else {
91
+ launchDisk = await runDiskOf({ store, agentId, control, ...(target.runId ? { runId: target.runId } : {}),
92
+ ...(target.launch?.archilDisk ? { launch: target.launch.archilDisk } : {}), ...(options.signal ? { signal: options.signal } : {}) });
93
+ }
94
+ const disk = (options.control?.makeDisk ?? archilDisk)({ disk: launchDisk.diskId, region: settings.region, s3BaseUrl: settings.s3Url,
95
+ key: () => value, ...(options.control?.baseUrl ? { baseUrl: options.control.baseUrl } : {}) });
96
+ const opened = [];
97
+ const open = (key) => {
98
+ const work = archilWorkspace(disk, key, { image: { baseImage: settings.image ?? DEFAULT_ARCHIL_EXEC_IMAGE } });
99
+ opened.push(work);
100
+ return work;
101
+ };
102
+ let ended;
103
+ return { mode: "archil", launchDisk, open, end: () => ended ??= (async () => { if (!target.readOnly)
104
+ for (const work of opened)
105
+ await work.sweep(); })() };
106
+ }
107
+ /** Immutable cache on the agent's disk, or the caller's explicit pinned run disk. Account credentials stay in the
108
+ * resolver's closure; no secret or large snapshot is written to settings. Mode 2 never falls back to local files. */
109
+ export async function sourceWorkspace(store, agentId, options, target = {}) {
110
+ const place = await backend(store, agentId, options, target);
111
+ const workspace = place.open(sourceSnapshotsKey(agentId));
112
+ return { mode: place.mode, workspace: target.readOnly ? readOnlyWorkspace(workspace) : workspace,
113
+ ...(place.launchDisk ? { launchDisk: place.launchDisk } : {}), end: place.end };
114
+ }
115
+ /** Existing immutable source bytes only. Opening or closing a reader never allocates a disk, updates its ownership,
116
+ * writes files or sweeps execution spill. A missing retained source is an explicit prerequisite, not an empty cache. */
117
+ export function sourceSnapshotReader(store, agentId, options, target = {}) {
118
+ return sourceWorkspace(store, agentId, options, { ...target, readOnly: true });
119
+ }
120
+ /** Runner verification opens only its private completed receipt. It allocates no disk, makes no directory, seeds
121
+ * nothing and gives no private file access to model tools. Missing pinned Mode 2 storage is a refusal. */
122
+ export async function sourceRunControl(store, target, options) {
123
+ const place = await backend(store, target.agentId, options, { ...target, requirePinned: true, readOnly: true });
124
+ return { mode: place.mode, workspace: readOnlyWorkspace(place.open(sourceRunControlKey(target.agentId, target.runId))),
125
+ ...(place.launchDisk ? { launchDisk: place.launchDisk } : {}), end: async () => { } };
126
+ }
127
+ /** The caller holds the run's strict executor drain and storage sync across this operation. Git's temporary copy
128
+ * lives beside the private seed receipt, never in the model's project. It is removed only after all reads/commands
129
+ * have settled. This capability does not seed, change authority, or publish a checkpoint pointer. */
130
+ export async function captureManagedProject(store, target, options) {
131
+ const signal = target.signal ?? options.signal;
132
+ const place = await backend(store, target.agentId, options, { ...target, requirePinned: true });
133
+ const controlKey = sourceRunControlKey(target.agentId, target.runId), control = place.open(controlKey);
134
+ const name = `capture-${randomUUID()}`, scratch = place.open(`${controlKey}/${name}`);
135
+ let opened = false;
136
+ try {
137
+ return await captureProject({ ...target, ...(signal ? { signal } : {}), git: async (work, given) => {
138
+ await scratch.mkdir("");
139
+ opened = true;
140
+ return captureGit(work, scratch, given);
141
+ } });
142
+ }
143
+ finally {
144
+ try {
145
+ if (opened)
146
+ await control.remove(name, { recursive: true, force: true });
147
+ }
148
+ finally {
149
+ await place.end();
150
+ }
151
+ }
152
+ }
153
+ const EXEC_ENV = { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_SYSTEM: "/dev/null", GIT_CONFIG_GLOBAL: "/dev/null", GIT_ATTR_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0" };
154
+ const GIT = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "core.attributesFile=/dev/null", "-c", "protocol.allow=never", "-c", "gc.auto=0", "-c", "maintenance.auto=false"];
155
+ async function checkedExec(work, argv, signal, stdin) {
156
+ const answer = await work.exec([...argv], { env: EXEC_ENV, timeoutMs: 30_000, maxOutput: 1024 * 1024, ...(signal ? { signal } : {}), ...(stdin ? { stdin } : {}) });
157
+ if (answer.code !== 0 || answer.signal || answer.timedOut || answer.truncated)
158
+ throw new SnapshotError("prerequisite", "The destination could not complete and verify source metadata preparation.");
159
+ return Buffer.from(answer.stdout).toString("utf8").trim();
160
+ }
161
+ /** These commands restore objects, HEAD and the baseline index only. No checkout, source Git config, hook, filter,
162
+ * helper, credential or remote is invoked. The dirty/untracked/deleted working tree is supplied separately as bytes. */
163
+ function gitPreparation(signal) {
164
+ return async (work, git, bundle) => {
165
+ if (!git.head || git.history !== "complete")
166
+ throw new SnapshotError("prerequisite", "A complete Git history is required for this project.");
167
+ await checkedExec(work, [...GIT, "init", "--quiet", "--template=", "--initial-branch=agentrun-source"], signal);
168
+ const bundlePath = ".git/agentrun-source.bundle";
169
+ await work.write(bundlePath, bundle);
170
+ try {
171
+ await checkedExec(work, [...GIT, "bundle", "verify", bundlePath], signal);
172
+ await checkedExec(work, [...GIT, "bundle", "unbundle", bundlePath], signal);
173
+ if (git.branch !== null) {
174
+ const ref = `refs/heads/${git.branch}`;
175
+ await checkedExec(work, [...GIT, "check-ref-format", ref], signal);
176
+ await checkedExec(work, [...GIT, "update-ref", ref, git.head], signal);
177
+ await checkedExec(work, [...GIT, "symbolic-ref", "HEAD", ref], signal);
178
+ if (await checkedExec(work, [...GIT, "symbolic-ref", "HEAD"], signal) !== ref)
179
+ throw new SnapshotError("corrupt", "The restored Git branch does not match the source.");
180
+ }
181
+ else
182
+ await checkedExec(work, [...GIT, "update-ref", "--no-deref", "HEAD", git.head], signal);
183
+ await checkedExec(work, [...GIT, "read-tree", "--reset", git.head], signal);
184
+ const head = await checkedExec(work, [...GIT, "rev-parse", "--verify", "HEAD"], signal);
185
+ const tree = await checkedExec(work, [...GIT, "rev-parse", "--verify", `${git.head}^{tree}`], signal);
186
+ if (head !== git.head || await checkedExec(work, [...GIT, "write-tree"], signal) !== tree)
187
+ throw new SnapshotError("corrupt", "The restored Git HEAD or index does not match its source baseline.");
188
+ }
189
+ finally {
190
+ await work.remove(bundlePath, { force: true });
191
+ }
192
+ };
193
+ }
194
+ const modeOrder = (entries) => [...entries].sort((a, b) => (a.type === "directory" ? 1 : 0) - (b.type === "directory" ? 1 : 0) || b.path.split("/").length - a.path.split("/").length);
195
+ const MODE_SCRIPT = `set -eu
196
+ action=$1
197
+ tab=$(printf '\\t')
198
+ while IFS="$tab" read -r mode kind path; do
199
+ target="./$path"
200
+ part="$target"
201
+ while :; do
202
+ [ ! -L "$part" ] || exit 31
203
+ [ "$part" != . ] || break
204
+ part=\${part%/*}
205
+ done
206
+ if [ "$kind" = directory ]; then [ -d "$target" ]; else [ -f "$target" ]; fi
207
+ if [ "$action" = apply ]; then chmod -- "$mode" "$target"; fi
208
+ [ "$(stat -c '%a' -- "$target")" = "$mode" ] || exit 32
209
+ done
210
+ sync -f .
211
+ `;
212
+ function preparation(mode, data, key, signal) {
213
+ return {
214
+ restoreGit: gitPreparation(signal),
215
+ applyModes: async (work, entries) => {
216
+ if (mode === "local") {
217
+ for (const entry of modeOrder(entries)) {
218
+ const path = [DISK_DIR, key, ...relativeSegments(entry.path)].join("/");
219
+ const held = await openBeneath(data, path, constants.O_RDONLY | constants.O_NONBLOCK | (entry.type === "directory" ? constants.O_DIRECTORY : 0));
220
+ try {
221
+ const stat = await held.stat();
222
+ if (entry.type === "directory" ? !stat.isDirectory() : !stat.isFile())
223
+ throw new SnapshotError("conflict", "A source file changed kind during preparation.");
224
+ await held.chmod(entry.mode);
225
+ await held.sync();
226
+ if (((await held.stat()).mode & 0o777) !== entry.mode)
227
+ throw new SnapshotError("prerequisite", "The destination did not retain a source file mode.");
228
+ }
229
+ finally {
230
+ await held.close();
231
+ }
232
+ }
233
+ }
234
+ else {
235
+ const input = Buffer.from(modeOrder(entries).map(entry => `${entry.mode.toString(8)}\t${entry.type}\t${entry.path || "."}\n`).join(""));
236
+ await checkedExec(work, ["sh", "-c", MODE_SCRIPT, "source-modes", "apply"], signal, input);
237
+ // A separate exec verifies persistence, not merely chmod's local exit status inside one transient container.
238
+ await checkedExec(work, ["sh", "-c", MODE_SCRIPT, "source-modes", "verify"], signal, input);
239
+ }
240
+ },
241
+ };
242
+ }
243
+ /** Called under the start path's exclusive reservation, before any run is admitted. Upload placement may already
244
+ * have made inputs/ and pinned a disk. All operations settle before this returns; end does not disable rollback. */
245
+ export async function openRunPlacement(store, target, options) {
246
+ if (await store.runs.get(target.runId))
247
+ throw new SnapshotError("unsafe_resume", "An admitted run's project cannot be prepared again.");
248
+ const place = await backend(store, target.agentId, options, target), key = runKey(target.agentId, target.runId);
249
+ const controlKey = sourceRunControlKey(target.agentId, target.runId);
250
+ const workspace = place.open(key), control = place.open(controlKey), parent = place.open(key.slice(0, key.lastIndexOf("/")));
251
+ const existing = await workspace.list("").catch(error => { if (error instanceof WorkspaceError && error.code === "NOT_FOUND")
252
+ return []; throw error; });
253
+ if (existing.length && (!target.launch.filesPlaced || existing.some(entry => entry.name !== "inputs" || entry.kind !== "dir"))) {
254
+ throw new SnapshotError("conflict", "This run's project folder is not an empty, exclusively reserved destination.");
255
+ }
256
+ if (await control.stat("source-seed.json"))
257
+ throw new SnapshotError("unsafe_resume", "A previous source placement must be resolved before starting this run.");
258
+ let undone = false;
259
+ return { mode: place.mode, workspace, control, ...(place.launchDisk ? { launchDisk: place.launchDisk } : {}),
260
+ preparation: preparation(place.mode, options.data, key, options.signal), end: place.end,
261
+ undo: async () => {
262
+ if (undone)
263
+ return;
264
+ if (await store.runs.get(target.runId))
265
+ throw new SnapshotError("unsafe_resume", "The admitted run keeps its project; placement rollback was refused.");
266
+ // Workspace roots are deliberately not removable on Archil. The server's private parent can remove these
267
+ // two named children without granting a model any access to siblings, receipts or another run.
268
+ await parent.remove(key.slice(key.lastIndexOf("/") + 1), { recursive: true, force: true });
269
+ await parent.remove(controlKey.slice(controlKey.lastIndexOf("/") + 1), { recursive: true, force: true });
270
+ undone = true;
271
+ },
272
+ };
273
+ }
@@ -1,3 +1,4 @@
1
+ import { type SourceSyncBinding } from "../source-sync/types.js";
1
2
  import { type SdkBinding } from "../sdk/runtimes.js";
2
3
  import type { NativeBinding } from "../native/types.js";
3
4
  import { type NativeRuntime } from "../native/runtimes.js";
@@ -46,6 +47,7 @@ export type RevisionComputer = {
46
47
  surface?: "code" | "tools";
47
48
  exec?: boolean;
48
49
  record?: boolean;
50
+ needs?: string[];
49
51
  };
50
52
  /** A revision's tool settings as its body keeps them: a map of a tool's key to its settings ({provider?, permission?,
51
53
  * pin?}), checked and made canonical by the caller (agents-store.ts, through tool-plane's settingsIssues +
@@ -72,6 +74,7 @@ export declare const cliLearningOf: (body: unknown) => CliLearningBinding | unde
72
74
  export declare function learningSettingForBody(body: unknown): LearningSetting | undefined;
73
75
  export type { SdkBinding } from "../sdk/runtimes.js";
74
76
  export type AgenticBody = {
77
+ sourceSync?: SourceSyncBinding;
75
78
  cli_learning?: CliLearningBinding;
76
79
  sdk?: SdkBinding;
77
80
  native?: NativeBinding;
@@ -110,6 +113,7 @@ export type WorkflowBody = {
110
113
  * checked and canonical (agents-store.ts via tool-plane's one copy); this validator keeps it as given. */
111
114
  export type RevisionBodyInput = {
112
115
  kind: "agentic";
116
+ sourceSync?: SourceSyncBinding;
113
117
  cli_learning?: CliLearningBinding;
114
118
  sdk?: SdkBinding;
115
119
  native?: NativeBinding;
@@ -5,11 +5,13 @@
5
5
  // revision's own row (store schema `revisions`). Everything the old validator accepted it accepts, plus the agent-level
6
6
  // argument `pin` form in tool settings (the lead's ruling): at most 8 arguments mapped to JSON scalars, keys sorted, so
7
7
  // two equal pins are one revision.
8
+ import { sourceSyncOf } from "../source-sync/types.js";
8
9
  import { sdkBindingOf } from "../sdk/runtimes.js";
9
10
  import { createHash } from "node:crypto";
10
11
  import { nativeBindingOf } from "../native/binding.js";
11
12
  import { isNativeRuntime } from "../native/runtimes.js";
12
13
  import { learningSettingIssue, learningSettingOf } from "../learning-setting.js";
14
+ import { needsIssues } from "../computer-needs.js";
13
15
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
14
16
  export class AgentBodyInvalid extends Error {
15
17
  constructor(message) {
@@ -59,10 +61,10 @@ function placeOf(place) {
59
61
  /** A GPU type as a body keeps it: the vendor's own name ("T4", "A100-80GB", "RTX-PRO-6000"). */
60
62
  const GPU_TYPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
61
63
  /** The keys a body's computer keeps. */
62
- const COMPUTER_KEYS = new Set(["kind", "provider", "image", "gpu", "persistent", "surface", "exec", "record"]);
63
- /** A computer as a body keeps it: `{kind, provider?, image?, gpu?, persistent?, surface?, exec?, record?}`, nothing
64
- * else: kind and provider ids, image a name with no spaces around it, gpu `{type, count}`, a GPU type name and a whole
65
- * count from 1, persistent, exec and record booleans, and surface code or tools. */
64
+ const COMPUTER_KEYS = new Set(["kind", "provider", "image", "gpu", "persistent", "surface", "exec", "record", "needs"]);
65
+ /** A computer as a body keeps it: `{kind, provider?, image?, gpu?, persistent?, surface?, exec?, record?, needs?}`,
66
+ * nothing else: kind and provider ids, image a name with no spaces around it, gpu `{type, count}`, a GPU type name and a
67
+ * whole count from 1, persistent, exec and record booleans, surface code or tools, and needs a list of program names. */
66
68
  function computerOf(computer) {
67
69
  const image = isObject(computer) ? computer.image : undefined;
68
70
  const named = (value) => typeof value === "string" && value !== "" && value === value.trim();
@@ -75,8 +77,12 @@ function computerOf(computer) {
75
77
  if (gpu !== undefined && (!isObject(gpu) || Object.keys(gpu).some((key) => key !== "type" && key !== "count") || typeof gpu.type !== "string" || !GPU_TYPE.test(gpu.type) || !Number.isSafeInteger(gpu.count) || gpu.count < 1)) {
76
78
  invalid("the computer's gpu is not {type, count}: a GPU type name (letters, digits, dots, underscores and dashes) and a whole count from 1");
77
79
  }
80
+ const needs = computer.needs;
81
+ const needsIssue = needs === undefined ? undefined : needsIssues(needs, "the computer's needs")[0];
82
+ if (needsIssue)
83
+ invalid(needsIssue.message);
78
84
  const kept = gpu;
79
- return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}), ...(ok.persistent !== undefined ? { persistent: ok.persistent } : {}), ...(ok.surface !== undefined ? { surface: ok.surface } : {}), ...(ok.exec !== undefined ? { exec: ok.exec } : {}), ...(ok.record !== undefined ? { record: ok.record } : {}) };
85
+ return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}), ...(ok.persistent !== undefined ? { persistent: ok.persistent } : {}), ...(ok.surface !== undefined ? { surface: ok.surface } : {}), ...(ok.exec !== undefined ? { exec: ok.exec } : {}), ...(ok.record !== undefined ? { record: ok.record } : {}), ...(needs !== undefined ? { needs: [...needs] } : {}) };
80
86
  }
81
87
  /** The body of a new revision and the text of each skill it names (path to text), everything checked here, before any
82
88
  * write. The body keeps each skill path to its text's SHA-256; `skills` is the texts, for the revision's row. */
@@ -148,7 +154,12 @@ export function bodyOf(input) {
148
154
  invalid("sdk, native and cli_learning connections are mutually exclusive");
149
155
  if (input.cli_learning !== undefined && (!cliLearningOf(input) || Object.keys(input.cli_learning).some(key => !["runtime", "connection_id", "project"].includes(key)) || !input.cli_learning.connection_id || !input.cli_learning.project))
150
156
  invalid("cli_learning requires a registered runtime, connection_id and project");
157
+ if (input.sourceSync !== undefined && !sourceSyncOf(input))
158
+ invalid("sourceSync is a complete server-owned source provenance binding");
159
+ if (input.sourceSync && (input.native || input.cli_learning || input.sdk))
160
+ invalid("a managed source revision has no external execution binding");
151
161
  const body = {
162
+ ...(input.sourceSync ? { sourceSync: { ...input.sourceSync } } : {}),
152
163
  ...(input.sdk ? { sdk: { ...input.sdk } } : {}),
153
164
  ...(input.cli_learning ? { cli_learning: { ...input.cli_learning } } : {}),
154
165
  instructions: input.instructions,
@@ -1,5 +1,5 @@
1
- export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
- export type { ConstraintRule, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
1
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
+ export type { ConstraintRule, SettingsGuard, McpGuard, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -92,7 +92,8 @@ export declare const HAND_BACKS_KEPT_MS: number;
92
92
  * was cut (`cause`: drain, crash, lease_lapse, retry; null on a turn's first), why this one let the run go unfinished
93
93
  * (`cut`), its runner, the run's state it took the run from, the first journal entry id it could write
94
94
  * (`journal_from`) and when it claimed. Written in the claim's own transaction, its cut in its release's. Data only:
95
- * the usage read (run-usage.ts) splits a run's cost by it, and nothing decides what a run does on it. In STORE_DDL, and
95
+ * the usage read (run-usage.ts) splits a run's cost by it; source-project recovery uses the actual claim and journal
96
+ * boundary to report a terminal attempt with no checkpoint, never to replay work or invent a capture. In STORE_DDL, and
96
97
  * added at a server open to a store an earlier build of this version made, as COMPUTER_INTERVALS is: a claim made before
97
98
  * it has no row. */
98
99
  export declare const RUN_ATTEMPTS = "CREATE TABLE IF NOT EXISTS run_attempts (\n run_id TEXT NOT NULL,\n epoch INTEGER NOT NULL,\n turn INTEGER NOT NULL CHECK (turn >= 1),\n attempt INTEGER NOT NULL CHECK (attempt >= 1),\n cause TEXT CHECK (cause IS NULL OR cause IN ('drain', 'crash', 'lease_lapse', 'retry')),\n cut TEXT CHECK (cut IS NULL OR cut IN ('drain', 'lease_lapse', 'retry')),\n runner TEXT NOT NULL,\n from_state TEXT NOT NULL,\n journal_from INTEGER NOT NULL,\n claimed_at INTEGER NOT NULL,\n PRIMARY KEY (run_id, epoch)\n ) STRICT";
@@ -200,7 +200,8 @@ export const HAND_BACKS_KEPT_MS = 24 * 60 * 60_000;
200
200
  * was cut (`cause`: drain, crash, lease_lapse, retry; null on a turn's first), why this one let the run go unfinished
201
201
  * (`cut`), its runner, the run's state it took the run from, the first journal entry id it could write
202
202
  * (`journal_from`) and when it claimed. Written in the claim's own transaction, its cut in its release's. Data only:
203
- * the usage read (run-usage.ts) splits a run's cost by it, and nothing decides what a run does on it. In STORE_DDL, and
203
+ * the usage read (run-usage.ts) splits a run's cost by it; source-project recovery uses the actual claim and journal
204
+ * boundary to report a terminal attempt with no checkpoint, never to replay work or invent a capture. In STORE_DDL, and
204
205
  * added at a server open to a store an earlier build of this version made, as COMPUTER_INTERVALS is: a claim made before
205
206
  * it has no row. */
206
207
  export const RUN_ATTEMPTS = `CREATE TABLE IF NOT EXISTS run_attempts (
@@ -73,10 +73,14 @@ export type RunModelKey = {
73
73
  readonly key: string;
74
74
  readonly origin: string;
75
75
  };
76
- /** What a run's launch holds sealed: its handed MCP credentials and its own model key, each when it has one. */
76
+ /** A run's own tool keys (`keys` at its start or with a message, run-keys.ts), by name. */
77
+ export type RunToolKeys = Readonly<Record<string, string>>;
78
+ /** What a run's launch holds sealed: its handed MCP credentials, its own model key and its own tool keys, each when it
79
+ * has one. */
77
80
  export type RunLaunchSecrets = {
78
81
  readonly mcp?: RunMcpAuth;
79
82
  readonly model?: RunModelKey;
83
+ readonly keys?: RunToolKeys;
80
84
  };
81
85
  /** Seals a run's launch secrets as its launch's sealed column (AAD run_launch|<run_id>|sealed); null when it holds none. */
82
86
  export declare function sealRunLaunch(key: Buffer, runId: string, secrets: RunLaunchSecrets): Uint8Array | null;
@@ -73,10 +73,18 @@ export function openMcpCredential(key, row) {
73
73
  /** Seals a run's launch secrets as its launch's sealed column (AAD run_launch|<run_id>|sealed); null when it holds none. */
74
74
  export function sealRunLaunch(key, runId, secrets) {
75
75
  const mcp = secrets.mcp && Object.keys(secrets.mcp).length ? secrets.mcp : undefined;
76
- if (!mcp && !secrets.model)
76
+ const keys = secrets.keys && Object.keys(secrets.keys).length ? secrets.keys : undefined;
77
+ if (!mcp && !secrets.model && !keys)
77
78
  return null;
78
- return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ ...(mcp ? { mcp } : {}), ...(secrets.model ? { model: secrets.model } : {}) }));
79
+ return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ ...(mcp ? { mcp } : {}), ...(secrets.model ? { model: secrets.model } : {}), ...(keys ? { keys } : {}) }));
79
80
  }
81
+ /** The tool keys of an opened launch: each name with text for its value, none else. */
82
+ const toolKeysOf = (keys) => {
83
+ if (typeof keys !== "object" || keys === null || Array.isArray(keys))
84
+ return undefined;
85
+ const out = Object.fromEntries(Object.entries(keys).filter((entry) => typeof entry[1] === "string"));
86
+ return Object.keys(out).length ? out : undefined;
87
+ };
80
88
  /** A run's launch secrets, opened: none when its launch holds none; undefined when the bytes do not open under `key` for
81
89
  * this run (sealed for another run, or under another key). */
82
90
  export function openRunLaunch(key, runId, sealed) {
@@ -85,7 +93,8 @@ export function openRunLaunch(key, runId, sealed) {
85
93
  try {
86
94
  const opened = JSON.parse(unsealColumn(key, sealedAt.runLaunch(runId), sealed).toString("utf8"));
87
95
  const model = typeof opened.model?.key === "string" && typeof opened.model.origin === "string" ? { key: opened.model.key, origin: opened.model.origin } : undefined;
88
- return { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(model ? { model } : {}) };
96
+ const keys = toolKeysOf(opened.keys);
97
+ return { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) };
89
98
  }
90
99
  catch {
91
100
  return undefined;
@@ -0,0 +1,11 @@
1
+ import type { Dialect } from "../dialect.js";
2
+ import type { Runs } from "../store.js";
3
+ import type { SqliteExecutor } from "./connection.js";
4
+ /** Uses the ordinary store connection. As with usageMetadata, PostgreSQL's precise JSON Unicode refusal permits a
5
+ * read/parse compatibility fallback; generic DB errors propagate. Not called inside a Store.snapshot transaction. */
6
+ export declare function readProjectCheckpoints(executor: Pick<SqliteExecutor, "all"> & {
7
+ readonly dialect: Dialect;
8
+ }, filter: {
9
+ agentId: string;
10
+ runId?: string;
11
+ }): ReturnType<Runs["projectCheckpoints"]>;
@@ -0,0 +1,70 @@
1
+ import { PI_TABLE } from "../schema.js";
2
+ const fields = ["version", "status", "sourceId", "runId", "epoch", "baselineRevision", "baselineDigest", "revision", "digest", "reason", "stage"];
3
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4
+ const pick = (value) => Object.fromEntries(fields.flatMap(field => object(value)[field] === undefined ? [] : [[field, object(value)[field]]]));
5
+ const terminal = (state) => state === "ended" || state === "failed" || state === "stopped";
6
+ /** Uses the ordinary store connection. As with usageMetadata, PostgreSQL's precise JSON Unicode refusal permits a
7
+ * read/parse compatibility fallback; generic DB errors propagate. Not called inside a Store.snapshot transaction. */
8
+ export async function readProjectCheckpoints(executor, filter) {
9
+ const d = executor.dialect;
10
+ const where = `r.agent_id = ? AND r.purged_at IS NULL${filter.runId === undefined ? "" : " AND r.id = ?"}`;
11
+ const from = `FROM ${PI_TABLE.entries} e JOIN runs r ON r.id = e.run_id LEFT JOIN run_launch l ON l.run_id = r.id WHERE ${where} AND e.conversation_id = 1`;
12
+ const params = [filter.agentId, ...(filter.runId === undefined ? [] : [filter.runId])];
13
+ const columns = fields.map((field, index) => `${d.jsonValue("e.record", ["data", "projectCheckpoint", field])} AS field_${index}`);
14
+ // Binding is structural here; the recovery domain additionally checks the revision's source identity/digest.
15
+ // Read individual members, never input, output or sealed launch data on the ordinary projection path.
16
+ const placed = `${d.jsonValue("l.body", ["source_project", "version"])} = '1' AND ${d.jsonText("l.body", ["source_project", "baselineRevision"])} = r.revision_id`;
17
+ const end = (alias) => `${d.jsonText(`${alias}.record`, ["kind"])} = 'agentrun.end' AND ${d.jsonText(`${alias}.record`, ["data", "state"])} IN ('ended', 'failed', 'stopped')`;
18
+ const latest = `LEFT JOIN run_attempts a ON a.run_id = r.id AND a.epoch = (SELECT max(prior.epoch) FROM run_attempts prior WHERE prior.run_id = r.id)`;
19
+ const owner = `(SELECT max(own.epoch) FROM run_attempts own WHERE own.run_id = r.id AND own.journal_from <= e.id)`;
20
+ try {
21
+ // One statement observes end rows and missing-end attempts consistently: a terminal commit between two reads
22
+ // must not disappear from both results. Real entries precede the latest attempt's synthetic recovery status.
23
+ const rows = await executor.all(`SELECT r.id AS run_id, r.revision_id, e.id AS entry_id, ${owner} AS attempt_epoch, 0 AS missing_order, ${columns.join(", ")} ${from}
24
+ AND ${end("e")} AND (${d.jsonValue("e.record", ["data", "projectCheckpoint"])} IS NOT NULL OR (${placed}))
25
+ UNION ALL
26
+ SELECT r.id AS run_id, r.revision_id, NULL AS entry_id, a.epoch AS attempt_epoch, 1 AS missing_order, ${fields.map((_, index) => `NULL AS field_${index}`).join(", ")}
27
+ FROM runs r JOIN run_launch l ON l.run_id = r.id ${latest}
28
+ WHERE ${where} AND r.state IN ('ended', 'failed', 'stopped') AND a.epoch IS NOT NULL AND (${placed})
29
+ AND NOT EXISTS (SELECT 1 FROM ${PI_TABLE.entries} ended WHERE ended.run_id = r.id AND ended.conversation_id = 1 AND ended.id >= a.journal_from AND ${end("ended")})
30
+ ORDER BY run_id, missing_order, entry_id`, ...params, ...params);
31
+ return rows.map(row => ({ runId: String(row.run_id), revisionId: String(row.revision_id), entryId: row.entry_id === null ? null : Number(row.entry_id),
32
+ ...(row.attempt_epoch === null ? {} : { attemptEpoch: Number(row.attempt_epoch) }), checkpoint: Object.fromEntries(fields.flatMap((field, index) => {
33
+ const value = row[`field_${index}`];
34
+ return value == null ? [] : [[field, JSON.parse(String(value))]];
35
+ })) }));
36
+ }
37
+ catch (error) {
38
+ let unicode = false;
39
+ for (let cause = error, depth = 0; cause && depth < 6; cause = cause.cause, depth++)
40
+ if (cause.code === "22P05" || (cause.code === "22P02" && cause.reason === "json_surrogate"))
41
+ unicode = true;
42
+ if (d.name !== "postgres" || !unicode)
43
+ throw error;
44
+ // Exceptional old text may contain a NUL/surrogate in an unrelated answer or launch input. PostgreSQL cannot
45
+ // extract any member then; preserve JS semantics without reading sealed bytes or dropping recovery evidence.
46
+ const rows = await executor.all(`SELECT r.id AS run_id, r.revision_id, r.state, l.body, e.id AS entry_id, e.record, a.epoch AS attempt_epoch, ${owner} AS entry_attempt_epoch, a.journal_from
47
+ FROM runs r LEFT JOIN run_launch l ON l.run_id = r.id ${latest}
48
+ LEFT JOIN ${PI_TABLE.entries} e ON e.run_id = r.id AND e.conversation_id = 1 WHERE ${where} ORDER BY r.id, e.id`, ...params);
49
+ const results = [];
50
+ const missing = new Map();
51
+ const ended = new Set();
52
+ for (const row of rows) {
53
+ const launch = object(row.body === null ? undefined : JSON.parse(row.body)), source = object(launch.source_project);
54
+ const bound = source.version === 1 && source.baselineRevision === row.revision_id;
55
+ const entry = object(row.record === null ? undefined : JSON.parse(row.record)), data = object(entry.data);
56
+ const isEnd = entry.kind === "agentrun.end" && terminal(data.state);
57
+ if (row.entry_id !== null && isEnd && (data.projectCheckpoint !== undefined || bound))
58
+ results.push({ runId: row.run_id, revisionId: row.revision_id, entryId: Number(row.entry_id),
59
+ ...(row.entry_attempt_epoch === null ? {} : { attemptEpoch: Number(row.entry_attempt_epoch) }), checkpoint: pick(data.projectCheckpoint) });
60
+ if (isEnd && row.entry_id !== null && row.journal_from !== null && Number(row.entry_id) >= Number(row.journal_from))
61
+ ended.add(row.run_id);
62
+ if (bound && terminal(row.state) && row.attempt_epoch !== null)
63
+ missing.set(row.run_id, { revisionId: row.revision_id, attemptEpoch: Number(row.attempt_epoch) });
64
+ }
65
+ for (const [runId, row] of missing)
66
+ if (!ended.has(runId))
67
+ results.push({ runId, ...row, entryId: null, checkpoint: {} });
68
+ return results.sort((a, b) => a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : a.entryId === null ? 1 : b.entryId === null ? -1 : a.entryId - b.entryId);
69
+ }
70
+ }
@@ -1,10 +1,10 @@
1
1
  import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow, type Runs } from "../store.js";
2
2
  import type { Dialect } from "../dialect.js";
3
3
  import type { SqliteExecutor } from "./connection.js";
4
- export { postgresReadableJson, postgresUnicodeRefusal };
5
- /** JSON text `column` as a read of one id or flag out of it inside a transaction takes it, where a refused statement
6
- * aborts the transaction and can't be read again: on Postgres its copy with those escapes blanked (postgresReadableJson),
7
- * on SQLite (whose json functions read them) the column itself. */
4
+ /** JSON text `column` (a launch body, a command's body, a journal record) as every read of one id, number or flag out of
5
+ * it takes it: on Postgres its copy with escaped NULs and lone surrogates blanked (postgresReadableJson), so a run's text
6
+ * never makes the read fail; on SQLite (whose json functions read them) the column itself. Only a read that returns a
7
+ * member as written (readUsageMetadata, readLearningStarts) reads the column and retries on postgresUnicodeRefusal. */
8
8
  export declare const readableJson: (dialect: Dialect, column: string) => string;
9
9
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
10
10
  * trigger path both call it, so the row lands with its run or not at all. */
@@ -19,14 +19,6 @@ export declare function writeLaunchSealed(tx: Pick<SqliteExecutor, "run" | "get"
19
19
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
20
20
  * none, never a default. */
21
21
  export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
22
- /** Whether `error` (or a cause of it, six deep) is Postgres refusing a JSON document for an escaped NUL or a lone
23
- * surrogate in it: the text type keeps them, but every json function decodes the whole document's strings. */
24
- declare function postgresUnicodeRefusal(error: unknown): boolean;
25
- /** Postgres SQL for JSON text `column` with its escaped NULs and surrogates (\u0000, \ud800-\udfff) read as escaped
26
- * spaces, for a read of one number or id out of a document whose other strings may hold one (0026_run_disk.sql blanks
27
- * them for its backfill). A replaced escape stays an escape, so it is still JSON. Only an escape is replaced: u0000 after
28
- * an escaped backslash (the text \u0000 in an id, written \\u0000) is text and is kept, so an id reads as it is. */
29
- declare const postgresReadableJson: (column: string) => string;
30
22
  /** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
31
23
  * the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
32
24
  * Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
@@ -5,12 +5,10 @@
5
5
  import { StoreLaunchMissing } from "../store.js";
6
6
  const RUN_LAUNCH_COLUMNS = "run_id, body, sealed, created_at";
7
7
  const runLaunchOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), createdAt: r.created_at });
8
- // For the store's other reads of a run's JSON (a launch body, a command's body, a journal record): one id or flag out of
9
- // a document whose strings may hold an escaped NUL or a lone surrogate.
10
- export { postgresReadableJson, postgresUnicodeRefusal };
11
- /** JSON text `column` as a read of one id or flag out of it inside a transaction takes it, where a refused statement
12
- * aborts the transaction and can't be read again: on Postgres its copy with those escapes blanked (postgresReadableJson),
13
- * on SQLite (whose json functions read them) the column itself. */
8
+ /** JSON text `column` (a launch body, a command's body, a journal record) as every read of one id, number or flag out of
9
+ * it takes it: on Postgres its copy with escaped NULs and lone surrogates blanked (postgresReadableJson), so a run's text
10
+ * never makes the read fail; on SQLite (whose json functions read them) the column itself. Only a read that returns a
11
+ * member as written (readUsageMetadata, readLearningStarts) reads the column and retries on postgresUnicodeRefusal. */
14
12
  export const readableJson = (dialect, column) => (dialect.name === "postgres" ? postgresReadableJson(column) : column);
15
13
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
16
14
  * trigger path both call it, so the row lands with its run or not at all. */
@@ -132,18 +130,6 @@ export async function readLearningStarts(executor, agentId, where) {
132
130
  /** The ids of agent `agentId`'s runs started after `at` whose learning seed was read at or before it (the launch body's
133
131
  * `learning.seededAt`), in one read of that one number a run started after `at`: never a run's section or input. */
134
132
  export async function readSeededBefore(executor, agentId, at) {
135
- const read = (body) => executor.all(`SELECT run_id, ${executor.dialect.jsonText(body, ["learning", "seededAt"])} AS seeded_at FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND started_at > ?)`, agentId, at);
136
- let rows;
137
- try {
138
- rows = await read("body");
139
- }
140
- catch (error) {
141
- // A body holding an escaped NUL or a lone surrogate anywhere (a run's input) makes Postgres refuse the whole read: the
142
- // one number is read again from copies with those escapes blanked (postgresReadableJson), never a run's text. On an
143
- // ordinary store connection, as readUsageMetadata's, so the retry is outside a failed transaction.
144
- if (executor.dialect.name !== "postgres" || !postgresUnicodeRefusal(error))
145
- throw error;
146
- rows = await read(postgresReadableJson("body"));
147
- }
133
+ const rows = await executor.all(`SELECT run_id, ${executor.dialect.jsonText(readableJson(executor.dialect, "body"), ["learning", "seededAt"])} AS seeded_at FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND started_at > ?)`, agentId, at);
148
134
  return rows.flatMap((row) => (row.seeded_at !== null && Number(row.seeded_at) <= at ? [row.run_id] : []));
149
135
  }