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