@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,98 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import { type BoxOffer } from "./boxes.js";
3
+ /** The setting that names another image for Docker boxes than this server's own. */
4
+ export declare const DOCKER_IMAGE_ENV = "AGENTRUN_DOCKER_IMAGE";
5
+ /** What the default image has, in words. */
6
+ export declare const RECIPE_HAS = "python, git, curl, node, npm, rg";
7
+ /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
8
+ * for that tag on 2026-11-03, so a build gets the same base wherever it runs. To move it, read the tag's index digest
9
+ * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
10
+ * registry-1.docker.io/v2/library/python/manifests/3.12-slim accepting an OCI index or a manifest list: its
11
+ * `docker-content-digest`), and put it here. The recipe's hash changes with it, and so does the image's tag
12
+ * (DEFAULT_DOCKER_IMAGE), so every server builds the new one at its next start. */
13
+ export declare const BOX_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30";
14
+ /** The default image's recipe: a Dockerfile that needs no other file, written alone into a private context directory for
15
+ * each build (buildContext). Its hash names the image. */
16
+ export declare const BOX_RECIPE: string;
17
+ /** The label the built image carries: its recipe's sha256. */
18
+ export declare const RECIPE_LABEL = "agentrun.box-image";
19
+ export declare const RECIPE_HASH: string;
20
+ /** The default image: this server's own, built from BOX_RECIPE, its tag the recipe's hash. */
21
+ export declare const DEFAULT_DOCKER_IMAGE: string;
22
+ /** The image a Docker box starts from on a server or a run with `env`. */
23
+ export declare const boxImageOf: (env: NodeJS.ProcessEnv) => string;
24
+ /** Where the image's state is kept for the run's processes, in the data directory. */
25
+ export declare const IMAGE_STATE_FILE = "box-image.json";
26
+ /** How long the start's pull, or build, may take; past it, it is stopped and docker is unavailable. */
27
+ export declare const PULL_TIMEOUT_MS: number;
28
+ export declare const BUILD_TIMEOUT_MS: number;
29
+ /** How long Docker may take to say whether it has the image. */
30
+ export declare const INSPECT_TIMEOUT_MS = 5000;
31
+ /** How long past the pull's deadline a run still waits on a file that says preparing: the server's own timer ends the
32
+ * pull at the deadline, so only a server that is gone leaves the file saying preparing after it. */
33
+ export declare const STALE_AFTER_MS = 30000;
34
+ /** How long after a failed build or pull it is tried once more. */
35
+ export declare const RETRY_AFTER_MS = 5000;
36
+ /** How long the server's close waits for the image's last record to be saved, so a docker that hangs cannot hold it. */
37
+ export declare const CLOSE_WAIT_MS = 5000;
38
+ /** The image's state: `ready`; `preparing` while the server pulls it; `unavailable`, with why. */
39
+ export type ImageState = {
40
+ state: "ready";
41
+ } | {
42
+ state: "preparing";
43
+ reason: string;
44
+ } | {
45
+ state: "unavailable";
46
+ reason: string;
47
+ };
48
+ /** The file's record: the image, its state, and while it is coming, the time it is stopped by (`until`, epoch ms) and
49
+ * the timeline row a run that waits for it writes (`row`). `writer`: the server that wrote it, its pid and start time,
50
+ * where /proc gives that. */
51
+ export type ImageRecord = {
52
+ image: string;
53
+ state: ImageState["state"];
54
+ reason?: string;
55
+ until?: number;
56
+ row?: string;
57
+ writer?: {
58
+ pid: number;
59
+ startTime: string;
60
+ };
61
+ };
62
+ export type DockerImage = {
63
+ readonly image: string;
64
+ /** The state now. */
65
+ state(): ImageState;
66
+ /** Settles with the state once it is ready or unavailable. */
67
+ readonly settled: Promise<ImageState>;
68
+ /** Stops a build or pull in progress and waits, at most CLOSE_WAIT_MS, for its last record to be saved: the server's
69
+ * close (and a start that failed) calls it before the data directory's lock goes, so no record of this server lands
70
+ * after the next one took the lock. */
71
+ close(): Promise<void>;
72
+ };
73
+ /** Removes the record: this server has no Docker box, so no run waits on its image. */
74
+ export declare const clearImage: (data: string) => Promise<void>;
75
+ /**
76
+ * The image's readiness on this server: asked of Docker now (within INSPECT_TIMEOUT_MS), and when Docker has none (or,
77
+ * for the default, has one of another recipe), built from BOX_RECIPE or pulled, in the background, within its bound; a
78
+ * try that fails, but not for want of time, is made once more, `retryAfterMs` later. `onChange` is told each state after
79
+ * the first. The record in the data directory follows the state.
80
+ */
81
+ export declare function dockerImage(env: NodeJS.ProcessEnv, data: string, image: string, options?: {
82
+ pullTimeoutMs?: number;
83
+ buildTimeoutMs?: number;
84
+ inspectTimeoutMs?: number;
85
+ retryAfterMs?: number;
86
+ onChange?: (state: ImageState, ms: number) => void;
87
+ warn?: (message: string) => void;
88
+ }): Promise<DockerImage>;
89
+ /** Docker's offer with the image's state on it: available while it is ready or preparing, else unavailable with why. */
90
+ export declare function withImage(offer: BoxOffer, image: ImageState): BoxOffer;
91
+ /**
92
+ * Before a run's box is made from `image`: returns once the server's record says the image is ready, or says nothing
93
+ * of it (no record, another image); waits while it says the image is being built or pulled, telling `note` once, as the
94
+ * run's timeline row; and throws, with the server's reason, when that failed, and saying to restart the server when the
95
+ * server that was making it is gone (its writer, or where that cannot be told, its deadline). A cancel of `context`
96
+ * ends the wait.
97
+ */
98
+ export declare function awaitImage(data: string, image: string, context: Context, note: (summary: string) => Promise<void> | void): Promise<void>;
@@ -0,0 +1,285 @@
1
+ // The image a Docker box starts from, made ready at the server's start, so a run's first tool call is never a silent pull
2
+ // or build. By default it is this server's own, built here from BOX_RECIPE (python 3.12 with git, curl, node, npm and rg,
3
+ // and socat, the relay to the box's network proxy when it has one: box-egress.ts), tagged
4
+ // `agentrun-box:<the recipe's hash>` and labelled with the whole hash (RECIPE_LABEL): built on first use, and again only
5
+ // when the recipe changes. AGENTRUN_DOCKER_IMAGE names another image instead, which is pulled when Docker has none.
6
+ //
7
+ // Once docker answers its probe (boxes.ts), the server asks Docker for the image (`docker image inspect`). When Docker has
8
+ // it (the built one with this recipe's hash), the box is ready. When not, the server builds or pulls it once, in the
9
+ // background, within BUILD_TIMEOUT_MS or PULL_TIMEOUT_MS: docker is then available and preparing ("building the box
10
+ // image (...)", "pulling <image>"), and ready once the image is in. A build or pull that fails is tried once more,
11
+ // RETRY_AFTER_MS later, docker preparing meanwhile with why ("trying once more: <the failure>"); one that fails again, or
12
+ // does not finish in time, makes docker unavailable with the reason, until a restart tries again. Docker's own output
13
+ // is never in a reason, as for the probes: the reason says what kind of failure it was, and what to do. The build
14
+ // reaches the network (the base image, apt); a box never does by Docker's network (`--network none`, run-box.ts), only,
15
+ // with the server's host list, through its egress proxy (box-egress.ts).
16
+ //
17
+ // The state is written to IMAGE_STATE_FILE in the data directory at each change, for the run's processes: a run's first
18
+ // box create reads it there (awaitImage, from run-box.ts) and, while the image is coming, waits for it, with one row on
19
+ // the run's timeline, instead of a `docker run` that pulls inside the tool call. Each record names its writer, the server
20
+ // (its pid and start time). A server that went away mid-way (killed, or closed while the image came) leaves the file
21
+ // saying preparing: a run that reads it once that writer is gone (the check box/sweep.ts makes of a box record's writer),
22
+ // or past its deadline where the writer cannot be told (no /proc), stops waiting and fails its call in words that say to
23
+ // restart the server, which builds or pulls the image again; never the `docker run` of an image that is not there.
24
+ import { execFile } from "node:child_process";
25
+ import { createHash } from "node:crypto";
26
+ import { chmod, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
27
+ import { tmpdir } from "node:os";
28
+ import { join } from "node:path";
29
+ import { startTimeOf, writerGone } from "./box/sweep.js";
30
+ import { BOX_KEYS } from "./boxes.js";
31
+ /** The setting that names another image for Docker boxes than this server's own. */
32
+ export const DOCKER_IMAGE_ENV = "AGENTRUN_DOCKER_IMAGE";
33
+ /** What the default image has, in words. */
34
+ export const RECIPE_HAS = "python, git, curl, node, npm, rg";
35
+ /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
36
+ * for that tag on 2026-11-03, so a build gets the same base wherever it runs. To move it, read the tag's index digest
37
+ * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
38
+ * registry-1.docker.io/v2/library/python/manifests/3.12-slim accepting an OCI index or a manifest list: its
39
+ * `docker-content-digest`), and put it here. The recipe's hash changes with it, and so does the image's tag
40
+ * (DEFAULT_DOCKER_IMAGE), so every server builds the new one at its next start. */
41
+ export const BOX_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30";
42
+ /** The default image's recipe: a Dockerfile that needs no other file, written alone into a private context directory for
43
+ * each build (buildContext). Its hash names the image. */
44
+ export const BOX_RECIPE = [
45
+ `FROM ${BOX_BASE}`,
46
+ "RUN apt-get update \\",
47
+ " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git curl ca-certificates nodejs npm ripgrep socat \\",
48
+ " && rm -rf /var/lib/apt/lists/*",
49
+ "",
50
+ ].join("\n");
51
+ /** The label the built image carries: its recipe's sha256. */
52
+ export const RECIPE_LABEL = "agentrun.box-image";
53
+ export const RECIPE_HASH = createHash("sha256").update(BOX_RECIPE).digest("hex");
54
+ /** The default image: this server's own, built from BOX_RECIPE, its tag the recipe's hash. */
55
+ export const DEFAULT_DOCKER_IMAGE = `agentrun-box:${RECIPE_HASH.slice(0, 12)}`;
56
+ /** The image a Docker box starts from on a server or a run with `env`. */
57
+ export const boxImageOf = (env) => env[DOCKER_IMAGE_ENV] || DEFAULT_DOCKER_IMAGE;
58
+ /** Where the image's state is kept for the run's processes, in the data directory. */
59
+ export const IMAGE_STATE_FILE = "box-image.json";
60
+ /** How long the start's pull, or build, may take; past it, it is stopped and docker is unavailable. */
61
+ export const PULL_TIMEOUT_MS = 10 * 60_000;
62
+ export const BUILD_TIMEOUT_MS = 10 * 60_000;
63
+ /** How long Docker may take to say whether it has the image. */
64
+ export const INSPECT_TIMEOUT_MS = 5_000;
65
+ /** How long past the pull's deadline a run still waits on a file that says preparing: the server's own timer ends the
66
+ * pull at the deadline, so only a server that is gone leaves the file saying preparing after it. */
67
+ export const STALE_AFTER_MS = 30_000;
68
+ /** How long after a failed build or pull it is tried once more. */
69
+ export const RETRY_AFTER_MS = 5_000;
70
+ /** How long the server's close waits for the image's last record to be saved, so a docker that hangs cannot hold it. */
71
+ export const CLOSE_WAIT_MS = 5_000;
72
+ /** How often a waiting run reads the file again. */
73
+ const POLL_MS = 250;
74
+ /** `docker` with `args`, in the server's environment without the boxes' keys, nothing on its stdin, killed after
75
+ * `timeoutMs` or on `signal`. */
76
+ function docker(env, args, timeoutMs, options = {}) {
77
+ const dockerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => !BOX_KEYS.includes(name)));
78
+ return new Promise((resolve) => {
79
+ const child = execFile("docker", args, { env: dockerEnv, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 32 * 1024 * 1024, ...(options.signal ? { signal: options.signal } : {}) }, (error, stdout, stderr) => {
80
+ const failed = error;
81
+ resolve({ code: !failed ? 0 : failed.killed ? "timeout" : typeof failed.code === "number" ? failed.code : (failed.code ?? failed.name), stdout: String(stdout), stderr: String(stderr) });
82
+ });
83
+ child.stdin?.on("error", () => undefined);
84
+ child.stdin?.end();
85
+ });
86
+ }
87
+ /** Seconds or minutes, in words. */
88
+ const span = (ms) => (ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} min` : `${Math.round(ms / 1000)} s`);
89
+ const exitOf = (answer) => (typeof answer.code === "number" ? `exit ${answer.code}` : answer.code);
90
+ const UNREACHABLE = /dial tcp|no such host|i\/o timeout|connection refused|network is unreachable|TLS handshake timeout|Client\.Timeout|Temporary failure resolving|Could not resolve|Could not connect/i;
91
+ const reasonOf = (failure) => `${failure.cause}: ${failure.next}`;
92
+ /** Why the build of the default image failed, and the next step. */
93
+ function buildFailure(answer, timeoutMs) {
94
+ const next = `set ${DOCKER_IMAGE_ENV} to an image this machine has, or restart the server to build it again`;
95
+ if (answer.code === "timeout")
96
+ return { cause: `the build of the box image did not finish within ${span(timeoutMs)}`, next };
97
+ if (/no space left on device/i.test(answer.stderr))
98
+ return { cause: "the build of the box image ran out of disk space", next: "free some, then restart the server" };
99
+ // A base that could not be fetched for want of a network says so in both ways: the network is the cause.
100
+ if (UNREACHABLE.test(answer.stderr))
101
+ return { cause: "the build of the box image could not reach the network (it pulls python:3.12-slim and installs git, curl, nodejs, npm, ripgrep and socat with apt)", next };
102
+ if (/pull access denied|manifest unknown|not found: manifest|failed to resolve source metadata|failed to fetch anonymous token/i.test(answer.stderr))
103
+ return { cause: "the build of the box image could not pull its base, python:3.12-slim", next };
104
+ if (/Unable to locate package|has no installation candidate|E: Package/i.test(answer.stderr))
105
+ return { cause: "apt could not install what the box image needs (git, curl, nodejs, npm, ripgrep, socat)", next };
106
+ return { cause: `docker build of the box image failed (${exitOf(answer)})`, next };
107
+ }
108
+ /** Why a pull failed, and the next step. */
109
+ function pullFailure(image, answer, timeoutMs) {
110
+ const see = `run \`docker pull ${image}\` on this machine to see why, then restart the server`;
111
+ if (answer.code === "timeout")
112
+ return { cause: `the pull of ${image} did not finish within ${span(timeoutMs)}`, next: `run \`docker pull ${image}\` on this machine, then restart the server` };
113
+ if (/pull access denied|unauthorized|authentication required|denied:/i.test(answer.stderr))
114
+ return { cause: `the registry refused the pull of ${image} (no such repository, or it needs a docker login)`, next: see };
115
+ if (/manifest unknown|manifest for .* not found|not found: manifest/i.test(answer.stderr))
116
+ return { cause: `the registry has no ${image}`, next: "name an image it has in AGENTRUN_DOCKER_IMAGE, then restart the server" };
117
+ if (UNREACHABLE.test(answer.stderr))
118
+ return { cause: `the registry could not be reached to pull ${image}`, next: see };
119
+ return { cause: `docker pull ${image} failed (${exitOf(answer)})`, next: see };
120
+ }
121
+ /** This process, as a record names its writer: its pid and start time, where /proc gives that (Linux). */
122
+ function self() {
123
+ const startTime = startTimeOf(process.pid);
124
+ return startTime ? { writer: { pid: process.pid, startTime } } : {};
125
+ }
126
+ /** Writes the record for the run's processes, whole or not at all, naming this server as its writer. */
127
+ async function record(data, value) {
128
+ const file = join(data, IMAGE_STATE_FILE);
129
+ await writeFile(`${file}.partial`, `${JSON.stringify({ ...value, ...self() })}\n`, { mode: 0o600 });
130
+ await rename(`${file}.partial`, file);
131
+ }
132
+ /** Removes the record: this server has no Docker box, so no run waits on its image. */
133
+ export const clearImage = (data) => rm(join(data, IMAGE_STATE_FILE), { force: true });
134
+ /** `docker build` of the default image: BOX_RECIPE written alone as `Dockerfile` into a fresh directory of its own (0700,
135
+ * under TMPDIR), which is the build's context and is removed when the build ends, however it ends. A file on disk, not
136
+ * stdin, so what was built can be read where it was built. */
137
+ async function buildContext(env, image, timeoutMs, signal) {
138
+ const dir = await mkdtemp(join(env.TMPDIR || tmpdir(), "agentrun-box-"));
139
+ try {
140
+ await chmod(dir, 0o700);
141
+ await writeFile(join(dir, "Dockerfile"), BOX_RECIPE, { mode: 0o600 });
142
+ return await docker(env, ["build", "--quiet", "--label", `${RECIPE_LABEL}=${RECIPE_HASH}`, "--tag", image, dir], timeoutMs, { signal });
143
+ }
144
+ finally {
145
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
146
+ }
147
+ }
148
+ /** The labels of `image` as `docker image inspect` gives them, or none when it has none. */
149
+ const labelsOf = (stdout) => {
150
+ try {
151
+ const value = JSON.parse(stdout.trim() || "null");
152
+ return value && typeof value === "object" ? value : {};
153
+ }
154
+ catch {
155
+ return {};
156
+ }
157
+ };
158
+ /**
159
+ * The image's readiness on this server: asked of Docker now (within INSPECT_TIMEOUT_MS), and when Docker has none (or,
160
+ * for the default, has one of another recipe), built from BOX_RECIPE or pulled, in the background, within its bound; a
161
+ * try that fails, but not for want of time, is made once more, `retryAfterMs` later. `onChange` is told each state after
162
+ * the first. The record in the data directory follows the state.
163
+ */
164
+ export async function dockerImage(env, data, image, options = {}) {
165
+ const built = image === DEFAULT_DOCKER_IMAGE;
166
+ const timeoutMs = built ? (options.buildTimeoutMs ?? BUILD_TIMEOUT_MS) : (options.pullTimeoutMs ?? PULL_TIMEOUT_MS);
167
+ let state;
168
+ const write = (extra = {}) => record(data, { image, state: state.state, ...("reason" in state ? { reason: state.reason } : {}), ...extra }).catch(() => undefined);
169
+ const inspected = await docker(env, ["image", "inspect", "--format", "{{json .Config.Labels}}", image], options.inspectTimeoutMs ?? INSPECT_TIMEOUT_MS);
170
+ const controller = new AbortController();
171
+ // Docker says `No such image`; Podman, standing in for it, `image not known`.
172
+ const missing = inspected.code !== 0 && /no such image|image not known/i.test(inspected.stderr);
173
+ if (inspected.code === 0 && (!built || labelsOf(inspected.stdout)[RECIPE_LABEL] === RECIPE_HASH))
174
+ state = { state: "ready" };
175
+ else if (inspected.code !== 0 && !missing) {
176
+ const why = inspected.code === "timeout" ? `did not answer within ${span(options.inspectTimeoutMs ?? INSPECT_TIMEOUT_MS)}` : `failed (${exitOf(inspected)})`;
177
+ state = { state: "unavailable", reason: `docker image inspect ${image} ${why}: run it on this machine as this server's user to see why, then restart the server` };
178
+ }
179
+ else
180
+ state = { state: "preparing", reason: built ? `building the box image (${RECIPE_HAS})` : `pulling ${image}` };
181
+ if (state.state !== "preparing") {
182
+ await write();
183
+ const settled = state;
184
+ return { image, state: () => settled, settled: Promise.resolve(settled), close: async () => undefined };
185
+ }
186
+ const started = Date.now();
187
+ const row = built ? `Preparing the box image: building it (${RECIPE_HAS})…` : `Preparing the box image: pulling ${image}…`;
188
+ await write({ until: started + timeoutMs, row });
189
+ const retryAfterMs = options.retryAfterMs ?? RETRY_AFTER_MS;
190
+ // The build's network is Docker's default, for the base image and apt; a box made from it has none of Docker's (run-box.ts).
191
+ const attempt = () => built
192
+ ? buildContext(env, image, timeoutMs, controller.signal).catch((error) => ({ code: error.code ?? error.name, stdout: "", stderr: "" }))
193
+ : docker(env, ["pull", "--quiet", image], timeoutMs, { signal: controller.signal });
194
+ const failure = (answer) => (built ? buildFailure(answer, timeoutMs) : pullFailure(image, answer, timeoutMs));
195
+ const settled = attempt().then(async (first) => {
196
+ let answer = first;
197
+ // One try more, after a pause, for a failure that may pass (the network, the registry); not for one that already
198
+ // took the whole bound.
199
+ if (answer.code !== 0 && answer.code !== "timeout" && !controller.signal.aborted) {
200
+ state = { state: "preparing", reason: `trying once more: ${failure(answer).cause}` };
201
+ // A record of the retry that cannot be saved leaves the first try's: a run keeps waiting on it, as this server
202
+ // that wrote it still runs (a named writer decides, not its deadline). Removed, it would send a waiting run to a
203
+ // `docker run` of an image that is not there yet.
204
+ await write({ until: Date.now() + retryAfterMs + timeoutMs, row });
205
+ options.onChange?.(state, Date.now() - started);
206
+ await sleep(retryAfterMs, controller.signal).catch(() => undefined);
207
+ if (!controller.signal.aborted)
208
+ answer = await attempt();
209
+ }
210
+ if (controller.signal.aborted)
211
+ return state;
212
+ state = answer.code === 0 ? { state: "ready" } : { state: "unavailable", reason: reasonOf(failure(answer)) };
213
+ // A final state that cannot be written leaves no record: a run then makes its box as it would with none, never
214
+ // waiting on the `preparing` the record last said.
215
+ await record(data, { image, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }).catch(async (error) => {
216
+ await clearImage(data).catch(() => undefined);
217
+ options.warn?.(`the record of the box image's state could not be written (${error.code ?? error.name}), so it was removed: runs make their boxes without waiting on it`);
218
+ });
219
+ options.onChange?.(state, Date.now() - started);
220
+ return state;
221
+ });
222
+ const close = async () => {
223
+ controller.abort();
224
+ // A build or pull that ended just before the abort may be saving its last record: that save ends first, within bound.
225
+ let timer;
226
+ await Promise.race([settled.then(() => undefined, () => undefined), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_WAIT_MS)))]);
227
+ clearTimeout(timer);
228
+ };
229
+ return { image, state: () => state, settled, close };
230
+ }
231
+ /** Docker's offer with the image's state on it: available while it is ready or preparing, else unavailable with why. */
232
+ export function withImage(offer, image) {
233
+ if (!offer.available)
234
+ return offer;
235
+ if (image.state === "ready")
236
+ return { ...offer, state: "ready" };
237
+ return { id: offer.id, available: image.state === "preparing", state: image.state, reason: image.reason };
238
+ }
239
+ /** The record the server left, or undefined when there is none or it is not one. */
240
+ async function recordIn(data) {
241
+ try {
242
+ const value = JSON.parse(await readFile(join(data, IMAGE_STATE_FILE), "utf8"));
243
+ return typeof value?.image === "string" && typeof value.state === "string" ? value : undefined;
244
+ }
245
+ catch {
246
+ return undefined;
247
+ }
248
+ }
249
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
250
+ if (signal?.aborted)
251
+ return reject(signal.reason ?? new Error("aborted"));
252
+ const timer = setTimeout(() => (signal?.removeEventListener("abort", stop), resolve()), ms);
253
+ const stop = () => (clearTimeout(timer), reject(signal?.reason ?? new Error("aborted")));
254
+ signal?.addEventListener("abort", stop, { once: true });
255
+ });
256
+ /**
257
+ * Before a run's box is made from `image`: returns once the server's record says the image is ready, or says nothing
258
+ * of it (no record, another image); waits while it says the image is being built or pulled, telling `note` once, as the
259
+ * run's timeline row; and throws, with the server's reason, when that failed, and saying to restart the server when the
260
+ * server that was making it is gone (its writer, or where that cannot be told, its deadline). A cancel of `context`
261
+ * ends the wait.
262
+ */
263
+ export async function awaitImage(data, image, context, note) {
264
+ let noted = false;
265
+ for (;;) {
266
+ const at = await recordIn(data);
267
+ if (!at || at.image !== image || at.state === "ready")
268
+ return;
269
+ if (at.state === "unavailable")
270
+ throw new Error(`its image ${image} is not ready: ${at.reason ?? "the server could not make it ready"}`);
271
+ if (typeof at.until !== "number")
272
+ return;
273
+ // Its writer named, that decides: a server that runs is still making the image. Only where it cannot be told does
274
+ // the deadline.
275
+ if (at.writer ? writerGone(at.writer) : Date.now() > at.until + STALE_AFTER_MS) {
276
+ const making = image === DEFAULT_DOCKER_IMAGE ? ["building", "build"] : ["pulling", "pull"];
277
+ throw new Error(`its image ${image} is not ready: the server stopped while ${making[0]} it: restart the server to ${making[1]} it again`);
278
+ }
279
+ if (!noted) {
280
+ noted = true;
281
+ await Promise.resolve(note(at.row ?? `Preparing the box image ${image}…`)).catch(() => undefined);
282
+ }
283
+ await sleep(POLL_MS, context.abortSignal);
284
+ }
285
+ }
@@ -0,0 +1,80 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /** One program started in a VM sandbox, in binary mode: the part of the SDK's process the relay carries. */
3
+ export type VmProcess = {
4
+ readonly stdin: {
5
+ writeBytes(bytes: Uint8Array): Promise<void>;
6
+ close(): Promise<void>;
7
+ };
8
+ readonly stdout: AsyncIterable<Uint8Array>;
9
+ readonly stderr: AsyncIterable<Uint8Array>;
10
+ wait(): Promise<number>;
11
+ };
12
+ /** The part of the SDK's sandbox the relay calls. */
13
+ export type VmSandbox = {
14
+ readonly sandboxId: string;
15
+ exec(command: string[], params: {
16
+ mode: "binary";
17
+ timeoutMs?: number;
18
+ workdir?: string;
19
+ }): Promise<VmProcess>;
20
+ poll(): Promise<number | null>;
21
+ getTags(): Promise<Record<string, string>>;
22
+ };
23
+ /** The part of the SDK's client the relay calls: a sandbox by its id. */
24
+ export type VmSdk = {
25
+ readonly sandboxes: {
26
+ fromId(id: string): Promise<VmSandbox>;
27
+ };
28
+ };
29
+ /** The relay's handler of a run's VM calls, over the server's client `sdk`: `handle(runId, path, req, res)` answers the
30
+ * call at `path` (what follows `/runs/<id>/vm/`), the caller's token already checked. `drop(runId)` lets go of the run's
31
+ * programs (at its end). */
32
+ export declare function vmRelay(sdk: VmSdk, secrets?: () => readonly string[]): {
33
+ handle(runId: string, path: string, req: IncomingMessage, res: ServerResponse): Promise<void>;
34
+ drop(runId: string): void;
35
+ };
36
+ /** How the run's process's relay client waits on the relay: never on a clock of its own. A program's exit (`wait`) and
37
+ * its output streams take as long as the program runs, which its caller bounds (bash's timeout, and pi-transport's
38
+ * backstop over it); Node's own fetch would give up after 300 s with no answer or no bytes, failing a longer command
39
+ * as lost. */
40
+ export declare const RELAY_AGENT_OPTIONS: Readonly<{
41
+ headersTimeout: 0;
42
+ bodyTimeout: 0;
43
+ }>;
44
+ /** The SDK client a run's process hands pi-transport's VM provider: each call it makes of a box goes to the relay in data
45
+ * root `root`, with the run's own door token. It finds a sandbox and runs programs in it; it makes, lists and ends none. */
46
+ export declare function relayedVmSdk(root: string, runDir: string, runId: string, agentOptions?: {
47
+ headersTimeout: number;
48
+ bodyTimeout: number;
49
+ }): {
50
+ apps: {
51
+ fromName: () => never;
52
+ };
53
+ images: {
54
+ fromRegistry: () => never;
55
+ fromId: () => never;
56
+ };
57
+ sandboxes: {
58
+ create: () => never;
59
+ list: () => never;
60
+ fromId: (id: string) => Promise<{
61
+ sandboxId: string;
62
+ poll: () => Promise<number | null>;
63
+ getTags: () => Promise<Record<string, string>>;
64
+ terminate: () => Promise<number>;
65
+ exec: (command: string[], params: {
66
+ mode: "binary";
67
+ timeoutMs?: number;
68
+ workdir?: string;
69
+ }) => Promise<{
70
+ stdin: {
71
+ writeBytes: (bytes: Uint8Array) => Promise<void>;
72
+ close: () => Promise<undefined>;
73
+ };
74
+ stdout: AsyncIterable<Uint8Array<ArrayBufferLike>>;
75
+ stderr: AsyncIterable<Uint8Array<ArrayBufferLike>>;
76
+ wait: () => Promise<number>;
77
+ }>;
78
+ }>;
79
+ };
80
+ };