@parcha/agentrun-serve 0.1.0-beta.35 → 0.1.0-beta.36

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 (372) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +260 -168
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-images.d.ts +15 -0
  15. package/dist/attach-images.js +59 -0
  16. package/dist/background.d.ts +0 -6
  17. package/dist/background.js +0 -28
  18. package/dist/box-image.d.ts +1 -97
  19. package/dist/box-image.js +4 -284
  20. package/dist/box-paths.d.ts +2 -7
  21. package/dist/box-paths.js +7 -13
  22. package/dist/box-settings.d.ts +0 -11
  23. package/dist/box-settings.js +4 -29
  24. package/dist/browser-commands.js +1 -1
  25. package/dist/browser-computer.d.ts +47 -3
  26. package/dist/browser-computer.js +286 -18
  27. package/dist/browser-person.d.ts +19 -2
  28. package/dist/browser-person.js +55 -6
  29. package/dist/browser-wait-ended.d.ts +23 -0
  30. package/dist/browser-wait-ended.js +42 -0
  31. package/dist/cap.d.ts +13 -41
  32. package/dist/cap.js +24 -73
  33. package/dist/cli.js +4 -22
  34. package/dist/computer-routes.d.ts +1 -4
  35. package/dist/computer-routes.js +3 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +38 -1
  38. package/dist/computer-view.d.ts +11 -2
  39. package/dist/computer-view.js +2 -1
  40. package/dist/computers.d.ts +48 -7
  41. package/dist/computers.js +100 -23
  42. package/dist/console/assets/index-BI4Byidu.js +550 -0
  43. package/dist/console/assets/index-C19gUF2n.css +1 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/docker-daemon.d.ts +2 -2
  46. package/dist/docker-daemon.js +2 -2
  47. package/dist/errors.js +5 -5
  48. package/dist/faux-computers.js +4 -0
  49. package/dist/files.d.ts +1 -9
  50. package/dist/files.js +1 -9
  51. package/dist/github.d.ts +22 -2
  52. package/dist/github.js +42 -8
  53. package/dist/gpu-words.d.ts +14 -0
  54. package/dist/gpu-words.js +21 -0
  55. package/dist/graph-view.d.ts +2 -0
  56. package/dist/graph-view.js +25 -1
  57. package/dist/handed-values.d.ts +1 -1
  58. package/dist/handed-values.js +1 -1
  59. package/dist/harness-install.d.ts +60 -3
  60. package/dist/harness-install.js +322 -34
  61. package/dist/harness.js +1 -1
  62. package/dist/host-tools.d.ts +8 -9
  63. package/dist/host-tools.js +7 -7
  64. package/dist/index.d.ts +1 -3
  65. package/dist/index.js +1 -2
  66. package/dist/key-refusal.d.ts +1 -1
  67. package/dist/key-refusal.js +2 -2
  68. package/dist/learn/check.d.ts +7 -1
  69. package/dist/learn/check.js +123 -5
  70. package/dist/learn/commit.d.ts +40 -6
  71. package/dist/learn/commit.js +164 -20
  72. package/dist/learn/folder.d.ts +5 -0
  73. package/dist/learn/folder.js +33 -0
  74. package/dist/learn/grade.d.ts +18 -1
  75. package/dist/learn/grade.js +86 -16
  76. package/dist/learn/index.d.ts +1 -1
  77. package/dist/learn/index.js +1 -1
  78. package/dist/learn/learning.sh +12 -1
  79. package/dist/learn/notes.d.ts +3 -0
  80. package/dist/learn/notes.js +3 -0
  81. package/dist/learn/reflect.d.ts +5 -2
  82. package/dist/learn/reflect.js +43 -29
  83. package/dist/learn/skills.d.ts +4 -0
  84. package/dist/learn/skills.js +7 -0
  85. package/dist/learned-nodes.d.ts +6 -2
  86. package/dist/learned-workflow.d.ts +19 -9
  87. package/dist/learned-workflow.js +62 -34
  88. package/dist/learning-cost.d.ts +79 -0
  89. package/dist/learning-cost.js +69 -0
  90. package/dist/learning-routes.d.ts +8 -3
  91. package/dist/learning-routes.js +9 -6
  92. package/dist/learning-words.d.ts +3 -0
  93. package/dist/learning-words.js +6 -2
  94. package/dist/learning.d.ts +13 -6
  95. package/dist/learning.js +4 -2
  96. package/dist/mcp-probe.d.ts +8 -1
  97. package/dist/mcp-probe.js +62 -20
  98. package/dist/mcp-secret-writes.js +4 -0
  99. package/dist/mcp-servers-store.js +8 -3
  100. package/dist/model.d.ts +5 -5
  101. package/dist/model.js +6 -6
  102. package/dist/openapi.d.ts +2 -0
  103. package/dist/openapi.js +204 -47
  104. package/dist/owner.d.ts +0 -1
  105. package/dist/owner.js +0 -2
  106. package/dist/paid-calls.js +1 -1
  107. package/dist/place-offers.d.ts +97 -0
  108. package/dist/place-offers.js +206 -0
  109. package/dist/place.d.ts +9 -13
  110. package/dist/place.js +22 -32
  111. package/dist/port-models.d.ts +2 -1
  112. package/dist/port-models.js +5 -3
  113. package/dist/print.d.ts +1 -8
  114. package/dist/print.js +1 -14
  115. package/dist/propose.d.ts +1 -0
  116. package/dist/propose.js +25 -10
  117. package/dist/run-cut.d.ts +5 -0
  118. package/dist/run-cut.js +19 -0
  119. package/dist/run-db.js +3 -3
  120. package/dist/run-launch.d.ts +14 -1
  121. package/dist/run-launch.js +7 -2
  122. package/dist/run-learning-served.d.ts +1 -1
  123. package/dist/run-manifest.d.ts +2 -2
  124. package/dist/run-manifest.js +2 -2
  125. package/dist/run-secrets.js +3 -3
  126. package/dist/run-timeline-served.js +56 -44
  127. package/dist/run-view.d.ts +5 -2
  128. package/dist/run-view.js +4 -3
  129. package/dist/runnable.d.ts +2 -2
  130. package/dist/runnable.js +6 -2
  131. package/dist/runner/adapter-loop.d.ts +16 -1
  132. package/dist/runner/adapter-loop.js +131 -30
  133. package/dist/runner/adapter-run-spec.d.ts +25 -4
  134. package/dist/runner/adapter-run-spec.js +103 -24
  135. package/dist/runner/adapters/pi.d.ts +11 -3
  136. package/dist/runner/adapters/pi.js +35 -12
  137. package/dist/runner/beside.js +6 -2
  138. package/dist/runner/cli-run-spec.d.ts +7 -0
  139. package/dist/runner/cli-run-spec.js +92 -38
  140. package/dist/runner/commands.d.ts +5 -1
  141. package/dist/runner/commands.js +3 -3
  142. package/dist/runner/conformance/harness.d.ts +0 -1
  143. package/dist/runner/conformance/harness.js +8 -5
  144. package/dist/runner/github-app.js +2 -2
  145. package/dist/runner/harness-loops.js +1 -1
  146. package/dist/runner/journal-kinds.d.ts +15 -5
  147. package/dist/runner/journal-kinds.js +6 -1
  148. package/dist/runner/learning-end.d.ts +15 -0
  149. package/dist/runner/learning-end.js +26 -5
  150. package/dist/runner/learning-factory.js +6 -2
  151. package/dist/runner/learning-loop.d.ts +73 -1
  152. package/dist/runner/learning-loop.js +203 -18
  153. package/dist/runner/learning-seed.d.ts +2 -0
  154. package/dist/runner/learning-seed.js +1 -1
  155. package/dist/runner/loop-contract.d.ts +8 -0
  156. package/dist/runner/loop-contract.js +6 -0
  157. package/dist/runner/loop.d.ts +5 -1
  158. package/dist/runner/loop.js +20 -0
  159. package/dist/runner/main.js +12 -2
  160. package/dist/runner/mcp-claim.d.ts +4 -0
  161. package/dist/runner/mcp-claim.js +29 -1
  162. package/dist/runner/mcp-github.d.ts +4 -2
  163. package/dist/runner/mcp-github.js +0 -7
  164. package/dist/runner/mcp-run.d.ts +2 -0
  165. package/dist/runner/mcp-run.js +1 -0
  166. package/dist/runner/metrics.d.ts +4 -0
  167. package/dist/runner/metrics.js +9 -0
  168. package/dist/runner/model-route.d.ts +3 -0
  169. package/dist/runner/model-route.js +5 -2
  170. package/dist/runner/pr-checkout.d.ts +59 -0
  171. package/dist/runner/pr-checkout.js +176 -0
  172. package/dist/runner/reflect-hook.d.ts +1 -0
  173. package/dist/runner/reflect-hook.js +3 -3
  174. package/dist/runner/runner.js +47 -12
  175. package/dist/runner/spec-holds.d.ts +8 -3
  176. package/dist/runner/spec-holds.js +12 -10
  177. package/dist/runner/store-port.d.ts +4 -1
  178. package/dist/runner/store-secrets.js +17 -1
  179. package/dist/runner/subagent.d.ts +44 -0
  180. package/dist/runner/subagent.js +188 -0
  181. package/dist/runner/workflow-host.d.ts +18 -2
  182. package/dist/runner/workflow-host.js +23 -3
  183. package/dist/runner/workflow-loop.d.ts +5 -2
  184. package/dist/runner/workflow-loop.js +9 -8
  185. package/dist/runner/workflow-spec.d.ts +26 -14
  186. package/dist/runner/workflow-spec.js +97 -30
  187. package/dist/runs-over-store.d.ts +11 -6
  188. package/dist/runs-over-store.js +111 -24
  189. package/dist/sealing.js +1 -2
  190. package/dist/secret-cut.d.ts +1 -1
  191. package/dist/secret-cut.js +1 -1
  192. package/dist/server.d.ts +32 -49
  193. package/dist/server.js +249 -199
  194. package/dist/store/agent-body.d.ts +9 -2
  195. package/dist/store/agent-body.js +16 -8
  196. package/dist/store/deadline.js +9 -5
  197. package/dist/store/index.d.ts +3 -3
  198. package/dist/store/index.js +2 -2
  199. package/dist/store/journal/storage.js +2 -1
  200. package/dist/store/postgres/connection.js +9 -4
  201. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  202. package/dist/store/schema.d.ts +2 -1
  203. package/dist/store/schema.js +11 -8
  204. package/dist/store/seal.d.ts +13 -0
  205. package/dist/store/seal.js +19 -0
  206. package/dist/store/sqlite/connection.d.ts +5 -0
  207. package/dist/store/sqlite/connection.js +88 -47
  208. package/dist/store/sqlite/run-patch.d.ts +18 -2
  209. package/dist/store/sqlite/run-patch.js +31 -2
  210. package/dist/store/sqlite/store.js +65 -11
  211. package/dist/store/store.d.ts +62 -12
  212. package/dist/store/store.js +22 -1
  213. package/dist/store-reads/analytics.js +3 -2
  214. package/dist/store-reads/cap.d.ts +1 -3
  215. package/dist/store-reads/cap.js +8 -6
  216. package/dist/store-reads/decisions.d.ts +2 -2
  217. package/dist/store-reads/decisions.js +3 -6
  218. package/dist/store-reads/journal.js +45 -12
  219. package/dist/store-reads/learning.d.ts +15 -1
  220. package/dist/store-reads/learning.js +68 -10
  221. package/dist/store-reads/runs.d.ts +6 -4
  222. package/dist/store-reads/runs.js +17 -10
  223. package/dist/store-reads/stats.js +5 -1
  224. package/dist/store-view.js +45 -19
  225. package/dist/template-eval.js +2 -1
  226. package/dist/templates.d.ts +64 -0
  227. package/dist/templates.js +101 -16
  228. package/dist/timeline/timeline.d.ts +3 -1
  229. package/dist/timeline/timeline.js +19 -4
  230. package/dist/tool-blurbs.js +1 -0
  231. package/dist/tool-budget.d.ts +8 -0
  232. package/dist/tool-budget.js +7 -1
  233. package/dist/tool-gate.d.ts +7 -1
  234. package/dist/tool-gate.js +7 -2
  235. package/dist/tool-plane.d.ts +33 -19
  236. package/dist/tool-plane.js +64 -27
  237. package/dist/tools.d.ts +18 -34
  238. package/dist/tools.js +104 -70
  239. package/dist/trigger-signatures.d.ts +1 -0
  240. package/dist/trigger-signatures.js +3 -1
  241. package/dist/triggers.d.ts +3 -3
  242. package/dist/triggers.js +2 -2
  243. package/dist/turn-end.d.ts +0 -3
  244. package/dist/turn-end.js +0 -3
  245. package/dist/usage-lines.d.ts +1 -1
  246. package/dist/validate.d.ts +6 -0
  247. package/dist/validate.js +30 -3
  248. package/dist/webhooks.d.ts +2 -1
  249. package/dist/webhooks.js +5 -2
  250. package/dist/workflow/decision-recovery.d.ts +23 -0
  251. package/dist/workflow/decision-recovery.js +80 -0
  252. package/dist/workflow/decisions.d.ts +134 -0
  253. package/dist/workflow/decisions.js +46 -0
  254. package/dist/workflow/host-session.d.ts +5 -0
  255. package/dist/workflow/host-session.js +85 -0
  256. package/dist/workflow/host-tools.d.ts +3 -0
  257. package/dist/workflow/host-tools.js +3 -0
  258. package/dist/workflow/node-runner.d.ts +112 -0
  259. package/dist/workflow/node-runner.js +270 -0
  260. package/dist/workflow/node.d.ts +88 -0
  261. package/dist/workflow/node.js +99 -0
  262. package/dist/workflow/operator-error.d.ts +4 -0
  263. package/dist/workflow/operator-error.js +4 -0
  264. package/dist/workflow/pi-versions.d.ts +9 -0
  265. package/dist/workflow/pi-versions.js +8 -0
  266. package/dist/workflow/readers.d.ts +36 -0
  267. package/dist/workflow/readers.js +145 -0
  268. package/dist/workflow/record-file.d.ts +10 -0
  269. package/dist/workflow/record-file.js +56 -0
  270. package/dist/workflow/record-tool.d.ts +76 -0
  271. package/dist/workflow/record-tool.js +126 -0
  272. package/dist/workflow/record.d.ts +151 -0
  273. package/dist/workflow/record.js +401 -0
  274. package/dist/workflow/run-error.d.ts +16 -0
  275. package/dist/workflow/run-error.js +26 -0
  276. package/dist/workflow/runner.d.ts +6 -0
  277. package/dist/workflow/runner.js +240 -0
  278. package/dist/workflow/store.d.ts +23 -0
  279. package/dist/workflow/store.js +242 -0
  280. package/dist/workflow/task.d.ts +133 -0
  281. package/dist/workflow/task.js +411 -0
  282. package/dist/workflow/thinking.d.ts +3 -0
  283. package/dist/workflow/thinking.js +7 -0
  284. package/dist/workflow/tool-context.d.ts +21 -0
  285. package/dist/workflow/tool-context.js +13 -0
  286. package/dist/workflow/types.d.ts +126 -0
  287. package/dist/workflow/types.js +1 -0
  288. package/dist/workflow/wal.d.ts +11 -0
  289. package/dist/workflow/wal.js +106 -0
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/agent-computer.d.ts +137 -0
  292. package/dist/workspace/agent-computer.js +292 -0
  293. package/dist/workspace/archil-claim.d.ts +11 -0
  294. package/dist/workspace/archil-claim.js +18 -10
  295. package/dist/workspace/archil-disks.d.ts +49 -0
  296. package/dist/workspace/archil-disks.js +185 -0
  297. package/dist/workspace/archil-exec.js +2 -3
  298. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  299. package/dist/workspace/archil-mount-credential.js +13 -4
  300. package/dist/workspace/computer-deps.d.ts +16 -8
  301. package/dist/workspace/computer-deps.js +18 -7
  302. package/dist/workspace/computer-for-claim.d.ts +42 -6
  303. package/dist/workspace/computer-for-claim.js +209 -9
  304. package/dist/workspace/computer-janitor.d.ts +3 -2
  305. package/dist/workspace/computer-janitor.js +43 -9
  306. package/dist/workspace/computer-ledger.d.ts +3 -1
  307. package/dist/workspace/computer-ledger.js +7 -0
  308. package/dist/workspace/index.d.ts +3 -2
  309. package/dist/workspace/index.js +1 -0
  310. package/dist/workspace/resolve-computer.d.ts +42 -11
  311. package/dist/workspace/resolve-computer.js +65 -13
  312. package/dist/workspace/run-disk.d.ts +34 -0
  313. package/dist/workspace/run-disk.js +91 -0
  314. package/dist/workspace/run-tools.d.ts +4 -4
  315. package/dist/workspace/run-tools.js +8 -6
  316. package/dist/workspace/server-run-workspace.d.ts +3 -2
  317. package/dist/workspace/server-run-workspace.js +17 -4
  318. package/dist/workspace.js +1 -1
  319. package/package.json +10 -15
  320. package/templates/README.md +9 -6
  321. package/templates/code-review/agent.md +27 -11
  322. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  323. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  324. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  325. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  326. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  327. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  328. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  329. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  330. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  331. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  332. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  333. package/templates/code-review/evals/re-review/prompt.md +1 -1
  334. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  335. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  336. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  337. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  338. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  339. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  340. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  341. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  342. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  343. package/templates/code-review/findings.schema.json +131 -27
  344. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  345. package/templates/code-review/skills/review/DEEP.md +130 -0
  346. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  347. package/templates/code-review/skills/review/SKILL.md +104 -154
  348. package/dist/box/record.d.ts +0 -6
  349. package/dist/box/record.js +0 -41
  350. package/dist/box/sweep.d.ts +0 -53
  351. package/dist/box/sweep.js +0 -193
  352. package/dist/box-egress-vm.d.ts +0 -118
  353. package/dist/box-egress-vm.js +0 -354
  354. package/dist/box-egress.d.ts +0 -105
  355. package/dist/box-egress.js +0 -256
  356. package/dist/box-relay-vm.d.ts +0 -84
  357. package/dist/box-relay-vm.js +0 -437
  358. package/dist/box-relay.d.ts +0 -36
  359. package/dist/box-relay.js +0 -207
  360. package/dist/boxes.d.ts +0 -109
  361. package/dist/boxes.js +0 -249
  362. package/dist/budget.d.ts +0 -71
  363. package/dist/budget.js +0 -199
  364. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  365. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  366. package/dist/daytona-api.d.ts +0 -10
  367. package/dist/daytona-api.js +0 -20
  368. package/dist/egress-proxy.d.ts +0 -45
  369. package/dist/egress-proxy.js +0 -416
  370. package/dist/egress-table.d.ts +0 -24
  371. package/dist/egress-table.js +0 -165
  372. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -0,0 +1,106 @@
1
+ // Whether a SQLite WAL holds a commit, read as SQLite's own recovery reads it (walIndexRecover): the 32-byte header
2
+ // (its magic, which sets the checksums' byte order, the page size, the two salts and the header's checksum), then each
3
+ // frame (a 24-byte header and a page) whose salts are the header's and whose checksum, chained from the header's, holds.
4
+ // Recovery takes the WAL's end at the last such frame that is a commit (its nTruncate, the database size after the
5
+ // commit, not 0); a WAL with frames and no commit yet recovers to no frame at all. A lock-free reader of a run's
6
+ // database (vfs=unix-none, an exclusive locking mode, the WAL index in heap) that opens such a WAL recovers none, and its
7
+ // close then checkpoints nothing and removes the WAL (sqlite3WalClose), under a writer whose first transaction is still
8
+ // being written there: that writer's commits go into a removed file and are lost. A reader opens a WAL only once this
9
+ // says it holds a commit, and the database file alone (immutable) before then.
10
+ //
11
+ // A WAL is only ever appended to by the run's writer (no automatic checkpoint, and no checkpoint of its own: it ends by
12
+ // process.exit), so a prefix verified once stays verified: the walk resumes from where it stopped, kept per file under
13
+ // its inode and the header's salts and checksum. A new header (a WAL made again, or restarted with new salts) starts it
14
+ // over.
15
+ import fs from "node:fs";
16
+ /** A WAL header's magic: its low bit set, the checksums read their words big-endian; clear, little-endian. */
17
+ const MAGIC = 0x377f0682;
18
+ /** The one WAL format version SQLite writes and reads (WAL_MAX_VERSION). */
19
+ const WAL_VERSION = 3007000;
20
+ const HEADER = 32;
21
+ const FRAME_HEADER = 24;
22
+ const walked = new Map();
23
+ /** SQLite's walChecksumBytes over `data` (its length a multiple of 8), from `s1`/`s2`: each two 32-bit words x0, x1 (read
24
+ * big-endian when `bigEnd`, else little-endian) add s1 += x0 + s2; s2 += x1 + s1, modulo 2^32. */
25
+ function checksum(data, bigEnd, s1, s2) {
26
+ for (let at = 0; at < data.length; at += 8) {
27
+ const x0 = bigEnd ? data.readUInt32BE(at) : data.readUInt32LE(at);
28
+ const x1 = bigEnd ? data.readUInt32BE(at + 4) : data.readUInt32LE(at + 4);
29
+ s1 = (s1 + x0 + s2) >>> 0;
30
+ s2 = (s2 + x1 + s1) >>> 0;
31
+ }
32
+ return [s1, s2];
33
+ }
34
+ /** Forgets the walk kept for `wal`: a WAL a checkpoint removed. A WAL found gone is forgotten by walHasCommit too, so the
35
+ * walks kept are of WALs that still exist. */
36
+ export function forgetWalWalk(wal) {
37
+ walked.delete(wal);
38
+ }
39
+ /** How many walks are kept (tests). */
40
+ export function keptWalWalks() {
41
+ return walked.size;
42
+ }
43
+ /**
44
+ * Whether the WAL at `wal` holds a commit SQLite's recovery would take: a frame whose salts are the header's, whose
45
+ * chained checksum holds, and whose nTruncate is not 0. No WAL, a short one, a header that is not one, or frames with no
46
+ * verified commit yet: false.
47
+ */
48
+ export function walHasCommit(wal) {
49
+ let fd;
50
+ try {
51
+ fd = fs.openSync(wal, "r");
52
+ }
53
+ catch {
54
+ walked.delete(wal);
55
+ return false;
56
+ }
57
+ try {
58
+ const at = fs.fstatSync(fd);
59
+ if (at.size < HEADER + FRAME_HEADER)
60
+ return false;
61
+ const header = Buffer.alloc(HEADER);
62
+ if (fs.readSync(fd, header, 0, HEADER, 0) < HEADER)
63
+ return false;
64
+ const magic = header.readUInt32BE(0);
65
+ if ((magic & 0xfffffffe) !== MAGIC || header.readUInt32BE(4) !== WAL_VERSION)
66
+ return false;
67
+ const bigEnd = (magic & 1) === 1;
68
+ const pageSize = header.readUInt32BE(8);
69
+ if (pageSize < 512 || pageSize > 65536 || (pageSize & (pageSize - 1)) !== 0)
70
+ return false;
71
+ const [h1, h2] = checksum(header.subarray(0, 24), bigEnd, 0, 0);
72
+ if (h1 !== header.readUInt32BE(24) || h2 !== header.readUInt32BE(28))
73
+ return false;
74
+ const salt1 = header.readUInt32BE(16);
75
+ const salt2 = header.readUInt32BE(20);
76
+ const key = `${at.dev}:${at.ino}:${header.toString("hex")}`;
77
+ let walk = walked.get(wal);
78
+ if (walk?.key !== key)
79
+ walk = { key, offset: HEADER, s1: h1, s2: h2, committed: false };
80
+ walked.set(wal, walk);
81
+ if (walk.committed)
82
+ return true;
83
+ const frame = Buffer.alloc(FRAME_HEADER + pageSize);
84
+ while (walk.offset + frame.length <= at.size) {
85
+ if (fs.readSync(fd, frame, 0, frame.length, walk.offset) < frame.length)
86
+ break;
87
+ if (frame.readUInt32BE(0) === 0 || frame.readUInt32BE(8) !== salt1 || frame.readUInt32BE(12) !== salt2)
88
+ break;
89
+ let [s1, s2] = checksum(frame.subarray(0, 8), bigEnd, walk.s1, walk.s2);
90
+ [s1, s2] = checksum(frame.subarray(FRAME_HEADER), bigEnd, s1, s2);
91
+ if (s1 !== frame.readUInt32BE(16) || s2 !== frame.readUInt32BE(20))
92
+ break;
93
+ walk.offset += frame.length;
94
+ walk.s1 = s1;
95
+ walk.s2 = s2;
96
+ if (frame.readUInt32BE(4) !== 0) {
97
+ walk.committed = true;
98
+ return true;
99
+ }
100
+ }
101
+ return false;
102
+ }
103
+ finally {
104
+ fs.closeSync(fd);
105
+ }
106
+ }
@@ -2,7 +2,7 @@ import type { Context } from "@earendil-works/chord";
2
2
  import type { Storage } from "@earendil-works/pi-durable";
3
3
  import type { Workflow } from "@parcha/agentrun-dsl";
4
4
  import type { GraphDiff, NodeState, WorkflowGraph } from "@parcha/agentrun-dsl/graph";
5
- import type { createWorkflowExtension, WorkflowCaller, WorkflowOutcome } from "@parcha/agentrun-pi/durable";
5
+ import type { createWorkflowExtension, WorkflowCaller, WorkflowOutcome } from "./workflow/task.js";
6
6
  /** A workflow run that can't be read here, in words. */
7
7
  export declare class WorkflowRunUnread extends Error {
8
8
  constructor(message: string);
@@ -0,0 +1,137 @@
1
+ import { type ComputerOwner, type ComputerProvider, type Result } from "@parcha/agentrun-computer";
2
+ import type { Store } from "../store/index.js";
3
+ /** The settings key of this server's id. */
4
+ export declare const SERVER_ID_KEY = "server_id";
5
+ /** This server's id: 12 hex digits, made once and kept in its store (the first writer wins a race), so its agents'
6
+ * computers keep their owner across restarts and are told apart from another server's on one vendor account. */
7
+ export declare function serverIdOf(store: {
8
+ settings: Pick<Store["settings"], "putIfAbsent">;
9
+ }): Promise<string>;
10
+ /** Where an agent's computer is: held by a run, detached between runs, or being deleted (with why it is not yet, when a
11
+ * delete failed). */
12
+ export type AgentComputerState = "held" | "detached" | "deleting";
13
+ /** An agent's computer as this server records it. `image`: the configuration's, absent for the provider's default. */
14
+ export interface AgentComputerRecord {
15
+ readonly v: 1;
16
+ readonly provider: string;
17
+ readonly image?: string;
18
+ readonly id: string;
19
+ readonly name: string;
20
+ readonly state: AgentComputerState;
21
+ /** The run that holds it, while held. */
22
+ readonly run?: string;
23
+ /** When it took this state, ISO time. */
24
+ readonly at: string;
25
+ /** Why a delete has not happened yet, in the provider's words. */
26
+ readonly why?: string;
27
+ }
28
+ type Settings = {
29
+ settings: Pick<Store["settings"], "get" | "put">;
30
+ };
31
+ /** The agent's computer as recorded, or undefined when it has none (or the row does not read as one). */
32
+ export declare function agentComputerOf(store: {
33
+ settings: Pick<Store["settings"], "get">;
34
+ }, agentId: string): Promise<AgentComputerRecord | undefined>;
35
+ type Computer = {
36
+ readonly provider: string;
37
+ readonly image?: string | undefined;
38
+ readonly id: string;
39
+ readonly name: string;
40
+ };
41
+ /** Records the agent's computer in `state` now, by the run that holds it (agentComputerHold): held by `run`, or detached. */
42
+ export declare function keepAgentComputer(store: Settings, agentId: string, computer: Computer, state: AgentComputerState, extra?: {
43
+ readonly run?: string;
44
+ readonly why?: string;
45
+ }): Promise<void>;
46
+ /** The agent's record goes, where it still names the computer `id` (a removeIf on the record as read): a record a later
47
+ * claim wrote of another computer is kept. */
48
+ export declare function forgetAgentComputer(store: {
49
+ settings: Pick<Store["settings"], "get" | "removeIf">;
50
+ }, agentId: string, id: string): Promise<void>;
51
+ type Holding = {
52
+ settings: Pick<Store["settings"], "get" | "putIfAbsent" | "replaceIf" | "removeIf">;
53
+ };
54
+ /** How long a hold that is letting go (its run detaching the computer at its end, or this server deleting it) keeps every
55
+ * other run off: the most a provider's detach or delete is waited on. A holder that died while letting go is taken over
56
+ * after it. */
57
+ export declare const HOLD_RELEASE_MS: number;
58
+ /** Whether a holder is a run still going, by the store's run rows. With no run rows to read, every run is: never two runs
59
+ * on one agent's computer. A delete's hold is no run's: its letting-go time alone keeps others off. */
60
+ export declare function liveHolderOf(store: {
61
+ readonly runs?: Pick<Store["runs"], "get"> | undefined;
62
+ }): (holder: string) => Promise<boolean>;
63
+ /** A run's hold on the agent's computer (holdAgentComputer). */
64
+ export interface AgentComputerHold {
65
+ readonly run: string;
66
+ /** Whether the hold row is still this take's: not let go, nor taken over (by another run, or a later claim of this one). */
67
+ holds(): Promise<boolean>;
68
+ /** Marks the hold as letting go, before the computer is detached at the run's end: no other run takes it over until it
69
+ * lets go, or HOLD_RELEASE_MS passes. False, with nothing marked, when another run has taken it over since: the
70
+ * computer is that run's now, and is left as it is. */
71
+ releasing(): Promise<boolean>;
72
+ /** The hold row goes, where it is still this one, so the agent's next run takes the computer at once. */
73
+ letGo(): Promise<void>;
74
+ }
75
+ /**
76
+ * Takes the agent's computer for `run`'s claim at `epoch`, before anything is listed or made, so two runs of one agent
77
+ * that claim at once never both make one. The hold is one settings row per agent naming its holder and the claim's
78
+ * epoch, taken with the store's putIfAbsent (of two writers the first wins). A hold of another run still going
79
+ * (`isLive`), or any hold letting go (until its time: its holder is detaching or deleting the computer), refuses this
80
+ * one in words naming it. A hold of `run`'s own at a higher epoch refuses this claim (fenced); one at this epoch or
81
+ * below (a claim this one resumes) is taken over, as is a hold of a run that ended: with the store's replaceIf on the
82
+ * row as read, so of two that find the same holder only one replaces it, and one that finds the row changed (taken, or
83
+ * let go) reads it again. Each take is its own row, so a hold taken over is no longer the old take's: its cleanup
84
+ * (releasing, letGo) finds the row changed and does nothing. `until`: a hold that keeps others off until then from
85
+ * the start (a delete's, which has no epoch).
86
+ */
87
+ export declare function holdAgentComputer(store: Holding, agentId: string, run: string, isLive: (holder: string) => Promise<boolean>, { epoch, until }?: {
88
+ readonly epoch?: number;
89
+ readonly until?: number;
90
+ }): Promise<AgentComputerHold>;
91
+ /**
92
+ * `remove` (a provider's delete of the agent's computer `id`) under the agent's hold, taken as a delete of this server's,
93
+ * so no run attaches the computer while it goes and none has it deleted from under it; then the agent's record goes,
94
+ * where it still names that computer. Not taken (a run holds it): refused in words, and nothing is deleted. `due` is
95
+ * asked again under the hold, since what decided the delete was read before it: an agent that wants its computer again
96
+ * meanwhile (unarchived, persistent turned back on) keeps it, refused in words.
97
+ */
98
+ export declare function deleteUnderHold(store: Holding & {
99
+ readonly runs?: Pick<Store["runs"], "get"> | undefined;
100
+ }, agentId: string, id: string, due: () => Promise<boolean>, remove: () => Promise<Result<void>>): Promise<Result<void>>;
101
+ /** The agent's computer as GET /agents/{agent_id} shows it, or null when it has none. */
102
+ export declare function agentComputerView(record: AgentComputerRecord | undefined): Record<string, unknown> | null;
103
+ type Agents = {
104
+ agents: Pick<Store["agents"], "get" | "revision">;
105
+ };
106
+ /** Whether the agent still has a use for a computer of `provider` and `image`: it is here, not archived, and its current
107
+ * setting is persistent on that provider and image. */
108
+ export declare function wantsComputer(store: Agents, agentId: string, provider: string, image: string | undefined): Promise<boolean>;
109
+ type Runs = {
110
+ readonly runs?: Pick<Store["runs"], "get"> | undefined;
111
+ };
112
+ /**
113
+ * The janitor's ownerGone for this server and one provider: an owner another server names is never gone to this one; one
114
+ * of this server's is gone when its agent has no use for a computer of this provider (gone from the store, archived, or
115
+ * its setting not persistent here) and no run holds its computer now (heldNow): a run's computer is never deleted from
116
+ * under it, and that run's end deletes it. An owner with no server is no agent's of this server's, so never gone here.
117
+ */
118
+ export declare function ownerGoneOf(store: Agents & Holding & Runs, serverId: string, provider: string): (owner: ComputerOwner) => Promise<boolean>;
119
+ /** Whether the agent still has a use for a computer of `provider`: it is here, not archived, and persistent there. */
120
+ export declare function wantsOn(store: Agents, agentId: string, provider: string): Promise<boolean>;
121
+ /**
122
+ * Deletes the agent's computer when the agent has no use for it any more (wantsComputer), under the agent's hold: given
123
+ * `hold` (the run that holds it, at its end), under that one; else taken as a delete of this server's, and where a run
124
+ * holds it, nothing is done now: that run's end reconciles again. The record is moved to deleting, and goes once the
125
+ * provider has deleted the computer, each a replaceIf or removeIf on the record as read, so a record a later run wrote
126
+ * (a replacement) is never erased. A delete that fails keeps it deleting, with the provider's words, for the next
127
+ * reconcile or the janitor. `makeProvider` builds the computer's provider; it throws, in words, when it cannot. Answers
128
+ * what happened, or undefined when there was nothing to do now.
129
+ */
130
+ export declare function reconcileAgentComputer(store: Settings & Agents & Holding & Runs, agentId: string, makeProvider: MakeProvider, hold?: AgentComputerHold): Promise<Reconciled | undefined>;
131
+ type MakeProvider = (provider: string, image: string | undefined) => Promise<Pick<ComputerProvider, "release">>;
132
+ type Reconciled = {
133
+ readonly deleted: string;
134
+ } | {
135
+ readonly failed: string;
136
+ };
137
+ export {};
@@ -0,0 +1,292 @@
1
+ // An agent's own computer: the one its computer setting asks for with `persistent: true`, kept between its runs. The
2
+ // provider keeps it under an owner (the computer package's spec.owner: this server's id and the agent's), and this
3
+ // server keeps one record per agent in its store's settings (agent_computer:<agent id>): the provider, the
4
+ // configuration's image, the computer, and whether a run holds it. The claim writes the record (computer-for-claim.ts),
5
+ // the agent's view shows it (GET /agents/{agent_id}'s own_computer), and reconcileAgentComputer deletes the computer
6
+ // once the agent has no use for it: archived, persistent turned off, or a setting on another provider or image. The
7
+ // janitor asks the same question of an owner it lists (ownerGoneOf). Nothing here knows a vendor: a provider is made by the caller.
8
+ import { randomBytes } from "node:crypto";
9
+ import { configurationOf, PROVIDERS, serves } from "@parcha/agentrun-computer";
10
+ /** The settings key of this server's id. */
11
+ export const SERVER_ID_KEY = "server_id";
12
+ /** This server's id: 12 hex digits, made once and kept in its store (the first writer wins a race), so its agents'
13
+ * computers keep their owner across restarts and are told apart from another server's on one vendor account. */
14
+ export async function serverIdOf(store) {
15
+ const kept = await store.settings.putIfAbsent(SERVER_ID_KEY, { v: 1, id: randomBytes(6).toString("hex") });
16
+ const id = kept?.id;
17
+ if (typeof id !== "string" || !/^[0-9a-f]{12}$/.test(id))
18
+ throw new Error(`this server's store keeps a ${SERVER_ID_KEY} that does not read as one`);
19
+ return id;
20
+ }
21
+ const recordKey = (agentId) => `agent_computer:${agentId}`;
22
+ const STATES = ["held", "detached", "deleting"];
23
+ /** The agent's computer as recorded, or undefined when it has none (or the row does not read as one). */
24
+ export async function agentComputerOf(store, agentId) {
25
+ const row = (await store.settings.get(recordKey(agentId)));
26
+ if (typeof row !== "object" || row === null || row.v !== 1)
27
+ return undefined;
28
+ if (typeof row.provider !== "string" || typeof row.id !== "string" || typeof row.name !== "string" || typeof row.at !== "string" || !STATES.includes(row.state))
29
+ return undefined;
30
+ return row;
31
+ }
32
+ /** The record of `computer` in `state` now: held by `run`, or detached or deleting with none. */
33
+ function recordOf(computer, state, extra = {}) {
34
+ return {
35
+ v: 1,
36
+ provider: computer.provider,
37
+ ...(computer.image === undefined ? {} : { image: computer.image }),
38
+ id: computer.id,
39
+ name: computer.name,
40
+ state,
41
+ ...(state === "held" && extra.run !== undefined ? { run: extra.run } : {}),
42
+ at: new Date().toISOString(),
43
+ ...(extra.why === undefined ? {} : { why: extra.why }),
44
+ };
45
+ }
46
+ /** Records the agent's computer in `state` now, by the run that holds it (agentComputerHold): held by `run`, or detached. */
47
+ export async function keepAgentComputer(store, agentId, computer, state, extra = {}) {
48
+ await store.settings.put(recordKey(agentId), recordOf(computer, state, extra));
49
+ }
50
+ /** The agent's record goes, where it still names the computer `id` (a removeIf on the record as read): a record a later
51
+ * claim wrote of another computer is kept. */
52
+ export async function forgetAgentComputer(store, agentId, id) {
53
+ const record = await agentComputerOf(store, agentId);
54
+ if (record?.id === id)
55
+ await store.settings.removeIf(recordKey(agentId), record);
56
+ }
57
+ const holdKey = (agentId) => `agent_computer_hold:${agentId}`;
58
+ /** How long a hold that is letting go (its run detaching the computer at its end, or this server deleting it) keeps every
59
+ * other run off: the most a provider's detach or delete is waited on. A holder that died while letting go is taken over
60
+ * after it. */
61
+ export const HOLD_RELEASE_MS = 15 * 60_000;
62
+ /** The holder a delete of this server's takes the hold under (reconcileAgentComputer, the janitor): no run's id. */
63
+ const DELETER = "delete:";
64
+ /** A run state in which the run still holds what it claimed. */
65
+ const LIVE_RUN = new Set(["queued", "running", "parked"]);
66
+ /** Whether a holder is a run still going, by the store's run rows. With no run rows to read, every run is: never two runs
67
+ * on one agent's computer. A delete's hold is no run's: its letting-go time alone keeps others off. */
68
+ export function liveHolderOf(store) {
69
+ const { runs } = store;
70
+ return async (holder) => !holder.startsWith(DELETER) && (!runs || LIVE_RUN.has((await runs.get(holder))?.state ?? ""));
71
+ }
72
+ /** Why a run cannot have the agent's computer: another run, still going, holds it, a holder is letting it go, or a later
73
+ * claim of the same run holds it. */
74
+ class HeldComputer extends Error {
75
+ }
76
+ const heldBy = (holder) => new HeldComputer(`this agent's own computer is held by run ${holder}, which is still going: an agent's own computer serves one run at a time. Start this run again once that one ends`);
77
+ const lettingGo = (holder) => new HeldComputer(`this agent's own computer is being ${holder.startsWith(DELETER) ? "deleted by this server" : `detached by run ${holder}`}: start this run again in a moment`);
78
+ const fencedBy = (run, epoch, mine) => new HeldComputer(`fenced: this agent's own computer is held by run ${run}'s claim at epoch ${epoch}, above this claim's ${mine}; nothing changed`);
79
+ /**
80
+ * Takes the agent's computer for `run`'s claim at `epoch`, before anything is listed or made, so two runs of one agent
81
+ * that claim at once never both make one. The hold is one settings row per agent naming its holder and the claim's
82
+ * epoch, taken with the store's putIfAbsent (of two writers the first wins). A hold of another run still going
83
+ * (`isLive`), or any hold letting go (until its time: its holder is detaching or deleting the computer), refuses this
84
+ * one in words naming it. A hold of `run`'s own at a higher epoch refuses this claim (fenced); one at this epoch or
85
+ * below (a claim this one resumes) is taken over, as is a hold of a run that ended: with the store's replaceIf on the
86
+ * row as read, so of two that find the same holder only one replaces it, and one that finds the row changed (taken, or
87
+ * let go) reads it again. Each take is its own row, so a hold taken over is no longer the old take's: its cleanup
88
+ * (releasing, letGo) finds the row changed and does nothing. `until`: a hold that keeps others off until then from
89
+ * the start (a delete's, which has no epoch).
90
+ */
91
+ export async function holdAgentComputer(store, agentId, run, isLive, { epoch, until } = {}) {
92
+ const key = holdKey(agentId);
93
+ let mine = {
94
+ v: 1,
95
+ run,
96
+ ...(epoch === undefined ? {} : { epoch }),
97
+ id: randomBytes(6).toString("hex"),
98
+ at: new Date().toISOString(),
99
+ ...(until === undefined ? {} : { until: new Date(until).toISOString() }),
100
+ };
101
+ const hold = {
102
+ run,
103
+ holds: async () => JSON.stringify((await store.settings.get(key)) ?? null) === JSON.stringify(mine),
104
+ async releasing() {
105
+ const next = { ...mine, until: new Date(Date.now() + HOLD_RELEASE_MS).toISOString() };
106
+ if (!(await store.settings.replaceIf(key, mine, next)))
107
+ return false;
108
+ mine = next;
109
+ return true;
110
+ },
111
+ async letGo() {
112
+ await store.settings.removeIf(key, mine);
113
+ },
114
+ };
115
+ for (let tries = 0; tries < 3; tries++) {
116
+ const held = (await store.settings.putIfAbsent(key, mine));
117
+ const holder = typeof held?.run === "string" ? held.run : undefined;
118
+ // This take's own row, put now: kept as the store reads it back, for the compare-and-sets that follow.
119
+ if (held?.id === mine.id) {
120
+ mine = held;
121
+ return hold;
122
+ }
123
+ if (holder === run && epoch !== undefined && typeof held?.epoch === "number" && held.epoch > epoch)
124
+ throw fencedBy(run, held.epoch, epoch);
125
+ if (holder !== undefined && typeof held?.until === "string" && Date.parse(held.until) > Date.now())
126
+ throw lettingGo(holder);
127
+ if (holder !== undefined && holder !== run && (await isLive(holder)))
128
+ throw heldBy(holder);
129
+ // An ended run's hold, an earlier claim's of this run (or a row that names none): replaced only while it is still the
130
+ // row read.
131
+ if (await store.settings.replaceIf(key, held ?? null, mine))
132
+ return hold;
133
+ }
134
+ throw new Error("this agent's own computer changed hands three times while this run claimed it: start this run again");
135
+ }
136
+ /**
137
+ * `remove` (a provider's delete of the agent's computer `id`) under the agent's hold, taken as a delete of this server's,
138
+ * so no run attaches the computer while it goes and none has it deleted from under it; then the agent's record goes,
139
+ * where it still names that computer. Not taken (a run holds it): refused in words, and nothing is deleted. `due` is
140
+ * asked again under the hold, since what decided the delete was read before it: an agent that wants its computer again
141
+ * meanwhile (unarchived, persistent turned back on) keeps it, refused in words.
142
+ */
143
+ export async function deleteUnderHold(store, agentId, id, due, remove) {
144
+ let hold;
145
+ try {
146
+ hold = await holdAgentComputer(store, agentId, `${DELETER}${randomBytes(6).toString("hex")}`, liveHolderOf(store), { until: Date.now() + HOLD_RELEASE_MS });
147
+ }
148
+ catch (error) {
149
+ if (error instanceof HeldComputer)
150
+ return { ok: false, error: { code: "refused", message: error.message } };
151
+ throw error;
152
+ }
153
+ try {
154
+ if (!(await due()))
155
+ return { ok: false, error: { code: "refused", message: `the agent ${agentId} wants its computer again, so it is kept` } };
156
+ const removed = await remove();
157
+ if (removed.ok)
158
+ await forgetAgentComputer(store, agentId, id);
159
+ return removed;
160
+ }
161
+ finally {
162
+ await hold.letGo();
163
+ }
164
+ }
165
+ /** The agent's computer as GET /agents/{agent_id} shows it, or null when it has none. */
166
+ export function agentComputerView(record) {
167
+ if (!record)
168
+ return null;
169
+ return {
170
+ provider: record.provider,
171
+ ...(record.image === undefined ? {} : { image: record.image }),
172
+ id: record.id,
173
+ name: record.name,
174
+ state: record.state,
175
+ ...(record.run === undefined ? {} : { run_id: record.run }),
176
+ since: record.at,
177
+ ...(record.why === undefined ? {} : { why: record.why }),
178
+ };
179
+ }
180
+ /** The image of the configuration a setting of `kind` on `provider` selects with `image` (the default one where it names
181
+ * none), as the claim records it: two settings that select one configuration are one computer. */
182
+ function configurationImage(provider, kind, image) {
183
+ const entry = PROVIDERS.find((one) => one.id === provider);
184
+ if (!entry)
185
+ return image;
186
+ const settingKind = kind;
187
+ return configurationOf(entry.capabilities.filter((one) => serves(one, settingKind)), image, entry.defaultImage?.[settingKind])?.image ?? image;
188
+ }
189
+ /** The persistent setting the agent's current revision asks for (its provider and the image of the configuration it
190
+ * selects), or undefined when it asks for none (or the agent is archived, or this store has no such agent). */
191
+ async function wantedSetting(store, agentId) {
192
+ const agent = await store.agents.get(agentId);
193
+ if (!agent || agent.archivedAt != null || agent.currentRevision === null)
194
+ return undefined;
195
+ const body = (await store.agents.revision(agent.currentRevision))?.body;
196
+ const computer = body?.computer;
197
+ if (computer?.persistent !== true || typeof computer.provider !== "string" || typeof computer.kind !== "string" || computer.kind === "none")
198
+ return undefined;
199
+ const image = configurationImage(computer.provider, computer.kind, computer.image);
200
+ return { provider: computer.provider, ...(image === undefined ? {} : { image }) };
201
+ }
202
+ /** Whether the agent still has a use for a computer of `provider` and `image`: it is here, not archived, and its current
203
+ * setting is persistent on that provider and image. */
204
+ export async function wantsComputer(store, agentId, provider, image) {
205
+ const wanted = await wantedSetting(store, agentId);
206
+ return wanted !== undefined && wanted.provider === provider && wanted.image === image;
207
+ }
208
+ /** Whether the agent's hold keeps others off now: a run still going holds it, or a holder is letting it go. */
209
+ async function heldNow(store, agentId) {
210
+ const held = (await store.settings.get(holdKey(agentId)));
211
+ if (typeof held?.run !== "string")
212
+ return false;
213
+ return (typeof held.until === "string" && Date.parse(held.until) > Date.now()) || (await liveHolderOf(store)(held.run));
214
+ }
215
+ /**
216
+ * The janitor's ownerGone for this server and one provider: an owner another server names is never gone to this one; one
217
+ * of this server's is gone when its agent has no use for a computer of this provider (gone from the store, archived, or
218
+ * its setting not persistent here) and no run holds its computer now (heldNow): a run's computer is never deleted from
219
+ * under it, and that run's end deletes it. An owner with no server is no agent's of this server's, so never gone here.
220
+ */
221
+ export function ownerGoneOf(store, serverId, provider) {
222
+ return async (owner) => {
223
+ if (owner.server !== serverId)
224
+ return false;
225
+ if (await wantsOn(store, owner.agent, provider))
226
+ return false;
227
+ return !(await heldNow(store, owner.agent));
228
+ };
229
+ }
230
+ /** Whether the agent still has a use for a computer of `provider`: it is here, not archived, and persistent there. */
231
+ export async function wantsOn(store, agentId, provider) {
232
+ return (await wantedSetting(store, agentId))?.provider === provider;
233
+ }
234
+ /**
235
+ * Deletes the agent's computer when the agent has no use for it any more (wantsComputer), under the agent's hold: given
236
+ * `hold` (the run that holds it, at its end), under that one; else taken as a delete of this server's, and where a run
237
+ * holds it, nothing is done now: that run's end reconciles again. The record is moved to deleting, and goes once the
238
+ * provider has deleted the computer, each a replaceIf or removeIf on the record as read, so a record a later run wrote
239
+ * (a replacement) is never erased. A delete that fails keeps it deleting, with the provider's words, for the next
240
+ * reconcile or the janitor. `makeProvider` builds the computer's provider; it throws, in words, when it cannot. Answers
241
+ * what happened, or undefined when there was nothing to do now.
242
+ */
243
+ export async function reconcileAgentComputer(store, agentId, makeProvider, hold) {
244
+ if (!(await unwantedRecord(store, agentId)))
245
+ return undefined;
246
+ if (hold !== undefined)
247
+ return (await hold.holds()) ? deleteUnwanted(store, agentId, makeProvider) : undefined;
248
+ let own;
249
+ try {
250
+ own = await holdAgentComputer(store, agentId, `${DELETER}${randomBytes(6).toString("hex")}`, liveHolderOf(store), { until: Date.now() + HOLD_RELEASE_MS });
251
+ }
252
+ catch (error) {
253
+ if (error instanceof HeldComputer)
254
+ return undefined;
255
+ throw error;
256
+ }
257
+ try {
258
+ return await deleteUnwanted(store, agentId, makeProvider);
259
+ }
260
+ finally {
261
+ await own.letGo();
262
+ }
263
+ }
264
+ /** The agent's record, where the agent has no use for its computer any more; else undefined. */
265
+ async function unwantedRecord(store, agentId) {
266
+ const record = await agentComputerOf(store, agentId);
267
+ return record && !(await wantsComputer(store, agentId, record.provider, record.image)) ? record : undefined;
268
+ }
269
+ /** reconcileAgentComputer's delete, once the caller holds the agent's computer: the record read again under the hold. */
270
+ async function deleteUnwanted(store, agentId, makeProvider) {
271
+ const record = await unwantedRecord(store, agentId);
272
+ if (!record)
273
+ return undefined;
274
+ const deleting = recordOf(record, "deleting");
275
+ if (!(await store.settings.replaceIf(recordKey(agentId), record, deleting)))
276
+ return undefined;
277
+ let why;
278
+ try {
279
+ const provider = await makeProvider(record.provider, record.image);
280
+ const released = await provider.release({ id: record.id, name: record.name }, "delete");
281
+ if (released.ok) {
282
+ await store.settings.removeIf(recordKey(agentId), deleting);
283
+ return { deleted: record.name };
284
+ }
285
+ why = released.error.message;
286
+ }
287
+ catch (error) {
288
+ why = error instanceof Error ? error.message : String(error);
289
+ }
290
+ await store.settings.replaceIf(recordKey(agentId), deleting, recordOf(record, "deleting", { why }));
291
+ return { failed: why };
292
+ }
@@ -2,6 +2,8 @@ import { ARCHIL_API_KEY_ROW, type ArchilSettings } from "../archil-settings.js";
2
2
  import type { KeyEnv } from "../key-meta.js";
3
3
  import type { SealedKeys } from "../store/store.js";
4
4
  import { type ArchilDisk, type ArchilDiskOptions, type ArchilImage } from "./archil-disk.js";
5
+ import type { LaunchDisk } from "../run-launch.js";
6
+ import { type RunDisk, type RunDiskOptions } from "./run-disk.js";
5
7
  export { ARCHIL_API_KEY_ROW, type ArchilSettings };
6
8
  /** A claim this step refused, in words a person reads: no Archil call was made. */
7
9
  export declare class ArchilClaimRefused extends Error {
@@ -35,10 +37,19 @@ export interface ArchilClaimOptions {
35
37
  };
36
38
  /** The server's environment, passed in (never read here): an ARCHIL_API_KEY variable overrides the saved key. */
37
39
  readonly env?: KeyEnv;
40
+ /** The run whose disk the claim resolves (run-disk.ts runDiskOf): its agent, the disk its launch record names, and the
41
+ * store the agent's disk and the server's id are kept in. */
42
+ readonly run: {
43
+ readonly agentId: string;
44
+ readonly launch?: LaunchDisk;
45
+ readonly store: RunDiskOptions["store"];
46
+ };
38
47
  }
39
48
  export interface ArchilClaim {
40
49
  /** The claim's disk: its key is this step's, asked for on every call. */
41
50
  readonly disk: ArchilDisk;
51
+ /** Whose disk it is: the run's launch named it (a customer's), or it is the run's agent's. */
52
+ readonly diskKind: RunDisk["kind"];
42
53
  /** The disk's region (a computer's mount names it). */
43
54
  readonly region: string;
44
55
  /** The exec image, pinned by digest: the saved one, else DEFAULT_ARCHIL_EXEC_IMAGE. */
@@ -1,5 +1,6 @@
1
1
  // The Archil claim step: once per claim in Mode 2, before the run's loop starts, the claim's Archil disk is made from the
2
- // server's Archil settings (archil-settings.ts, the store's one settings row) and its keys come from the store's
2
+ // server's Archil settings (archil-settings.ts, the store's one settings row) on the run's own disk (run-disk.ts: the one
3
+ // its launch names, else its agent's, made on its first run), and its keys come from the store's
3
4
  // sealed_keys rows under archil-settings.ts's names, opened with the runner's seal key. A saved exec image must be pinned
4
5
  // by digest (`<name>@sha256:<64 hex>`): any other refuses the claim before a key is read. With none saved, the exec runs
5
6
  // in DEFAULT_ARCHIL_EXEC_IMAGE, never Archil's own default (its git is older than a bash policy's floor).
@@ -20,6 +21,7 @@ import { archilApiKey } from "./archil-key.js";
20
21
  import { archilDisk, pinnedImage } from "./archil-disk.js";
21
22
  import { mintMountToken, nicknameOf, removeMountToken, removeOlderMountTokens, removeRunMountTokens } from "./archil-mount-credential.js";
22
23
  import { COMPUTER_LIFETIME_MS } from "./computer-deps.js";
24
+ import { runDiskOf } from "./run-disk.js";
23
25
  export { ARCHIL_API_KEY_ROW };
24
26
  /** A claim this step refused, in words a person reads: no Archil call was made. */
25
27
  export class ArchilClaimRefused extends Error {
@@ -36,7 +38,7 @@ const LOST_MINT_REREAD_MS = 2_000;
36
38
  export async function archilClaim(options) {
37
39
  const { settings, sealKey } = options;
38
40
  if (settings === undefined) {
39
- throw new ArchilClaimRefused("This server's Archil disk is not set up (its disk, region and S3 endpoint): Mode 2 keeps a run's folder on it, so the run can't start.");
41
+ throw new ArchilClaimRefused("This server's Archil disk is not set up (its key's region and S3 endpoint): Mode 2 keeps a run's folder on an Archil disk, so the run can't start.");
40
42
  }
41
43
  let image;
42
44
  try {
@@ -51,10 +53,21 @@ export async function archilClaim(options) {
51
53
  let released = false;
52
54
  const apiKey = (await archilApiKey({ ...(options.env ? { env: options.env } : {}), keys: options.keys, sealKey })).value;
53
55
  held.add(apiKey);
56
+ // The run's disk first (run-disk.ts): its launch's, else its agent's, made now when it has none; every call below is on
57
+ // it alone, the run's mount credential minted, revoked and reclaimed there.
58
+ const control = { region: settings.region, key: () => apiKey, ...(options.mount?.baseUrl ? { baseUrl: options.mount.baseUrl } : {}), ...(options.mount?.fetch ? { fetch: options.mount.fetch } : {}) };
59
+ let chosen;
60
+ try {
61
+ chosen = await runDiskOf({ store: options.run.store, agentId: options.run.agentId, ...(options.mount ? { runId: options.mount.runId } : {}), ...(options.run.launch ? { launch: options.run.launch } : {}), control, signal: options.signal });
62
+ }
63
+ catch (error) {
64
+ held.clear();
65
+ throw error;
66
+ }
54
67
  let disk;
55
68
  try {
56
69
  disk = (options.makeDisk ?? archilDisk)({
57
- disk: settings.diskId,
70
+ disk: chosen.diskId,
58
71
  region: settings.region,
59
72
  s3BaseUrl: settings.s3Url,
60
73
  key: () => {
@@ -68,13 +81,7 @@ export async function archilClaim(options) {
68
81
  held.clear();
69
82
  throw new ArchilClaimRefused(`This server's Archil settings can't make its disk: ${error.message}`, { cause: error });
70
83
  }
71
- const credentialOptions = {
72
- disk: settings.diskId,
73
- region: settings.region,
74
- key: () => apiKey,
75
- ...(options.mount?.baseUrl ? { baseUrl: options.mount.baseUrl } : {}),
76
- ...(options.mount?.fetch ? { fetch: options.mount.fetch } : {}),
77
- };
84
+ const credentialOptions = { ...control, disk: chosen.diskId };
78
85
  let minted;
79
86
  /** A mint was asked for since the last revoke: its user may stand at Archil though no answer said so. */
80
87
  let asked = false;
@@ -122,6 +129,7 @@ export async function archilClaim(options) {
122
129
  lost();
123
130
  return {
124
131
  disk,
132
+ diskKind: chosen.kind,
125
133
  region: settings.region,
126
134
  image,
127
135
  secrets: held,