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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -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;
@@ -88,6 +91,7 @@ export type AgenticBody = {
88
91
  learning?: LearningSetting;
89
92
  toolSettings?: ToolSettings;
90
93
  maxCostUsd?: number;
94
+ maxRequests?: number;
91
95
  approvals?: "ask" | "never";
92
96
  inputSchema?: Record<string, unknown>;
93
97
  outputSchema?: Record<string, unknown>;
@@ -102,12 +106,14 @@ export type WorkflowBody = {
102
106
  computer?: RevisionComputer;
103
107
  toolSettings?: ToolSettings;
104
108
  maxCostUsd?: number;
109
+ maxRequests?: number;
105
110
  approvals?: "ask" | "never";
106
111
  };
107
112
  /** The input a revision's body is built from (the control plane's, in the store's own shape). `toolSettings` is already
108
113
  * checked and canonical (agents-store.ts via tool-plane's one copy); this validator keeps it as given. */
109
114
  export type RevisionBodyInput = {
110
115
  kind: "agentic";
116
+ sourceSync?: SourceSyncBinding;
111
117
  cli_learning?: CliLearningBinding;
112
118
  sdk?: SdkBinding;
113
119
  native?: NativeBinding;
@@ -124,6 +130,7 @@ export type RevisionBodyInput = {
124
130
  learning?: LearningSetting;
125
131
  toolSettings?: ToolSettings;
126
132
  maxCostUsd?: number;
133
+ maxRequests?: number;
127
134
  approvals?: "ask" | "never";
128
135
  inputSchema?: Record<string, unknown>;
129
136
  outputSchema?: Record<string, unknown>;
@@ -138,6 +145,7 @@ export type RevisionBodyInput = {
138
145
  computer?: unknown;
139
146
  toolSettings?: ToolSettings;
140
147
  maxCostUsd?: number;
148
+ maxRequests?: number;
141
149
  approvals?: "ask" | "never";
142
150
  };
143
151
  /** The body of a new revision and the text of each skill it names (path to text), everything checked here, before any
@@ -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. */
@@ -113,7 +119,10 @@ export function bodyOf(input) {
113
119
  // A default spend cap, for a revision of either kind.
114
120
  if (input.maxCostUsd !== undefined && !(typeof input.maxCostUsd === "number" && Number.isFinite(input.maxCostUsd) && input.maxCostUsd > 0))
115
121
  invalid("the maxCostUsd is not a number above 0");
116
- const capped = input.maxCostUsd !== undefined ? { maxCostUsd: input.maxCostUsd } : {};
122
+ // The agent's own limit on each run's requests on free models (definition.max_requests), under the server's.
123
+ if (input.maxRequests !== undefined && !(typeof input.maxRequests === "number" && Number.isSafeInteger(input.maxRequests) && input.maxRequests >= 1))
124
+ invalid("the maxRequests is not a whole number above 0");
125
+ const capped = { ...(input.maxCostUsd !== undefined ? { maxCostUsd: input.maxCostUsd } : {}), ...(input.maxRequests !== undefined ? { maxRequests: input.maxRequests } : {}) };
117
126
  // Whether the agent runs unattended (its definition.approvals): "never" lets an ask run without a person, for a revision
118
127
  // of either kind. "ask" (the default, as an agent read says it) is taken and kept as no value, so the default stays
119
128
  // implicit and a definition put back as it reads is the same revision; "never" is kept.
@@ -145,7 +154,12 @@ export function bodyOf(input) {
145
154
  invalid("sdk, native and cli_learning connections are mutually exclusive");
146
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))
147
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");
148
161
  const body = {
162
+ ...(input.sourceSync ? { sourceSync: { ...input.sourceSync } } : {}),
149
163
  ...(input.sdk ? { sdk: { ...input.sdk } } : {}),
150
164
  ...(input.cli_learning ? { cli_learning: { ...input.cli_learning } } : {}),
151
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, 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, 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";
@@ -21,6 +21,8 @@ interface SqliteExecutor {
21
21
  get<R extends object>(sql: string, ...params: SqliteValue[]): Promise<R | undefined>;
22
22
  all<R extends object>(sql: string, ...params: SqliteValue[]): Promise<R[]>;
23
23
  }
24
+ /** A run's first id to mint: pi's root conversation is 1. */
25
+ export declare const JOURNAL_FIRST_ID = 2;
24
26
  type StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;
25
27
  /** A document a commit changed, as the live view reads it: its value at that seq, or `retired` with none. */
26
28
  export type JournalDocument = {
@@ -14,7 +14,8 @@ function readsOf(db) {
14
14
  };
15
15
  }
16
16
  /** A run's first id to mint: pi's root conversation is 1. */
17
- const FIRST_ID = 2;
17
+ export const JOURNAL_FIRST_ID = 2;
18
+ const FIRST_ID = JOURNAL_FIRST_ID;
18
19
  const parseJson = (value) => JSON.parse(String(value));
19
20
  const encodeJson = (value) => JSON.stringify(value);
20
21
  // Some SQLite bindings replace lone UTF-16 surrogates. JSON encoding keeps indexed identities lossless.
@@ -0,0 +1,27 @@
1
+ -- The store's schema on Postgres, version 25: each claim of a run, with the turn it works and its attempt at it, as
2
+ -- store/schema.ts keeps it on SQLite (RUN_ATTEMPTS). Applied once, after 0024, inside the transaction migrate.ts opens.
3
+ -- Never edit this file once applied: a change is a new file. Additive: a runner of version 24 never reads it, and a claim
4
+ -- it makes has no row.
5
+ --
6
+ -- run_attempts: one row per claim (run_id, epoch), written in the claim's own transaction: the turn it works and its
7
+ -- attempt at it, why the attempt before was cut (cause: drain, crash, lease_lapse, retry; null on a turn's first), why
8
+ -- this claim let the run go unfinished (cut, written by its release or its runner's lost lease), its runner, the run's
9
+ -- state it took the run from, the first journal entry id it could write and when it claimed. Data only: the usage read
10
+ -- splits a run's cost by it. Made only where missing, so a store whose record of this file was lost applies it again
11
+ -- unharmed.
12
+
13
+ CREATE TABLE IF NOT EXISTS run_attempts (
14
+ run_id TEXT COLLATE "C" NOT NULL,
15
+ epoch BIGINT NOT NULL,
16
+ turn BIGINT NOT NULL CHECK (turn >= 1),
17
+ attempt BIGINT NOT NULL CHECK (attempt >= 1),
18
+ cause TEXT COLLATE "C" CHECK (cause IS NULL OR cause IN ('drain', 'crash', 'lease_lapse', 'retry')),
19
+ cut TEXT COLLATE "C" CHECK (cut IS NULL OR cut IN ('drain', 'lease_lapse', 'retry')),
20
+ runner TEXT COLLATE "C" NOT NULL,
21
+ from_state TEXT COLLATE "C" NOT NULL,
22
+ journal_from BIGINT NOT NULL,
23
+ claimed_at BIGINT NOT NULL,
24
+ PRIMARY KEY (run_id, epoch)
25
+ );
26
+
27
+ UPDATE store_meta SET schema_version = 25 WHERE singleton = 1;
@@ -0,0 +1,23 @@
1
+ -- Version 26: a run's disk (runs.disk, as store/schema.ts keeps it on SQLite): the disk the run's launch named as its own
2
+ -- (a customer's Archil disk, by its id), set once with the queued run; null for the default disk's. Learning reads an
3
+ -- agent's runs on one disk alone. Every run already here takes its disk from its launch body, as a new run's is taken at
4
+ -- its create; a run purged before this (0021) has no launch body left, so it reads as the default disk's, with nothing
5
+ -- of it left to learn from. Applied once, after 0025, inside the transaction migrate.ts opens. Never edit this file once
6
+ -- applied: a change is a new file.
7
+ --
8
+ -- The disk is read from a copy of each body that names one, its escaped NULs and surrogates (\u0000, \ud800-\udfff) read
9
+ -- as escaped spaces: Postgres's json functions refuse a whole document over one, and a run's input may hold one. A
10
+ -- replaced escape stays an escape (an escaped backslash before u0000 keeps its own), so the copy is still JSON, and only
11
+ -- the disk's id and kind are read from it (an Archil disk id holds neither).
12
+ ALTER TABLE runs ADD COLUMN IF NOT EXISTS disk TEXT COLLATE "C";
13
+ UPDATE runs SET disk = launch.disk_id
14
+ FROM (
15
+ SELECT run_id, readable #>> '{archil_disk,disk_id}' AS disk_id, readable #>> '{archil_disk,kind}' AS kind
16
+ FROM (
17
+ SELECT run_id, regexp_replace(body, '\\u(0000|[dD][89a-fA-F][0-9a-fA-F]{2})', '\\u0020', 'g')::json AS readable
18
+ FROM run_launch
19
+ WHERE strpos(body, '"archil_disk"') > 0
20
+ ) AS bodies
21
+ ) AS launch
22
+ WHERE launch.run_id = runs.id AND launch.kind = 'launch';
23
+ UPDATE store_meta SET schema_version = 26 WHERE singleton = 1;
@@ -1,4 +1,4 @@
1
- export declare const SCHEMA_VERSION = 14;
1
+ export declare const SCHEMA_VERSION = 15;
2
2
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
3
3
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
4
4
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
@@ -19,6 +19,11 @@ export declare const RUNS_COST_UPPER_BOUND = "ALTER TABLE runs ADD COLUMN cost_u
19
19
  /** A run's labels (JSON, null for none): in STORE_DDL, and added at a server open to a store an earlier build of this version
20
20
  * made, as RUNS_COST_UPPER_BOUND is (a run started before reads as given none). */
21
21
  export declare const RUNS_LABELS: string;
22
+ /** Version 14 → 15 on SQLite (the server's open, sqlite/store.ts), given the runs' columns now: each run's disk
23
+ * (RunRow.disk), written for every run already there from its launch body, as a new run's is at its create, and the
24
+ * version, in one durable write. A run whose launch named no disk of its own reads as the default disk's, and so does a
25
+ * run purged before (its launch body gone): nothing of it is left to learn from. */
26
+ export declare function diskUpgrade(runColumns: ReadonlySet<string>): readonly string[];
22
27
  /** A trigger's package mark (TriggerRow.templateId): the id of the template package whose apply made or last kept it, null
23
28
  * for one a person made. In STORE_DDL, and added at a server open to a store an earlier build of this version made, as
24
29
  * RUNS_LABELS is (a trigger made before reads as no package's). */
@@ -83,6 +88,15 @@ export declare const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at O
83
88
  export declare const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
84
89
  /** How long a hand-back's row is kept: the longest window the capacity read takes. */
85
90
  export declare const HAND_BACKS_KEPT_MS: number;
91
+ /** Each claim of a run (store.runAttempts, RunAttemptRow): the turn it works and its attempt at it, why the attempt before
92
+ * was cut (`cause`: drain, crash, lease_lapse, retry; null on a turn's first), why this one let the run go unfinished
93
+ * (`cut`), its runner, the run's state it took the run from, the first journal entry id it could write
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; 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
97
+ * added at a server open to a store an earlier build of this version made, as COMPUTER_INTERVALS is: a claim made before
98
+ * it has no row. */
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";
86
100
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
87
101
  * run and each agent was purged (null: none was), and the version, in one durable write. */
88
102
  export declare function purgeUpgrade(runColumns: ReadonlySet<string>, agentColumns: ReadonlySet<string>): readonly string[];
@@ -20,7 +20,8 @@
20
20
  // (IMPORTED_TEMPLATES), as it does the one-answer index. A hosted machine's minted token (minted_tokens, MINTED_TOKENS) is
21
21
  // added the same way, and so is each runner's word that it is there and whether it refused to claim (runners, RUNNERS),
22
22
  // and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS). Each runner's
23
- // version and slots (runners.version, .slots: RUNNERS_ADDED) and each hand-back (hand_backs, HAND_BACKS) are added the same way.
23
+ // version and slots (runners.version, .slots: RUNNERS_ADDED), each hand-back (hand_backs, HAND_BACKS) and each claim of a
24
+ // run with the turn it works and its attempt at it (run_attempts, RUN_ATTEMPTS) are added the same way.
24
25
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
25
26
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
26
27
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -36,9 +37,10 @@
36
37
  // .incarnation), the run the machine works for (.run), why the server refused to relay its dial (.refused), and where each
37
38
  // such runner takes the dials the server relays to it (runners.host and .port, dial-relay.ts). Version 14 keeps when a run or
38
39
  // an agent was purged (runs.purged_at, agents.purged_at; DELETE /runs/{id} and /agents/{id}, agent-delete.ts): its row is
39
- // then a tombstone, its content gone and its cost kept. The server upgrades these in place at its open (listingUpgrade from
40
- // 11, relayUpgrade from 12, then purgeUpgrade from 13); a runner waits for it.
41
- export const SCHEMA_VERSION = 14;
40
+ // then a tombstone, its content gone and its cost kept. Version 15 keeps the disk a run's launch named as its own
41
+ // (runs.disk; a run on one learns nothing, learn/learning-of.ts). The server upgrades these in place at its open
42
+ // (listingUpgrade from 11, relayUpgrade from 12, purgeUpgrade from 13, then diskUpgrade from 14); a runner waits for it.
43
+ export const SCHEMA_VERSION = 15;
42
44
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
43
45
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
44
46
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
@@ -64,6 +66,17 @@ export const RUNS_COST_UPPER_BOUND = `ALTER TABLE runs ADD COLUMN ${COST_UPPER_B
64
66
  /** A run's labels (JSON, null for none): in STORE_DDL, and added at a server open to a store an earlier build of this version
65
67
  * made, as RUNS_COST_UPPER_BOUND is (a run started before reads as given none). */
66
68
  export const RUNS_LABELS = `ALTER TABLE runs ADD COLUMN ${json("labels", true)}`;
69
+ /** Version 14 → 15 on SQLite (the server's open, sqlite/store.ts), given the runs' columns now: each run's disk
70
+ * (RunRow.disk), written for every run already there from its launch body, as a new run's is at its create, and the
71
+ * version, in one durable write. A run whose launch named no disk of its own reads as the default disk's, and so does a
72
+ * run purged before (its launch body gone): nothing of it is left to learn from. */
73
+ export function diskUpgrade(runColumns) {
74
+ return [
75
+ ...(runColumns.has("disk") ? [] : ["ALTER TABLE runs ADD COLUMN disk TEXT"]),
76
+ "UPDATE runs SET disk = (SELECT json_extract(body, '$.archil_disk.disk_id') FROM run_launch WHERE run_launch.run_id = runs.id AND json_extract(body, '$.archil_disk.kind') = 'launch')",
77
+ "UPDATE store_meta SET schema_version = 15 WHERE singleton = 1",
78
+ ];
79
+ }
67
80
  /** A trigger's package mark (TriggerRow.templateId): the id of the template package whose apply made or last kept it, null
68
81
  * for one a person made. In STORE_DDL, and added at a server open to a store an earlier build of this version made, as
69
82
  * RUNS_LABELS is (a trigger made before reads as no package's). */
@@ -183,6 +196,27 @@ export const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_b
183
196
  export const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
184
197
  /** How long a hand-back's row is kept: the longest window the capacity read takes. */
185
198
  export const HAND_BACKS_KEPT_MS = 24 * 60 * 60_000;
199
+ /** Each claim of a run (store.runAttempts, RunAttemptRow): the turn it works and its attempt at it, why the attempt before
200
+ * was cut (`cause`: drain, crash, lease_lapse, retry; null on a turn's first), why this one let the run go unfinished
201
+ * (`cut`), its runner, the run's state it took the run from, the first journal entry id it could write
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; 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
205
+ * added at a server open to a store an earlier build of this version made, as COMPUTER_INTERVALS is: a claim made before
206
+ * it has no row. */
207
+ export const RUN_ATTEMPTS = `CREATE TABLE IF NOT EXISTS run_attempts (
208
+ run_id TEXT NOT NULL,
209
+ epoch INTEGER NOT NULL,
210
+ turn INTEGER NOT NULL CHECK (turn >= 1),
211
+ attempt INTEGER NOT NULL CHECK (attempt >= 1),
212
+ cause TEXT CHECK (cause IS NULL OR cause IN ('drain', 'crash', 'lease_lapse', 'retry')),
213
+ cut TEXT CHECK (cut IS NULL OR cut IN ('drain', 'lease_lapse', 'retry')),
214
+ runner TEXT NOT NULL,
215
+ from_state TEXT NOT NULL,
216
+ journal_from INTEGER NOT NULL,
217
+ claimed_at INTEGER NOT NULL,
218
+ PRIMARY KEY (run_id, epoch)
219
+ ) STRICT`;
186
220
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
187
221
  * run and each agent was purged (null: none was), and the version, in one durable write. */
188
222
  export function purgeUpgrade(runColumns, agentColumns) {
@@ -380,6 +414,10 @@ export const STORE_DDL = [
380
414
  -- server and only filtered on (runs.list). Null when it was given none. Added at a server open to a store an earlier
381
415
  -- build of this version made (RUNS_LABELS), its runs reading as given none.
382
416
  ${json("labels", true)},
417
+ -- The disk the run's launch named as its own (RunRow.disk: a customer's Archil disk, by its id), set once with the queued
418
+ -- run from its launch body; null for the default disk's. Learning reads an agent's runs on one disk alone. Version 15
419
+ -- (diskUpgrade): added then and written from each run's launch. A purge keeps it on the run's tombstone.
420
+ disk TEXT,
383
421
  started_at INTEGER NOT NULL,
384
422
  ended_at INTEGER,
385
423
  -- The run's listing (RUN_LISTING_COLUMNS): what a runs list shows of it, kept on its row so a list reads rows alone.
@@ -634,6 +672,7 @@ export const STORE_DDL = [
634
672
  HAND_BACKS_RUN,
635
673
  COMPUTER_INTERVALS,
636
674
  COMPUTER_INTERVALS_RUN,
675
+ RUN_ATTEMPTS,
637
676
  // An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
638
677
  // pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
639
678
  // sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,