@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,389 @@
1
+ // The box relay's VM half: how a run's process reaches its VM box without the VM provider's token. The token and the SDK
2
+ // client are the server's alone (boxes.ts, BOX_KEYS), so a run's process runs pi-transport's VM provider over a client of
3
+ // its own (relayedVmSdk) whose every call comes here, on loopback with its run's own door token (box-relay.ts checks it),
4
+ // and is made here with the server's client only when it is one of the calls a run's tools make of that run's own box:
5
+ // find it, read its state and its tags, start a program in it, and that program's input, output and exit. Nothing else
6
+ // passes: no create, listing, end or tag change (the server makes and seeds the box, pulls its work/ back and ends it),
7
+ // and no call to a sandbox that does not carry the run's label. The SDK speaks gRPC, so the relay carries its calls, not
8
+ // its bytes on the wire: each program started here is held by an id of its own until its exit is read and its output
9
+ // streams are done.
10
+ import { randomUUID } from "node:crypto";
11
+ import { relayAddress } from "./box-relay.js";
12
+ import { redacted } from "./key-refusal.js";
13
+ /** 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. */
14
+ const RUN_LABEL = "agentrun.run";
15
+ /** The most bytes one relayed write to a program's input may send. */
16
+ const MAX_INPUT_BYTES = 64 * 2 ** 20;
17
+ /** The most programs one run may hold here at once. */
18
+ const MAX_EXECS_PER_RUN = 64;
19
+ /** How many bytes of a program's output stream the relay holds before it stops reading the stream, until the run's
20
+ * process reads them. */
21
+ const MAX_BUFFERED_BYTES = 16 * 2 ** 20;
22
+ /** How long a program the run's process stopped asking about is held, once it exited. A program is let go:
23
+ * - once its exit was read (or failed to be) and both its output replies ended, whole or broken (settle);
24
+ * - at once when a caller goes away mid-read (the reply's close);
25
+ * - at the run's end (drop), whatever it is doing;
26
+ * - else EXEC_KEEP_MS after its exit: an exit or an output not read yet is still the caller's to read.
27
+ * A program still running holds its slot until it exits or the run ends. */
28
+ const EXEC_KEEP_MS = 10 * 60_000;
29
+ /** The most sandboxes the relay remembers the run of; past it, it asks the provider again. */
30
+ const KNOWN_MAX = 1024;
31
+ /** Its message is the SDK's, which can quote anything: cut of every value the server holds, and of secret-shaped text,
32
+ * by serve's one rule (key-refusal.ts redacted), before it goes to the run's process. */
33
+ const failureOf = (error, secrets = []) => {
34
+ const name = error?.constructor?.name ?? "Error";
35
+ const code = error?.code;
36
+ return { name, ...(typeof code === "number" ? { code } : {}), message: redacted(String(error?.message ?? error), secrets).slice(0, 300) };
37
+ };
38
+ function pump(source) {
39
+ const iterator = source[Symbol.asyncIterator]();
40
+ const state = {
41
+ chunks: [], bytes: 0, done: false, cancelled: false,
42
+ // Let go: what it holds is dropped, the source's read is ended, and whoever waits on it is woken.
43
+ cancel() {
44
+ if (state.cancelled)
45
+ return;
46
+ state.cancelled = true;
47
+ state.chunks.length = 0;
48
+ state.bytes = 0;
49
+ state.done = true;
50
+ void Promise.resolve(iterator.return?.()).catch(() => undefined);
51
+ state.space?.();
52
+ state.wake?.();
53
+ },
54
+ };
55
+ void (async () => {
56
+ try {
57
+ for (;;) {
58
+ const next = await iterator.next();
59
+ if (next.done || state.cancelled)
60
+ break;
61
+ state.chunks.push(next.value);
62
+ state.bytes += next.value.length;
63
+ state.wake?.();
64
+ while (state.bytes > MAX_BUFFERED_BYTES && !state.cancelled)
65
+ await new Promise((resolve) => (state.space = resolve));
66
+ }
67
+ }
68
+ catch (error) {
69
+ if (!state.cancelled)
70
+ state.failure = error ?? new Error("the stream failed");
71
+ }
72
+ state.done = true;
73
+ state.wake?.();
74
+ })();
75
+ return state;
76
+ }
77
+ /** The relay's handler of a run's VM calls, over the server's client `sdk`: `handle(runId, path, req, res)` answers the
78
+ * call at `path` (what follows `/runs/<id>/vm/`), the caller's token already checked. `drop(runId)` lets go of the run's
79
+ * programs (at its end). */
80
+ export function vmRelay(sdk, secrets = () => []) {
81
+ const known = new Map();
82
+ const execs = new Map();
83
+ /** The programs each run is starting now: counted with those it holds, so starts at once cannot pass the limit. */
84
+ const starting = new Map();
85
+ /** Sandbox `id` and the run its label names, as the provider says; undefined when it has none. */
86
+ const sandboxOf = async (id) => {
87
+ const held = known.get(id);
88
+ if (held)
89
+ return held;
90
+ const sandbox = await sdk.sandboxes.fromId(id);
91
+ const tags = await sandbox.getTags();
92
+ const value = { sandbox, run: typeof tags[RUN_LABEL] === "string" ? tags[RUN_LABEL] : undefined };
93
+ if (known.size >= KNOWN_MAX)
94
+ known.clear();
95
+ known.set(id, value);
96
+ return value;
97
+ };
98
+ const answer = (res, status, body) => {
99
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
100
+ res.end(JSON.stringify(body));
101
+ };
102
+ const failed = (res, error) => void (res.headersSent ? res.destroy() : answer(res, 502, { failure: failureOf(error, secrets()) }));
103
+ const notThere = (res) => answer(res, 404, { failure: { name: "NotFoundError", code: 5, message: "no such sandbox" } });
104
+ const refused = (res, path) => answer(res, 403, { message: `the box relay does not make ${path}: a run's process reaches only its own box's programs and files` });
105
+ const forget = (id) => {
106
+ const held = execs.get(id);
107
+ if (held?.timer)
108
+ clearTimeout(held.timer);
109
+ // Its streams' reads end with it, and a reply still writing one is let go.
110
+ held?.streams.stdout.cancel();
111
+ held?.streams.stderr.cancel();
112
+ execs.delete(id);
113
+ };
114
+ /** A program is let go once its exit was read and both its streams' replies ended (delivered whole, or broken because
115
+ * the stream failed), or EXEC_KEEP_MS after its exit. */
116
+ const settle = (id) => {
117
+ const held = execs.get(id);
118
+ if (!held || held.exited === undefined)
119
+ return;
120
+ if (held.waited && held.finished.size === 2)
121
+ return forget(id);
122
+ held.timer ??= setTimeout(() => forget(id), EXEC_KEEP_MS);
123
+ held.timer.unref?.();
124
+ };
125
+ async function handle(runId, path, req, res) {
126
+ if (req.method !== "POST")
127
+ return answer(res, 405, { message: "the Modal sandbox relay takes POST" });
128
+ const onSandbox = /^sandbox\/([^/]+)\/(find|poll|tags|exec)$/.exec(path);
129
+ if (onSandbox) {
130
+ const id = decodeURIComponent(onSandbox[1]);
131
+ let found;
132
+ try {
133
+ found = await sandboxOf(id);
134
+ }
135
+ catch (error) {
136
+ return failureOf(error).name === "NotFoundError" || failureOf(error).code === 5 ? notThere(res) : failed(res, error);
137
+ }
138
+ // A sandbox of another run, or of none, is not there for this one: as the provider answers one it does not have.
139
+ if (found.run !== runId)
140
+ return notThere(res);
141
+ try {
142
+ switch (onSandbox[2]) {
143
+ case "find":
144
+ return answer(res, 200, { id });
145
+ case "poll":
146
+ return answer(res, 200, { code: await found.sandbox.poll() });
147
+ case "tags":
148
+ return answer(res, 200, { tags: await found.sandbox.getTags() });
149
+ default: {
150
+ const body = (await jsonOf(req));
151
+ const command = body?.command;
152
+ if (!Array.isArray(command) || !command.length || !command.every((part) => typeof part === "string"))
153
+ return answer(res, 400, { message: "exec names its command: a list of strings" });
154
+ const pending = starting.get(runId) ?? 0;
155
+ if ([...execs.values()].filter((held) => held.run === runId).length + pending >= MAX_EXECS_PER_RUN)
156
+ return answer(res, 429, { message: `a run holds at most ${MAX_EXECS_PER_RUN} programs in its box at once` });
157
+ // Its slot is taken before the start is awaited, and given back once the program is held or did not start.
158
+ starting.set(runId, pending + 1);
159
+ let process;
160
+ try {
161
+ process = await found.sandbox.exec(command, { mode: "binary", ...(typeof body?.workdir === "string" ? { workdir: body.workdir } : {}), ...(typeof body?.timeoutMs === "number" ? { timeoutMs: body.timeoutMs } : {}) });
162
+ }
163
+ finally {
164
+ const left = (starting.get(runId) ?? 1) - 1;
165
+ if (left > 0)
166
+ starting.set(runId, left);
167
+ else
168
+ starting.delete(runId);
169
+ }
170
+ const exec = randomUUID();
171
+ const held = { run: runId, process, streams: { stdout: pump(process.stdout), stderr: pump(process.stderr) }, waited: false, read: new Set(), finished: new Set() };
172
+ execs.set(exec, held);
173
+ process.wait().then((code) => {
174
+ held.exited = code;
175
+ settle(exec);
176
+ }, () => {
177
+ held.exited = -1;
178
+ settle(exec);
179
+ });
180
+ return answer(res, 200, { exec });
181
+ }
182
+ }
183
+ }
184
+ catch (error) {
185
+ return failed(res, error);
186
+ }
187
+ }
188
+ const onExec = /^exec\/([^/]+)\/(stdin|stdin-close|stdout|stderr|wait)$/.exec(path);
189
+ if (!onExec)
190
+ return refused(res, path);
191
+ const id = decodeURIComponent(onExec[1]);
192
+ const held = execs.get(id);
193
+ // Another run's program is not there for this one.
194
+ if (!held || held.run !== runId)
195
+ return answer(res, 404, { message: "no such program" });
196
+ try {
197
+ switch (onExec[2]) {
198
+ case "stdin": {
199
+ const bytes = await bytesOf(req);
200
+ if (bytes === null)
201
+ return answer(res, 413, { message: `a write sends at most ${MAX_INPUT_BYTES} bytes` });
202
+ await held.process.stdin.writeBytes(new Uint8Array(bytes));
203
+ return answer(res, 200, {});
204
+ }
205
+ case "stdin-close":
206
+ await held.process.stdin.close();
207
+ return answer(res, 200, {});
208
+ case "wait": {
209
+ // The exit is read whether the provider gives it or fails to: either way the caller has its answer, and the
210
+ // program goes once its streams' replies have ended.
211
+ let code;
212
+ try {
213
+ code = await held.process.wait();
214
+ }
215
+ catch (error) {
216
+ held.waited = true;
217
+ held.exited ??= -1;
218
+ failed(res, error);
219
+ return settle(id);
220
+ }
221
+ held.waited = true;
222
+ answer(res, 200, { code });
223
+ return settle(id);
224
+ }
225
+ default: {
226
+ const name = onExec[2];
227
+ if (held.read.has(name))
228
+ return answer(res, 409, { message: `the program's ${name} is read once` });
229
+ held.read.add(name);
230
+ const stream = held.streams[name];
231
+ res.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store" });
232
+ // A caller that goes away (its process ended, or it stopped reading) lets the stream go: its read is ended and
233
+ // nothing waits on it.
234
+ let gone = false;
235
+ let woke = () => { };
236
+ res.once("close", () => {
237
+ if (res.writableFinished)
238
+ return;
239
+ gone = true;
240
+ stream.cancel();
241
+ woke();
242
+ });
243
+ for (;;) {
244
+ while (stream.chunks.length && !gone) {
245
+ const chunk = stream.chunks.shift();
246
+ stream.bytes -= chunk.length;
247
+ stream.space?.();
248
+ if (!res.write(chunk))
249
+ await new Promise((resolve) => {
250
+ woke = resolve;
251
+ res.once("drain", resolve);
252
+ });
253
+ }
254
+ if (stream.done || gone)
255
+ break;
256
+ await new Promise((resolve) => (stream.wake = woke = resolve));
257
+ }
258
+ if (gone)
259
+ return void forget(id);
260
+ // A stream that broke, or was let go before it was all sent (the run's end), is a broken answer, never a short
261
+ // one: the caller sees its read fail.
262
+ if (stream.failure !== undefined || stream.cancelled)
263
+ res.destroy();
264
+ else
265
+ res.end();
266
+ // Ended either way: a failed stream holds no slot once its exit is read too.
267
+ held.finished.add(name);
268
+ settle(id);
269
+ return;
270
+ }
271
+ }
272
+ }
273
+ catch (error) {
274
+ return failed(res, error);
275
+ }
276
+ }
277
+ return {
278
+ handle,
279
+ drop(runId) {
280
+ for (const [id, held] of execs)
281
+ if (held.run === runId)
282
+ forget(id);
283
+ },
284
+ };
285
+ }
286
+ async function bytesOf(req) {
287
+ const parts = [];
288
+ let size = 0;
289
+ for await (const part of req) {
290
+ size += part.length;
291
+ if (size > MAX_INPUT_BYTES)
292
+ return null;
293
+ parts.push(part);
294
+ }
295
+ return Buffer.concat(parts);
296
+ }
297
+ const jsonOf = async (req) => {
298
+ const bytes = await bytesOf(req);
299
+ try {
300
+ return bytes ? JSON.parse(bytes.toString("utf8") || "null") : null;
301
+ }
302
+ catch {
303
+ return null;
304
+ }
305
+ };
306
+ /** An error as the SDK would throw it, from the relay's answer: its class's name, so pi-transport's provider reads it the
307
+ * same (NotFoundError, a gRPC code). */
308
+ function errorOf(failure, fallback) {
309
+ const name = failure?.name && /^[A-Za-z]+$/.test(failure.name) ? failure.name : "Error";
310
+ const Named = { [name]: class extends Error {
311
+ } }[name];
312
+ return Object.assign(new Named(failure?.message ?? fallback), typeof failure?.code === "number" ? { code: failure.code } : {});
313
+ }
314
+ /** 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
315
+ * its output streams take as long as the program runs, which its caller bounds (bash's timeout, and pi-transport's
316
+ * backstop over it); Node's own fetch would give up after 300 s with no answer or no bytes, failing a longer command
317
+ * as lost. */
318
+ export const RELAY_AGENT_OPTIONS = Object.freeze({ headersTimeout: 0, bodyTimeout: 0 });
319
+ /** 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
320
+ * root `root`, with the run's own door token. It finds a sandbox and runs programs in it; it makes, lists and ends none. */
321
+ export function relayedVmSdk(root, runDir, runId, agentOptions = RELAY_AGENT_OPTIONS) {
322
+ // Its own dispatcher, with the waits above: made at its first call, kept for the process.
323
+ let opened;
324
+ const open = () => (opened ??= import("undici").then(({ Agent, fetch }) => ({ dispatcher: new Agent(agentOptions), dial: fetch })));
325
+ const call = async (path, body, json = true) => {
326
+ const [{ url, token }, { dispatcher, dial }] = await Promise.all([relayAddress(root, runDir), open()]);
327
+ return dial(`${url}/runs/${encodeURIComponent(runId)}/vm/${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, ...(json ? { "content-type": "application/json" } : { "content-type": "application/octet-stream" }) }, ...(body === undefined ? {} : { body: body }), redirect: "error", dispatcher });
328
+ };
329
+ const result = async (path, body) => {
330
+ const answer = await call(path, body === undefined ? undefined : JSON.stringify(body));
331
+ const value = (await answer.json().catch(() => null));
332
+ if (!answer.ok)
333
+ throw errorOf(value?.failure, value?.message ?? `the box relay answered ${answer.status}`);
334
+ return value;
335
+ };
336
+ /** A program's output stream: read from the relay once its reader starts, failing as the relay's answer fails. */
337
+ const stream = (exec, name) => ({
338
+ async *[Symbol.asyncIterator]() {
339
+ const answer = await call(`exec/${exec}/${name}`);
340
+ if (!answer.ok || !answer.body)
341
+ throw errorOf(undefined, `the box relay answered ${answer.status} to the program's ${name}`);
342
+ for await (const chunk of answer.body)
343
+ yield chunk;
344
+ },
345
+ });
346
+ const sandbox = (sandboxId) => {
347
+ const at = `sandbox/${encodeURIComponent(sandboxId)}`;
348
+ return {
349
+ sandboxId,
350
+ poll: async () => (await result(`${at}/poll`, {})).code,
351
+ getTags: async () => (await result(`${at}/tags`, {})).tags,
352
+ terminate: async () => {
353
+ throw new Error("a run's process ends no box: the server does");
354
+ },
355
+ exec: async (command, params) => {
356
+ const { exec } = await result(`${at}/exec`, { command, ...(params.workdir ? { workdir: params.workdir } : {}), ...(params.timeoutMs === undefined ? {} : { timeoutMs: params.timeoutMs }) });
357
+ const id = encodeURIComponent(exec);
358
+ return {
359
+ stdin: {
360
+ writeBytes: async (bytes) => {
361
+ const answer = await call(`exec/${id}/stdin`, bytes, false);
362
+ if (!answer.ok)
363
+ throw errorOf((await answer.json().catch(() => null))?.failure, `the box relay answered ${answer.status} to a write`);
364
+ },
365
+ close: async () => void (await result(`exec/${id}/stdin-close`, {})),
366
+ },
367
+ stdout: stream(id, "stdout"),
368
+ stderr: stream(id, "stderr"),
369
+ wait: async () => (await result(`exec/${id}/wait`, {})).code,
370
+ };
371
+ },
372
+ };
373
+ };
374
+ const none = (what) => () => {
375
+ throw new Error(`a run's process ${what} no box: the server does`);
376
+ };
377
+ return {
378
+ apps: { fromName: none("names") },
379
+ images: { fromRegistry: none("names"), fromId: none("names") },
380
+ sandboxes: {
381
+ create: none("makes"),
382
+ list: none("lists"),
383
+ fromId: async (id) => {
384
+ await result(`sandbox/${encodeURIComponent(id)}/find`, {});
385
+ return sandbox(id);
386
+ },
387
+ },
388
+ };
389
+ }
@@ -0,0 +1,45 @@
1
+ import type { vmRelay } from "./box-relay-vm.js";
2
+ /** The relay's address in the data directory: `{"url": "http://<loopback>:<port>"}`. */
3
+ export declare const BOX_RELAY_FILE = ".box-relay";
4
+ /** What a run's Daytona provider sends as its key: never a key. The relay sends the server's in its place. */
5
+ export declare const RELAYED_KEY = "relayed-by-the-server";
6
+ export type BoxRelayOptions = {
7
+ /** The data directory: where the relay's address goes. */
8
+ root: string;
9
+ /** Run `runId`'s own door token, which a call for that run must carry; undefined for a run that has none. */
10
+ tokenOf(runId: string): string | undefined;
11
+ /** Daytona's API and the server's key for it; absent on a server with no Daytona box. */
12
+ apiUrl?: string;
13
+ apiKey?: string;
14
+ /** For tests. Default the global `fetch`. */
15
+ fetch?: typeof fetch;
16
+ /** The VM half (box-relay-vm.ts), on a server with the VM box. */
17
+ vm?: ReturnType<typeof vmRelay>;
18
+ /** Whether `runId` is a run this server holds in a remote box that has not ended. */
19
+ serves(runId: string): boolean;
20
+ /** The run's box, found by its label or made with its work/ seeded (run-box.ts ensureRemoteBox): its id, and whether it is new. */
21
+ ensure(runId: string): Promise<{
22
+ id: string;
23
+ made: boolean;
24
+ }>;
25
+ };
26
+ export type BoxRelay = {
27
+ url: string;
28
+ close(): Promise<void>;
29
+ };
30
+ /** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
31
+ export declare function startBoxRelay(options: BoxRelayOptions): Promise<BoxRelay>;
32
+ /** The relay's address, from the data directory `root`, and the run's own door token, from its directory `runDir`: read
33
+ * at each call. */
34
+ export declare function relayAddress(root: string, runDir: string): Promise<{
35
+ url: string;
36
+ token: string;
37
+ }>;
38
+ /** The `fetch` a run's Daytona provider uses: each call goes to the relay, which sends it on with the key. */
39
+ export declare const relayFetch: (root: string, runDir: string, runId: string) => typeof fetch;
40
+ /** Asks the relay for run `runId`'s box: made and seeded by the server when it has none. */
41
+ export declare function relayedBox(root: string, runDir: string, runId: string, signal?: AbortSignal): Promise<{
42
+ id: string;
43
+ made: boolean;
44
+ apiUrl?: string;
45
+ }>;
@@ -0,0 +1,227 @@
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
+ /** What a run's Daytona provider sends as its key: never a key. The relay sends the server's in its place. */
23
+ export const RELAYED_KEY = "relayed-by-the-server";
24
+ /** The header that names the Daytona URL a relayed call is for. */
25
+ const TARGET = "x-agentrun-target";
26
+ /** 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. */
27
+ const RUN_LABEL = "agentrun.run";
28
+ /** The most bytes one relayed call may send: a file a tool writes, or a program's input. */
29
+ const MAX_BODY_BYTES = 64 * 2 ** 20;
30
+ /** The toolbox calls a run's tools make, by their route after the sandbox's id, and the one method each takes. */
31
+ const TOOLBOX = { "process/execute": "POST", "files/upload-v2": "POST", "files/download": "GET", "files/permissions": "POST" };
32
+ /** The most sandboxes the relay remembers the run of; past it, it asks Daytona again. */
33
+ const KNOWN_MAX = 1024;
34
+ const digest = (text) => createHash("sha256").update(text).digest();
35
+ /** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
36
+ export async function startBoxRelay(options) {
37
+ const base = (options.apiUrl ?? "").replace(/\/+$/, "");
38
+ const upstream = options.fetch ?? fetch;
39
+ const api = { apiUrl: base, apiKey: options.apiKey ?? "", ...(options.fetch ? { fetch: options.fetch } : {}) };
40
+ // Each sandbox's run (its label) and its toolbox's address, as Daytona answered the server: neither changes.
41
+ const known = new Map();
42
+ const remember = (id, value) => {
43
+ if (known.size >= KNOWN_MAX)
44
+ known.clear();
45
+ known.set(id, value);
46
+ };
47
+ /** The run whose label sandbox `id` carries, as Daytona says; undefined for a sandbox that has none, or is not there. */
48
+ const runOf = async (id) => {
49
+ const held = known.get(id);
50
+ if (held)
51
+ return held.run;
52
+ const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}`);
53
+ if (answer.status === 404)
54
+ return undefined;
55
+ if (!answer.ok)
56
+ throw new Error(`Daytona answered ${answer.status} to the read of a sandbox`);
57
+ const info = (await answer.json().catch(() => null));
58
+ const run = typeof info?.labels?.[RUN_LABEL] === "string" ? info.labels[RUN_LABEL] : undefined;
59
+ remember(id, { run, ...(typeof info?.toolboxProxyUrl === "string" ? { proxy: info.toolboxProxyUrl } : {}) });
60
+ return run;
61
+ };
62
+ /** Sandbox `id`'s toolbox address, without a trailing slash. */
63
+ const proxyOf = async (id) => {
64
+ const held = known.get(id);
65
+ if (held?.proxy)
66
+ return held.proxy.replace(/\/+$/, "");
67
+ const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}/toolbox-proxy-url`);
68
+ if (!answer.ok)
69
+ return undefined;
70
+ const url = (await answer.json().catch(() => null))?.url;
71
+ if (typeof url !== "string")
72
+ return undefined;
73
+ if (held)
74
+ held.proxy = url;
75
+ return url.replace(/\/+$/, "");
76
+ };
77
+ /** The sandbox a relayed call is for, when it is one a run's tools make; else why not. */
78
+ const sandboxOf = async (method, target) => {
79
+ const call = `${method} ${target.origin}${target.pathname}`;
80
+ const refused = { refused: `the box relay does not send ${call}: a run's process reaches only its own box's programs and files` };
81
+ const api = `${base}/sandbox/`;
82
+ const whole = `${target.origin}${target.pathname}`;
83
+ if (whole.startsWith(api)) {
84
+ // A read of the sandbox (attach, status) or of its toolbox's address: GET, no query.
85
+ const named = /^([^/]+)(\/toolbox-proxy-url)?$/.exec(whole.slice(api.length));
86
+ if (!named || method !== "GET" || target.search)
87
+ return refused;
88
+ return { id: decodeURIComponent(named[1]) };
89
+ }
90
+ const routed = /^(.+)\/([^/]+)\/(process\/execute|files\/upload-v2|files\/download|files\/permissions)$/.exec(whole);
91
+ if (!routed || TOOLBOX[routed[3]] !== method)
92
+ return refused;
93
+ const id = decodeURIComponent(routed[2]);
94
+ // The toolbox call goes only to the address Daytona gives that sandbox's toolbox: never to a host the call names.
95
+ if ((await runOf(id)) === undefined || (await proxyOf(id)) !== routed[1])
96
+ return refused;
97
+ return { id };
98
+ };
99
+ const answer = (res, status, body) => {
100
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
101
+ res.end(JSON.stringify(body));
102
+ };
103
+ const forward = async (runId, req, res) => {
104
+ const method = req.method ?? "GET";
105
+ const target = URL.parse(String(req.headers[TARGET] ?? ""));
106
+ if (!target)
107
+ return answer(res, 400, { message: `a relayed call names its Daytona URL in ${TARGET}` });
108
+ const named = await sandboxOf(method, target);
109
+ if ("refused" in named)
110
+ return answer(res, 403, { message: named.refused });
111
+ // A sandbox of another run, or of none, is not there for this one: as Daytona answers a sandbox it does not have.
112
+ if ((await runOf(named.id)) !== runId)
113
+ return answer(res, 404, { statusCode: 404, message: "sandbox not found" });
114
+ const body = method === "GET" ? undefined : await bytesOf(req);
115
+ if (body === null)
116
+ return answer(res, 413, { message: `a relayed call sends at most ${MAX_BODY_BYTES} bytes` });
117
+ const abort = new AbortController();
118
+ res.once("close", () => void (res.writableFinished || abort.abort()));
119
+ const type = req.headers["content-type"];
120
+ let sent;
121
+ try {
122
+ sent = await upstream(target.href, {
123
+ method,
124
+ headers: { authorization: `Bearer ${options.apiKey}`, "x-daytona-source": "pi-transport", ...(type ? { "content-type": type } : {}) },
125
+ ...(body ? { body: new Uint8Array(body) } : {}),
126
+ // Never followed: a box that holds its toolbox's port could point the key at another run's sandbox.
127
+ redirect: "error",
128
+ signal: abort.signal,
129
+ });
130
+ }
131
+ catch (error) {
132
+ const refused = redirectRefusal(error);
133
+ if (refused)
134
+ return answer(res, 502, { message: `the box relay refuses ${method} ${target.pathname}: ${refused}` });
135
+ throw error;
136
+ }
137
+ res.writeHead(sent.status, { "content-type": sent.headers.get("content-type") ?? "application/octet-stream", "cache-control": "no-store" });
138
+ if (!sent.body)
139
+ return void res.end();
140
+ Readable.fromWeb(sent.body).on("error", () => res.destroy()).pipe(res);
141
+ };
142
+ const server = createServer((req, res) => {
143
+ void (async () => {
144
+ const path = /^\/runs\/([^/]+)\/(box|daytona|vm\/.+)$/.exec(new URL(req.url ?? "/", "http://relay").pathname);
145
+ const runId = path ? decodeURIComponent(path[1]) : "";
146
+ // The calling run's own token, and only for its own run: one run's process never speaks for another's.
147
+ const token = path ? options.tokenOf(runId) : undefined;
148
+ const auth = String(req.headers.authorization ?? "");
149
+ if (!path || !token || !timingSafeEqual(digest(auth), digest(`Bearer ${token}`)))
150
+ return answer(res, 401, { message: "the box relay takes a run's call only with that run's own door token" });
151
+ if (!options.serves(runId))
152
+ return answer(res, 404, { message: "no run of this server is in a remote box by that id" });
153
+ if (path[2] === "box") {
154
+ if (req.method !== "POST")
155
+ return answer(res, 405, { message: "POST asks for the run's box" });
156
+ const box = await options.ensure(runId);
157
+ remember(box.id, { run: runId });
158
+ return answer(res, 200, { id: box.id, made: box.made, ...(options.apiKey ? { api_url: base } : {}) });
159
+ }
160
+ if (path[2].startsWith("vm/"))
161
+ return options.vm ? options.vm.handle(runId, path[2].slice(3), req, res) : answer(res, 404, { message: "this server has no Modal sandbox" });
162
+ if (!options.apiKey)
163
+ return answer(res, 404, { message: "this server has no Daytona box" });
164
+ return forward(runId, req, res);
165
+ })().catch((error) => {
166
+ if (res.headersSent)
167
+ return void res.destroy();
168
+ // The cause's message only: no header, key or answer's body of Daytona's is in it.
169
+ answer(res, 502, { message: `the box relay could not complete the call: ${error?.message ?? String(error)}` });
170
+ });
171
+ });
172
+ await new Promise((resolve, reject) => {
173
+ server.once("error", reject);
174
+ server.listen(0, LOOPBACK, () => resolve());
175
+ });
176
+ const url = `http://${LOOPBACK}:${server.address().port}`;
177
+ await writeWhole(join(options.root, BOX_RELAY_FILE), `${JSON.stringify({ url })}\n`);
178
+ return {
179
+ url,
180
+ close: async () => {
181
+ await rm(join(options.root, BOX_RELAY_FILE), { force: true });
182
+ await new Promise((resolve) => {
183
+ server.closeAllConnections();
184
+ server.close(() => resolve());
185
+ });
186
+ },
187
+ };
188
+ }
189
+ /** A request's body, or null past MAX_BODY_BYTES. */
190
+ async function bytesOf(req) {
191
+ const parts = [];
192
+ let size = 0;
193
+ for await (const part of req) {
194
+ size += part.length;
195
+ if (size > MAX_BODY_BYTES)
196
+ return null;
197
+ parts.push(part);
198
+ }
199
+ return Buffer.concat(parts);
200
+ }
201
+ /** The relay's address, from the data directory `root`, and the run's own door token, from its directory `runDir`: read
202
+ * at each call. */
203
+ export async function relayAddress(root, runDir) {
204
+ const [file, token] = await Promise.all([readJson(join(root, BOX_RELAY_FILE)), readFile(join(runDir, RUN_DOOR_TOKEN), "utf8").catch(() => "")]);
205
+ const url = file && typeof file === "object" && !Array.isArray(file) && typeof file.url === "string" ? file.url : undefined;
206
+ if (!url || !token.trim())
207
+ throw new Error("this server's box relay is not running, and a run reaches its remote box only through it");
208
+ return { url, token: token.trim() };
209
+ }
210
+ /** The `fetch` a run's Daytona provider uses: each call goes to the relay, which sends it on with the key. */
211
+ export const relayFetch = (root, runDir, runId) => (async (input, init) => {
212
+ const { url, token } = await relayAddress(root, runDir);
213
+ const headers = new Headers(init?.headers);
214
+ headers.set("authorization", `Bearer ${token}`);
215
+ headers.set(TARGET, input instanceof Request ? input.url : String(input));
216
+ return fetch(`${url}/runs/${encodeURIComponent(runId)}/daytona`, { ...init, headers });
217
+ });
218
+ /** Asks the relay for run `runId`'s box: made and seeded by the server when it has none. */
219
+ export async function relayedBox(root, runDir, runId, signal) {
220
+ const { url, token } = await relayAddress(root, runDir);
221
+ const sent = await fetch(`${url}/runs/${encodeURIComponent(runId)}/box`, { method: "POST", headers: { authorization: `Bearer ${token}` }, redirect: "error", ...(signal ? { signal } : {}) });
222
+ const body = (await sent.json().catch(() => null));
223
+ if (!sent.ok || typeof body?.id !== "string") {
224
+ throw new Error(`the server did not give the run its box: ${typeof body?.message === "string" ? body.message : `it answered ${sent.status}`}`);
225
+ }
226
+ return { id: body.id, made: body.made === true, ...(typeof body.api_url === "string" ? { apiUrl: body.api_url } : {}) };
227
+ }