@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29
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.
- package/CHANGELOG.md +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1724 -0
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +96 -1
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,283 @@
|
|
|
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 and curl), tagged
|
|
3
|
+
// `agentrun-box:<the recipe's hash>` and labelled with the whole hash (RECIPE_LABEL): built on first use, and again only
|
|
4
|
+
// when the recipe changes. AGENTRUN_DOCKER_IMAGE names another image instead, which is pulled when Docker has none.
|
|
5
|
+
//
|
|
6
|
+
// Once docker answers its probe (boxes.ts), the server asks Docker for the image (`docker image inspect`). When Docker has
|
|
7
|
+
// it (the built one with this recipe's hash), the box is ready. When not, the server builds or pulls it once, in the
|
|
8
|
+
// background, within BUILD_TIMEOUT_MS or PULL_TIMEOUT_MS: docker is then available and preparing ("building the box
|
|
9
|
+
// image (...)", "pulling <image>"), and ready once the image is in. A build or pull that fails is tried once more,
|
|
10
|
+
// RETRY_AFTER_MS later, docker preparing meanwhile with why ("trying once more: <the failure>"); one that fails again, or
|
|
11
|
+
// does not finish in time, makes docker unavailable with the reason, until a restart tries again. Docker's own output
|
|
12
|
+
// is never in a reason, as for the probes: the reason says what kind of failure it was, and what to do. The build
|
|
13
|
+
// reaches the network (the base image, apt); a box never does (`--network none`, run-box.ts).
|
|
14
|
+
//
|
|
15
|
+
// The state is written to IMAGE_STATE_FILE in the data directory at each change, for the run's processes: a run's first
|
|
16
|
+
// box create reads it there (awaitImage, from run-box.ts) and, while the image is coming, waits for it, with one row on
|
|
17
|
+
// the run's timeline, instead of a `docker run` that pulls inside the tool call. Each record names its writer, the server
|
|
18
|
+
// (its pid and start time). A server that went away mid-way (killed, or closed while the image came) leaves the file
|
|
19
|
+
// saying preparing: a run that reads it once that writer is gone (the check box/sweep.ts makes of a box record's writer),
|
|
20
|
+
// or past its deadline where the writer cannot be told (no /proc), stops waiting and fails its call in words that say to
|
|
21
|
+
// restart the server, which builds or pulls the image again; never the `docker run` of an image that is not there.
|
|
22
|
+
import { execFile } from "node:child_process";
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { chmod, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { startTimeOf, writerGone } from "./box/sweep.js";
|
|
28
|
+
import { BOX_KEYS } from "./boxes.js";
|
|
29
|
+
/** The setting that names another image for Docker boxes than this server's own. */
|
|
30
|
+
export const DOCKER_IMAGE_ENV = "AGENTRUN_DOCKER_IMAGE";
|
|
31
|
+
/** What the default image has, in words. */
|
|
32
|
+
export const RECIPE_HAS = "python, git, curl, node, rg";
|
|
33
|
+
/** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
|
|
34
|
+
* 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
|
|
35
|
+
* again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
|
|
36
|
+
* registry-1.docker.io/v2/library/python/manifests/3.12-slim accepting an OCI index or a manifest list: its
|
|
37
|
+
* `docker-content-digest`), and put it here. The recipe's hash changes with it, and so does the image's tag
|
|
38
|
+
* (DEFAULT_DOCKER_IMAGE), so every server builds the new one at its next start. */
|
|
39
|
+
export const BOX_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30";
|
|
40
|
+
/** The default image's recipe: a Dockerfile that needs no other file, written alone into a private context directory for
|
|
41
|
+
* each build (buildContext). Its hash names the image. */
|
|
42
|
+
export const BOX_RECIPE = [
|
|
43
|
+
`FROM ${BOX_BASE}`,
|
|
44
|
+
"RUN apt-get update \\",
|
|
45
|
+
" && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git curl ca-certificates nodejs ripgrep \\",
|
|
46
|
+
" && rm -rf /var/lib/apt/lists/*",
|
|
47
|
+
"",
|
|
48
|
+
].join("\n");
|
|
49
|
+
/** The label the built image carries: its recipe's sha256. */
|
|
50
|
+
export const RECIPE_LABEL = "agentrun.box-image";
|
|
51
|
+
export const RECIPE_HASH = createHash("sha256").update(BOX_RECIPE).digest("hex");
|
|
52
|
+
/** The default image: this server's own, built from BOX_RECIPE, its tag the recipe's hash. */
|
|
53
|
+
export const DEFAULT_DOCKER_IMAGE = `agentrun-box:${RECIPE_HASH.slice(0, 12)}`;
|
|
54
|
+
/** The image a Docker box starts from on a server or a run with `env`. */
|
|
55
|
+
export const boxImageOf = (env) => env[DOCKER_IMAGE_ENV] || DEFAULT_DOCKER_IMAGE;
|
|
56
|
+
/** Where the image's state is kept for the run's processes, in the data directory. */
|
|
57
|
+
export const IMAGE_STATE_FILE = "box-image.json";
|
|
58
|
+
/** How long the start's pull, or build, may take; past it, it is stopped and docker is unavailable. */
|
|
59
|
+
export const PULL_TIMEOUT_MS = 10 * 60_000;
|
|
60
|
+
export const BUILD_TIMEOUT_MS = 10 * 60_000;
|
|
61
|
+
/** How long Docker may take to say whether it has the image. */
|
|
62
|
+
export const INSPECT_TIMEOUT_MS = 5_000;
|
|
63
|
+
/** How long past the pull's deadline a run still waits on a file that says preparing: the server's own timer ends the
|
|
64
|
+
* pull at the deadline, so only a server that is gone leaves the file saying preparing after it. */
|
|
65
|
+
export const STALE_AFTER_MS = 30_000;
|
|
66
|
+
/** How long after a failed build or pull it is tried once more. */
|
|
67
|
+
export const RETRY_AFTER_MS = 5_000;
|
|
68
|
+
/** How long the server's close waits for the image's last record to be saved, so a docker that hangs cannot hold it. */
|
|
69
|
+
export const CLOSE_WAIT_MS = 5_000;
|
|
70
|
+
/** How often a waiting run reads the file again. */
|
|
71
|
+
const POLL_MS = 250;
|
|
72
|
+
/** `docker` with `args`, in the server's environment without the boxes' keys, nothing on its stdin, killed after
|
|
73
|
+
* `timeoutMs` or on `signal`. */
|
|
74
|
+
function docker(env, args, timeoutMs, options = {}) {
|
|
75
|
+
const dockerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => !BOX_KEYS.includes(name)));
|
|
76
|
+
return new Promise((resolve) => {
|
|
77
|
+
const child = execFile("docker", args, { env: dockerEnv, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 32 * 1024 * 1024, ...(options.signal ? { signal: options.signal } : {}) }, (error, stdout, stderr) => {
|
|
78
|
+
const failed = error;
|
|
79
|
+
resolve({ code: !failed ? 0 : failed.killed ? "timeout" : typeof failed.code === "number" ? failed.code : (failed.code ?? failed.name), stdout: String(stdout), stderr: String(stderr) });
|
|
80
|
+
});
|
|
81
|
+
child.stdin?.on("error", () => undefined);
|
|
82
|
+
child.stdin?.end();
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/** Seconds or minutes, in words. */
|
|
86
|
+
const span = (ms) => (ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} min` : `${Math.round(ms / 1000)} s`);
|
|
87
|
+
const exitOf = (answer) => (typeof answer.code === "number" ? `exit ${answer.code}` : answer.code);
|
|
88
|
+
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;
|
|
89
|
+
const reasonOf = (failure) => `${failure.cause}: ${failure.next}`;
|
|
90
|
+
/** Why the build of the default image failed, and the next step. */
|
|
91
|
+
function buildFailure(answer, timeoutMs) {
|
|
92
|
+
const next = `set ${DOCKER_IMAGE_ENV} to an image this machine has, or restart the server to build it again`;
|
|
93
|
+
if (answer.code === "timeout")
|
|
94
|
+
return { cause: `the build of the box image did not finish within ${span(timeoutMs)}`, next };
|
|
95
|
+
if (/no space left on device/i.test(answer.stderr))
|
|
96
|
+
return { cause: "the build of the box image ran out of disk space", next: "free some, then restart the server" };
|
|
97
|
+
// A base that could not be fetched for want of a network says so in both ways: the network is the cause.
|
|
98
|
+
if (UNREACHABLE.test(answer.stderr))
|
|
99
|
+
return { cause: "the build of the box image could not reach the network (it pulls python:3.12-slim and installs git, curl, nodejs and ripgrep with apt)", next };
|
|
100
|
+
if (/pull access denied|manifest unknown|not found: manifest|failed to resolve source metadata|failed to fetch anonymous token/i.test(answer.stderr))
|
|
101
|
+
return { cause: "the build of the box image could not pull its base, python:3.12-slim", next };
|
|
102
|
+
if (/Unable to locate package|has no installation candidate|E: Package/i.test(answer.stderr))
|
|
103
|
+
return { cause: "apt could not install what the box image needs (git, curl, nodejs, ripgrep)", next };
|
|
104
|
+
return { cause: `docker build of the box image failed (${exitOf(answer)})`, next };
|
|
105
|
+
}
|
|
106
|
+
/** Why a pull failed, and the next step. */
|
|
107
|
+
function pullFailure(image, answer, timeoutMs) {
|
|
108
|
+
const see = `run \`docker pull ${image}\` on this machine to see why, then restart the server`;
|
|
109
|
+
if (answer.code === "timeout")
|
|
110
|
+
return { cause: `the pull of ${image} did not finish within ${span(timeoutMs)}`, next: `run \`docker pull ${image}\` on this machine, then restart the server` };
|
|
111
|
+
if (/pull access denied|unauthorized|authentication required|denied:/i.test(answer.stderr))
|
|
112
|
+
return { cause: `the registry refused the pull of ${image} (no such repository, or it needs a docker login)`, next: see };
|
|
113
|
+
if (/manifest unknown|manifest for .* not found|not found: manifest/i.test(answer.stderr))
|
|
114
|
+
return { cause: `the registry has no ${image}`, next: "name an image it has in AGENTRUN_DOCKER_IMAGE, then restart the server" };
|
|
115
|
+
if (UNREACHABLE.test(answer.stderr))
|
|
116
|
+
return { cause: `the registry could not be reached to pull ${image}`, next: see };
|
|
117
|
+
return { cause: `docker pull ${image} failed (${exitOf(answer)})`, next: see };
|
|
118
|
+
}
|
|
119
|
+
/** This process, as a record names its writer: its pid and start time, where /proc gives that (Linux). */
|
|
120
|
+
function self() {
|
|
121
|
+
const startTime = startTimeOf(process.pid);
|
|
122
|
+
return startTime ? { writer: { pid: process.pid, startTime } } : {};
|
|
123
|
+
}
|
|
124
|
+
/** Writes the record for the run's processes, whole or not at all, naming this server as its writer. */
|
|
125
|
+
async function record(data, value) {
|
|
126
|
+
const file = join(data, IMAGE_STATE_FILE);
|
|
127
|
+
await writeFile(`${file}.partial`, `${JSON.stringify({ ...value, ...self() })}\n`, { mode: 0o600 });
|
|
128
|
+
await rename(`${file}.partial`, file);
|
|
129
|
+
}
|
|
130
|
+
/** Removes the record: this server has no Docker box, so no run waits on its image. */
|
|
131
|
+
export const clearImage = (data) => rm(join(data, IMAGE_STATE_FILE), { force: true });
|
|
132
|
+
/** `docker build` of the default image: BOX_RECIPE written alone as `Dockerfile` into a fresh directory of its own (0700,
|
|
133
|
+
* under TMPDIR), which is the build's context and is removed when the build ends, however it ends. A file on disk, not
|
|
134
|
+
* stdin, so what was built can be read where it was built. */
|
|
135
|
+
async function buildContext(env, image, timeoutMs, signal) {
|
|
136
|
+
const dir = await mkdtemp(join(env.TMPDIR || tmpdir(), "agentrun-box-"));
|
|
137
|
+
try {
|
|
138
|
+
await chmod(dir, 0o700);
|
|
139
|
+
await writeFile(join(dir, "Dockerfile"), BOX_RECIPE, { mode: 0o600 });
|
|
140
|
+
return await docker(env, ["build", "--quiet", "--label", `${RECIPE_LABEL}=${RECIPE_HASH}`, "--tag", image, dir], timeoutMs, { signal });
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** The labels of `image` as `docker image inspect` gives them, or none when it has none. */
|
|
147
|
+
const labelsOf = (stdout) => {
|
|
148
|
+
try {
|
|
149
|
+
const value = JSON.parse(stdout.trim() || "null");
|
|
150
|
+
return value && typeof value === "object" ? value : {};
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return {};
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* The image's readiness on this server: asked of Docker now (within INSPECT_TIMEOUT_MS), and when Docker has none (or,
|
|
158
|
+
* for the default, has one of another recipe), built from BOX_RECIPE or pulled, in the background, within its bound; a
|
|
159
|
+
* try that fails, but not for want of time, is made once more, `retryAfterMs` later. `onChange` is told each state after
|
|
160
|
+
* the first. The record in the data directory follows the state.
|
|
161
|
+
*/
|
|
162
|
+
export async function dockerImage(env, data, image, options = {}) {
|
|
163
|
+
const built = image === DEFAULT_DOCKER_IMAGE;
|
|
164
|
+
const timeoutMs = built ? (options.buildTimeoutMs ?? BUILD_TIMEOUT_MS) : (options.pullTimeoutMs ?? PULL_TIMEOUT_MS);
|
|
165
|
+
let state;
|
|
166
|
+
const write = (extra = {}) => record(data, { image, state: state.state, ...("reason" in state ? { reason: state.reason } : {}), ...extra }).catch(() => undefined);
|
|
167
|
+
const inspected = await docker(env, ["image", "inspect", "--format", "{{json .Config.Labels}}", image], options.inspectTimeoutMs ?? INSPECT_TIMEOUT_MS);
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
// Docker says `No such image`; Podman, standing in for it, `image not known`.
|
|
170
|
+
const missing = inspected.code !== 0 && /no such image|image not known/i.test(inspected.stderr);
|
|
171
|
+
if (inspected.code === 0 && (!built || labelsOf(inspected.stdout)[RECIPE_LABEL] === RECIPE_HASH))
|
|
172
|
+
state = { state: "ready" };
|
|
173
|
+
else if (inspected.code !== 0 && !missing) {
|
|
174
|
+
const why = inspected.code === "timeout" ? `did not answer within ${span(options.inspectTimeoutMs ?? INSPECT_TIMEOUT_MS)}` : `failed (${exitOf(inspected)})`;
|
|
175
|
+
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` };
|
|
176
|
+
}
|
|
177
|
+
else
|
|
178
|
+
state = { state: "preparing", reason: built ? `building the box image (${RECIPE_HAS})` : `pulling ${image}` };
|
|
179
|
+
if (state.state !== "preparing") {
|
|
180
|
+
await write();
|
|
181
|
+
const settled = state;
|
|
182
|
+
return { image, state: () => settled, settled: Promise.resolve(settled), close: async () => undefined };
|
|
183
|
+
}
|
|
184
|
+
const started = Date.now();
|
|
185
|
+
const row = built ? `Preparing the box image: building it (${RECIPE_HAS})…` : `Preparing the box image: pulling ${image}…`;
|
|
186
|
+
await write({ until: started + timeoutMs, row });
|
|
187
|
+
const retryAfterMs = options.retryAfterMs ?? RETRY_AFTER_MS;
|
|
188
|
+
// The build's network is Docker's default, for the base image and apt; a box made from it has none (run-box.ts).
|
|
189
|
+
const attempt = () => built
|
|
190
|
+
? buildContext(env, image, timeoutMs, controller.signal).catch((error) => ({ code: error.code ?? error.name, stdout: "", stderr: "" }))
|
|
191
|
+
: docker(env, ["pull", "--quiet", image], timeoutMs, { signal: controller.signal });
|
|
192
|
+
const failure = (answer) => (built ? buildFailure(answer, timeoutMs) : pullFailure(image, answer, timeoutMs));
|
|
193
|
+
const settled = attempt().then(async (first) => {
|
|
194
|
+
let answer = first;
|
|
195
|
+
// One try more, after a pause, for a failure that may pass (the network, the registry); not for one that already
|
|
196
|
+
// took the whole bound.
|
|
197
|
+
if (answer.code !== 0 && answer.code !== "timeout" && !controller.signal.aborted) {
|
|
198
|
+
state = { state: "preparing", reason: `trying once more: ${failure(answer).cause}` };
|
|
199
|
+
// A record of the retry that cannot be saved leaves the first try's: a run keeps waiting on it, as this server
|
|
200
|
+
// that wrote it still runs (a named writer decides, not its deadline). Removed, it would send a waiting run to a
|
|
201
|
+
// `docker run` of an image that is not there yet.
|
|
202
|
+
await write({ until: Date.now() + retryAfterMs + timeoutMs, row });
|
|
203
|
+
options.onChange?.(state, Date.now() - started);
|
|
204
|
+
await sleep(retryAfterMs, controller.signal).catch(() => undefined);
|
|
205
|
+
if (!controller.signal.aborted)
|
|
206
|
+
answer = await attempt();
|
|
207
|
+
}
|
|
208
|
+
if (controller.signal.aborted)
|
|
209
|
+
return state;
|
|
210
|
+
state = answer.code === 0 ? { state: "ready" } : { state: "unavailable", reason: reasonOf(failure(answer)) };
|
|
211
|
+
// A final state that cannot be written leaves no record: a run then makes its box as it would with none, never
|
|
212
|
+
// waiting on the `preparing` the record last said.
|
|
213
|
+
await record(data, { image, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }).catch(async (error) => {
|
|
214
|
+
await clearImage(data).catch(() => undefined);
|
|
215
|
+
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`);
|
|
216
|
+
});
|
|
217
|
+
options.onChange?.(state, Date.now() - started);
|
|
218
|
+
return state;
|
|
219
|
+
});
|
|
220
|
+
const close = async () => {
|
|
221
|
+
controller.abort();
|
|
222
|
+
// A build or pull that ended just before the abort may be saving its last record: that save ends first, within bound.
|
|
223
|
+
let timer;
|
|
224
|
+
await Promise.race([settled.then(() => undefined, () => undefined), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_WAIT_MS)))]);
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
};
|
|
227
|
+
return { image, state: () => state, settled, close };
|
|
228
|
+
}
|
|
229
|
+
/** Docker's offer with the image's state on it: available while it is ready or preparing, else unavailable with why. */
|
|
230
|
+
export function withImage(offer, image) {
|
|
231
|
+
if (!offer.available)
|
|
232
|
+
return offer;
|
|
233
|
+
if (image.state === "ready")
|
|
234
|
+
return { ...offer, state: "ready" };
|
|
235
|
+
return { id: offer.id, available: image.state === "preparing", state: image.state, reason: image.reason };
|
|
236
|
+
}
|
|
237
|
+
/** The record the server left, or undefined when there is none or it is not one. */
|
|
238
|
+
async function recordIn(data) {
|
|
239
|
+
try {
|
|
240
|
+
const value = JSON.parse(await readFile(join(data, IMAGE_STATE_FILE), "utf8"));
|
|
241
|
+
return typeof value?.image === "string" && typeof value.state === "string" ? value : undefined;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
248
|
+
if (signal?.aborted)
|
|
249
|
+
return reject(signal.reason ?? new Error("aborted"));
|
|
250
|
+
const timer = setTimeout(() => (signal?.removeEventListener("abort", stop), resolve()), ms);
|
|
251
|
+
const stop = () => (clearTimeout(timer), reject(signal?.reason ?? new Error("aborted")));
|
|
252
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
253
|
+
});
|
|
254
|
+
/**
|
|
255
|
+
* Before a run's box is made from `image`: returns once the server's record says the image is ready, or says nothing
|
|
256
|
+
* of it (no record, another image); waits while it says the image is being built or pulled, telling `note` once, as the
|
|
257
|
+
* run's timeline row; and throws, with the server's reason, when that failed, and saying to restart the server when the
|
|
258
|
+
* server that was making it is gone (its writer, or where that cannot be told, its deadline). A cancel of `context`
|
|
259
|
+
* ends the wait.
|
|
260
|
+
*/
|
|
261
|
+
export async function awaitImage(data, image, context, note) {
|
|
262
|
+
let noted = false;
|
|
263
|
+
for (;;) {
|
|
264
|
+
const at = await recordIn(data);
|
|
265
|
+
if (!at || at.image !== image || at.state === "ready")
|
|
266
|
+
return;
|
|
267
|
+
if (at.state === "unavailable")
|
|
268
|
+
throw new Error(`its image ${image} is not ready: ${at.reason ?? "the server could not make it ready"}`);
|
|
269
|
+
if (typeof at.until !== "number")
|
|
270
|
+
return;
|
|
271
|
+
// Its writer named, that decides: a server that runs is still making the image. Only where it cannot be told does
|
|
272
|
+
// the deadline.
|
|
273
|
+
if (at.writer ? writerGone(at.writer) : Date.now() > at.until + STALE_AFTER_MS) {
|
|
274
|
+
const making = image === DEFAULT_DOCKER_IMAGE ? ["building", "build"] : ["pulling", "pull"];
|
|
275
|
+
throw new Error(`its image ${image} is not ready: the server stopped while ${making[0]} it: restart the server to ${making[1]} it again`);
|
|
276
|
+
}
|
|
277
|
+
if (!noted) {
|
|
278
|
+
noted = true;
|
|
279
|
+
await Promise.resolve(note(at.row ?? `Preparing the box image ${image}…`)).catch(() => undefined);
|
|
280
|
+
}
|
|
281
|
+
await sleep(POLL_MS, context.abortSignal);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** The relay's address in the data directory: `{"url": "http://<loopback>:<port>"}`. */
|
|
2
|
+
export declare const BOX_RELAY_FILE = ".box-relay";
|
|
3
|
+
/** What a run's Daytona provider sends as its key: never a key. The relay sends the server's in its place. */
|
|
4
|
+
export declare const RELAYED_KEY = "relayed-by-the-server";
|
|
5
|
+
export type BoxRelayOptions = {
|
|
6
|
+
/** The data directory: where the relay's address goes. */
|
|
7
|
+
root: string;
|
|
8
|
+
/** Run `runId`'s own door token, which a call for that run must carry; undefined for a run that has none. */
|
|
9
|
+
tokenOf(runId: string): string | undefined;
|
|
10
|
+
/** Daytona's API and the server's key for it. */
|
|
11
|
+
apiUrl: string;
|
|
12
|
+
apiKey: string;
|
|
13
|
+
/** For tests. Default the global `fetch`. */
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
/** Whether `runId` is a run this server holds in a Daytona box that has not ended. */
|
|
16
|
+
serves(runId: string): boolean;
|
|
17
|
+
/** 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. */
|
|
18
|
+
ensure(runId: string): Promise<{
|
|
19
|
+
id: string;
|
|
20
|
+
made: boolean;
|
|
21
|
+
}>;
|
|
22
|
+
};
|
|
23
|
+
export type BoxRelay = {
|
|
24
|
+
url: string;
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
};
|
|
27
|
+
/** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
|
|
28
|
+
export declare function startBoxRelay(options: BoxRelayOptions): Promise<BoxRelay>;
|
|
29
|
+
/** The relay's address, from the data directory `root`, and the run's own door token, from its directory `runDir`: read
|
|
30
|
+
* at each call. */
|
|
31
|
+
export declare function relayAddress(root: string, runDir: string): Promise<{
|
|
32
|
+
url: string;
|
|
33
|
+
token: string;
|
|
34
|
+
}>;
|
|
35
|
+
/** The `fetch` a run's Daytona provider uses: each call goes to the relay, which sends it on with the key. */
|
|
36
|
+
export declare const relayFetch: (root: string, runDir: string, runId: string) => typeof fetch;
|
|
37
|
+
/** Asks the relay for run `runId`'s box: made and seeded by the server when it has none. */
|
|
38
|
+
export declare function relayedBox(root: string, runDir: string, runId: string, signal?: AbortSignal): Promise<{
|
|
39
|
+
id: string;
|
|
40
|
+
made: boolean;
|
|
41
|
+
apiUrl: string;
|
|
42
|
+
}>;
|
|
@@ -0,0 +1,222 @@
|
|
|
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.
|
|
10
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { readFile, rm } from "node:fs/promises";
|
|
12
|
+
import { createServer } from "node:http";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { Readable } from "node:stream";
|
|
15
|
+
import { daytonaCall, redirectRefusal } from "./daytona-api.js";
|
|
16
|
+
import { readJson, RUN_DOOR_TOKEN, writeWhole } from "./files.js";
|
|
17
|
+
/** The relay's address in the data directory: `{"url": "http://<loopback>:<port>"}`. */
|
|
18
|
+
export const BOX_RELAY_FILE = ".box-relay";
|
|
19
|
+
/** Where the relay listens: only this machine's runs reach it. */
|
|
20
|
+
const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule the relay listens on loopback only, for the runs of this machine
|
|
21
|
+
/** What a run's Daytona provider sends as its key: never a key. The relay sends the server's in its place. */
|
|
22
|
+
export const RELAYED_KEY = "relayed-by-the-server";
|
|
23
|
+
/** The header that names the Daytona URL a relayed call is for. */
|
|
24
|
+
const TARGET = "x-agentrun-target";
|
|
25
|
+
/** 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. */
|
|
26
|
+
const RUN_LABEL = "agentrun.run";
|
|
27
|
+
/** The most bytes one relayed call may send: a file a tool writes, or a program's input. */
|
|
28
|
+
const MAX_BODY_BYTES = 64 * 2 ** 20;
|
|
29
|
+
/** The toolbox calls a run's tools make, by their route after the sandbox's id, and the one method each takes. */
|
|
30
|
+
const TOOLBOX = { "process/execute": "POST", "files/upload-v2": "POST", "files/download": "GET", "files/permissions": "POST" };
|
|
31
|
+
/** The most sandboxes the relay remembers the run of; past it, it asks Daytona again. */
|
|
32
|
+
const KNOWN_MAX = 1024;
|
|
33
|
+
const digest = (text) => createHash("sha256").update(text).digest();
|
|
34
|
+
/** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
|
|
35
|
+
export async function startBoxRelay(options) {
|
|
36
|
+
const base = options.apiUrl.replace(/\/+$/, "");
|
|
37
|
+
const upstream = options.fetch ?? fetch;
|
|
38
|
+
const api = { apiUrl: base, apiKey: options.apiKey, ...(options.fetch ? { fetch: options.fetch } : {}) };
|
|
39
|
+
// Each sandbox's run (its label) and its toolbox's address, as Daytona answered the server: neither changes.
|
|
40
|
+
const known = new Map();
|
|
41
|
+
const remember = (id, value) => {
|
|
42
|
+
if (known.size >= KNOWN_MAX)
|
|
43
|
+
known.clear();
|
|
44
|
+
known.set(id, value);
|
|
45
|
+
};
|
|
46
|
+
/** The run whose label sandbox `id` carries, as Daytona says; undefined for a sandbox that has none, or is not there. */
|
|
47
|
+
const runOf = async (id) => {
|
|
48
|
+
const held = known.get(id);
|
|
49
|
+
if (held)
|
|
50
|
+
return held.run;
|
|
51
|
+
const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}`);
|
|
52
|
+
if (answer.status === 404)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (!answer.ok)
|
|
55
|
+
throw new Error(`Daytona answered ${answer.status} to the read of a sandbox`);
|
|
56
|
+
const info = (await answer.json().catch(() => null));
|
|
57
|
+
const run = typeof info?.labels?.[RUN_LABEL] === "string" ? info.labels[RUN_LABEL] : undefined;
|
|
58
|
+
remember(id, { run, ...(typeof info?.toolboxProxyUrl === "string" ? { proxy: info.toolboxProxyUrl } : {}) });
|
|
59
|
+
return run;
|
|
60
|
+
};
|
|
61
|
+
/** Sandbox `id`'s toolbox address, without a trailing slash. */
|
|
62
|
+
const proxyOf = async (id) => {
|
|
63
|
+
const held = known.get(id);
|
|
64
|
+
if (held?.proxy)
|
|
65
|
+
return held.proxy.replace(/\/+$/, "");
|
|
66
|
+
const answer = await daytonaCall(api, "GET", `/sandbox/${encodeURIComponent(id)}/toolbox-proxy-url`);
|
|
67
|
+
if (!answer.ok)
|
|
68
|
+
return undefined;
|
|
69
|
+
const url = (await answer.json().catch(() => null))?.url;
|
|
70
|
+
if (typeof url !== "string")
|
|
71
|
+
return undefined;
|
|
72
|
+
if (held)
|
|
73
|
+
held.proxy = url;
|
|
74
|
+
return url.replace(/\/+$/, "");
|
|
75
|
+
};
|
|
76
|
+
/** The sandbox a relayed call is for, when it is one a run's tools make; else why not. */
|
|
77
|
+
const sandboxOf = async (method, target) => {
|
|
78
|
+
const call = `${method} ${target.origin}${target.pathname}`;
|
|
79
|
+
const refused = { refused: `the box relay does not send ${call}: a run's process reaches only its own box's programs and files` };
|
|
80
|
+
const api = `${base}/sandbox/`;
|
|
81
|
+
const whole = `${target.origin}${target.pathname}`;
|
|
82
|
+
if (whole.startsWith(api)) {
|
|
83
|
+
// A read of the sandbox (attach, status) or of its toolbox's address: GET, no query.
|
|
84
|
+
const named = /^([^/]+)(\/toolbox-proxy-url)?$/.exec(whole.slice(api.length));
|
|
85
|
+
if (!named || method !== "GET" || target.search)
|
|
86
|
+
return refused;
|
|
87
|
+
return { id: decodeURIComponent(named[1]) };
|
|
88
|
+
}
|
|
89
|
+
const routed = /^(.+)\/([^/]+)\/(process\/execute|files\/upload-v2|files\/download|files\/permissions)$/.exec(whole);
|
|
90
|
+
if (!routed || TOOLBOX[routed[3]] !== method)
|
|
91
|
+
return refused;
|
|
92
|
+
const id = decodeURIComponent(routed[2]);
|
|
93
|
+
// The toolbox call goes only to the address Daytona gives that sandbox's toolbox: never to a host the call names.
|
|
94
|
+
if ((await runOf(id)) === undefined || (await proxyOf(id)) !== routed[1])
|
|
95
|
+
return refused;
|
|
96
|
+
return { id };
|
|
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 forward = async (runId, req, res) => {
|
|
103
|
+
const method = req.method ?? "GET";
|
|
104
|
+
const target = URL.parse(String(req.headers[TARGET] ?? ""));
|
|
105
|
+
if (!target)
|
|
106
|
+
return answer(res, 400, { message: `a relayed call names its Daytona URL in ${TARGET}` });
|
|
107
|
+
const named = await sandboxOf(method, target);
|
|
108
|
+
if ("refused" in named)
|
|
109
|
+
return answer(res, 403, { message: named.refused });
|
|
110
|
+
// A sandbox of another run, or of none, is not there for this one: as Daytona answers a sandbox it does not have.
|
|
111
|
+
if ((await runOf(named.id)) !== runId)
|
|
112
|
+
return answer(res, 404, { statusCode: 404, message: "sandbox not found" });
|
|
113
|
+
const body = method === "GET" ? undefined : await bytesOf(req);
|
|
114
|
+
if (body === null)
|
|
115
|
+
return answer(res, 413, { message: `a relayed call sends at most ${MAX_BODY_BYTES} bytes` });
|
|
116
|
+
const abort = new AbortController();
|
|
117
|
+
res.once("close", () => void (res.writableFinished || abort.abort()));
|
|
118
|
+
const type = req.headers["content-type"];
|
|
119
|
+
let sent;
|
|
120
|
+
try {
|
|
121
|
+
sent = await upstream(target.href, {
|
|
122
|
+
method,
|
|
123
|
+
headers: { authorization: `Bearer ${options.apiKey}`, "x-daytona-source": "pi-transport", ...(type ? { "content-type": type } : {}) },
|
|
124
|
+
...(body ? { body: new Uint8Array(body) } : {}),
|
|
125
|
+
// Never followed: a box that holds its toolbox's port could point the key at another run's sandbox.
|
|
126
|
+
redirect: "error",
|
|
127
|
+
signal: abort.signal,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const refused = redirectRefusal(error);
|
|
132
|
+
if (refused)
|
|
133
|
+
return answer(res, 502, { message: `the box relay refuses ${method} ${target.pathname}: ${refused}` });
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
res.writeHead(sent.status, { "content-type": sent.headers.get("content-type") ?? "application/octet-stream", "cache-control": "no-store" });
|
|
137
|
+
if (!sent.body)
|
|
138
|
+
return void res.end();
|
|
139
|
+
Readable.fromWeb(sent.body).on("error", () => res.destroy()).pipe(res);
|
|
140
|
+
};
|
|
141
|
+
const server = createServer((req, res) => {
|
|
142
|
+
void (async () => {
|
|
143
|
+
const path = /^\/runs\/([^/]+)\/(box|daytona)$/.exec(new URL(req.url ?? "/", "http://relay").pathname);
|
|
144
|
+
const runId = path ? decodeURIComponent(path[1]) : "";
|
|
145
|
+
// The calling run's own token, and only for its own run: one run's process never speaks for another's.
|
|
146
|
+
const token = path ? options.tokenOf(runId) : undefined;
|
|
147
|
+
const auth = String(req.headers.authorization ?? "");
|
|
148
|
+
if (!path || !token || !timingSafeEqual(digest(auth), digest(`Bearer ${token}`)))
|
|
149
|
+
return answer(res, 401, { message: "the box relay takes a run's call only with that run's own door token" });
|
|
150
|
+
if (!options.serves(runId))
|
|
151
|
+
return answer(res, 404, { message: "no run of this server is in a Daytona box by that id" });
|
|
152
|
+
if (path[2] === "box") {
|
|
153
|
+
if (req.method !== "POST")
|
|
154
|
+
return answer(res, 405, { message: "POST asks for the run's box" });
|
|
155
|
+
const box = await options.ensure(runId);
|
|
156
|
+
remember(box.id, { run: runId });
|
|
157
|
+
return answer(res, 200, { id: box.id, made: box.made, api_url: base });
|
|
158
|
+
}
|
|
159
|
+
return forward(runId, req, res);
|
|
160
|
+
})().catch((error) => {
|
|
161
|
+
if (res.headersSent)
|
|
162
|
+
return void res.destroy();
|
|
163
|
+
// The cause's message only: no header, key or answer's body of Daytona's is in it.
|
|
164
|
+
answer(res, 502, { message: `the box relay could not complete the call: ${error?.message ?? String(error)}` });
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
await new Promise((resolve, reject) => {
|
|
168
|
+
server.once("error", reject);
|
|
169
|
+
server.listen(0, LOOPBACK, () => resolve());
|
|
170
|
+
});
|
|
171
|
+
const url = `http://${LOOPBACK}:${server.address().port}`;
|
|
172
|
+
await writeWhole(join(options.root, BOX_RELAY_FILE), `${JSON.stringify({ url })}\n`);
|
|
173
|
+
return {
|
|
174
|
+
url,
|
|
175
|
+
close: async () => {
|
|
176
|
+
await rm(join(options.root, BOX_RELAY_FILE), { force: true });
|
|
177
|
+
await new Promise((resolve) => {
|
|
178
|
+
server.closeAllConnections();
|
|
179
|
+
server.close(() => resolve());
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** A request's body, or null past MAX_BODY_BYTES. */
|
|
185
|
+
async function bytesOf(req) {
|
|
186
|
+
const parts = [];
|
|
187
|
+
let size = 0;
|
|
188
|
+
for await (const part of req) {
|
|
189
|
+
size += part.length;
|
|
190
|
+
if (size > MAX_BODY_BYTES)
|
|
191
|
+
return null;
|
|
192
|
+
parts.push(part);
|
|
193
|
+
}
|
|
194
|
+
return Buffer.concat(parts);
|
|
195
|
+
}
|
|
196
|
+
/** The relay's address, from the data directory `root`, and the run's own door token, from its directory `runDir`: read
|
|
197
|
+
* at each call. */
|
|
198
|
+
export async function relayAddress(root, runDir) {
|
|
199
|
+
const [file, token] = await Promise.all([readJson(join(root, BOX_RELAY_FILE)), readFile(join(runDir, RUN_DOOR_TOKEN), "utf8").catch(() => "")]);
|
|
200
|
+
const url = file && typeof file === "object" && !Array.isArray(file) && typeof file.url === "string" ? file.url : undefined;
|
|
201
|
+
if (!url || !token.trim())
|
|
202
|
+
throw new Error("this server's box relay is not running, and a run reaches its Daytona box only through it");
|
|
203
|
+
return { url, token: token.trim() };
|
|
204
|
+
}
|
|
205
|
+
/** The `fetch` a run's Daytona provider uses: each call goes to the relay, which sends it on with the key. */
|
|
206
|
+
export const relayFetch = (root, runDir, runId) => (async (input, init) => {
|
|
207
|
+
const { url, token } = await relayAddress(root, runDir);
|
|
208
|
+
const headers = new Headers(init?.headers);
|
|
209
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
210
|
+
headers.set(TARGET, input instanceof Request ? input.url : String(input));
|
|
211
|
+
return fetch(`${url}/runs/${encodeURIComponent(runId)}/daytona`, { ...init, headers });
|
|
212
|
+
});
|
|
213
|
+
/** Asks the relay for run `runId`'s box: made and seeded by the server when it has none. */
|
|
214
|
+
export async function relayedBox(root, runDir, runId, signal) {
|
|
215
|
+
const { url, token } = await relayAddress(root, runDir);
|
|
216
|
+
const sent = await fetch(`${url}/runs/${encodeURIComponent(runId)}/box`, { method: "POST", headers: { authorization: `Bearer ${token}` }, redirect: "error", ...(signal ? { signal } : {}) });
|
|
217
|
+
const body = (await sent.json().catch(() => null));
|
|
218
|
+
if (!sent.ok || typeof body?.id !== "string" || typeof body.api_url !== "string") {
|
|
219
|
+
throw new Error(`the server did not give the run its box: ${typeof body?.message === "string" ? body.message : `it answered ${sent.status}`}`);
|
|
220
|
+
}
|
|
221
|
+
return { id: body.id, made: body.made === true, apiUrl: body.api_url };
|
|
222
|
+
}
|
package/dist/boxes.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { BoxProvider } from "@parcha/pi-transport";
|
|
2
|
+
/** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
|
|
3
|
+
export declare const VM_PROVIDER: {
|
|
4
|
+
readonly id: "modal";
|
|
5
|
+
readonly client: "ModalClient";
|
|
6
|
+
readonly keys: readonly ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"];
|
|
7
|
+
};
|
|
8
|
+
/** Every box a place may name, in the order capabilities lists them. */
|
|
9
|
+
export declare const BOX_IDS: readonly ["bwrap", "docker", "modal", "daytona"];
|
|
10
|
+
export type BoxId = (typeof BOX_IDS)[number];
|
|
11
|
+
/** One box: whether this server has it, and why when not (or how it was checked). `state`, set where the server knows
|
|
12
|
+
* more than the probe did (box-image.ts): `preparing` is available, its image still coming. */
|
|
13
|
+
export type BoxOffer = {
|
|
14
|
+
id: BoxId;
|
|
15
|
+
available: boolean;
|
|
16
|
+
state?: BoxState;
|
|
17
|
+
reason?: string;
|
|
18
|
+
};
|
|
19
|
+
/** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
|
|
20
|
+
export declare const BOX_STATES: readonly ["ready", "preparing", "unavailable"];
|
|
21
|
+
export type BoxState = (typeof BOX_STATES)[number];
|
|
22
|
+
/** The boxes this server set up at its start. */
|
|
23
|
+
export type BoxRegistry = {
|
|
24
|
+
/** Every box, in BOX_IDS order. */
|
|
25
|
+
offers(): BoxOffer[];
|
|
26
|
+
/** An available box's provider; undefined for any other. */
|
|
27
|
+
provider(id: BoxId): BoxProvider | undefined;
|
|
28
|
+
};
|
|
29
|
+
/** The setting that lists the boxes to set up: a comma list of box ids. */
|
|
30
|
+
export declare const BOXES_ENV = "AGENTRUN_BOXES";
|
|
31
|
+
/** The VM provider's app, which its sandboxes live in (made when missing). */
|
|
32
|
+
export declare const BOX_APP_ENV = "AGENTRUN_BOX_APP";
|
|
33
|
+
/** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
|
|
34
|
+
export declare const DAYTONA_API_URL = "https://app.daytona.io/api";
|
|
35
|
+
/** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
|
|
36
|
+
* key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
|
|
37
|
+
export declare function daytonaApi(env: NodeJS.ProcessEnv): {
|
|
38
|
+
apiKey: string;
|
|
39
|
+
apiUrl: string;
|
|
40
|
+
} | undefined;
|
|
41
|
+
/** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
|
|
42
|
+
export declare const BOX_KEYS: readonly string[];
|
|
43
|
+
/** How long one box's probe may take; the probes run at once, so this bounds them all. */
|
|
44
|
+
export declare const PROBE_TIMEOUT_MS = 5000;
|
|
45
|
+
/** The boxes `env` lists in AGENTRUN_BOXES; a name that is no box throws, naming it. */
|
|
46
|
+
export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
|
|
47
|
+
/** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
|
|
48
|
+
* `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
|
|
49
|
+
* unavailable, with a short reason that holds no key and no answer's body. */
|
|
50
|
+
export declare function boxRegistry(env: NodeJS.ProcessEnv, options?: {
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
}): Promise<BoxRegistry>;
|
|
53
|
+
/** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
|
|
54
|
+
export declare function boxesLog(offers: readonly BoxOffer[], listed: ReadonlySet<BoxId>): Record<string, string>;
|