@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
package/dist/box-relay.js DELETED
@@ -1,207 +0,0 @@
1
- // The box relay: how a run's process reaches its Daytona box without Daytona's key. The key is the server's alone
2
- // (BOX_KEYS, SERVER_ONLY in runs.ts), so a run's Daytona provider sends each of its calls here instead, on loopback with
3
- // its run's own door token (RUN_DOOR_TOKEN, the token its door takes, handed to that run's process alone), and the relay
4
- // sends it on with the key only when it is one of the calls a run's tools make of that run's own box: a read of the
5
- // sandbox, its toolbox's address, and its toolbox's programs and files. Nothing else passes: no call for another run (its
6
- // token is not this one), no create, listing, stop or delete (the server makes and seeds the box, pulls its work/ back
7
- // and destroys it), no call to a sandbox that does not carry the run's label, and no redirect, ever followed: one would
8
- // carry the key. The relay's address is a file in the data directory, read again at each call, so a run's process that
9
- // outlives its server reaches the next one. A run in the VM box reaches it the same way, through the VM half
10
- // (box-relay-vm.ts), which makes the calls with the server's own client.
11
- import { createHash, timingSafeEqual } from "node:crypto";
12
- import { readFile, rm } from "node:fs/promises";
13
- import { createServer } from "node:http";
14
- import { join } from "node:path";
15
- import { Readable } from "node:stream";
16
- import { daytonaCall, redirectRefusal } from "./daytona-api.js";
17
- import { readJson, RUN_DOOR_TOKEN, writeWhole } from "./files.js";
18
- /** The relay's address in the data directory: `{"url": "http://<loopback>:<port>"}`. */
19
- export const BOX_RELAY_FILE = ".box-relay";
20
- /** Where the relay listens: only this machine's runs reach it. */
21
- const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule the relay listens on loopback only, for the runs of this machine
22
- /** The header that names the Daytona URL a relayed call is for. */
23
- const TARGET = "x-agentrun-target";
24
- /** The label that names a box's run (run-box.ts RUN_LABEL), kept here so the run's process loads no more than it needs. */
25
- const RUN_LABEL = "agentrun.run";
26
- /** The most bytes one relayed call may send: a file a tool writes, or a program's input. */
27
- const MAX_BODY_BYTES = 64 * 2 ** 20;
28
- /** The toolbox calls a run's tools make, by their route after the sandbox's id, and the one method each takes. */
29
- const TOOLBOX = { "process/execute": "POST", "files/upload-v2": "POST", "files/download": "GET", "files/permissions": "POST" };
30
- /** The most sandboxes the relay remembers the run of; past it, it asks Daytona again. */
31
- const KNOWN_MAX = 1024;
32
- const digest = (text) => createHash("sha256").update(text).digest();
33
- /** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
34
- export async function startBoxRelay(options) {
35
- const base = (options.apiUrl ?? "").replace(/\/+$/, "");
36
- const upstream = options.fetch ?? fetch;
37
- const api = { apiUrl: base, apiKey: options.apiKey ?? "", ...(options.fetch ? { fetch: options.fetch } : {}) };
38
- // Each sandbox's run (its label) and its toolbox's address, as Daytona answered the server: neither changes.
39
- const known = new Map();
40
- const remember = (id, value) => {
41
- if (known.size >= KNOWN_MAX)
42
- known.clear();
43
- known.set(id, value);
44
- };
45
- /** The run whose label sandbox `id` carries, as Daytona says; undefined for a sandbox that has none, or is not there. */
46
- const runOf = async (id) => {
47
- const held = known.get(id);
48
- if (held)
49
- return held.run;
50
- const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}`);
51
- if (answer.status === 404)
52
- return undefined;
53
- if (!answer.ok)
54
- throw new Error(`Daytona answered ${answer.status} to the read of a sandbox`);
55
- const info = (await answer.json().catch(() => null));
56
- const run = typeof info?.labels?.[RUN_LABEL] === "string" ? info.labels[RUN_LABEL] : undefined;
57
- remember(id, { run, ...(typeof info?.toolboxProxyUrl === "string" ? { proxy: info.toolboxProxyUrl } : {}) });
58
- return run;
59
- };
60
- /** Sandbox `id`'s toolbox address, without a trailing slash. */
61
- const proxyOf = async (id) => {
62
- const held = known.get(id);
63
- if (held?.proxy)
64
- return held.proxy.replace(/\/+$/, "");
65
- const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}/toolbox-proxy-url`);
66
- if (!answer.ok)
67
- return undefined;
68
- const url = (await answer.json().catch(() => null))?.url;
69
- if (typeof url !== "string")
70
- return undefined;
71
- if (held)
72
- held.proxy = url;
73
- return url.replace(/\/+$/, "");
74
- };
75
- /** The sandbox a relayed call is for, when it is one a run's tools make; else why not. */
76
- const sandboxOf = async (method, target) => {
77
- const call = `${method} ${target.origin}${target.pathname}`;
78
- const refused = { refused: `the box relay does not send ${call}: a run's process reaches only its own box's programs and files` };
79
- const api = `${base}/sandbox/`;
80
- const whole = `${target.origin}${target.pathname}`;
81
- if (whole.startsWith(api)) {
82
- // A read of the sandbox (attach, status) or of its toolbox's address: GET, no query.
83
- const named = /^([^/]+)(\/toolbox-proxy-url)?$/.exec(whole.slice(api.length));
84
- if (!named || method !== "GET" || target.search)
85
- return refused;
86
- return { id: decodeURIComponent(named[1]) };
87
- }
88
- const routed = /^(.+)\/([^/]+)\/(process\/execute|files\/upload-v2|files\/download|files\/permissions)$/.exec(whole);
89
- if (!routed || TOOLBOX[routed[3]] !== method)
90
- return refused;
91
- const id = decodeURIComponent(routed[2]);
92
- // The toolbox call goes only to the address Daytona gives that sandbox's toolbox: never to a host the call names.
93
- if ((await runOf(id)) === undefined || (await proxyOf(id)) !== routed[1])
94
- return refused;
95
- return { id };
96
- };
97
- const answer = (res, status, body) => {
98
- res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
99
- res.end(JSON.stringify(body));
100
- };
101
- const forward = async (runId, req, res) => {
102
- const method = req.method ?? "GET";
103
- const target = URL.parse(String(req.headers[TARGET] ?? ""));
104
- if (!target)
105
- return answer(res, 400, { message: `a relayed call names its Daytona URL in ${TARGET}` });
106
- const named = await sandboxOf(method, target);
107
- if ("refused" in named)
108
- return answer(res, 403, { message: named.refused });
109
- // A sandbox of another run, or of none, is not there for this one: as Daytona answers a sandbox it does not have.
110
- if ((await runOf(named.id)) !== runId)
111
- return answer(res, 404, { statusCode: 404, message: "sandbox not found" });
112
- const body = method === "GET" ? undefined : await bytesOf(req);
113
- if (body === null)
114
- return answer(res, 413, { message: `a relayed call sends at most ${MAX_BODY_BYTES} bytes` });
115
- const abort = new AbortController();
116
- res.once("close", () => void (res.writableFinished || abort.abort()));
117
- const type = req.headers["content-type"];
118
- let sent;
119
- try {
120
- sent = await upstream(target.href, {
121
- method,
122
- headers: { authorization: `Bearer ${options.apiKey}`, "x-daytona-source": "pi-transport", ...(type ? { "content-type": type } : {}) },
123
- ...(body ? { body: new Uint8Array(body) } : {}),
124
- // Never followed: a box that holds its toolbox's port could point the key at another run's sandbox.
125
- redirect: "error",
126
- signal: abort.signal,
127
- });
128
- }
129
- catch (error) {
130
- const refused = redirectRefusal(error);
131
- if (refused)
132
- return answer(res, 502, { message: `the box relay refuses ${method} ${target.pathname}: ${refused}` });
133
- throw error;
134
- }
135
- res.writeHead(sent.status, { "content-type": sent.headers.get("content-type") ?? "application/octet-stream", "cache-control": "no-store" });
136
- if (!sent.body)
137
- return void res.end();
138
- Readable.fromWeb(sent.body).on("error", () => res.destroy()).pipe(res);
139
- };
140
- const server = createServer((req, res) => {
141
- void (async () => {
142
- const path = /^\/runs\/([^/]+)\/(box|daytona|vm\/.+)$/.exec(new URL(req.url ?? "/", "http://relay").pathname);
143
- const runId = path ? decodeURIComponent(path[1]) : "";
144
- // The calling run's own token, and only for its own run: one run's process never speaks for another's.
145
- const token = path ? options.tokenOf(runId) : undefined;
146
- const auth = String(req.headers.authorization ?? "");
147
- if (!path || !token || !timingSafeEqual(digest(auth), digest(`Bearer ${token}`)))
148
- return answer(res, 401, { message: "the box relay takes a run's call only with that run's own door token" });
149
- if (!options.serves(runId))
150
- return answer(res, 404, { message: "no run of this server is in a remote box by that id" });
151
- if (path[2] === "box") {
152
- if (req.method !== "POST")
153
- return answer(res, 405, { message: "POST asks for the run's box" });
154
- const box = await options.ensure(runId);
155
- remember(box.id, { run: runId });
156
- return answer(res, 200, { id: box.id, made: box.made, ...(box.replaced ? { replaced: true } : {}), ...(options.apiKey ? { api_url: base } : {}) });
157
- }
158
- if (path[2].startsWith("vm/"))
159
- return options.vm ? options.vm.handle(runId, path[2].slice(3), req, res) : answer(res, 404, { message: "this server has no Modal sandbox" });
160
- if (!options.apiKey)
161
- return answer(res, 404, { message: "this server has no Daytona box" });
162
- return forward(runId, req, res);
163
- })().catch((error) => {
164
- if (res.headersSent)
165
- return void res.destroy();
166
- // The cause's message only: no header, key or answer's body of Daytona's is in it.
167
- answer(res, 502, { message: `the box relay could not complete the call: ${error?.message ?? String(error)}` });
168
- });
169
- });
170
- await new Promise((resolve, reject) => {
171
- server.once("error", reject);
172
- server.listen(0, LOOPBACK, () => resolve());
173
- });
174
- const url = `http://${LOOPBACK}:${server.address().port}`;
175
- await writeWhole(join(options.root, BOX_RELAY_FILE), `${JSON.stringify({ url })}\n`);
176
- return {
177
- url,
178
- close: async () => {
179
- await rm(join(options.root, BOX_RELAY_FILE), { force: true });
180
- await new Promise((resolve) => {
181
- server.closeAllConnections();
182
- server.close(() => resolve());
183
- });
184
- },
185
- };
186
- }
187
- /** A request's body, or null past MAX_BODY_BYTES. */
188
- async function bytesOf(req) {
189
- const parts = [];
190
- let size = 0;
191
- for await (const part of req) {
192
- size += part.length;
193
- if (size > MAX_BODY_BYTES)
194
- return null;
195
- parts.push(part);
196
- }
197
- return Buffer.concat(parts);
198
- }
199
- /** The relay's address, from the data directory `root`, and the run's own door token, from its directory `runDir`: read
200
- * at each call. */
201
- export async function relayAddress(root, runDir) {
202
- const [file, token] = await Promise.all([readJson(join(root, BOX_RELAY_FILE)), readFile(join(runDir, RUN_DOOR_TOKEN), "utf8").catch(() => "")]);
203
- const url = file && typeof file === "object" && !Array.isArray(file) && typeof file.url === "string" ? file.url : undefined;
204
- if (!url || !token.trim())
205
- throw new Error("this server's box relay is not running, and a run reaches its remote box only through it");
206
- return { url, token: token.trim() };
207
- }
package/dist/boxes.d.ts DELETED
@@ -1,109 +0,0 @@
1
- import type { BoxProvider } from "@parcha/pi-transport";
2
- /** Why the VM box has no network, said in capabilities whenever the server's host list is set: its provider's SDK takes
3
- * a domain list at a sandbox's create, but has no read of a sandbox's network back, so the server could not check that
4
- * a box holds the list it asked for (as it does Daytona's), and it never leaves the provider's open default either. */
5
- export declare const VM_NO_LIST = "the Modal sandbox takes a host list, but this server cannot read a sandbox's list back to check that it holds, so the Modal sandbox has no network";
6
- /** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
7
- export declare const VM_PROVIDER: {
8
- readonly id: "modal";
9
- readonly client: "ModalClient";
10
- readonly keys: readonly ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"];
11
- };
12
- /** Every box a place may name, in the order capabilities lists them. */
13
- export declare const BOX_IDS: readonly ["bwrap", "docker", "modal", "daytona"];
14
- export type BoxId = (typeof BOX_IDS)[number];
15
- /** One box: whether this server has it, and why when not (or how it was checked). `state`, set where the server knows
16
- * more than the probe did (box-image.ts): `preparing` is available, its image still coming. */
17
- /** A box as capabilities show it. `network`: what an available box reaches (BOX_NETWORKS), with `network_reason` when
18
- * it is available and has none for a cause of its own (a Docker in a VM, a daemon elsewhere; a Daytona that could not
19
- * keep its domain list). `host_addresses`: for Docker from a container (compose.yaml), the Docker host's own addresses
20
- * its computers' egress proxy refuses as the host's (docker-host-addresses.ts: the read through the socket and
21
- * AGENTRUN_DOCKER_HOST_ADDRESSES). */
22
- export type BoxOffer = {
23
- id: BoxId;
24
- available: boolean;
25
- state?: BoxState;
26
- reason?: string;
27
- network?: BoxNetwork;
28
- network_reason?: string;
29
- host_addresses?: string[];
30
- };
31
- /** What an available box reaches: the hosts of `places.allow` (`allowlist`), or nothing (`none`). */
32
- export declare const BOX_NETWORKS: readonly ["allowlist", "none"];
33
- export type BoxNetwork = (typeof BOX_NETWORKS)[number];
34
- /** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
35
- export declare const BOX_STATES: readonly ["ready", "preparing", "unavailable"];
36
- export type BoxState = (typeof BOX_STATES)[number];
37
- /** The boxes this server set up at its start. */
38
- export type BoxRegistry = {
39
- /** Every box, in BOX_IDS order. */
40
- offers(): BoxOffer[];
41
- /** An available box's provider; undefined for any other. */
42
- provider(id: BoxId): BoxProvider | undefined;
43
- /** The VM box's SDK client, when it is available: the box relay makes a run's calls with it (box-relay-vm.ts). */
44
- vmClient(): unknown;
45
- };
46
- /** What boxRegistry takes beyond the environment: the probes' bound, and, for tests only, the module that stands in for
47
- * the VM provider's SDK (startServe's `fauxVm`, under --faux) and the group file and this process's groups that say
48
- * whether a refused docker socket is a membership granted since this process started (`groups`). */
49
- export type BoxRegistryOptions = {
50
- timeoutMs?: number;
51
- vmSdk?: () => Promise<Record<string, unknown>>;
52
- groups?: {
53
- file: string;
54
- user: string;
55
- ids: readonly number[];
56
- };
57
- };
58
- /** The setting that lists the boxes to set up: a comma list of box ids, empty or `none` for no box. */
59
- export declare const BOXES_ENV = "AGENTRUN_BOXES";
60
- /** The boxes a server sets up when AGENTRUN_BOXES is not set at all: Docker, probed as if listed. */
61
- export declare const DEFAULT_BOXES: readonly BoxId[];
62
- /** The VM provider's app, which its sandboxes live in (made when missing). */
63
- export declare const BOX_APP_ENV = "AGENTRUN_BOX_APP";
64
- /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
65
- export declare const DAYTONA_API_URL = "https://app.daytona.io/api";
66
- /** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
67
- * key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
68
- export declare function daytonaApi(env: NodeJS.ProcessEnv): {
69
- apiKey: string;
70
- apiUrl: string;
71
- } | undefined;
72
- /** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
73
- export declare const BOX_KEYS: readonly string[];
74
- /** Why docker is unavailable when its daemon refuses this server's process its socket (EACCES on /var/run/docker.sock)
75
- * and the group file lists this user in the docker group: this process started before the user joined it (a systemd
76
- * user manager that has run since, kept by linger), so a restart of that manager, or a new login, gives it the group. */
77
- export declare const DOCKER_NOT_IN_GROUP = "This server's process isn't in the docker group: restart your user manager with `sudo systemctl restart user@$(id -u)`, or log in again if linger is off";
78
- /** The same, when the group file does not list this user in the docker group (or cannot say): joining comes first. */
79
- export declare const DOCKER_JOIN_GROUP = "This server's process isn't in the docker group: add this user to it with `sudo usermod -aG docker $USER`, then restart your user manager with `sudo systemctl restart user@$(id -u)`, or log in again if linger is off";
80
- /** How long one box's probe may take; the probes run at once, so this bounds them all. */
81
- export declare const PROBE_TIMEOUT_MS = 5000;
82
- /** Whether `env` leaves the boxes to this server's default (DEFAULT_BOXES): AGENTRUN_BOXES is not set at all. */
83
- export declare const boxesByDefault: (env: NodeJS.ProcessEnv) => boolean;
84
- /** The boxes `env` lists in AGENTRUN_BOXES, DEFAULT_BOXES when it is not set, none when it is empty or `none`; a name
85
- * that is no box throws, naming it, and so does `none` with another. */
86
- export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
87
- /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
88
- * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
89
- * unavailable, with a short reason that holds no key and no answer's body. */
90
- export declare function boxRegistry(env: NodeJS.ProcessEnv, options?: BoxRegistryOptions): Promise<BoxRegistry>;
91
- /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
92
- export declare function boxesLog(offers: readonly BoxOffer[], listed: ReadonlySet<BoxId>): Record<string, string>;
93
- /** What `docker version` says of this machine's Docker daemon: it answers (`up`), or why not. `absent`: no daemon
94
- * answers this process (no docker command, a call that fails, or one that names no daemon); not absent: one is there,
95
- * and its socket refuses this process (the group it lacks). */
96
- export type DockerDaemon = {
97
- readonly up: true;
98
- } | {
99
- readonly up: false;
100
- readonly absent: boolean;
101
- readonly reason: string;
102
- };
103
- /** Asks this machine's Docker daemon its version (`docker version`), as the Docker box's start probe and the Docker
104
- * computer's check (docker-daemon.ts) do: the CLI is on PATH and its daemon answers this user. `signal` bounds it. */
105
- export declare function askDockerDaemon(env: NodeJS.ProcessEnv, signal: AbortSignal, groups?: {
106
- file: string;
107
- user: string;
108
- ids: readonly number[];
109
- }): Promise<DockerDaemon>;
package/dist/boxes.js DELETED
@@ -1,249 +0,0 @@
1
- // The boxes this server can give a run: Docker, Daytona and a VM provider, each a pi-transport provider built from the
2
- // server's settings and probed once at its start. bwrap comes later. The registry says which boxes this server has, why
3
- // it lacks the others, and hands out an available box's provider (and the VM box's client, for the box relay).
4
- //
5
- // AGENTRUN_BOXES lists the boxes to set up. Not set at all, it is docker alone (DEFAULT_BOXES): a plain start probes
6
- // Docker and offers it when Docker answers, so a new agent lands in its box (place.ts); every other box is the operator's
7
- // to list. Set, it wins: a box it does not list is never probed and is unavailable, its reason naming the setting that
8
- // lists it, an empty value or `none` sets up no box, and a name in it that is no box refuses the start. Every reason says
9
- // what to do next.
10
- // pi-transport is a dependency of this package (a plain install has the Docker box) and the VM provider's SDK is the
11
- // host's; each is loaded by the
12
- // probe that needs it, and a box whose module is not installed says what to install. The keys are the server's own: the
13
- // launcher hands them over with its other secrets (secrets.ts), the probes read them here, and no run's process is
14
- // handed one (SERVER_ONLY in runs.ts).
15
- import { execFile } from "node:child_process";
16
- import { randomUUID } from "node:crypto";
17
- import { readFile } from "node:fs/promises";
18
- import { userInfo } from "node:os";
19
- import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
20
- import { withoutSecrets } from "./secrets.js";
21
- /** Why the VM box has no network, said in capabilities whenever the server's host list is set: its provider's SDK takes
22
- * a domain list at a sandbox's create, but has no read of a sandbox's network back, so the server could not check that
23
- * a box holds the list it asked for (as it does Daytona's), and it never leaves the provider's open default either. */
24
- export const VM_NO_LIST = "the Modal sandbox takes a host list, but this server cannot read a sandbox's list back to check that it holds, so the Modal sandbox has no network";
25
- /** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
26
- export const VM_PROVIDER = { id: "modal", client: "ModalClient", keys: ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"] };
27
- const VM = VM_PROVIDER.id;
28
- /** Every box a place may name, in the order capabilities lists them. */
29
- export const BOX_IDS = ["bwrap", "docker", VM, "daytona"];
30
- /** What an available box reaches: the hosts of `places.allow` (`allowlist`), or nothing (`none`). */
31
- export const BOX_NETWORKS = ["allowlist", "none"];
32
- /** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
33
- export const BOX_STATES = ["ready", "preparing", "unavailable"];
34
- /** The setting that lists the boxes to set up: a comma list of box ids, empty or `none` for no box. */
35
- export const BOXES_ENV = "AGENTRUN_BOXES";
36
- /** The boxes a server sets up when AGENTRUN_BOXES is not set at all: Docker, probed as if listed. */
37
- export const DEFAULT_BOXES = ["docker"];
38
- /** The AGENTRUN_BOXES that sets up no box, as an empty one does. */
39
- const NO_BOXES = "none";
40
- /** The VM provider's app, which its sandboxes live in (made when missing). */
41
- export const BOX_APP_ENV = "AGENTRUN_BOX_APP";
42
- const DEFAULT_BOX_APP = "agentrun";
43
- const DAYTONA_KEY = "DAYTONA_API_KEY";
44
- /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
45
- export const DAYTONA_API_URL = "https://app.daytona.io/api";
46
- /** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
47
- * key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
48
- export function daytonaApi(env) {
49
- const apiKey = env[DAYTONA_KEY];
50
- return apiKey ? { apiKey, apiUrl: env.DAYTONA_API_URL || DAYTONA_API_URL } : undefined;
51
- }
52
- /** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
53
- export const BOX_KEYS = [DAYTONA_KEY, ...VM_PROVIDER.keys];
54
- /** Why docker is unavailable when its daemon refuses this server's process its socket (EACCES on /var/run/docker.sock)
55
- * and the group file lists this user in the docker group: this process started before the user joined it (a systemd
56
- * user manager that has run since, kept by linger), so a restart of that manager, or a new login, gives it the group. */
57
- export const DOCKER_NOT_IN_GROUP = "This server's process isn't in the docker group: restart your user manager with `sudo systemctl restart user@$(id -u)`, or log in again if linger is off";
58
- /** The same, when the group file does not list this user in the docker group (or cannot say): joining comes first. */
59
- export const DOCKER_JOIN_GROUP = "This server's process isn't in the docker group: add this user to it with `sudo usermod -aG docker $USER`, then restart your user manager with `sudo systemctl restart user@$(id -u)`, or log in again if linger is off";
60
- /** Whether the group file lists `user` in the docker group while this process's groups (`ids`) lack that group: a
61
- * membership granted after this process started. False when it cannot say (no file, no docker group, users listed
62
- * elsewhere, as a directory service lists them). */
63
- async function joinedSince(groups) {
64
- const line = (await readFile(groups.file, "utf8").catch(() => "")).split("\n").find((entry) => entry.startsWith("docker:"));
65
- if (!line)
66
- return false;
67
- const [, , gid, members = ""] = line.split(":");
68
- return groups.user !== "" && members.split(",").map((name) => name.trim()).includes(groups.user) && !groups.ids.includes(Number(gid));
69
- }
70
- /** This process's user and groups, read from the system's group file: the probe's default for `groups`. A user with no
71
- * name (a numeric uid with no passwd entry, as in a container) is none: membership cannot be checked, so joining is said. */
72
- const ownGroups = () => {
73
- let user = "";
74
- try {
75
- user = userInfo().username;
76
- }
77
- catch { }
78
- return { file: "/etc/group", user, ids: process.getgroups?.() ?? [] };
79
- };
80
- /** docker's own words for a socket that refused this process (the CLI's, or the connect's EACCES). Matched, never shown. */
81
- const SOCKET_DENIED = /permission denied while trying to connect to the docker daemon socket|docker\.sock: connect: permission denied/i;
82
- /** How long one box's probe may take; the probes run at once, so this bounds them all. */
83
- export const PROBE_TIMEOUT_MS = 5_000;
84
- /** Why box `id` is unavailable when AGENTRUN_BOXES does not list it: the setting that does, keeping what it lists now. */
85
- const notEnabled = (id, enabled) => `not enabled on this server: start AgentRun with ${BOXES_ENV}=${BOX_IDS.filter((box) => box === id || enabled.has(box)).join(",")}`;
86
- const NOT_YET = "the bwrap box is not in this release yet: use the docker box";
87
- const NOT_PROBED = "configured; not probed at start";
88
- const TRANSPORT = "@parcha/pi-transport";
89
- const unavailable = (id, reason) => ({ offer: { id, available: false, reason } });
90
- const available = (id, provider, reason, client) => ({ offer: { id, available: true, ...(reason ? { reason } : {}) }, provider, ...(client === undefined ? {} : { client }) });
91
- /** Whether `env` leaves the boxes to this server's default (DEFAULT_BOXES): AGENTRUN_BOXES is not set at all. */
92
- export const boxesByDefault = (env) => env[BOXES_ENV] === undefined;
93
- /** The boxes `env` lists in AGENTRUN_BOXES, DEFAULT_BOXES when it is not set, none when it is empty or `none`; a name
94
- * that is no box throws, naming it, and so does `none` with another. */
95
- export function enabledBoxes(env) {
96
- if (boxesByDefault(env))
97
- return new Set(DEFAULT_BOXES);
98
- const names = env[BOXES_ENV].split(",").map((name) => name.trim()).filter(Boolean);
99
- if (names.includes(NO_BOXES)) {
100
- if (names.length > 1)
101
- throw new Error(`${BOXES_ENV}=${NO_BOXES} sets up no box, so it names no other: list the boxes to set up, or ${NO_BOXES} alone`);
102
- return new Set();
103
- }
104
- const unknown = names.filter((name) => !BOX_IDS.includes(name));
105
- if (unknown.length)
106
- throw new Error(`${BOXES_ENV} names ${unknown.join(", ")}, which ${unknown.length === 1 ? "is not a box" : "are not boxes"}: list any of ${BOX_IDS.join(", ")}`);
107
- return new Set(names);
108
- }
109
- /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
110
- * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
111
- * unavailable, with a short reason that holds no key and no answer's body. */
112
- export async function boxRegistry(env, options = {}) {
113
- const enabled = enabledBoxes(env);
114
- const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
115
- const probed = await Promise.all(BOX_IDS.map((id) => {
116
- if (id === "bwrap")
117
- return unavailable(id, NOT_YET);
118
- if (!enabled.has(id))
119
- return unavailable(id, notEnabled(id, enabled));
120
- return bounded(id, timeoutMs, (signal) => PROBES[id](env, signal, options));
121
- }));
122
- return {
123
- offers: () => probed.map(({ offer }) => ({ ...offer })),
124
- provider: (id) => probed.find(({ offer }) => offer.id === id && offer.available)?.provider,
125
- vmClient: () => probed.find(({ offer }) => offer.id === VM && offer.available)?.client,
126
- };
127
- }
128
- /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
129
- export function boxesLog(offers, listed) {
130
- const ids = (yes) => offers.filter((offer) => offer.available === yes).map((offer) => offer.id).join(",") || "none";
131
- const why = offers.filter((offer) => !offer.available && listed.has(offer.id));
132
- return { available: ids(true), unavailable: ids(false), ...Object.fromEntries(why.map((offer) => [offer.id, offer.reason ?? ""])) };
133
- }
134
- /** `probe`, aborted after `timeoutMs`. Never rejects. */
135
- async function bounded(id, timeoutMs, probe) {
136
- const controller = new AbortController();
137
- let timer;
138
- const late = new Promise((resolve) => {
139
- timer = setTimeout(() => {
140
- controller.abort();
141
- resolve(unavailable(id, id === "docker" ? `Docker isn't answering on this machine (docker version took over ${timeoutMs} ms): start Docker, then restart AgentRun` : `its probe did not finish within ${timeoutMs} ms`));
142
- }, timeoutMs);
143
- });
144
- try {
145
- return await Promise.race([probe(controller.signal).catch((error) => unavailable(id, `its probe failed (${errorName(error)})`)), late]);
146
- }
147
- finally {
148
- clearTimeout(timer);
149
- }
150
- }
151
- /** What kind of error, never its message: a message can hold an answer's body, a path or a key. */
152
- function errorName(error) {
153
- const code = error?.code;
154
- if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code))
155
- return code;
156
- return error instanceof Error ? error.name : "not an error";
157
- }
158
- /** A module of package `name`, which may not be installed: then the box says to install it. */
159
- async function load(name, importer) {
160
- try {
161
- return { ok: true, value: await importer() };
162
- }
163
- catch (error) {
164
- const missing = error?.code === "ERR_MODULE_NOT_FOUND" && String(error.message).includes(`'${name}'`);
165
- return { ok: false, reason: missing ? `install ${name} to use this box` : `${name} did not load (${errorName(error)})` };
166
- }
167
- }
168
- /** Asks this machine's Docker daemon its version (`docker version`), as the Docker box's start probe and the Docker
169
- * computer's check (docker-daemon.ts) do: the CLI is on PATH and its daemon answers this user. `signal` bounds it. */
170
- export async function askDockerDaemon(env, signal, groups = ownGroups()) {
171
- // Its environment is the server's through the cut a run's takes (withoutSecrets): no box key, no other secret, no
172
- // name shaped like a key.
173
- const dockerEnv = withoutSecrets(env);
174
- const answer = await new Promise((resolve) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { env: dockerEnv, signal, maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {
175
- const code = error?.code;
176
- resolve({ ...(error ? { failed: typeof code === "number" ? `exit ${code}` : errorName(error), ...(SOCKET_DENIED.test(String(stderr)) ? { denied: true } : {}) } : {}), out: String(stdout) });
177
- }));
178
- const absent = (reason) => ({ up: false, absent: true, reason });
179
- // The box's probe runs once, at the start: each fix takes a restart. Docker is on by default, so its reason is often a
180
- // first-time user's first read: what is wrong in plain words, what the probe saw, then what to do.
181
- if (answer.failed === "ENOENT")
182
- return absent("Docker isn't running on this machine (no docker command on PATH): install or start Docker, then restart AgentRun");
183
- // Its socket refused this process: the group it lacks, and how to get it without a reboot (the words, never docker's):
184
- // a restart alone where the group file already lists this user, else joining it first.
185
- if (answer.denied)
186
- return { up: false, absent: false, reason: (await joinedSince(groups)) ? DOCKER_NOT_IN_GROUP : DOCKER_JOIN_GROUP };
187
- if (answer.failed)
188
- return absent(`Docker isn't running on this machine, or this user may not use it (docker version failed: ${answer.failed}): start Docker, or add this user to the docker group, then restart AgentRun`);
189
- if (!answer.out.trim())
190
- return absent("Docker isn't running on this machine (docker version named no daemon): start Docker, then restart AgentRun");
191
- return { up: true };
192
- }
193
- const PROBES = {
194
- /** `docker version` names the daemon's version: the CLI is on PATH and its daemon answers this user. */
195
- async docker(env, signal, options) {
196
- const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/docker").then((module) => module.dockerBoxes));
197
- if (!boxes.ok)
198
- return unavailable("docker", boxes.reason);
199
- const daemon = await askDockerDaemon(env, signal, options.groups);
200
- return daemon.up ? available("docker", boxes.value()) : unavailable("docker", daemon.reason);
201
- },
202
- /** One authenticated read the provider makes anyway: the box with a name no box has (lowercase letters, digits and
203
- * dashes). An answer of no such box (404) means Daytona took the key; 401 or 403 means it refused it. */
204
- async daytona(env, signal) {
205
- const apiKey = env[DAYTONA_KEY];
206
- if (!apiKey)
207
- return unavailable("daytona", `needs ${DAYTONA_KEY}`);
208
- const apiUrl = env.DAYTONA_API_URL || undefined;
209
- if (apiUrl !== undefined && !URL.canParse(apiUrl))
210
- return unavailable("daytona", "DAYTONA_API_URL is not a URL");
211
- const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/daytona").then((module) => module.daytonaBoxes));
212
- if (!boxes.ok)
213
- return unavailable("daytona", boxes.reason);
214
- const provider = boxes.value({ apiKey, ...(apiUrl ? { apiUrl } : {}), ...(env.DAYTONA_TARGET ? { target: env.DAYTONA_TARGET } : {}) });
215
- const found = await provider.attach(`agentrun-probe-${randomUUID()}`, withAbortSignal(signal, BACKGROUND_CONTEXT));
216
- if (found.ok)
217
- return available("daytona", provider);
218
- if (found.error.code === "unauthorized")
219
- return unavailable("daytona", `Daytona refused ${DAYTONA_KEY}`);
220
- return unavailable("daytona", `Daytona did not answer the probe (${found.error.code})`);
221
- },
222
- /** The SDK is installed and the token is set; nothing is asked of the provider at start. The client gets the token as
223
- * arguments: the server's environment does not hold it (secrets.ts). */
224
- async [VM](env, _signal, options) {
225
- const missing = VM_PROVIDER.keys.filter((name) => !env[name]);
226
- if (missing.length)
227
- return unavailable(VM, `needs ${missing.join(" and ")}`);
228
- const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/modal").then((module) => module.modalBoxes));
229
- if (!boxes.ok)
230
- return unavailable(VM, boxes.reason);
231
- const vmBoxes = boxes.value;
232
- // The SDK is not a dependency of this package (the host installs it), so its name is a value here, not a literal import.
233
- const sdk = await load(VM, options.vmSdk ?? (() => import(VM)));
234
- if (!sdk.ok)
235
- return unavailable(VM, sdk.reason);
236
- const Client = sdk.value[VM_PROVIDER.client];
237
- if (typeof Client !== "function")
238
- return unavailable(VM, `the installed ${VM} package has no ${VM_PROVIDER.client}`);
239
- const [tokenId, tokenSecret] = VM_PROVIDER.keys.map((name) => env[name]);
240
- let client;
241
- try {
242
- client = new Client({ tokenId, tokenSecret });
243
- }
244
- catch (error) {
245
- return unavailable(VM, `its SDK's client did not start (${errorName(error)})`);
246
- }
247
- return available(VM, vmBoxes(client, { appName: env[BOX_APP_ENV] || DEFAULT_BOX_APP }), NOT_PROBED, client);
248
- },
249
- };
package/dist/budget.d.ts DELETED
@@ -1,71 +0,0 @@
1
- import { type CapRefusal, type RunSpend } from "./cap.js";
2
- export declare const BUDGET_PAUSE = "budget.json";
3
- export declare const CAP_RAISED = "cap.json";
4
- export declare const CAP_STOPPED = "cap-stopped.json";
5
- /** How long a workflow run's pause keeps its process before it lets it go (the lead's ruling: 10 minutes). */
6
- export declare const BUDGET_HOLD_MS: number;
7
- /** Where a step stands in its workflow: its node's label and execution path. */
8
- export type StepAt = {
9
- label: string;
10
- path: string | null;
11
- };
12
- /** What `budget.json` holds: the refusal the run waits at, its figures, and the node. */
13
- export type BudgetMark = {
14
- words: string;
15
- cap_usd: number;
16
- spent_usd?: number;
17
- needs_usd?: number;
18
- least_cap_usd?: number;
19
- bound_usd?: number;
20
- node: string | null;
21
- path: string | null;
22
- at: string;
23
- };
24
- /** What `cap-stopped.json` holds: the refusal that ended the run, and the node. */
25
- export type CapStopped = {
26
- words: string;
27
- node: string | null;
28
- at: string;
29
- };
30
- /** A step its cap refused for good: thrown where the step stood, never an item's failure (it is no EffectFailure and
31
- * declares no itemFailure), so the workflow fails on it and the server reads `cap-stopped.json`. */
32
- export declare class CapStop extends Error {
33
- readonly refusal: CapRefusal;
34
- readonly at: StepAt | undefined;
35
- readonly name = "CapStop";
36
- readonly code = "spend_cap_reached";
37
- constructor(refusal: CapRefusal, at: StepAt | undefined);
38
- }
39
- /** The pause the run at `root` stands at, as its process wrote it; undefined when it waits at none. */
40
- export declare const budgetPausedIn: (root: string) => BudgetMark | undefined;
41
- /** The pause's mark taken away: a raise sent its run on, here when no process waits at it (it was let go). */
42
- export declare const clearBudgetPause: (root: string) => void;
43
- /** The run's waits for a raise, in its process: `spend` is the run's spend (cap.ts), `holdMs` how long a pause keeps the
44
- * process, `letGo` what lets it go. `step` counts the steps in flight (app.ts wraps each node, call and decision
45
- * with it), a step run inside another (a model node's verification decision) as part of that one; a pause lets the
46
- * process go only when every one of them is waiting, a step whose nested decision waits counting as waiting. */
47
- export declare function budgetWaits(root: string, spend: RunSpend, { holdMs, letGo }: {
48
- holdMs?: number;
49
- letGo: () => void;
50
- }): {
51
- /** `fn`, counted as a step in flight while it runs, unless it runs inside another step (its work, counted there). */
52
- step<P, R>(fn: (params: P) => Promise<R>): (params: P) => Promise<R>;
53
- /** What the step at `path` has waited so far, in ms: the interpreter's deps.held, which its deadline does not count.
54
- * A map's items each have a path of their own (`.../items/<i>/body`), so each holds its own time. */
55
- held(path: string): number;
56
- /** Waits for a raise of the cap that refused `refusal`, at `at`: true once the cap is above it (now, or by a raise
57
- * that comes), false on a cancel or `signal`. The first wait writes the pause's mark; the last one to end on a raise
58
- * takes it away. */
59
- wait(refusal: CapRefusal, signal?: AbortSignal, at?: StepAt): Promise<boolean>;
60
- /** Keeps a refusal no raise fixes, at `at`, for the server: the first one, which the run ends on. The step's own
61
- * refusal is kept too, by its path, for `stopped` to read once the step fails on it. */
62
- record(refusal: CapRefusal, at?: StepAt): void;
63
- /** The refusal no raise fixes that the step at `path` met (a model node's request, recorded by capModels), if any:
64
- * its failure is then a CapStop, never the node's own failure, which a collecting map would take for an item's.
65
- * `alone`: the step is the only one running, so a refusal kept with no path of its own (its request lost its
66
- * node's context) is its. */
67
- stopped(path: string | null | undefined, alone?: boolean): CapStop | undefined;
68
- /** Ends the step at `at` on a refusal no raise fixes: its words kept for the server, and CapStop thrown. */
69
- stop(refusal: CapRefusal, at?: StepAt): never;
70
- };
71
- export type BudgetWaits = ReturnType<typeof budgetWaits>;