@parcha/agentrun-computer 0.0.0-stage → 0.1.0-beta.32
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/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +2401 -2
- package/box/Dockerfile +69 -0
- package/box/agentrun-archil +168 -0
- package/box/build-daytona.py +26 -0
- package/box/build-e2b.mjs +32 -0
- package/box/build-modal.py +17 -0
- package/dist/actions.d.ts +18 -0
- package/dist/actions.js +139 -0
- package/dist/browser.d.ts +151 -0
- package/dist/browser.js +305 -0
- package/dist/browserbase.d.ts +139 -0
- package/dist/browserbase.js +408 -0
- package/dist/child.d.ts +40 -0
- package/dist/child.js +127 -0
- package/dist/client.d.ts +22 -0
- package/dist/client.js +136 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/archil.d.ts +68 -0
- package/dist/conformance/archil.js +152 -0
- package/dist/conformance/browserbase.d.ts +35 -0
- package/dist/conformance/browserbase.js +45 -0
- package/dist/conformance/cases/apps.d.ts +2 -0
- package/dist/conformance/cases/apps.js +155 -0
- package/dist/conformance/cases/browser.d.ts +4 -0
- package/dist/conformance/cases/browser.js +105 -0
- package/dist/conformance/cases/drift.d.ts +2 -0
- package/dist/conformance/cases/drift.js +64 -0
- package/dist/conformance/cases/exec.d.ts +2 -0
- package/dist/conformance/cases/exec.js +125 -0
- package/dist/conformance/cases/files.d.ts +2 -0
- package/dist/conformance/cases/files.js +294 -0
- package/dist/conformance/cases/health.d.ts +2 -0
- package/dist/conformance/cases/health.js +71 -0
- package/dist/conformance/cases/index.d.ts +9 -0
- package/dist/conformance/cases/index.js +37 -0
- package/dist/conformance/cases/input.d.ts +12 -0
- package/dist/conformance/cases/input.js +109 -0
- package/dist/conformance/cases/isolation.d.ts +21 -0
- package/dist/conformance/cases/isolation.js +92 -0
- package/dist/conformance/cases/lifetime.d.ts +2 -0
- package/dist/conformance/cases/lifetime.js +64 -0
- package/dist/conformance/cases/mount.d.ts +2 -0
- package/dist/conformance/cases/mount.js +252 -0
- package/dist/conformance/cases/process.d.ts +2 -0
- package/dist/conformance/cases/process.js +240 -0
- package/dist/conformance/cases/provider.d.ts +2 -0
- package/dist/conformance/cases/provider.js +302 -0
- package/dist/conformance/cases/screen.d.ts +9 -0
- package/dist/conformance/cases/screen.js +230 -0
- package/dist/conformance/cases/settings.d.ts +57 -0
- package/dist/conformance/cases/settings.js +142 -0
- package/dist/conformance/cases/touch.d.ts +2 -0
- package/dist/conformance/cases/touch.js +117 -0
- package/dist/conformance/cases/util.d.ts +7 -0
- package/dist/conformance/cases/util.js +8 -0
- package/dist/conformance/cdp.d.ts +13 -0
- package/dist/conformance/cdp.js +88 -0
- package/dist/conformance/cli.d.ts +29 -0
- package/dist/conformance/cli.js +231 -0
- package/dist/conformance/daytona-sweep.d.ts +18 -0
- package/dist/conformance/daytona-sweep.js +118 -0
- package/dist/conformance/daytona.d.ts +83 -0
- package/dist/conformance/daytona.js +107 -0
- package/dist/conformance/docker.d.ts +38 -0
- package/dist/conformance/docker.js +70 -0
- package/dist/conformance/drift-daemon.d.ts +8 -0
- package/dist/conformance/drift-daemon.js +41 -0
- package/dist/conformance/e2b-diagnose.d.ts +16 -0
- package/dist/conformance/e2b-diagnose.js +61 -0
- package/dist/conformance/e2b-sweep.d.ts +18 -0
- package/dist/conformance/e2b-sweep.js +125 -0
- package/dist/conformance/e2b.d.ts +74 -0
- package/dist/conformance/e2b.js +111 -0
- package/dist/conformance/fixture.d.ts +65 -0
- package/dist/conformance/fixture.js +98 -0
- package/dist/conformance/index.d.ts +8 -0
- package/dist/conformance/index.js +8 -0
- package/dist/conformance/kernel.d.ts +31 -0
- package/dist/conformance/kernel.js +40 -0
- package/dist/conformance/kind.d.ts +23 -0
- package/dist/conformance/kind.js +58 -0
- package/dist/conformance/modal-sweep.d.ts +22 -0
- package/dist/conformance/modal-sweep.js +190 -0
- package/dist/conformance/modal.d.ts +69 -0
- package/dist/conformance/modal.js +76 -0
- package/dist/conformance/orgo.d.ts +41 -0
- package/dist/conformance/orgo.js +69 -0
- package/dist/conformance/phone-harness.d.ts +61 -0
- package/dist/conformance/phone-harness.js +241 -0
- package/dist/conformance/png.d.ts +16 -0
- package/dist/conformance/png.js +132 -0
- package/dist/conformance/report.d.ts +2 -0
- package/dist/conformance/report.js +86 -0
- package/dist/conformance/runner.d.ts +11 -0
- package/dist/conformance/runner.js +585 -0
- package/dist/conformance/tar.d.ts +13 -0
- package/dist/conformance/tar.js +105 -0
- package/dist/conformance/types.d.ts +257 -0
- package/dist/conformance/types.js +24 -0
- package/dist/daemon-copy.d.ts +40 -0
- package/dist/daemon-copy.js +259 -0
- package/dist/daytona.d.ts +178 -0
- package/dist/daytona.js +1484 -0
- package/dist/desktop.d.ts +24 -0
- package/dist/desktop.js +68 -0
- package/dist/docker/egress-main.d.ts +1 -0
- package/dist/docker/egress-main.js +68 -0
- package/dist/docker/egress-proxy.d.ts +53 -0
- package/dist/docker/egress-proxy.js +450 -0
- package/dist/docker/egress-table.d.ts +39 -0
- package/dist/docker/egress-table.js +197 -0
- package/dist/docker/egress.d.ts +109 -0
- package/dist/docker/egress.js +318 -0
- package/dist/docker/image.d.ts +49 -0
- package/dist/docker/image.js +302 -0
- package/dist/docker/stage.d.ts +21 -0
- package/dist/docker/stage.js +290 -0
- package/dist/docker/volume.d.ts +24 -0
- package/dist/docker/volume.js +67 -0
- package/dist/docker.d.ts +150 -0
- package/dist/docker.js +1200 -0
- package/dist/drift.d.ts +200 -0
- package/dist/drift.js +416 -0
- package/dist/e2b.d.ts +335 -0
- package/dist/e2b.js +1515 -0
- package/dist/entry.d.ts +2 -0
- package/dist/entry.js +24 -0
- package/dist/files.d.ts +50 -0
- package/dist/files.js +208 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +26 -0
- package/dist/isolation.d.ts +29 -0
- package/dist/isolation.js +71 -0
- package/dist/janitor.d.ts +50 -0
- package/dist/janitor.js +135 -0
- package/dist/kernel.d.ts +113 -0
- package/dist/kernel.js +358 -0
- package/dist/kinds.d.ts +79 -0
- package/dist/kinds.js +133 -0
- package/dist/labels.d.ts +23 -0
- package/dist/labels.js +50 -0
- package/dist/modal.d.ts +302 -0
- package/dist/modal.js +1374 -0
- package/dist/mount-archil.d.ts +164 -0
- package/dist/mount-archil.js +471 -0
- package/dist/mount.d.ts +57 -0
- package/dist/mount.js +104 -0
- package/dist/orgo-channel.d.ts +96 -0
- package/dist/orgo-channel.js +391 -0
- package/dist/orgo.d.ts +139 -0
- package/dist/orgo.js +1006 -0
- package/dist/phone-harness.d.ts +185 -0
- package/dist/phone-harness.js +1420 -0
- package/dist/processes.d.ts +24 -0
- package/dist/processes.js +40 -0
- package/dist/protocol.d.ts +729 -0
- package/dist/protocol.js +54 -0
- package/dist/provider.d.ts +245 -0
- package/dist/provider.js +37 -0
- package/dist/providers.d.ts +68 -0
- package/dist/providers.js +25 -0
- package/dist/result.d.ts +15 -0
- package/dist/result.js +2 -0
- package/dist/screen-watch.d.ts +150 -0
- package/dist/screen-watch.js +490 -0
- package/dist/test-connection.d.ts +17 -0
- package/dist/test-connection.js +26 -0
- package/dist/wait.d.ts +23 -0
- package/dist/wait.js +65 -0
- package/package.json +62 -4
package/dist/daytona.js
ADDED
|
@@ -0,0 +1,1484 @@
|
|
|
1
|
+
// The Daytona provisioner, over Daytona's v0 REST API with fetch (no SDK), as pi-transport's Daytona box does. The daemon
|
|
2
|
+
// goes in through the toolbox's file upload and starts as a session command, dropped to a user with no capabilities;
|
|
3
|
+
// connect() carries stdio over a session command's input calls and its log stream. Every Daytona fact used here is cited
|
|
4
|
+
// in the README's Daytona section.
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { resolve } from "node:path";
|
|
8
|
+
import { PassThrough, Writable } from "node:stream";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { childCommands, daemonDrift, shellCommand } from "./child.js";
|
|
11
|
+
import { OWN_NETWORK_ONLY, readOwnNetwork, TOOL_USER } from "./isolation.js";
|
|
12
|
+
import { DaemonClient } from "./client.js";
|
|
13
|
+
import { COMPUTER_LABEL, DEADLINE_LABEL, helloDrift, WORK } from "./drift.js";
|
|
14
|
+
import { releaseOlder } from "./janitor.js";
|
|
15
|
+
import { epochOf, RUN_LABEL } from "./labels.js";
|
|
16
|
+
import { checkMount, readBackOf } from "./mount.js";
|
|
17
|
+
import { ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilLabels, archilMount, archilRefusals, archilRelease, mountDrift, readArchilMount, recordedMount, syncingClient, } from "./mount-archil.js";
|
|
18
|
+
import { MAX_LINE_BYTES } from "./protocol.js";
|
|
19
|
+
import { checkLifetime, } from "./provider.js";
|
|
20
|
+
import { fail, ok } from "./result.js";
|
|
21
|
+
import { daemonWatch } from "./screen-watch.js";
|
|
22
|
+
import { countTested } from "./test-connection.js";
|
|
23
|
+
import { waitUntil } from "./wait.js";
|
|
24
|
+
/**
|
|
25
|
+
* The mount kinds a Daytona computer takes: an Archil mount of the run's folder (mount-archil.ts), made as root through
|
|
26
|
+
* the toolbox, from a snapshot of box/Dockerfile, with the daemon user agentrun-tool (daemonUser "2510:2510").
|
|
27
|
+
*/
|
|
28
|
+
export const MOUNT = ["archil"];
|
|
29
|
+
/** The machine kind and groups of its one configuration: a linux computer. */
|
|
30
|
+
export const CAPABILITIES = [{ kind: "linux", groups: ["exec", "files", "processes"] }];
|
|
31
|
+
/**
|
|
32
|
+
* A DaytonaProvider from its options alone; it reads no environment, so the key, the API URL (default Daytona's own) and
|
|
33
|
+
* the target are the caller's: serve passes its DAYTONA_API_KEY, DAYTONA_API_URL and DAYTONA_TARGET, the conformance
|
|
34
|
+
* module the settings it reads. Throws in words when an option is missing or wrong, never echoing the key.
|
|
35
|
+
*/
|
|
36
|
+
export function create(options) {
|
|
37
|
+
const { apiKey, arch = "amd64", sandboxClass = "container", daemonPath } = options ?? {};
|
|
38
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
39
|
+
throw new Error("options.apiKey, the Daytona API key, is required: the provider reads no environment, so the caller passes it");
|
|
40
|
+
if (arch !== "amd64" && arch !== "arm64")
|
|
41
|
+
throw new Error(`options.arch is amd64 or arm64, not ${String(arch)}`);
|
|
42
|
+
if (sandboxClass !== "container" && sandboxClass !== "linux-vm")
|
|
43
|
+
throw new Error(`options.sandboxClass is container or linux-vm, not ${String(sandboxClass)}`);
|
|
44
|
+
return new DaytonaProvider({ ...options, apiKey, arch, sandboxClass, daemonPath: daemonPath || fileURLToPath(new URL(`./computerd-linux-${arch}`, import.meta.url)) });
|
|
45
|
+
}
|
|
46
|
+
/** The conformance CLI's module for Daytona: the run's idle stop and auto-delete, its snapshot, notes and drifted twin. */
|
|
47
|
+
export const conformance = () => import("./conformance/daytona.js");
|
|
48
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
49
|
+
const DEFAULT_API_URL = "https://app.daytona.io/api";
|
|
50
|
+
/** The image that asks for Daytona's default snapshot: the create sends no snapshot field. */
|
|
51
|
+
export const DAYTONA_DEFAULT_SNAPSHOT = "default";
|
|
52
|
+
/** The label, in the provider's own namespace beside the deadline's, that holds the image create was asked for: Daytona
|
|
53
|
+
* reports only the snapshot it resolved that image to, a name of its own for "default". */
|
|
54
|
+
const IMAGE_LABEL = `${COMPUTER_LABEL}.image`;
|
|
55
|
+
/** autoDeleteInterval when autoDeleteMinutes is unset: negative is disabled. */
|
|
56
|
+
const NO_AUTO_DELETE = -1;
|
|
57
|
+
const DEFAULTS = {
|
|
58
|
+
requestMs: 30_000,
|
|
59
|
+
createMs: 120_000,
|
|
60
|
+
startMs: 120_000,
|
|
61
|
+
deleteMs: 120_000,
|
|
62
|
+
goneMs: 120_000,
|
|
63
|
+
stopMs: 120_000,
|
|
64
|
+
uploadMs: 120_000,
|
|
65
|
+
execMs: 60_000,
|
|
66
|
+
helloMs: 30_000,
|
|
67
|
+
pollMs: 1_000,
|
|
68
|
+
retryMs: 500,
|
|
69
|
+
listedMs: 15_000,
|
|
70
|
+
listedStableMs: 1_000,
|
|
71
|
+
};
|
|
72
|
+
const RETRY_ATTEMPTS = 3;
|
|
73
|
+
const DELETE_ATTEMPTS = 4;
|
|
74
|
+
const LISTED_ROUNDS = 2;
|
|
75
|
+
const LISTED_POLL_MS = 150;
|
|
76
|
+
/** The longest pause between two reads while release waits: the pauses double from pollMs up to it. */
|
|
77
|
+
const RELEASE_POLL_MAX_MS = 5_000;
|
|
78
|
+
const MAX_PAGES = 1000;
|
|
79
|
+
const NAME = /^computer-[0-9a-f]{12}$/;
|
|
80
|
+
const USER = /^(\d+):(\d+)$/;
|
|
81
|
+
const MAX_ID = 4_294_967_294;
|
|
82
|
+
const MAX_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
|
|
83
|
+
/** Daytona's TTL is whole minutes, and its clock is not ours: the vendor's end may come this long after the deadline. */
|
|
84
|
+
const LIFETIME_SLACK_MS = 60_000 + 120_000;
|
|
85
|
+
const MAX_DOMAINS = 100;
|
|
86
|
+
const MAX_CIDRS = 10;
|
|
87
|
+
/** The toolbox's port, on every interface of the sandbox (daytonaio/daytona@b5a5d9e7 apps/daemon/pkg/toolbox/config/config.go:6). */
|
|
88
|
+
const TOOLBOX_PORT = 2280;
|
|
89
|
+
const INIT_SESSION = "agentrun-computerd";
|
|
90
|
+
const STAGING = "/tmp/agentrun-computerd-";
|
|
91
|
+
const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "mount"]);
|
|
92
|
+
/** The provider's root channel: argv run as root in a session of its own; the image's user is root, never sudo. */
|
|
93
|
+
const ROOT_RUN = [
|
|
94
|
+
"# agentrun-computer: root",
|
|
95
|
+
'[ "$(id -u)" = 0 ] || { echo "the toolbox runs commands as $(id -un), not root: a Daytona computer with an Archil mount needs a snapshot of box/Dockerfile, whose user is root"; exit 126; }',
|
|
96
|
+
'exec "$@"',
|
|
97
|
+
].join("\n");
|
|
98
|
+
/** An Archil spec's mount, or undefined. */
|
|
99
|
+
const archilOf = (spec) => (spec.mount?.kind === "archil" ? spec.mount : undefined);
|
|
100
|
+
/** A session command's log as text: Daytona's JSON of stdout and stderr, or its lines marked 01 01 01 and 02 02 02. */
|
|
101
|
+
function logText(bytes) {
|
|
102
|
+
const buffer = Buffer.from(bytes);
|
|
103
|
+
const parsed = parseJson(buffer);
|
|
104
|
+
if (parsed !== null && typeof parsed === "object" && (typeof parsed.stdout === "string" || typeof parsed.stderr === "string")) {
|
|
105
|
+
return [parsed.stdout, parsed.stderr].filter((part) => typeof part === "string").join("\n");
|
|
106
|
+
}
|
|
107
|
+
return buffer.toString("utf8").replace(/(^|\n)(?:\x01\x01\x01|\x02\x02\x02)/g, "$1");
|
|
108
|
+
}
|
|
109
|
+
const SIZE_FIELDS = new Set(["cpus", "memoryMb", "pids"]);
|
|
110
|
+
const NUL = "a NUL byte cannot be sent to Daytona";
|
|
111
|
+
const QUOTA = /quota|capacity|limit exceeded|too many/i;
|
|
112
|
+
const STARTING = new Set(["creating", "restoring", "starting", "pending_build", "building_snapshot", "pulling_snapshot", "resizing", "snapshotting", "forking", "resuming", "unknown"]);
|
|
113
|
+
const GONE = new Set(["destroyed", "destroying"]);
|
|
114
|
+
const STOPPED = new Set(["stopped", "archived", "paused"]);
|
|
115
|
+
/** On the way from started to stopped or paused: still running until Daytona reads it stopped. */
|
|
116
|
+
const LEAVING = new Set(["stopping", "pausing"]);
|
|
117
|
+
const OUT = Buffer.from([1, 1, 1]);
|
|
118
|
+
const ERR = Buffer.from([2, 2, 2]);
|
|
119
|
+
/** A line the client wrote, echoed back: a request or a notification is never a daemon's reply. */
|
|
120
|
+
const ECHO = /^\{"jsonrpc":"2\.0",("id":\d+,)?"method":/;
|
|
121
|
+
/**
|
|
122
|
+
* The three commands the provider sends into a sandbox, exactly: install (through /process/execute), init and stdio
|
|
123
|
+
* (each a session command), the child daemon's commands (childCommands). Exported so a test can run them where Daytona
|
|
124
|
+
* would, in a root container.
|
|
125
|
+
*/
|
|
126
|
+
export function daytonaCommands({ staging = "", deadline = "", user = TOOL_USER } = {}) {
|
|
127
|
+
return childCommands({ staging, deadline, user });
|
|
128
|
+
}
|
|
129
|
+
const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
130
|
+
const decoder = new TextDecoder();
|
|
131
|
+
const sleep = (ms, signal) => new Promise((done) => {
|
|
132
|
+
const timer = setTimeout(finish, ms);
|
|
133
|
+
function finish() {
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
signal?.removeEventListener("abort", finish);
|
|
136
|
+
done();
|
|
137
|
+
}
|
|
138
|
+
if (signal?.aborted)
|
|
139
|
+
finish();
|
|
140
|
+
else
|
|
141
|
+
signal?.addEventListener("abort", finish, { once: true });
|
|
142
|
+
});
|
|
143
|
+
const ours = (sb) => typeof sb?.id === "string" && sb.labels?.[COMPUTER_LABEL] === "1" && NAME.test(sb.name ?? "");
|
|
144
|
+
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
145
|
+
const policyWords = (policy) => (typeof policy === "string" ? policy : "other" in policy ? policy.other : JSON.stringify(policy));
|
|
146
|
+
const IPV4_CIDR = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/;
|
|
147
|
+
const DOMAIN = /^(\*\.)?([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
148
|
+
function isCidr(entry) {
|
|
149
|
+
const match = IPV4_CIDR.exec(entry);
|
|
150
|
+
return match !== null && match.slice(1, 5).every((part) => Number(part) <= 255 && String(Number(part)) === part) && Number(match[5]) <= 32;
|
|
151
|
+
}
|
|
152
|
+
/** A spec's allowlist split into Daytona's two lists, or why Daytona cannot hold it. */
|
|
153
|
+
function allowOf(entries) {
|
|
154
|
+
if (!Array.isArray(entries) || entries.length === 0)
|
|
155
|
+
return 'an allowlist needs at least one domain or CIDR; for no network ask for "none"';
|
|
156
|
+
const cidrs = [];
|
|
157
|
+
const domains = [];
|
|
158
|
+
for (const entry of entries) {
|
|
159
|
+
if (typeof entry !== "string")
|
|
160
|
+
return "an allowlist holds strings: domains or IPv4 CIDRs";
|
|
161
|
+
if (entry.includes(":"))
|
|
162
|
+
return `${JSON.stringify(entry)}: a Daytona CIDR list is IPv4 only, and a domain takes no scheme or port`;
|
|
163
|
+
if (/^[\d.]+(\/\d+)?$/.test(entry)) {
|
|
164
|
+
if (!isCidr(entry))
|
|
165
|
+
return `${JSON.stringify(entry)}: an IPv4 CIDR is A.B.C.D/N, N from 0 to 32`;
|
|
166
|
+
cidrs.push(entry);
|
|
167
|
+
}
|
|
168
|
+
else if (entry.length <= 253 && DOMAIN.test(entry))
|
|
169
|
+
domains.push(entry);
|
|
170
|
+
else
|
|
171
|
+
return `${JSON.stringify(entry)} is neither a domain (example.com, *.example.com: no scheme, path or port) nor an IPv4 CIDR`;
|
|
172
|
+
}
|
|
173
|
+
if (cidrs.length > 0 && domains.length > 0)
|
|
174
|
+
return "a Daytona allowlist is domains or IPv4 CIDRs, never both: Daytona keeps them apart";
|
|
175
|
+
if (domains.length > MAX_DOMAINS)
|
|
176
|
+
return `a Daytona domain allowlist holds at most ${MAX_DOMAINS} domains, not ${domains.length}`;
|
|
177
|
+
if (cidrs.length > MAX_CIDRS)
|
|
178
|
+
return `a Daytona CIDR allowlist holds at most ${MAX_CIDRS} CIDRs, not ${cidrs.length}`;
|
|
179
|
+
return { cidrs, domains };
|
|
180
|
+
}
|
|
181
|
+
/** The entries of a comma-separated list Daytona keeps, trimmed; none when it is unset; undefined for a shape it never sends. */
|
|
182
|
+
function entriesOf(list) {
|
|
183
|
+
if (list === undefined || list === null)
|
|
184
|
+
return [];
|
|
185
|
+
if (typeof list !== "string")
|
|
186
|
+
return undefined;
|
|
187
|
+
return list
|
|
188
|
+
.split(",")
|
|
189
|
+
.map((entry) => entry.trim())
|
|
190
|
+
.filter((entry) => entry !== "");
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* A sandbox's network as Daytona keeps it: none is block-all with no list, open is neither, an allowlist is one list.
|
|
194
|
+
* An outbound proxy, both lists, or a shape not read here is reported in words, never as a policy it might widen to.
|
|
195
|
+
*/
|
|
196
|
+
function networkOf(sb) {
|
|
197
|
+
if (typeof sb.outboundProxyUrl === "string" && sb.outboundProxyUrl !== "")
|
|
198
|
+
return { other: "an outbound proxy is set on it" };
|
|
199
|
+
const cidrs = entriesOf(sb.networkAllowList);
|
|
200
|
+
const domains = entriesOf(sb.domainAllowList);
|
|
201
|
+
if (cidrs === undefined || domains === undefined)
|
|
202
|
+
return { other: "an allow list in a shape this provider does not read" };
|
|
203
|
+
if (sb.networkBlockAll === true)
|
|
204
|
+
return cidrs.length + domains.length === 0 ? "none" : { other: "block-all with an allow list" };
|
|
205
|
+
if (sb.networkBlockAll !== false)
|
|
206
|
+
return { other: "Daytona did not report networkBlockAll" };
|
|
207
|
+
if (cidrs.length > 0 && domains.length > 0)
|
|
208
|
+
return { other: "both a CIDR and a domain allow list" };
|
|
209
|
+
if (cidrs.length > 0)
|
|
210
|
+
return { allow: cidrs };
|
|
211
|
+
if (domains.length > 0)
|
|
212
|
+
return { allow: domains };
|
|
213
|
+
return "open";
|
|
214
|
+
}
|
|
215
|
+
function samePolicy(a, b) {
|
|
216
|
+
if (typeof a === "string" || typeof b === "string")
|
|
217
|
+
return a === b;
|
|
218
|
+
if (!("allow" in a))
|
|
219
|
+
return false;
|
|
220
|
+
const left = new Set(a.allow.map((entry) => entry.toLowerCase()));
|
|
221
|
+
const right = new Set(b.allow.map((entry) => entry.toLowerCase()));
|
|
222
|
+
return left.size === right.size && [...left].every((entry) => right.has(entry));
|
|
223
|
+
}
|
|
224
|
+
/** The network fields a create or a change sends for a policy; undefined for one check() refuses. */
|
|
225
|
+
function networkBody(policy) {
|
|
226
|
+
if (policy === "none")
|
|
227
|
+
return { networkBlockAll: true };
|
|
228
|
+
if (policy === "open")
|
|
229
|
+
return { networkBlockAll: false };
|
|
230
|
+
const lists = allowOf(policy.allow);
|
|
231
|
+
if (typeof lists === "string")
|
|
232
|
+
return undefined;
|
|
233
|
+
return lists.cidrs.length > 0 ? { networkAllowList: lists.cidrs.join(","), domainAllowList: "" } : { domainAllowList: lists.domains.join(","), networkAllowList: "" };
|
|
234
|
+
}
|
|
235
|
+
function labelProblem(key, value) {
|
|
236
|
+
if (typeof value !== "string")
|
|
237
|
+
return `the label ${key} must be a string`;
|
|
238
|
+
if (key.includes("\0") || value.includes("\0"))
|
|
239
|
+
return `the label ${JSON.stringify(key)}: ${NUL}`;
|
|
240
|
+
if (key === "")
|
|
241
|
+
return "a label name must be non-empty";
|
|
242
|
+
if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
|
|
243
|
+
return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
|
|
244
|
+
// connect and list read an Archil mount from this label: only create writes it, from the spec's mount.
|
|
245
|
+
if (key === ARCHIL_MOUNT_LABEL)
|
|
246
|
+
return `the label ${key} is the provider's own: it records an Archil computer's mount`;
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
function filterProblem(labels) {
|
|
250
|
+
if (typeof labels !== "object" || labels === null || Array.isArray(labels))
|
|
251
|
+
return "labels must map names to strings";
|
|
252
|
+
for (const [key, value] of Object.entries(labels)) {
|
|
253
|
+
if (typeof value !== "string")
|
|
254
|
+
return `the label ${key} must be a string`;
|
|
255
|
+
if (key === "")
|
|
256
|
+
return "a label name must be non-empty";
|
|
257
|
+
}
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
/** The ISO deadline a sandbox's label holds, or undefined when it is missing or not the ISO time create writes. */
|
|
261
|
+
function deadlineOf(sb) {
|
|
262
|
+
const written = sb.labels?.[DEADLINE_LABEL];
|
|
263
|
+
const at = written === undefined ? Number.NaN : Date.parse(written);
|
|
264
|
+
return Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
|
|
265
|
+
}
|
|
266
|
+
function stateOf(sb) {
|
|
267
|
+
const state = sb.state ?? "";
|
|
268
|
+
return state === "started" || STARTING.has(state) || LEAVING.has(state) ? "running" : "stopped";
|
|
269
|
+
}
|
|
270
|
+
/** Whether a sandbox is going: Daytona is destroying it, or has been asked to. list() leaves such a one out. */
|
|
271
|
+
const going = (sb) => GONE.has(sb.state ?? "") || sb.desiredState === "destroyed";
|
|
272
|
+
/** A state as Daytona reported it, for words: the state, and the desired state when it differs. */
|
|
273
|
+
function stateWords(sb) {
|
|
274
|
+
if (sb === undefined)
|
|
275
|
+
return "gone (404)";
|
|
276
|
+
const state = sb.state ?? "in no state";
|
|
277
|
+
return sb.desiredState !== undefined && sb.desiredState !== sb.state ? `${state} (desired ${sb.desiredState})` : state;
|
|
278
|
+
}
|
|
279
|
+
function codeOf(status, text) {
|
|
280
|
+
if ((status === 400 || status === 403 || status === 429 || status === 507) && QUOTA.test(text))
|
|
281
|
+
return "limit";
|
|
282
|
+
if (status === 401 || status === 403)
|
|
283
|
+
return "denied";
|
|
284
|
+
if (status === 404 || status === 410)
|
|
285
|
+
return "not_found";
|
|
286
|
+
if (status === 408)
|
|
287
|
+
return "timeout";
|
|
288
|
+
if (status === 429)
|
|
289
|
+
return "limit";
|
|
290
|
+
if (status === 400 || status === 409 || status === 422)
|
|
291
|
+
return "invalid";
|
|
292
|
+
return "daytona";
|
|
293
|
+
}
|
|
294
|
+
/** Whether fetch failed on a redirect it was told not to follow. */
|
|
295
|
+
function redirected(cause) {
|
|
296
|
+
const inner = cause?.cause;
|
|
297
|
+
return /redirect/i.test(`${cause?.message ?? ""} ${inner?.message ?? ""}`);
|
|
298
|
+
}
|
|
299
|
+
function parseJson(bytes) {
|
|
300
|
+
const text = decoder.decode(bytes);
|
|
301
|
+
if (text === "")
|
|
302
|
+
return null;
|
|
303
|
+
try {
|
|
304
|
+
return JSON.parse(text);
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** Daytona's REST API: the control plane, and the toolbox of one sandbox. */
|
|
311
|
+
class Rest {
|
|
312
|
+
#base;
|
|
313
|
+
#key;
|
|
314
|
+
#fetch;
|
|
315
|
+
#timeouts;
|
|
316
|
+
constructor(base, key, fetcher, timeouts) {
|
|
317
|
+
this.#base = base.replace(/\/+$/, "");
|
|
318
|
+
this.#key = key;
|
|
319
|
+
this.#fetch = fetcher;
|
|
320
|
+
this.#timeouts = timeouts;
|
|
321
|
+
}
|
|
322
|
+
/** The headers of every call and log stream; split output keeps a session's stdout and stderr apart. */
|
|
323
|
+
headers() {
|
|
324
|
+
return { Authorization: `Bearer ${this.#key}`, "X-Daytona-Source": "agentrun-computer", "X-Daytona-Split-Output": "true" };
|
|
325
|
+
}
|
|
326
|
+
sandbox(idOrName = "", rest = "") {
|
|
327
|
+
return `${this.#base}/sandbox${idOrName === "" ? "" : `/${encodeURIComponent(idOrName)}`}${rest}`;
|
|
328
|
+
}
|
|
329
|
+
/** One call, bounded by its timeout and the caller's signal. A failure names the method, path and status, never a header. */
|
|
330
|
+
async call(method, url, init, signal) {
|
|
331
|
+
const what = `${method} ${new URL(url).pathname}`;
|
|
332
|
+
const attempts = init.retry === true ? RETRY_ATTEMPTS : 1;
|
|
333
|
+
const timeoutMs = init.timeoutMs ?? this.#timeouts.requestMs;
|
|
334
|
+
for (let attempt = 1;; attempt++) {
|
|
335
|
+
if (signal?.aborted)
|
|
336
|
+
return fail("aborted", `${what} was aborted`);
|
|
337
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
338
|
+
let failure;
|
|
339
|
+
let retryable = true;
|
|
340
|
+
try {
|
|
341
|
+
// Never a redirect: a followed one keeps the key, and could carry a toolbox call to another sandbox.
|
|
342
|
+
const headers = init.json === undefined ? this.headers() : { ...this.headers(), "Content-Type": "application/json" };
|
|
343
|
+
const response = await this.#fetch(url, {
|
|
344
|
+
method,
|
|
345
|
+
headers,
|
|
346
|
+
body: init.json === undefined ? init.form : JSON.stringify(init.json),
|
|
347
|
+
redirect: "error",
|
|
348
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
349
|
+
});
|
|
350
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
351
|
+
if (response.ok || (init.anyStatus === true && response.status < 500 && response.status !== 429))
|
|
352
|
+
return ok({ status: response.status, bytes });
|
|
353
|
+
const text = decoder.decode(bytes).replace(/\s+/g, " ").slice(0, 300);
|
|
354
|
+
retryable = response.status === 429 || response.status >= 500;
|
|
355
|
+
failure = { code: codeOf(response.status, text), message: `${what}: ${response.status} ${text}` };
|
|
356
|
+
}
|
|
357
|
+
catch (cause) {
|
|
358
|
+
if (signal?.aborted)
|
|
359
|
+
return fail("aborted", `${what} was aborted`);
|
|
360
|
+
if (timeout.aborted)
|
|
361
|
+
failure = { code: "timeout", message: `${what} did not answer within ${timeoutMs / 1000} s` };
|
|
362
|
+
else if (redirected(cause))
|
|
363
|
+
return fail("daytona", `${what}: Daytona answered with a redirect, which is never followed: it would carry the key`);
|
|
364
|
+
else
|
|
365
|
+
failure = { code: "daytona", message: `${what}: ${cause.message}` };
|
|
366
|
+
}
|
|
367
|
+
if (!retryable || attempt >= attempts)
|
|
368
|
+
return { ok: false, error: failure };
|
|
369
|
+
await sleep(this.#timeouts.retryMs * 2 ** (attempt - 1), signal);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
async json(method, url, init, signal) {
|
|
373
|
+
const answer = await this.call(method, url, init, signal);
|
|
374
|
+
return answer.ok ? ok(parseJson(answer.value.bytes)) : answer;
|
|
375
|
+
}
|
|
376
|
+
/** A sandbox by id or name; undefined when Daytona has none. */
|
|
377
|
+
async get(idOrName, signal) {
|
|
378
|
+
const found = await this.json("GET", this.sandbox(idOrName), { retry: true }, signal);
|
|
379
|
+
if (!found.ok)
|
|
380
|
+
return found.error.code === "not_found" ? ok(undefined) : found;
|
|
381
|
+
const sb = found.value;
|
|
382
|
+
return typeof sb?.id === "string" ? ok(sb) : fail("daytona", `GET /sandbox/${idOrName}: no sandbox in the answer`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Every way a sandbox, as Daytona reads it back, differs from what create asked for. Pure: no call. */
|
|
386
|
+
function sandboxDrift(spec, sb, expected) {
|
|
387
|
+
const found = [];
|
|
388
|
+
const mismatch = (field, declared, actual) => found.push(`${field}: declared ${show(declared)}, read back ${show(actual)}`);
|
|
389
|
+
// Daytona's default snapshot is whichever it names: a computer made from it is not held to a name.
|
|
390
|
+
if (spec.image !== DAYTONA_DEFAULT_SNAPSHOT && sb.snapshot !== spec.image)
|
|
391
|
+
mismatch("snapshot", spec.image, sb.snapshot);
|
|
392
|
+
const network = networkOf(sb);
|
|
393
|
+
if (!samePolicy(network, spec.network))
|
|
394
|
+
found.push(`network: declared ${policyWords(spec.network)}, read back ${policyWords(network)}`);
|
|
395
|
+
const labels = sb.labels ?? {};
|
|
396
|
+
if (labels[COMPUTER_LABEL] !== "1")
|
|
397
|
+
mismatch(`label ${COMPUTER_LABEL}`, "1", labels[COMPUTER_LABEL]);
|
|
398
|
+
if (labels[DEADLINE_LABEL] !== expected.deadline)
|
|
399
|
+
mismatch(`label ${DEADLINE_LABEL}`, expected.deadline, labels[DEADLINE_LABEL]);
|
|
400
|
+
if (labels[IMAGE_LABEL] !== spec.image)
|
|
401
|
+
mismatch(`label ${IMAGE_LABEL}`, spec.image, labels[IMAGE_LABEL]);
|
|
402
|
+
for (const [key, value] of Object.entries(spec.labels ?? {}))
|
|
403
|
+
if (labels[key] !== value)
|
|
404
|
+
mismatch(`label ${key}`, value, labels[key]);
|
|
405
|
+
if (sb.autoStopInterval !== expected.autoStopInterval)
|
|
406
|
+
mismatch("autoStopInterval", expected.autoStopInterval, sb.autoStopInterval);
|
|
407
|
+
if (sb.autoDeleteInterval !== expected.autoDeleteInterval)
|
|
408
|
+
mismatch("autoDeleteInterval", expected.autoDeleteInterval, sb.autoDeleteInterval);
|
|
409
|
+
const ends = typeof sb.autoDestroyAt === "string" ? Date.parse(sb.autoDestroyAt) : Number.NaN;
|
|
410
|
+
if (Number.isNaN(ends))
|
|
411
|
+
found.push(`autoDestroyAt: declared a TTL ending by ${expected.deadline}, read back ${show(sb.autoDestroyAt)}: Daytona would not end the computer`);
|
|
412
|
+
else if (ends > Date.parse(expected.deadline) + LIFETIME_SLACK_MS)
|
|
413
|
+
found.push(`autoDestroyAt: ${sb.autoDestroyAt} is past the deadline ${expected.deadline} by more than the TTL's minute and ${(LIFETIME_SLACK_MS - 60_000) / 60_000} minutes of clock skew`);
|
|
414
|
+
if (sb.sandboxClass !== expected.sandboxClass)
|
|
415
|
+
mismatch("sandboxClass", expected.sandboxClass, sb.sandboxClass);
|
|
416
|
+
if (sb.public !== false)
|
|
417
|
+
mismatch("public", false, sb.public);
|
|
418
|
+
if (sb.kvm === true)
|
|
419
|
+
mismatch("kvm", false, sb.kvm);
|
|
420
|
+
if (sb.gpu !== undefined && sb.gpu !== 0)
|
|
421
|
+
mismatch("gpu", 0, sb.gpu);
|
|
422
|
+
if (Array.isArray(sb.volumes) ? sb.volumes.length > 0 : sb.volumes !== undefined && sb.volumes !== null)
|
|
423
|
+
mismatch("volumes", [], sb.volumes);
|
|
424
|
+
if (typeof sb.linkedSandboxId === "string" && sb.linkedSandboxId !== "")
|
|
425
|
+
mismatch("linkedSandboxId", "none", sb.linkedSandboxId);
|
|
426
|
+
return found;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* The byte stream of one `computerd stdio` session command: writes go to its input, a whole line at a time and one
|
|
430
|
+
* call after another; reads come from its log stream, where Daytona prefixes each stdout line with 01 01 01 and each
|
|
431
|
+
* stderr line with 02 02 02. Stderr is kept for the error words; stdout carries the protocol lines alone.
|
|
432
|
+
*/
|
|
433
|
+
function sessionStream(socket, send) {
|
|
434
|
+
const readable = new PassThrough();
|
|
435
|
+
let stderr = "";
|
|
436
|
+
let rest = Buffer.alloc(0);
|
|
437
|
+
let queued = "";
|
|
438
|
+
let sending = false;
|
|
439
|
+
let opened = () => { };
|
|
440
|
+
const open = new Promise((done) => {
|
|
441
|
+
opened = done;
|
|
442
|
+
});
|
|
443
|
+
const lines = (bytes, last) => {
|
|
444
|
+
rest = rest.length === 0 ? bytes : Buffer.concat([rest, bytes]);
|
|
445
|
+
let at;
|
|
446
|
+
while ((at = rest.indexOf(0x0a)) >= 0 || (last && rest.length > 0)) {
|
|
447
|
+
const end = at >= 0 ? at + 1 : rest.length;
|
|
448
|
+
const line = rest.subarray(0, end);
|
|
449
|
+
rest = rest.subarray(end);
|
|
450
|
+
if (line.subarray(0, 3).equals(ERR))
|
|
451
|
+
stderr = (stderr + line.subarray(3).toString("utf8")).slice(-4096);
|
|
452
|
+
else {
|
|
453
|
+
const out = line.subarray(0, 3).equals(OUT) ? line.subarray(3) : line;
|
|
454
|
+
if (!ECHO.test(out.subarray(0, 64).toString("utf8")))
|
|
455
|
+
readable.write(out);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (rest.length > MAX_LINE_BYTES + 8)
|
|
459
|
+
readable.destroy(new Error("the daemon sent a line over the 1 MiB limit"));
|
|
460
|
+
};
|
|
461
|
+
socket.binaryType = "arraybuffer";
|
|
462
|
+
socket.addEventListener("open", () => opened(ok(undefined)));
|
|
463
|
+
socket.addEventListener("message", ({ data }) => {
|
|
464
|
+
if (readable.destroyed)
|
|
465
|
+
return;
|
|
466
|
+
if (data instanceof ArrayBuffer)
|
|
467
|
+
lines(Buffer.from(data), false);
|
|
468
|
+
else if (ArrayBuffer.isView(data))
|
|
469
|
+
lines(Buffer.from(data.buffer, data.byteOffset, data.byteLength), false);
|
|
470
|
+
else if (typeof data === "string")
|
|
471
|
+
lines(Buffer.from(data), false);
|
|
472
|
+
});
|
|
473
|
+
socket.addEventListener("error", (event) => {
|
|
474
|
+
opened(fail("daytona", `the log stream failed: ${event.message ?? "no reason given"}`));
|
|
475
|
+
if (!readable.destroyed)
|
|
476
|
+
readable.destroy(new Error(`the log stream failed${event.message ? `: ${event.message}` : ""}`));
|
|
477
|
+
});
|
|
478
|
+
socket.addEventListener("close", ({ code }) => {
|
|
479
|
+
opened(fail("daytona", `the log stream closed before it opened (code ${code ?? "none"})`));
|
|
480
|
+
if (readable.destroyed)
|
|
481
|
+
return;
|
|
482
|
+
lines(Buffer.alloc(0), true);
|
|
483
|
+
readable.end();
|
|
484
|
+
});
|
|
485
|
+
const flush = () => {
|
|
486
|
+
const at = queued.lastIndexOf("\n");
|
|
487
|
+
if (sending || at < 0 || readable.destroyed)
|
|
488
|
+
return;
|
|
489
|
+
const data = queued.slice(0, at + 1);
|
|
490
|
+
queued = queued.slice(at + 1);
|
|
491
|
+
sending = true;
|
|
492
|
+
void send(data).then((sent) => {
|
|
493
|
+
sending = false;
|
|
494
|
+
if (!sent.ok) {
|
|
495
|
+
if (!readable.destroyed)
|
|
496
|
+
readable.destroy(new Error(`writing to the daemon failed: ${sent.error.message}`));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
flush();
|
|
500
|
+
});
|
|
501
|
+
};
|
|
502
|
+
const writable = new Writable({
|
|
503
|
+
write(chunk, _encoding, done) {
|
|
504
|
+
queued += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
505
|
+
flush();
|
|
506
|
+
done();
|
|
507
|
+
},
|
|
508
|
+
});
|
|
509
|
+
return { readable, writable, open, stderr: () => stderr.trim() };
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Computers that are Daytona sandboxes. A spec's image is a Daytona snapshot (its id or name), which gives the class and
|
|
513
|
+
* the size. See the README's Daytona section for every call, and its citation.
|
|
514
|
+
*/
|
|
515
|
+
export class DaytonaProvider {
|
|
516
|
+
id = "daytona";
|
|
517
|
+
version = VERSION;
|
|
518
|
+
#rest;
|
|
519
|
+
#daemonPath;
|
|
520
|
+
#arch;
|
|
521
|
+
#class;
|
|
522
|
+
#target;
|
|
523
|
+
#uid;
|
|
524
|
+
#gid;
|
|
525
|
+
#webSocket;
|
|
526
|
+
#timeouts;
|
|
527
|
+
#autoStop;
|
|
528
|
+
#autoDelete;
|
|
529
|
+
#onNote;
|
|
530
|
+
constructor({ apiKey, onNote, apiUrl = DEFAULT_API_URL, daemonPath, arch = "amd64", sandboxClass = "container", target, daemonUser = TOOL_USER, autoStopMinutes = 0, autoDeleteMinutes, fetch: fetcher, webSocket, timeouts, }) {
|
|
531
|
+
this.#onNote = onNote;
|
|
532
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
533
|
+
throw new Error("a Daytona API key is required");
|
|
534
|
+
const base = new URL(apiUrl);
|
|
535
|
+
if (base.protocol !== "https:")
|
|
536
|
+
throw new Error(`the Daytona API URL must be https, so the key never crosses in the clear: ${base.protocol}`);
|
|
537
|
+
if (sandboxClass !== "container" && sandboxClass !== "linux-vm")
|
|
538
|
+
throw new Error(`sandboxClass is container or linux-vm, not ${String(sandboxClass)}`);
|
|
539
|
+
const user = USER.exec(daemonUser);
|
|
540
|
+
if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
|
|
541
|
+
throw new Error(`the daemon user ${daemonUser} must be uid:gid in numbers, such as 1000:1000`);
|
|
542
|
+
// The numbers, not the text: "00" is root as much as "0" is.
|
|
543
|
+
if (Number(user[1]) === 0 || Number(user[2]) === 0)
|
|
544
|
+
throw new Error(`the daemon user ${daemonUser} is root or in root's group; a Daytona computer's daemon runs as neither`);
|
|
545
|
+
const minutes = (name, value) => {
|
|
546
|
+
if (!isWhole(value) || value < 0)
|
|
547
|
+
throw new Error(`${name} is a whole number of minutes, 0 or more, not ${String(value)}`);
|
|
548
|
+
};
|
|
549
|
+
minutes("autoStopMinutes", autoStopMinutes);
|
|
550
|
+
if (autoDeleteMinutes !== undefined)
|
|
551
|
+
minutes("autoDeleteMinutes", autoDeleteMinutes);
|
|
552
|
+
this.#autoStop = autoStopMinutes;
|
|
553
|
+
this.#autoDelete = autoDeleteMinutes ?? NO_AUTO_DELETE;
|
|
554
|
+
this.#timeouts = { ...DEFAULTS, ...timeouts };
|
|
555
|
+
this.#rest = new Rest(apiUrl, apiKey, fetcher ?? fetch, this.#timeouts);
|
|
556
|
+
this.#daemonPath = resolve(daemonPath);
|
|
557
|
+
this.#arch = arch;
|
|
558
|
+
this.#class = sandboxClass;
|
|
559
|
+
this.#target = target;
|
|
560
|
+
[this.#uid, this.#gid] = [String(Number(user[1])), String(Number(user[2]))];
|
|
561
|
+
this.#webSocket = webSocket ?? ((url, init) => new WebSocket(url, init));
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* daemon child: Daytona's toolbox daemon is the sandbox's first process, and init is a command it runs in a session
|
|
565
|
+
* (#prepare), so deleting that session ends init and leaves the sandbox. maxLifetimeMs is the 30 days check() has
|
|
566
|
+
* always given; Daytona's TTL is in whole minutes and documents no cap of its own. The toolbox listens on 2280 on
|
|
567
|
+
* every interface and runs commands for whoever reaches it, so init starts with --own-network, and network none is
|
|
568
|
+
* all a computer takes until a proxy carries open and allowlists out of the daemon's own network.
|
|
569
|
+
*/
|
|
570
|
+
capabilities() {
|
|
571
|
+
return {
|
|
572
|
+
kind: "linux",
|
|
573
|
+
lifetime: "vendor",
|
|
574
|
+
network: ["none"],
|
|
575
|
+
isolation: this.#class === "linux-vm" ? "vm" : "container",
|
|
576
|
+
os: "linux",
|
|
577
|
+
daemon: "child",
|
|
578
|
+
groups: ["exec", "files", "processes"],
|
|
579
|
+
maxLifetimeMs: MAX_LIFETIME_MS,
|
|
580
|
+
release: ["stop", "delete"],
|
|
581
|
+
// autoDeleteInterval 0: Daytona deletes a sandbox as soon as it stops, so a stop keeps no computer.
|
|
582
|
+
stopDeletes: this.#autoDelete === 0,
|
|
583
|
+
mount: [...MOUNT],
|
|
584
|
+
vendorAgentPorts: [TOOLBOX_PORT],
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
check(spec) {
|
|
588
|
+
const refusals = [];
|
|
589
|
+
const refuse = (field, message) => refusals.push({ field, message });
|
|
590
|
+
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
591
|
+
const { image, lifetimeMs, network, labels } = given;
|
|
592
|
+
if (typeof image !== "string" || image.trim() === "")
|
|
593
|
+
refuse("image", `an image is required: the id or name of a Daytona snapshot, or "${DAYTONA_DEFAULT_SNAPSHOT}" for Daytona's default snapshot`);
|
|
594
|
+
else if (/[\0-\x1f]/.test(image))
|
|
595
|
+
refuse("image", "a snapshot name has no control characters");
|
|
596
|
+
refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
|
|
597
|
+
if (network === "open" || (typeof network === "object" && network !== null && "allow" in network))
|
|
598
|
+
refuse("network", OWN_NETWORK_ONLY);
|
|
599
|
+
else if (network !== "none")
|
|
600
|
+
refuse("network", 'network is required: "none"');
|
|
601
|
+
if (labels !== undefined) {
|
|
602
|
+
const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
|
|
603
|
+
const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
|
|
604
|
+
if (bad)
|
|
605
|
+
refuse("labels", bad);
|
|
606
|
+
}
|
|
607
|
+
const mounted = checkMount(given.mount, MOUNT);
|
|
608
|
+
refusals.push(...mounted);
|
|
609
|
+
if (mounted.length === 0 && given.mount?.kind === "archil") {
|
|
610
|
+
refusals.push(...archilRefusals(spec));
|
|
611
|
+
const tool = String(ARCHIL_TOOL_UID);
|
|
612
|
+
if (this.#uid !== tool || this.#gid !== tool) {
|
|
613
|
+
refuse("mount", `an Archil mount's tools run as agentrun-tool, ${tool}:${tool}, and this provider's daemon user is ${this.#uid}:${this.#gid}: give it daemonUser "${tool}:${tool}"`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
for (const [field, value] of Object.entries(given)) {
|
|
617
|
+
if (SPEC_FIELDS.has(field) || value === undefined)
|
|
618
|
+
continue;
|
|
619
|
+
if (SIZE_FIELDS.has(field))
|
|
620
|
+
refuse(field, `a Daytona computer has the size of its snapshot: name a snapshot of the size you need, not ${field}`);
|
|
621
|
+
else if (field === "user")
|
|
622
|
+
refuse(field, `a Daytona computer's daemon runs as the provider's daemon user (${this.#uid}:${this.#gid}), never as one a spec names`);
|
|
623
|
+
else if (field === "workdir")
|
|
624
|
+
refuse(field, `a Daytona computer works in ${WORK}, its home; a spec cannot name another`);
|
|
625
|
+
else
|
|
626
|
+
refuse(field, `a Daytona computer does not support ${field}`);
|
|
627
|
+
}
|
|
628
|
+
return refusals;
|
|
629
|
+
}
|
|
630
|
+
async create(spec, { signal } = {}) {
|
|
631
|
+
const refusals = this.check(spec);
|
|
632
|
+
if (refusals.length > 0)
|
|
633
|
+
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
634
|
+
let daemon;
|
|
635
|
+
try {
|
|
636
|
+
daemon = readFileSync(this.#daemonPath);
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
return fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
|
|
640
|
+
}
|
|
641
|
+
const sha256 = createHash("sha256").update(daemon).digest("hex");
|
|
642
|
+
if (signal?.aborted)
|
|
643
|
+
return fail("aborted", "create was aborted before Daytona was called");
|
|
644
|
+
const name = `computer-${randomBytes(6).toString("hex")}`;
|
|
645
|
+
const deadline = new Date(Date.now() + spec.lifetimeMs).toISOString();
|
|
646
|
+
const archil = archilOf(spec);
|
|
647
|
+
const body = {
|
|
648
|
+
name,
|
|
649
|
+
// "default" sends no snapshot, and Daytona makes the sandbox from its default snapshot.
|
|
650
|
+
...(spec.image === DAYTONA_DEFAULT_SNAPSHOT ? {} : { snapshot: spec.image }),
|
|
651
|
+
// An Archil computer carries its mount as a label: kind and source, never the token.
|
|
652
|
+
labels: { ...spec.labels, ...(archil ? archilLabels(archil) : {}), [COMPUTER_LABEL]: "1", [DEADLINE_LABEL]: deadline, [IMAGE_LABEL]: spec.image },
|
|
653
|
+
env: {},
|
|
654
|
+
public: false,
|
|
655
|
+
...(this.#target === undefined ? {} : { target: this.#target }),
|
|
656
|
+
ttlMinutes: Math.max(1, Math.ceil(spec.lifetimeMs / 60_000)),
|
|
657
|
+
autoStopInterval: this.#autoStop,
|
|
658
|
+
autoDeleteInterval: this.#autoDelete,
|
|
659
|
+
// An Archil computer's root reaches Archil: Daytona's network is open, and init's own namespace (loopback alone)
|
|
660
|
+
// holds the tools to none.
|
|
661
|
+
...(networkBody(archil ? "open" : spec.network) ?? { networkBlockAll: true }),
|
|
662
|
+
};
|
|
663
|
+
const posted = await this.#rest.json("POST", this.#rest.sandbox(), { json: body, timeoutMs: this.#timeouts.createMs }, signal);
|
|
664
|
+
const made = posted.ok ? posted.value : undefined;
|
|
665
|
+
if (!posted.ok || typeof made?.id !== "string") {
|
|
666
|
+
// A create Daytona refused with a 4xx made nothing. One that failed otherwise, or was aborted, may still have made
|
|
667
|
+
// the sandbox: it goes by its name, which is this provider's.
|
|
668
|
+
const refused = !posted.ok && ["invalid", "denied", "limit", "not_found"].includes(posted.error.code);
|
|
669
|
+
const removed = refused ? ok(undefined) : await this.#delete(name);
|
|
670
|
+
const left = removed.ok ? "" : `; a sandbox named ${name} may be left (${removed.error.message}), which Daytona ends by ${deadline}`;
|
|
671
|
+
if (!posted.ok)
|
|
672
|
+
return fail(posted.error.code, `${posted.error.code === "aborted" ? "create was aborted" : "Daytona did not create the sandbox"}: ${posted.error.message}${left}`);
|
|
673
|
+
return fail("daytona", `POST /sandbox: no sandbox id in the answer${left}`);
|
|
674
|
+
}
|
|
675
|
+
const ref = { id: made.id, name };
|
|
676
|
+
// From here the sandbox exists: every step takes the caller's signal, and a failure or an abort deletes it.
|
|
677
|
+
const prepared = await this.#prepare(spec, ref, made, deadline, daemon, sha256, signal);
|
|
678
|
+
if (signal?.aborted)
|
|
679
|
+
return this.#abandon(ref, { code: "aborted", message: "create was aborted" }, signal);
|
|
680
|
+
if (prepared.ok)
|
|
681
|
+
return ok(ref);
|
|
682
|
+
return this.#abandon(ref, prepared.error, signal);
|
|
683
|
+
}
|
|
684
|
+
async #abandon(ref, error, signal) {
|
|
685
|
+
// The delete itself is never signalled: it is sent even after an abort. The wait for the sandbox to go takes the
|
|
686
|
+
// caller's signal, as Modal's terminate does, so an aborted create returns once the delete is sent.
|
|
687
|
+
const deleted = await this.#delete(ref.id);
|
|
688
|
+
const removed = deleted.ok ? await this.#settle(ref, "gone", "delete", signal) : deleted;
|
|
689
|
+
const after = removed.ok
|
|
690
|
+
? "was deleted"
|
|
691
|
+
: deleted.ok && removed.error.code === "aborted"
|
|
692
|
+
? "was sent a delete, and the wait for it to go was aborted; Daytona ends it at its TTL if the delete did not take"
|
|
693
|
+
: `could not be deleted (${removed.error.message}); Daytona ends it at its TTL`;
|
|
694
|
+
return fail(error.code, `the computer ${ref.name} ${after}: ${error.message}`);
|
|
695
|
+
}
|
|
696
|
+
/** Everything between the create's answer and a computer that passed the drift check. */
|
|
697
|
+
async #prepare(spec, ref, made, deadline, daemon, sha256, signal) {
|
|
698
|
+
const started = await this.#waitStarted(made, signal);
|
|
699
|
+
if (!started.ok)
|
|
700
|
+
return started;
|
|
701
|
+
const sb = started.value;
|
|
702
|
+
const archil = archilOf(spec);
|
|
703
|
+
// An Archil computer's network at Daytona is open for root; init's own namespace holds the tools to the spec's none.
|
|
704
|
+
const vendor = sandboxDrift(archil ? { ...spec, network: "open" } : spec, sb, this.#sandboxExpected(deadline));
|
|
705
|
+
if (vendor.length > 0)
|
|
706
|
+
return fail("refused", `it did not match its spec: ${vendor.join("; ")}`);
|
|
707
|
+
const toolbox = await this.#toolbox(sb, signal);
|
|
708
|
+
if (!toolbox.ok)
|
|
709
|
+
return toolbox;
|
|
710
|
+
const staging = `${STAGING}${randomBytes(8).toString("hex")}`;
|
|
711
|
+
const form = new FormData();
|
|
712
|
+
form.append("file", new Blob([new Uint8Array(daemon)]), "computerd");
|
|
713
|
+
const uploaded = await this.#rest.call("POST", `${toolbox.value}/files/upload-v2?${new URLSearchParams({ path: staging })}`, { form, retry: true, timeoutMs: this.#timeouts.uploadMs }, signal);
|
|
714
|
+
if (!uploaded.ok)
|
|
715
|
+
return fail(uploaded.error.code, `the daemon's upload was refused: ${uploaded.error.message}`);
|
|
716
|
+
// Init's flags are built here (childCommands): every remote computer, an Archil one included, starts init with
|
|
717
|
+
// --own-network, init and every tool in a network namespace of their own, loopback alone; the archil client and
|
|
718
|
+
// serve, run as root through the toolbox, stay in the computer's namespace, which reaches Archil.
|
|
719
|
+
const commands = daytonaCommands({ staging, deadline, user: `${this.#uid}:${this.#gid}` });
|
|
720
|
+
const install = await this.#execute(toolbox.value, commands.install, signal);
|
|
721
|
+
if (!install.ok)
|
|
722
|
+
return install;
|
|
723
|
+
if (install.value.exitCode !== 0)
|
|
724
|
+
return fail("refused", `installing the daemon failed (exit ${install.value.exitCode}): ${install.value.result.trim().slice(0, 500)}`);
|
|
725
|
+
const read = /^sha256 ([0-9a-f]{64})$/m.exec(install.value.result)?.[1];
|
|
726
|
+
if (read !== sha256)
|
|
727
|
+
return fail("refused", `it did not match its spec: daemon: uploaded sha256 ${sha256}, the installed binary reads back ${show(read)}`);
|
|
728
|
+
// The run's folder, mounted before init starts, so no tool program runs before it is there.
|
|
729
|
+
let epoch;
|
|
730
|
+
if (archil) {
|
|
731
|
+
const labels = spec.labels ?? {};
|
|
732
|
+
const claim = epochOf(labels);
|
|
733
|
+
epoch = claim.ok ? claim.value : undefined;
|
|
734
|
+
const run = labels[RUN_LABEL];
|
|
735
|
+
const mounted = await archilMount({
|
|
736
|
+
root: this.#root(toolbox.value),
|
|
737
|
+
mount: archil,
|
|
738
|
+
self: ref,
|
|
739
|
+
releaseOlder: () => releaseOlder(this, run, epoch, signal ? { signal } : {}),
|
|
740
|
+
timeoutMs: this.#timeouts.execMs,
|
|
741
|
+
...(signal ? { signal } : {}),
|
|
742
|
+
});
|
|
743
|
+
if (!mounted.ok)
|
|
744
|
+
return mounted;
|
|
745
|
+
}
|
|
746
|
+
const session = await this.#rest.call("POST", `${toolbox.value}/process/session`, { json: { sessionId: INIT_SESSION } }, signal);
|
|
747
|
+
if (!session.ok)
|
|
748
|
+
return fail(session.error.code, `starting the daemon: ${session.error.message}`);
|
|
749
|
+
const init = await this.#rest.json("POST", `${toolbox.value}/process/session/${INIT_SESSION}/exec`, { json: { command: commands.init, runAsync: true, suppressInputEcho: true } }, signal);
|
|
750
|
+
if (!init.ok)
|
|
751
|
+
return fail(init.error.code, `starting the daemon: ${init.error.message}`);
|
|
752
|
+
const initId = init.value?.cmdId;
|
|
753
|
+
const opened = await this.#open(sb, toolbox.value, signal);
|
|
754
|
+
if (!opened.ok) {
|
|
755
|
+
if (opened.error.code === "aborted")
|
|
756
|
+
return opened;
|
|
757
|
+
const why = typeof initId === "string" ? await this.#initLog(toolbox.value, initId) : "";
|
|
758
|
+
return fail(opened.error.code, `the daemon did not answer: ${opened.error.message}${why ? `; init wrote: ${why}` : ""}`);
|
|
759
|
+
}
|
|
760
|
+
const daemonFound = await daemonDrift(opened.value, this.#daemonExpected(), this.#timeouts.helloMs, signal);
|
|
761
|
+
const mountRead = archil ? await this.#mountReadBack(opened.value.client, epoch, archil, signal) : undefined;
|
|
762
|
+
await opened.value.close();
|
|
763
|
+
if (!daemonFound.ok)
|
|
764
|
+
return daemonFound;
|
|
765
|
+
if (daemonFound.value.length > 0)
|
|
766
|
+
return fail("refused", `it did not match its spec: ${daemonFound.value.join("; ")}`);
|
|
767
|
+
if (archil && mountRead !== undefined) {
|
|
768
|
+
if (!mountRead.ok)
|
|
769
|
+
return mountRead;
|
|
770
|
+
const want = readBackOf(archil, epoch);
|
|
771
|
+
if (JSON.stringify(mountRead.value) !== JSON.stringify(want)) {
|
|
772
|
+
return fail("refused", `it did not match its spec: mount: declared ${show(want)}, read back ${show(mountRead.value ?? "nothing")}`);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return this.#waitListed(ref.id, signal);
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* What an Archil computer mounts at /workspace, read back through its computerd: the mount table, and whether the
|
|
779
|
+
* resident serve answers (exclusive), under `epoch`, the computer's label.
|
|
780
|
+
*/
|
|
781
|
+
#mountReadBack(client, epoch, recorded, signal) {
|
|
782
|
+
return readArchilMount(client, { ...(recorded ? { mount: recorded } : {}), ...(epoch === undefined ? {} : { epoch }) }, { name: "the computer", timeoutMs: this.#timeouts.helloMs, ...(signal ? { signal } : {}) });
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* The toolbox as the Archil mount's root channel: argv run as root (the snapshot's user is root, never sudo), in a
|
|
786
|
+
* session of its own, its stdin, when given, sent as the session command's input with no echo; its exit code polled
|
|
787
|
+
* until it ends or timeoutMs passes; its log read back; the session removed.
|
|
788
|
+
*/
|
|
789
|
+
#root(toolbox) {
|
|
790
|
+
return {
|
|
791
|
+
run: async (argv, { stdin, timeoutMs, signal }) => {
|
|
792
|
+
const sessionId = `agentrun-archil-${randomBytes(8).toString("hex")}`;
|
|
793
|
+
const session = `${toolbox}/process/session/${sessionId}`;
|
|
794
|
+
const made = await this.#rest.call("POST", `${toolbox}/process/session`, { json: { sessionId } }, signal);
|
|
795
|
+
if (!made.ok)
|
|
796
|
+
return made;
|
|
797
|
+
try {
|
|
798
|
+
const ran = await this.#rest.json("POST", `${session}/exec`, { json: { command: shellCommand(ROOT_RUN, argv), runAsync: true, suppressInputEcho: true } }, signal);
|
|
799
|
+
if (!ran.ok)
|
|
800
|
+
return ran;
|
|
801
|
+
const commandId = ran.value?.cmdId;
|
|
802
|
+
if (typeof commandId !== "string")
|
|
803
|
+
return fail("daytona", "POST exec: no command id in the answer");
|
|
804
|
+
const command = `${session}/command/${encodeURIComponent(commandId)}`;
|
|
805
|
+
if (stdin !== undefined) {
|
|
806
|
+
// Its words never carry stdin: it is the disk's token.
|
|
807
|
+
const sent = await this.#rest.call("POST", `${command}/input`, { json: { data: stdin } }, signal);
|
|
808
|
+
if (!sent.ok)
|
|
809
|
+
return fail(sent.error.code, `the command's stdin could not be sent (${sent.error.code})`);
|
|
810
|
+
}
|
|
811
|
+
const end = Date.now() + timeoutMs;
|
|
812
|
+
let exitCode;
|
|
813
|
+
while (exitCode === undefined) {
|
|
814
|
+
const read = await this.#rest.json("GET", session, { retry: true }, signal);
|
|
815
|
+
if (!read.ok)
|
|
816
|
+
return read;
|
|
817
|
+
const found = (read.value?.commands ?? []).find((one) => one.id === commandId);
|
|
818
|
+
if (typeof found?.exitCode === "number")
|
|
819
|
+
exitCode = found.exitCode;
|
|
820
|
+
else if (Date.now() >= end)
|
|
821
|
+
return fail("timeout", `the root command did not end within ${Math.round(timeoutMs / 1000)} s`);
|
|
822
|
+
else
|
|
823
|
+
await sleep(this.#timeouts.pollMs, signal);
|
|
824
|
+
if (signal?.aborted)
|
|
825
|
+
return fail("aborted", "the root command's wait was aborted");
|
|
826
|
+
}
|
|
827
|
+
const logs = await this.#rest.call("GET", `${command}/logs`, {}, signal);
|
|
828
|
+
return ok({ exitCode, output: logs.ok ? logText(logs.value.bytes).trim().slice(-2000) : "" });
|
|
829
|
+
}
|
|
830
|
+
finally {
|
|
831
|
+
await this.#rest.call("DELETE", session, {});
|
|
832
|
+
}
|
|
833
|
+
},
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
#sandboxExpected(deadline) {
|
|
837
|
+
return { deadline, sandboxClass: this.#class, autoStopInterval: this.#autoStop, autoDeleteInterval: this.#autoDelete };
|
|
838
|
+
}
|
|
839
|
+
#daemonExpected() {
|
|
840
|
+
const { kind, groups } = this.capabilities();
|
|
841
|
+
return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: this.#arch, kind, groups };
|
|
842
|
+
}
|
|
843
|
+
async #waitStarted(made, signal) {
|
|
844
|
+
const end = Date.now() + this.#timeouts.startMs;
|
|
845
|
+
let current = made;
|
|
846
|
+
for (let first = true;; first = false) {
|
|
847
|
+
// The create's answer may leave fields out, as a listing does: the drift check reads the sandbox's own read.
|
|
848
|
+
if (!first && current?.state === "started")
|
|
849
|
+
return ok(current);
|
|
850
|
+
if (current === undefined || GONE.has(current.state ?? "") || current.state === "error" || current.state === "build_failed") {
|
|
851
|
+
const reason = current?.errorReason ? `: ${current.errorReason}` : "";
|
|
852
|
+
return fail("daytona", `the sandbox went to ${current?.state ?? "deleted"} while starting${reason}`);
|
|
853
|
+
}
|
|
854
|
+
if (!first && Date.now() >= end)
|
|
855
|
+
return fail("timeout", `the sandbox did not start within ${this.#timeouts.startMs / 1000} s (state ${current.state})`);
|
|
856
|
+
if (!first)
|
|
857
|
+
await sleep(this.#timeouts.pollMs, signal);
|
|
858
|
+
if (signal?.aborted)
|
|
859
|
+
return fail("aborted", "create was aborted while the sandbox started");
|
|
860
|
+
const next = await this.#rest.get(made.id, signal);
|
|
861
|
+
if (!next.ok)
|
|
862
|
+
return next;
|
|
863
|
+
current = next.value;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Daytona's label listing trails a create (pi-transport measured 0.7 to 1.6 s, with flaps), and list() must show a
|
|
868
|
+
* computer once create returns: create waits until the listing has shown it, without a miss, for listedStableMs.
|
|
869
|
+
*/
|
|
870
|
+
async #waitListed(id, signal) {
|
|
871
|
+
const end = Date.now() + this.#timeouts.listedMs;
|
|
872
|
+
let streak;
|
|
873
|
+
for (let hits = 0;;) {
|
|
874
|
+
const listed = await this.#listOwn(signal);
|
|
875
|
+
if (!listed.ok)
|
|
876
|
+
return listed;
|
|
877
|
+
if (listed.value.some((sb) => sb.id === id)) {
|
|
878
|
+
streak ??= Date.now();
|
|
879
|
+
hits++;
|
|
880
|
+
if (hits >= LISTED_ROUNDS && Date.now() - streak >= this.#timeouts.listedStableMs)
|
|
881
|
+
return ok(undefined);
|
|
882
|
+
}
|
|
883
|
+
else {
|
|
884
|
+
streak = undefined;
|
|
885
|
+
hits = 0;
|
|
886
|
+
}
|
|
887
|
+
if (Date.now() >= end)
|
|
888
|
+
return fail("timeout", `the computer was not listed steadily within ${this.#timeouts.listedMs / 1000} s of its creation`);
|
|
889
|
+
await sleep(Math.min(LISTED_POLL_MS, this.#timeouts.pollMs), signal);
|
|
890
|
+
if (signal?.aborted)
|
|
891
|
+
return fail("aborted", "create was aborted while it waited for the listing");
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
async #toolbox(sb, signal) {
|
|
895
|
+
let proxy = sb.toolboxProxyUrl;
|
|
896
|
+
if (typeof proxy !== "string" || proxy === "") {
|
|
897
|
+
const found = await this.#rest.json("GET", this.#rest.sandbox(sb.id, "/toolbox-proxy-url"), { retry: true }, signal);
|
|
898
|
+
if (!found.ok)
|
|
899
|
+
return found;
|
|
900
|
+
proxy = found.value?.url;
|
|
901
|
+
}
|
|
902
|
+
let url;
|
|
903
|
+
try {
|
|
904
|
+
url = new URL(proxy ?? "");
|
|
905
|
+
}
|
|
906
|
+
catch {
|
|
907
|
+
return fail("daytona", `Daytona gave no toolbox URL for ${sb.id}`);
|
|
908
|
+
}
|
|
909
|
+
if (url.protocol !== "https:")
|
|
910
|
+
return fail("daytona", `the toolbox URL Daytona gave is not https (${url.protocol}), so the key is not sent to it`);
|
|
911
|
+
return ok(`${url.href.replace(/\/+$/, "")}/${encodeURIComponent(sb.id)}`);
|
|
912
|
+
}
|
|
913
|
+
async #execute(toolbox, command, signal) {
|
|
914
|
+
const seconds = Math.ceil(this.#timeouts.execMs / 1000);
|
|
915
|
+
const ran = await this.#rest.json("POST", `${toolbox}/process/execute`, { json: { command, timeout: seconds }, timeoutMs: this.#timeouts.execMs + 15_000 }, signal);
|
|
916
|
+
if (!ran.ok)
|
|
917
|
+
return ran;
|
|
918
|
+
const value = ran.value;
|
|
919
|
+
return ok({ exitCode: typeof value?.exitCode === "number" ? value.exitCode : -1, result: typeof value?.result === "string" ? value.result : "" });
|
|
920
|
+
}
|
|
921
|
+
/** What init wrote to stderr, for the words of a daemon that did not start. Best effort: empty when it cannot be read. */
|
|
922
|
+
async #initLog(toolbox, commandId) {
|
|
923
|
+
const logs = await this.#rest.call("GET", `${toolbox}/process/session/${INIT_SESSION}/command/${encodeURIComponent(commandId)}/logs`, {});
|
|
924
|
+
if (!logs.ok)
|
|
925
|
+
return "";
|
|
926
|
+
const bytes = Buffer.from(logs.value.bytes);
|
|
927
|
+
const parsed = parseJson(bytes);
|
|
928
|
+
if (typeof parsed?.stderr === "string")
|
|
929
|
+
return parsed.stderr.trim().slice(-500);
|
|
930
|
+
return bytes
|
|
931
|
+
.toString("utf8")
|
|
932
|
+
.split("\n")
|
|
933
|
+
.filter((line) => line.startsWith("\x02\x02\x02"))
|
|
934
|
+
.map((line) => line.slice(3))
|
|
935
|
+
.join("\n")
|
|
936
|
+
.trim()
|
|
937
|
+
.slice(-500);
|
|
938
|
+
}
|
|
939
|
+
/** One connection to the daemon, after hello, unchecked: a session of its own running the bridge. */
|
|
940
|
+
async #open(sb, toolbox, signal) {
|
|
941
|
+
const sessionId = `agentrun-stdio-${randomBytes(8).toString("hex")}`;
|
|
942
|
+
const session = `${toolbox}/process/session/${sessionId}`;
|
|
943
|
+
const made = await this.#rest.call("POST", `${toolbox}/process/session`, { json: { sessionId } }, signal);
|
|
944
|
+
if (!made.ok)
|
|
945
|
+
return made;
|
|
946
|
+
const removeSession = async () => {
|
|
947
|
+
await this.#rest.call("DELETE", session, {});
|
|
948
|
+
};
|
|
949
|
+
const ran = await this.#rest.json("POST", `${session}/exec`, { json: { command: daytonaCommands({ user: `${this.#uid}:${this.#gid}` }).stdio, runAsync: true, suppressInputEcho: true } }, signal);
|
|
950
|
+
const commandId = ran.ok ? ran.value?.cmdId : undefined;
|
|
951
|
+
if (!ran.ok || typeof commandId !== "string") {
|
|
952
|
+
await removeSession();
|
|
953
|
+
return ran.ok ? fail("daytona", "POST exec: no command id in the answer") : ran;
|
|
954
|
+
}
|
|
955
|
+
const command = `${session}/command/${encodeURIComponent(commandId)}`;
|
|
956
|
+
const logs = `${command.replace(/^https:/, "wss:")}/logs?follow=true`;
|
|
957
|
+
let socket;
|
|
958
|
+
try {
|
|
959
|
+
socket = this.#webSocket(logs, { headers: this.#rest.headers(), protocols: [] });
|
|
960
|
+
}
|
|
961
|
+
catch (error) {
|
|
962
|
+
await removeSession();
|
|
963
|
+
return fail("daytona", `opening the log stream: ${error.message}`);
|
|
964
|
+
}
|
|
965
|
+
const stream = sessionStream(socket, async (data) => {
|
|
966
|
+
const sent = await this.#rest.call("POST", `${command}/input`, { json: { data } });
|
|
967
|
+
return sent.ok ? ok(undefined) : sent;
|
|
968
|
+
});
|
|
969
|
+
const client = new DaemonClient(stream);
|
|
970
|
+
let closed;
|
|
971
|
+
const close = () => (closed ??= (async () => {
|
|
972
|
+
client.close();
|
|
973
|
+
socket.close(1000);
|
|
974
|
+
await removeSession();
|
|
975
|
+
})());
|
|
976
|
+
const bound = AbortSignal.timeout(this.#timeouts.helloMs);
|
|
977
|
+
const either = signal ? AbortSignal.any([signal, bound]) : bound;
|
|
978
|
+
const opened = await Promise.race([stream.open, new Promise((done) => either.addEventListener("abort", () => done(fail("aborted", "")), { once: true }))]);
|
|
979
|
+
const timedOut = () => fail("timeout", `the daemon in ${sb.name ?? sb.id} did not answer hello within ${this.#timeouts.helloMs / 1000} s`);
|
|
980
|
+
if (!opened.ok) {
|
|
981
|
+
await close();
|
|
982
|
+
if (signal?.aborted)
|
|
983
|
+
return fail("aborted", `connecting to ${sb.name ?? sb.id} was aborted`);
|
|
984
|
+
return opened.error.code === "aborted" ? timedOut() : opened;
|
|
985
|
+
}
|
|
986
|
+
const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: either });
|
|
987
|
+
if (!hello.ok) {
|
|
988
|
+
await close();
|
|
989
|
+
if (signal?.aborted)
|
|
990
|
+
return fail("aborted", `hello to the daemon in ${sb.name ?? sb.id} was aborted`);
|
|
991
|
+
if (hello.error.code === "aborted")
|
|
992
|
+
return timedOut();
|
|
993
|
+
if (hello.error.code !== "gone")
|
|
994
|
+
return hello;
|
|
995
|
+
return fail("daytona", `cannot reach the daemon in ${sb.name ?? sb.id}: ${stream.stderr() || hello.error.message}`);
|
|
996
|
+
}
|
|
997
|
+
return ok({ client, hello: hello.value, close });
|
|
998
|
+
}
|
|
999
|
+
/** A sandbox this provider made, by its ref; not_found for one that is gone or another's. */
|
|
1000
|
+
async #own(ref, signal) {
|
|
1001
|
+
const found = await this.#rest.get(ref.id, signal);
|
|
1002
|
+
if (!found.ok)
|
|
1003
|
+
return found;
|
|
1004
|
+
const sb = found.value;
|
|
1005
|
+
if (!ours(sb) || sb.name !== ref.name || going(sb))
|
|
1006
|
+
return fail("not_found", `no Daytona computer is ${ref.name} (${ref.id})`);
|
|
1007
|
+
return ok(sb);
|
|
1008
|
+
}
|
|
1009
|
+
/** The live view: screen.watch on a connection of the watch's own (daemonWatch); a sandbox has no screen. */
|
|
1010
|
+
watch(ref, handlers, options) {
|
|
1011
|
+
return daemonWatch(this, ref, handlers, options);
|
|
1012
|
+
}
|
|
1013
|
+
async connect(ref) {
|
|
1014
|
+
if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
|
|
1015
|
+
return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
|
|
1016
|
+
const found = await this.#own(ref);
|
|
1017
|
+
if (!found.ok)
|
|
1018
|
+
return found;
|
|
1019
|
+
if (found.value.state !== "started")
|
|
1020
|
+
return fail("refused", `${ref.name} is ${found.value.state ?? "in no state Daytona reports"}, not started: its daemon does not run`);
|
|
1021
|
+
const toolbox = await this.#toolbox(found.value);
|
|
1022
|
+
if (!toolbox.ok)
|
|
1023
|
+
return toolbox;
|
|
1024
|
+
const opened = await this.#open(found.value, toolbox.value);
|
|
1025
|
+
if (!opened.ok)
|
|
1026
|
+
return opened;
|
|
1027
|
+
const { kind, groups } = this.capabilities();
|
|
1028
|
+
const drifted = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: this.#arch });
|
|
1029
|
+
// An Archil computer's client syncs the run's folder after every call that may change it, before it answers.
|
|
1030
|
+
if (drifted.length === 0)
|
|
1031
|
+
return recordedMount(found.value.labels) ? ok({ ...opened.value, client: syncingClient(opened.value.client) }) : opened;
|
|
1032
|
+
await opened.value.close();
|
|
1033
|
+
return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drifted.join("; ")}`);
|
|
1034
|
+
}
|
|
1035
|
+
async attach(ref, { signal } = {}) {
|
|
1036
|
+
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
1037
|
+
if ((given.id === undefined) === (given.labels === undefined))
|
|
1038
|
+
return fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
1039
|
+
if (given.id !== undefined) {
|
|
1040
|
+
const id = given.id;
|
|
1041
|
+
if (typeof id !== "string" || id === "" || id.includes("/"))
|
|
1042
|
+
return fail("invalid", `${String(id)} is not a Daytona sandbox's id or a computer's name`);
|
|
1043
|
+
const found = await this.#rest.get(id, signal);
|
|
1044
|
+
if (!found.ok)
|
|
1045
|
+
return found;
|
|
1046
|
+
const sb = found.value;
|
|
1047
|
+
if (!ours(sb) || (sb.id !== id && sb.name !== id) || going(sb))
|
|
1048
|
+
return fail("not_found", `no Daytona computer has the id ${id}`);
|
|
1049
|
+
return this.#attached(sb, signal);
|
|
1050
|
+
}
|
|
1051
|
+
const problem = filterProblem(given.labels);
|
|
1052
|
+
if (problem)
|
|
1053
|
+
return fail("invalid", problem);
|
|
1054
|
+
const labels = given.labels;
|
|
1055
|
+
if (Object.keys(labels).length === 0)
|
|
1056
|
+
return fail("invalid", "attach by labels needs at least one label");
|
|
1057
|
+
const listed = await this.list(labels, { signal });
|
|
1058
|
+
if (!listed.ok)
|
|
1059
|
+
return listed;
|
|
1060
|
+
const words = JSON.stringify(labels);
|
|
1061
|
+
if (listed.value.length === 0)
|
|
1062
|
+
return fail("not_found", `no Daytona computer has the labels ${words}`);
|
|
1063
|
+
if (listed.value.length > 1)
|
|
1064
|
+
return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
|
|
1065
|
+
const match = listed.value[0].ref;
|
|
1066
|
+
const found = await this.#own(match, signal);
|
|
1067
|
+
if (!found.ok)
|
|
1068
|
+
return found.error.code === "not_found" ? fail("not_found", `no Daytona computer has the labels ${words}`) : found;
|
|
1069
|
+
return this.#attached(found.value, signal);
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* The drift check of a computer attach did not make: its spec read back from Daytona and held to what check()
|
|
1073
|
+
* allows, the sandbox as at create, and, when it runs, its daemon. One that drifts is refused and left as it is.
|
|
1074
|
+
*/
|
|
1075
|
+
async #attached(sb, signal) {
|
|
1076
|
+
const ref = { id: sb.id, name: sb.name };
|
|
1077
|
+
const found = [];
|
|
1078
|
+
const deadline = deadlineOf(sb);
|
|
1079
|
+
if (deadline === undefined)
|
|
1080
|
+
found.push(`deadline: the label ${DEADLINE_LABEL} reads ${show(sb.labels?.[DEADLINE_LABEL])}, not the ISO time create writes`);
|
|
1081
|
+
else if (deadline.getTime() > Date.now() + MAX_LIFETIME_MS + 60_000)
|
|
1082
|
+
found.push(`deadline: ${deadline.toISOString()} is past the 30 days create allows`);
|
|
1083
|
+
const network = networkOf(sb);
|
|
1084
|
+
if (typeof network === "object" && "other" in network)
|
|
1085
|
+
found.push(`network: ${network.other}, which this provider never makes`);
|
|
1086
|
+
// An Archil computer's Daytona network is open, for root to reach Archil; its spec's network is the tools', none.
|
|
1087
|
+
const archilComputer = recordedMount(sb.labels) !== undefined;
|
|
1088
|
+
if (archilComputer && network !== "open")
|
|
1089
|
+
found.push(`network: an Archil computer's Daytona network is open, for root to reach Archil; read back ${policyWords(network)}`);
|
|
1090
|
+
// The caller's labels: none of the provider's own, which are read back above (the mount's label by recordedMount).
|
|
1091
|
+
const labels = Object.fromEntries(Object.entries(sb.labels ?? {}).filter(([key]) => key !== COMPUTER_LABEL && !key.startsWith(`${COMPUTER_LABEL}.`) && key !== ARCHIL_MOUNT_LABEL));
|
|
1092
|
+
// The image create was asked for, from its label; a computer made before the label was written reports its snapshot.
|
|
1093
|
+
const asked = sb.labels?.[IMAGE_LABEL];
|
|
1094
|
+
const specNetwork = archilComputer || (typeof network === "object" && "other" in network) ? "none" : network;
|
|
1095
|
+
const spec = { image: asked ?? sb.snapshot, lifetimeMs: 1, network: specNetwork, labels };
|
|
1096
|
+
found.push(...this.check(spec).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
|
|
1097
|
+
const vendor = sandboxDrift(spec, sb, this.#sandboxExpected(sb.labels?.[DEADLINE_LABEL] ?? ""));
|
|
1098
|
+
found.push(...vendor.filter((line) => !line.startsWith("network:") &&
|
|
1099
|
+
!line.startsWith(`label ${DEADLINE_LABEL}`) &&
|
|
1100
|
+
!(asked === undefined && line.startsWith(`label ${IMAGE_LABEL}`)) &&
|
|
1101
|
+
!(deadline === undefined && line.startsWith("autoDestroyAt"))));
|
|
1102
|
+
let user = `${this.#uid}:${this.#gid}`;
|
|
1103
|
+
let workdir;
|
|
1104
|
+
let kind;
|
|
1105
|
+
// An Archil computer: its mount read back from inside it. Daytona's network is open for root, so the tools' is
|
|
1106
|
+
// init's own namespace, which the daemon's drift check reads back (lo alone, or attach refuses): "none".
|
|
1107
|
+
const recorded = recordedMount(sb.labels);
|
|
1108
|
+
let mount;
|
|
1109
|
+
const toolsNetwork = recorded ? "none" : spec.network;
|
|
1110
|
+
if (sb.state === "started") {
|
|
1111
|
+
const toolbox = await this.#toolbox(sb, signal);
|
|
1112
|
+
if (!toolbox.ok)
|
|
1113
|
+
return toolbox;
|
|
1114
|
+
const opened = await this.#open(sb, toolbox.value, signal);
|
|
1115
|
+
if (!opened.ok)
|
|
1116
|
+
return opened;
|
|
1117
|
+
const daemonFound = await daemonDrift(opened.value, this.#daemonExpected(), this.#timeouts.helloMs, signal);
|
|
1118
|
+
const claim = epochOf(sb.labels);
|
|
1119
|
+
const mountRead = recorded ? await this.#mountReadBack(opened.value.client, claim.ok ? claim.value : undefined, recorded, signal) : undefined;
|
|
1120
|
+
await opened.value.close();
|
|
1121
|
+
if (!daemonFound.ok)
|
|
1122
|
+
return daemonFound;
|
|
1123
|
+
found.push(...daemonFound.value);
|
|
1124
|
+
workdir = WORK;
|
|
1125
|
+
kind = opened.value.hello.kind;
|
|
1126
|
+
if (mountRead !== undefined) {
|
|
1127
|
+
if (!mountRead.ok)
|
|
1128
|
+
return mountRead;
|
|
1129
|
+
mount = mountRead.value;
|
|
1130
|
+
// Held to the whole read-back the label and the epoch make (exclusive included), as Modal and E2B hold it.
|
|
1131
|
+
if (recorded !== undefined)
|
|
1132
|
+
found.push(...mountDrift(readBackOf({ ...recorded, token: "" }, claim.ok ? claim.value : undefined), mount));
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (found.length > 0)
|
|
1136
|
+
return fail("refused", `the computer ${ref.name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
|
|
1137
|
+
return ok({
|
|
1138
|
+
...ref,
|
|
1139
|
+
spec: {
|
|
1140
|
+
image: spec.image,
|
|
1141
|
+
...(typeof sb.snapshot === "string" ? { snapshot: sb.snapshot } : {}),
|
|
1142
|
+
user,
|
|
1143
|
+
network: toolsNetwork,
|
|
1144
|
+
...(mount === undefined ? {} : { mount }),
|
|
1145
|
+
...(isWhole(sb.cpu) ? { cpus: sb.cpu } : {}),
|
|
1146
|
+
...(isWhole(sb.memory) ? { memoryMb: sb.memory * 1024 } : {}),
|
|
1147
|
+
...(workdir === undefined ? {} : { workdir }),
|
|
1148
|
+
...(deadline === undefined ? {} : { deadline }),
|
|
1149
|
+
...(kind === undefined ? {} : { kind }),
|
|
1150
|
+
},
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
/** Every sandbox with this provider's label, all pages: one label query, the way pi-transport asks. */
|
|
1154
|
+
async #listOwn(signal) {
|
|
1155
|
+
const found = [];
|
|
1156
|
+
const seen = new Set();
|
|
1157
|
+
let cursor;
|
|
1158
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
1159
|
+
const query = new URLSearchParams({ labels: JSON.stringify({ [COMPUTER_LABEL]: "1" }), limit: "100" });
|
|
1160
|
+
if (cursor !== undefined)
|
|
1161
|
+
query.set("cursor", cursor);
|
|
1162
|
+
const answer = await this.#rest.json("GET", `${this.#rest.sandbox()}?${query}`, { retry: true }, signal);
|
|
1163
|
+
if (!answer.ok)
|
|
1164
|
+
return answer;
|
|
1165
|
+
const value = answer.value;
|
|
1166
|
+
const items = Array.isArray(value) ? value : Array.isArray(value?.items) ? value.items : undefined;
|
|
1167
|
+
if (items === undefined)
|
|
1168
|
+
return fail("daytona", "GET /sandbox: the listing is not a page of sandboxes");
|
|
1169
|
+
found.push(...items);
|
|
1170
|
+
const next = Array.isArray(value) ? undefined : value?.nextCursor;
|
|
1171
|
+
if (typeof next !== "string" || next === "")
|
|
1172
|
+
return ok(found);
|
|
1173
|
+
if (seen.has(next))
|
|
1174
|
+
return fail("daytona", `GET /sandbox: the listing's cursor ${next} came back twice`);
|
|
1175
|
+
seen.add(next);
|
|
1176
|
+
cursor = next;
|
|
1177
|
+
}
|
|
1178
|
+
return fail("daytona", `GET /sandbox: the listing ran past ${MAX_PAGES} pages`);
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* For the sweep after a live run: every sandbox Daytona lists with agentrun.computer=1, whatever its name or state, as
|
|
1182
|
+
* Daytona reports it. list() keeps only this provider's computers; this keeps everything the label query returns.
|
|
1183
|
+
*/
|
|
1184
|
+
async listLabelled({ signal } = {}) {
|
|
1185
|
+
const listed = await this.#listOwn(signal);
|
|
1186
|
+
if (!listed.ok)
|
|
1187
|
+
return listed;
|
|
1188
|
+
return ok(listed.value.filter((sb) => typeof sb?.id === "string").map((sb) => ({ id: sb.id, ...(typeof sb.name === "string" ? { name: sb.name } : {}), ...(typeof sb.state === "string" ? { state: sb.state } : {}) })));
|
|
1189
|
+
}
|
|
1190
|
+
/** For the sweep: GET /sandbox/{id} once, retried as every read is, and the status Daytona answered (404: none). */
|
|
1191
|
+
async probe(id, { signal } = {}) {
|
|
1192
|
+
if (typeof id !== "string" || id === "" || id.includes("/"))
|
|
1193
|
+
return fail("invalid", `${String(id)} is not a Daytona sandbox's id`);
|
|
1194
|
+
const answer = await this.#rest.call("GET", this.#rest.sandbox(id), { retry: true, anyStatus: true }, signal);
|
|
1195
|
+
if (!answer.ok)
|
|
1196
|
+
return answer;
|
|
1197
|
+
const state = parseJson(answer.value.bytes)?.state;
|
|
1198
|
+
return ok({ status: answer.value.status, ...(typeof state === "string" ? { state } : {}) });
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Settings' test: one page of the account's sandboxes by the provider's own label, which makes nothing. The count is
|
|
1202
|
+
* read from the listing, with no read of each sandbox: a busy account answers as fast, and one sandbox's read never
|
|
1203
|
+
* fails a working key. A further page is "or more".
|
|
1204
|
+
*/
|
|
1205
|
+
async testConnection({ signal } = {}) {
|
|
1206
|
+
const query = new URLSearchParams({ labels: JSON.stringify({ [COMPUTER_LABEL]: "1" }), limit: "100" });
|
|
1207
|
+
const answer = await this.#rest.json("GET", `${this.#rest.sandbox()}?${query}`, { retry: true }, signal);
|
|
1208
|
+
if (!answer.ok)
|
|
1209
|
+
return countTested("Daytona", answer);
|
|
1210
|
+
const value = answer.value;
|
|
1211
|
+
const items = Array.isArray(value) ? value : Array.isArray(value?.items) ? value.items : undefined;
|
|
1212
|
+
if (items === undefined)
|
|
1213
|
+
return countTested("Daytona", fail("daytona", "GET /sandbox: the listing is not a page of sandboxes"));
|
|
1214
|
+
const next = Array.isArray(value) ? undefined : value?.nextCursor;
|
|
1215
|
+
return countTested("Daytona", ok({ count: items.filter((item) => ours(item) && !going(item)).length, more: typeof next === "string" && next !== "" }));
|
|
1216
|
+
}
|
|
1217
|
+
async list(labels, { signal } = {}) {
|
|
1218
|
+
const problem = filterProblem(labels);
|
|
1219
|
+
if (problem)
|
|
1220
|
+
return fail("invalid", problem);
|
|
1221
|
+
const listed = await this.#listOwn(signal);
|
|
1222
|
+
if (!listed.ok)
|
|
1223
|
+
return listed;
|
|
1224
|
+
const infos = [];
|
|
1225
|
+
for (const item of listed.value) {
|
|
1226
|
+
if (!ours(item) || going(item))
|
|
1227
|
+
continue;
|
|
1228
|
+
if (!Object.entries(labels).every(([key, value]) => item.labels?.[key] === value))
|
|
1229
|
+
continue;
|
|
1230
|
+
let sb = item;
|
|
1231
|
+
// A listing may leave the network out: the sandbox's own read says.
|
|
1232
|
+
if (item.networkBlockAll === undefined) {
|
|
1233
|
+
const read = await this.#rest.get(item.id, signal);
|
|
1234
|
+
if (!read.ok)
|
|
1235
|
+
return read;
|
|
1236
|
+
if (read.value === undefined)
|
|
1237
|
+
continue;
|
|
1238
|
+
sb = read.value;
|
|
1239
|
+
}
|
|
1240
|
+
// An Archil computer: its mount as labelled, under its epoch label, and its tools' network, init's own namespace
|
|
1241
|
+
// (create held its daemon to lo alone; attach and network() read it back from inside). Daytona's own report is
|
|
1242
|
+
// open, for root to reach Archil.
|
|
1243
|
+
const recorded = recordedMount(sb.labels);
|
|
1244
|
+
const claim = epochOf(sb.labels);
|
|
1245
|
+
const mount = recorded ? readBackOf({ ...recorded, token: "" }, claim.ok ? claim.value : undefined) : undefined;
|
|
1246
|
+
const network = recorded ? "none" : networkOf(sb);
|
|
1247
|
+
infos.push({ ref: { id: sb.id, name: sb.name }, labels: { ...(sb.labels ?? {}) }, deadline: deadlineOf(sb), state: stateOf(sb), network, ...(mount ? { mount } : {}) });
|
|
1248
|
+
}
|
|
1249
|
+
return ok(infos);
|
|
1250
|
+
}
|
|
1251
|
+
async network(ref, policy, { signal } = {}) {
|
|
1252
|
+
if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
|
|
1253
|
+
return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
|
|
1254
|
+
if (policy !== undefined) {
|
|
1255
|
+
const problem = this.check({ image: "-", lifetimeMs: 1, network: policy }).find((refusal) => refusal.field === "network");
|
|
1256
|
+
if (problem)
|
|
1257
|
+
return fail("invalid", problem.message);
|
|
1258
|
+
}
|
|
1259
|
+
const found = await this.#own(ref, signal);
|
|
1260
|
+
if (!found.ok)
|
|
1261
|
+
return found;
|
|
1262
|
+
// An Archil computer: Daytona's network is open for root, so the tools' network is read back from the daemon, init's
|
|
1263
|
+
// own namespace: "none" while it holds lo alone. It takes no other policy.
|
|
1264
|
+
if (recordedMount(found.value.labels)) {
|
|
1265
|
+
if (policy !== undefined && policy !== "none")
|
|
1266
|
+
return fail("refused", `${ref.name} has an Archil mount: its tools' network is none, init's own namespace, and it takes no other`);
|
|
1267
|
+
return this.#toolsNetwork(found.value, signal);
|
|
1268
|
+
}
|
|
1269
|
+
const current = networkOf(found.value);
|
|
1270
|
+
if (policy === undefined || samePolicy(current, policy))
|
|
1271
|
+
return ok(current);
|
|
1272
|
+
const changed = await this.#setNetwork(ref, policy, signal);
|
|
1273
|
+
// Read back whatever the change's answer: one that timed out may still have been applied. Never signalled, so an
|
|
1274
|
+
// aborted change is still checked.
|
|
1275
|
+
const after = await this.#own(ref);
|
|
1276
|
+
// What the network is now is not known, whatever the change answered: it is made safe.
|
|
1277
|
+
if (!after.ok) {
|
|
1278
|
+
const answered = changed.ok ? "" : ` (the change itself answered: ${changed.error.message})`;
|
|
1279
|
+
return this.#makeSafe(ref, after.error.code, `network ${policyWords(policy)} could not be read back after the change: ${after.error.message}${answered}`);
|
|
1280
|
+
}
|
|
1281
|
+
const read = networkOf(after.value);
|
|
1282
|
+
if (samePolicy(read, policy))
|
|
1283
|
+
return ok(read);
|
|
1284
|
+
if (!(typeof current === "object" && "other" in current) && samePolicy(read, current)) {
|
|
1285
|
+
return changed.ok ? fail("refused", `Daytona did not apply network ${policyWords(policy)}: ${ref.name} still reads back ${policyWords(read)}`) : this.#refusedChange(policy, changed.error);
|
|
1286
|
+
}
|
|
1287
|
+
// Never wider: a change Daytona applied otherwise is put back, or, failing that, the network is blocked.
|
|
1288
|
+
if (typeof current === "string" || "allow" in current) {
|
|
1289
|
+
const back = await this.#setNetwork(ref, current);
|
|
1290
|
+
const again = back.ok ? await this.#own(ref) : back;
|
|
1291
|
+
if (again.ok && samePolicy(networkOf(again.value), current)) {
|
|
1292
|
+
return fail("refused", `Daytona did not apply network ${policyWords(policy)} (it read back ${policyWords(read)}), so ${ref.name} is back on ${policyWords(current)}`);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
return this.#makeSafe(ref, "refused", `Daytona did not apply network ${policyWords(policy)} (it read back ${policyWords(read)})`);
|
|
1296
|
+
}
|
|
1297
|
+
/** The network of a computer's programs, read back as their user sees it (computerd probe): "none" while lo alone. */
|
|
1298
|
+
async #toolsNetwork(sb, signal) {
|
|
1299
|
+
if (sb.state !== "started")
|
|
1300
|
+
return fail("refused", `${sb.name ?? sb.id} is ${sb.state ?? "in no state Daytona reports"}, so its daemon cannot read its network back`);
|
|
1301
|
+
const toolbox = await this.#toolbox(sb, signal);
|
|
1302
|
+
if (!toolbox.ok)
|
|
1303
|
+
return toolbox;
|
|
1304
|
+
const opened = await this.#open(sb, toolbox.value, signal);
|
|
1305
|
+
if (!opened.ok)
|
|
1306
|
+
return opened;
|
|
1307
|
+
try {
|
|
1308
|
+
const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(this.#timeouts.helloMs)]) : AbortSignal.timeout(this.#timeouts.helloMs);
|
|
1309
|
+
const drift = await readOwnNetwork(opened.value.client, this.#timeouts.helloMs, bounded);
|
|
1310
|
+
if (!drift.ok)
|
|
1311
|
+
return drift;
|
|
1312
|
+
return ok(drift.value.length === 0 ? "none" : { other: drift.value.join("; ") });
|
|
1313
|
+
}
|
|
1314
|
+
finally {
|
|
1315
|
+
await opened.value.close();
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* A computer whose network is wider than asked, or not known, is blocked (none), and the block read back: Daytona may
|
|
1320
|
+
* answer a POST it does not apply. One that does not read back none is deleted. Never signalled, as every step after a
|
|
1321
|
+
* change is, so an aborted call still leaves the computer safe. Always a failure, in words: why, then what was done.
|
|
1322
|
+
*/
|
|
1323
|
+
async #makeSafe(ref, code, why) {
|
|
1324
|
+
const blocked = await this.#setNetwork(ref, "none");
|
|
1325
|
+
const again = blocked.ok ? await this.#own(ref) : undefined;
|
|
1326
|
+
if (again?.ok && samePolicy(networkOf(again.value), "none"))
|
|
1327
|
+
return fail(code, `${why}, so ${ref.name}'s network was blocked (none) and read back none`);
|
|
1328
|
+
const how = !blocked.ok
|
|
1329
|
+
? `blocking it (none) failed: ${blocked.error.message}`
|
|
1330
|
+
: again !== undefined && !again.ok
|
|
1331
|
+
? `blocking it (none) could not be read back: ${again.error.message}`
|
|
1332
|
+
: `blocking it (none) read back ${policyWords(networkOf(again.value))}`;
|
|
1333
|
+
const removed = await this.release(ref, "delete");
|
|
1334
|
+
return fail(code, `${why}; ${ref.name}'s network could not be made safe: ${how}, so ${removed.ok ? "it was deleted" : `it could not be deleted either: ${removed.error.message}`}`);
|
|
1335
|
+
}
|
|
1336
|
+
#refusedChange(policy, error) {
|
|
1337
|
+
if (error.code === "aborted" || error.code === "timeout")
|
|
1338
|
+
return fail(error.code, `the change to network ${policyWords(policy)} did not complete: ${error.message}`);
|
|
1339
|
+
const code = error.code === "invalid" || error.code === "denied" ? "refused" : error.code;
|
|
1340
|
+
return fail(code, `Daytona refused the change to network ${policyWords(policy)}: ${error.message}`);
|
|
1341
|
+
}
|
|
1342
|
+
async #setNetwork(ref, policy, signal) {
|
|
1343
|
+
const body = networkBody(policy);
|
|
1344
|
+
if (body === undefined)
|
|
1345
|
+
return fail("invalid", `network ${policyWords(policy)} is not one Daytona can hold`);
|
|
1346
|
+
return this.#rest.json("POST", this.#rest.sandbox(ref.id, "/network-settings"), { json: body }, signal);
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Daytona answers a delete or a stop before the sandbox is gone or stopped, and its listing trails both: release
|
|
1350
|
+
* returns once Daytona reads the computer as release left it, or fails naming the last state it read.
|
|
1351
|
+
*/
|
|
1352
|
+
async release(ref, how, { signal } = {}) {
|
|
1353
|
+
if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
|
|
1354
|
+
return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
|
|
1355
|
+
if (how !== "stop" && how !== "delete")
|
|
1356
|
+
return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
|
|
1357
|
+
const found = await this.#rest.get(ref.id, signal);
|
|
1358
|
+
if (!found.ok)
|
|
1359
|
+
return found;
|
|
1360
|
+
const sb = found.value;
|
|
1361
|
+
if (sb === undefined)
|
|
1362
|
+
return ok(undefined);
|
|
1363
|
+
// Already going (a second delete, or Daytona's own end): only the wait is left. Daytona renames a sandbox it
|
|
1364
|
+
// destroys, so the name is not held to the ref's here.
|
|
1365
|
+
if (going(sb))
|
|
1366
|
+
return this.#settle(ref, "gone", how, signal);
|
|
1367
|
+
if (!ours(sb) || sb.name !== ref.name)
|
|
1368
|
+
return fail("not_found", `no Daytona computer is ${ref.name} (${ref.id}): the sandbox is not this provider's, so it is left as it is`);
|
|
1369
|
+
const letGo = recordedMount(sb.labels) && sb.state === "started" ? await this.#letGo(sb, signal) : ok(undefined);
|
|
1370
|
+
const released = how === "stop" ? await this.#stop(ref, sb, signal) : await this.#delete(ref.id).then((deleted) => (deleted.ok ? this.#settle(ref, "gone", how, signal) : deleted));
|
|
1371
|
+
if (!letGo.ok && released.ok)
|
|
1372
|
+
this.#onNote?.({ computer: ref.name, note: `${ref.name} was ${how === "stop" ? "stopped" : "deleted"}, and ${letGo.error.message}` });
|
|
1373
|
+
return released;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* An Archil computer lets its folder go before it is stopped or deleted: a final sync through its computerd (when it
|
|
1377
|
+
* answers), then checkin as root. Neither stops the release: every call that changed the folder synced before it
|
|
1378
|
+
* answered, and a hold left behind is revoked by the run's next claim. What did not go cleanly is said through onNote.
|
|
1379
|
+
*/
|
|
1380
|
+
async #letGo(sb, signal) {
|
|
1381
|
+
const toolbox = await this.#toolbox(sb, signal);
|
|
1382
|
+
if (!toolbox.ok)
|
|
1383
|
+
return fail(toolbox.error.code, `the run's folder was not let go: the toolbox could not be reached (${toolbox.error.message})`);
|
|
1384
|
+
const opened = await this.#open(sb, toolbox.value, signal);
|
|
1385
|
+
try {
|
|
1386
|
+
return await archilRelease({ root: this.#root(toolbox.value), client: opened.ok ? opened.value.client : undefined, timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
|
|
1387
|
+
}
|
|
1388
|
+
finally {
|
|
1389
|
+
if (opened.ok)
|
|
1390
|
+
await opened.value.close();
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
async #stop(ref, sb, signal) {
|
|
1394
|
+
if (!STOPPED.has(sb.state ?? "")) {
|
|
1395
|
+
const stopped = await this.#rest.call("POST", this.#rest.sandbox(sb.id, "/stop"), {}, signal);
|
|
1396
|
+
if (!stopped.ok && stopped.error.code !== "invalid" && stopped.error.code !== "not_found")
|
|
1397
|
+
return stopped;
|
|
1398
|
+
}
|
|
1399
|
+
// With autoDeleteInterval 0, Daytona deletes a sandbox as it stops: such a stop is done once the computer is gone.
|
|
1400
|
+
return this.#settle(ref, this.#autoDelete === 0 ? "gone" : "stopped", "stop", signal);
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Waits, through waitUntil, until Daytona reads the sandbox as wanted, twice running, by its own read and by the
|
|
1404
|
+
* listing alike: "gone" is a 404 and no listed computer; "stopped" is stopped (or gone) and listed stopped (or not at
|
|
1405
|
+
* all, when gone). Pauses double from pollMs to 5 s, bounded by goneMs or stopMs and the caller's signal. A stop not
|
|
1406
|
+
* under way (neither stopping nor stopped) is asked for again. A failed read or listing, or a sandbox gone to error,
|
|
1407
|
+
* ends the wait with that error.
|
|
1408
|
+
*/
|
|
1409
|
+
async #settle(ref, want, how, signal) {
|
|
1410
|
+
let agreed = 0;
|
|
1411
|
+
let last = "unread";
|
|
1412
|
+
const read = async (readSignal) => {
|
|
1413
|
+
const got = await this.#rest.get(ref.id, readSignal);
|
|
1414
|
+
if (!got.ok) {
|
|
1415
|
+
if (got.error.code === "aborted")
|
|
1416
|
+
return { last };
|
|
1417
|
+
return { failed: fail(got.error.code, `release ${how} of ${ref.name}: reading it back failed (${got.error.message}); it last read ${last}`) };
|
|
1418
|
+
}
|
|
1419
|
+
const sb = got.value;
|
|
1420
|
+
last = stateWords(sb);
|
|
1421
|
+
if (sb !== undefined && (sb.state === "error" || sb.state === "build_failed") && sb.desiredState !== "destroyed") {
|
|
1422
|
+
return { failed: fail("daytona", `release ${how} of ${ref.name}: it went to ${sb.state}${sb.errorReason ? `: ${sb.errorReason}` : ""}`) };
|
|
1423
|
+
}
|
|
1424
|
+
const gone = sb === undefined || sb.state === "destroyed";
|
|
1425
|
+
const reached = gone ? "gone" : want === "stopped" && STOPPED.has(sb.state ?? "") ? "stopped" : undefined;
|
|
1426
|
+
if (reached === undefined) {
|
|
1427
|
+
agreed = 0;
|
|
1428
|
+
if (how === "stop" && sb !== undefined && !going(sb) && !LEAVING.has(sb.state ?? "")) {
|
|
1429
|
+
const again = await this.#rest.call("POST", this.#rest.sandbox(ref.id, "/stop"), {}, readSignal);
|
|
1430
|
+
if (!again.ok && again.error.code !== "invalid" && again.error.code !== "not_found" && again.error.code !== "aborted")
|
|
1431
|
+
return { failed: again };
|
|
1432
|
+
}
|
|
1433
|
+
return { last };
|
|
1434
|
+
}
|
|
1435
|
+
const listed = await this.#listOwn(readSignal);
|
|
1436
|
+
if (!listed.ok) {
|
|
1437
|
+
if (listed.error.code === "aborted")
|
|
1438
|
+
return { last };
|
|
1439
|
+
return { failed: fail(listed.error.code, `release ${how} of ${ref.name}: the listing failed (${listed.error.message}); it last read ${last}`) };
|
|
1440
|
+
}
|
|
1441
|
+
const item = listed.value.find((one) => one.id === ref.id);
|
|
1442
|
+
const shown = item === undefined || !ours(item) || going(item) ? undefined : stateOf(item);
|
|
1443
|
+
if (reached === "gone" ? shown === undefined : shown === "stopped")
|
|
1444
|
+
return ++agreed >= LISTED_ROUNDS ? { settled: true } : { last };
|
|
1445
|
+
agreed = 0;
|
|
1446
|
+
last = `${last}, listed ${shown ?? "not at all"}`;
|
|
1447
|
+
return { last };
|
|
1448
|
+
};
|
|
1449
|
+
const { pollMs, stopMs, goneMs } = this.#timeouts;
|
|
1450
|
+
const waited = await waitUntil(read, (state) => !("last" in state), {
|
|
1451
|
+
boundMs: how === "stop" ? stopMs : goneMs,
|
|
1452
|
+
signal,
|
|
1453
|
+
minMs: Math.min(pollMs, RELEASE_POLL_MAX_MS),
|
|
1454
|
+
maxMs: RELEASE_POLL_MAX_MS,
|
|
1455
|
+
what: `${ref.name} to be ${want} after its release ${how}`,
|
|
1456
|
+
describe: (state) => ("last" in state ? `Daytona read it ${state.last}` : "done"),
|
|
1457
|
+
});
|
|
1458
|
+
if (!waited.ok)
|
|
1459
|
+
return waited;
|
|
1460
|
+
return "failed" in waited.value ? waited.value.failed : ok(undefined);
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Deletes a sandbox and makes sure it is going, as pi-transport does: a DELETE that fails counts as done only when the
|
|
1464
|
+
* sandbox is gone or being destroyed; a forced stop comes before the last attempt. Never signalled: a delete that
|
|
1465
|
+
* cleans up after an abort must outlive it.
|
|
1466
|
+
*/
|
|
1467
|
+
async #delete(idOrName) {
|
|
1468
|
+
let failure;
|
|
1469
|
+
for (let attempt = 1; attempt <= DELETE_ATTEMPTS; attempt++) {
|
|
1470
|
+
const removed = await this.#rest.call("DELETE", this.#rest.sandbox(idOrName), { retry: true, timeoutMs: this.#timeouts.deleteMs });
|
|
1471
|
+
if (removed.ok || removed.error.code === "not_found")
|
|
1472
|
+
return ok(undefined);
|
|
1473
|
+
failure = removed.error;
|
|
1474
|
+
const found = await this.#rest.get(idOrName);
|
|
1475
|
+
if (found.ok && (found.value === undefined || GONE.has(found.value.state ?? "")))
|
|
1476
|
+
return ok(undefined);
|
|
1477
|
+
if (attempt === DELETE_ATTEMPTS - 1)
|
|
1478
|
+
await this.#rest.call("POST", this.#rest.sandbox(idOrName, "/stop?force=true"), { timeoutMs: this.#timeouts.deleteMs });
|
|
1479
|
+
if (attempt < DELETE_ATTEMPTS)
|
|
1480
|
+
await sleep(this.#timeouts.retryMs);
|
|
1481
|
+
}
|
|
1482
|
+
return { ok: false, error: failure ?? { code: "daytona", message: `could not delete ${idOrName}` } };
|
|
1483
|
+
}
|
|
1484
|
+
}
|