@parcha/agentrun-computer 0.1.0-beta.37 → 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.
Files changed (93) hide show
  1. package/README.md +259 -203
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +13 -0
  4. package/box/build-agent37.mjs +8 -27
  5. package/box/build-daytona.py +2 -2
  6. package/box/build-e2b.mjs +41 -18
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37-ssh.d.ts +89 -0
  9. package/dist/agent37-ssh.js +445 -0
  10. package/dist/agent37.d.ts +2 -63
  11. package/dist/agent37.js +104 -461
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/cases/apps.d.ts +6 -0
  20. package/dist/conformance/cases/apps.js +18 -5
  21. package/dist/conformance/cases/isolation.d.ts +7 -5
  22. package/dist/conformance/cases/isolation.js +44 -14
  23. package/dist/conformance/cases/mount.js +1 -1
  24. package/dist/conformance/cli.js +66 -6
  25. package/dist/conformance/daytona.d.ts +9 -20
  26. package/dist/conformance/daytona.js +12 -21
  27. package/dist/conformance/exec-stream.d.ts +45 -0
  28. package/dist/conformance/exec-stream.js +486 -0
  29. package/dist/conformance/sweep.js +8 -8
  30. package/dist/conformance/types.d.ts +2 -2
  31. package/dist/create-requests.d.ts +1 -1
  32. package/dist/daytona.d.ts +20 -131
  33. package/dist/daytona.js +405 -1450
  34. package/dist/descriptor.d.ts +6 -1
  35. package/dist/descriptor.js +7 -0
  36. package/dist/descriptors/agent37.d.ts +1 -1
  37. package/dist/descriptors/agent37.js +1 -1
  38. package/dist/descriptors/daytona.d.ts +6 -5
  39. package/dist/descriptors/daytona.js +9 -5
  40. package/dist/descriptors/index.d.ts +4 -5
  41. package/dist/descriptors/shared.d.ts +1 -1
  42. package/dist/descriptors/shared.js +2 -2
  43. package/dist/desktop.d.ts +18 -4
  44. package/dist/desktop.js +89 -9
  45. package/dist/docker.d.ts +0 -6
  46. package/dist/docker.js +1 -5
  47. package/dist/drift.js +4 -4
  48. package/dist/e2b.d.ts +10 -128
  49. package/dist/e2b.js +130 -233
  50. package/dist/host.d.ts +106 -87
  51. package/dist/host.js +8 -1
  52. package/dist/hosted/process.d.ts +22 -8
  53. package/dist/hosted/process.js +75 -44
  54. package/dist/hosted/provider.d.ts +35 -21
  55. package/dist/hosted/provider.js +312 -261
  56. package/dist/hosted/rest.d.ts +66 -0
  57. package/dist/hosted/rest.js +121 -0
  58. package/dist/hosted/scripts.d.ts +8 -2
  59. package/dist/hosted/scripts.js +27 -2
  60. package/dist/hosted/values.d.ts +5 -0
  61. package/dist/hosted/values.js +8 -0
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/kernel.d.ts +0 -6
  65. package/dist/kernel.js +1 -5
  66. package/dist/kinds.d.ts +3 -1
  67. package/dist/local-chrome.d.ts +0 -6
  68. package/dist/local-chrome.js +1 -5
  69. package/dist/modal.d.ts +7 -84
  70. package/dist/modal.js +50 -174
  71. package/dist/mount-archil.d.ts +8 -4
  72. package/dist/mount-archil.js +22 -11
  73. package/dist/mount.d.ts +10 -4
  74. package/dist/mount.js +8 -4
  75. package/dist/orgo.d.ts +0 -9
  76. package/dist/orgo.js +2 -9
  77. package/dist/phone-harness.d.ts +0 -6
  78. package/dist/phone-harness.js +0 -4
  79. package/dist/protocol.d.ts +4 -1
  80. package/dist/protocol.js +1 -0
  81. package/dist/provider.d.ts +2 -2
  82. package/dist/providers.d.ts +11 -12
  83. package/dist/screen-watch.js +34 -6
  84. package/dist/surface/api.d.ts +14 -2
  85. package/dist/surface/core.d.ts +16 -3
  86. package/dist/surface/core.js +95 -13
  87. package/dist/surface/outline.d.ts +2 -0
  88. package/dist/surface/outline.js +2 -1
  89. package/dist/surface/script.js +2 -0
  90. package/dist/ui-engine.js +19 -3
  91. package/package.json +2 -3
  92. package/dist/conformance/daytona-sweep.d.ts +0 -18
  93. package/dist/conformance/daytona-sweep.js +0 -126
package/dist/daytona.js CHANGED
@@ -1,954 +1,292 @@
1
- // The Daytona provisioner, over Daytona's v0 REST API with fetch (no SDK). The daemon
2
- // goes in through the toolbox's file upload and starts as a session command, dropped to a user with no capabilities;
3
- // connect() carries stdio over a session command's input calls and its log stream. Every Daytona fact used here is cited
4
- // in the README's Daytona section.
5
- import { createHash, randomBytes } from "node:crypto";
6
- import { readFileSync } from "node:fs";
7
- import { resolve } from "node:path";
8
- import { PassThrough, Writable } from "node:stream";
9
- import { fileURLToPath } from "node:url";
10
- import { childCommands, daemonDrift, installerOf, shellCommand } from "./hosted/scripts.js";
11
- import { OWN_NETWORK_ONLY, readOwnNetwork, TOOL_USER } from "./isolation.js";
12
- import { DaemonClient } from "./client.js";
13
- import { DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_REGION, DAYTONA_GPU_SNAPSHOT, daytonaGpu, daytonaGpuSnapshot } from "./descriptors/daytona.js";
14
- import { COMPUTER_LABEL, DEADLINE_LABEL, helloDrift, WORK } from "./drift.js";
15
- import { releaseOlder } from "./janitor.js";
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, checkTenure, runLifetimeMs, } from "./provider.js";
21
- import { errorOf, failFor, ok, vendorFail } from "./result.js";
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
- const { apiKey, arch = "amd64", sandboxClass = "container", daemonPath } = options ?? {};
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 DEFAULTS = {
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
- const LISTED_ROUNDS = 2;
76
- const LISTED_POLL_MS = 150;
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
- const INIT_SESSION = "agentrun-computerd";
91
- const STAGING = "/tmp/agentrun-computerd-";
92
- const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "mount", "gpu"]);
93
- /** The provider's root channel: argv run as root in a session of its own; the image's user is root, never sudo. */
94
- const ROOT_RUN = [
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 STOPPED = new Set(["stopped", "archived", "paused"]);
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 network as Daytona keeps it: none is block-all with no list, open is neither, an allowlist is one list.
195
- * An outbound proxy, both lists, or a shape not read here is reported in words, never as a policy it might widen to.
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
- return state === "started" || STARTING.has(state) || LEAVING.has(state) ? "running" : "stopped";
270
- }
271
- /** Whether a sandbox is going: Daytona is destroying it, or has been asked to. list() leaves such a one out. */
272
- const going = (sb) => GONE.has(sb.state ?? "") || sb.desiredState === "destroyed";
273
- /** A state as Daytona reported it, for words: the state, and the desired state when it differs. */
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
- * The byte stream of one `computerd stdio` session command: writes go to its input, a whole line at a time and one
441
- * call after another; reads come from its log stream, where Daytona prefixes each stdout line with 01 01 01 and each
442
- * stderr line with 02 02 02. Stderr is kept for the error words; stdout carries the protocol lines alone.
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 sessionStream(socket, send) {
445
- const readable = new PassThrough();
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
- * Computers that are Daytona sandboxes. A spec's image is a Daytona snapshot (its id or name), which gives the class and
524
- * the size. See the README's Daytona section for every call, and its citation.
525
- */
526
- export class DaytonaProvider {
527
- id = "daytona";
528
- version = VERSION;
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
- #daemonPath;
531
- #arch;
532
- #class;
102
+ #headers;
103
+ #webSocket;
533
104
  #target;
534
- #archilEgress;
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
- #onNote;
544
- constructor({ apiKey, onNote, apiUrl = DEFAULT_API_URL, daemonPath, arch = "amd64", sandboxClass = "container", target, archilEgress, gpuSnapshot, daemonUser = TOOL_USER, autoStopMinutes = 0, autoDeleteMinutes, fetch: fetcher, webSocket, timeouts, }) {
545
- this.#onNote = onNote;
546
- if (typeof apiKey !== "string" || apiKey === "")
547
- throw new Error("a Daytona API key is required");
548
- const base = new URL(apiUrl);
549
- if (base.protocol !== "https:")
550
- throw new Error(`the Daytona API URL must be https, so the key never crosses in the clear: ${base.protocol}`);
551
- if (sandboxClass !== "container" && sandboxClass !== "linux-vm")
552
- throw new Error(`sandboxClass is container or linux-vm, not ${String(sandboxClass)}`);
553
- const user = USER.exec(daemonUser);
554
- if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
555
- throw new Error(`the daemon user ${daemonUser} must be uid:gid in numbers, such as 1000:1000`);
556
- // The numbers, not the text: "00" is root as much as "0" is.
557
- if (Number(user[1]) === 0 || Number(user[2]) === 0)
558
- throw new Error(`the daemon user ${daemonUser} is root or in root's group; a Daytona computer's daemon runs as neither`);
559
- const minutes = (name, value) => {
560
- if (!isWhole(value) || value < 0)
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
- groups: ["exec", "files", "processes"],
128
+ isolation: options.sandboxClass === "linux-vm" ? "vm" : "container",
129
+ lifetime: "vendor",
595
130
  maxLifetimeMs: MAX_LIFETIME_MS,
596
- release: ["stop", "delete"],
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(this.#gpu.snapshot === DAYTONA_GPU_SNAPSHOT ? undefined : this.#gpu.snapshot),
137
+ gpu: daytonaGpu(options.gpu.snapshot === DAYTONA_GPU_SNAPSHOT ? undefined : options.gpu.snapshot),
603
138
  };
604
139
  }
605
- check(spec) {
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
- const refuse = (field, message) => refusals.push({ field, message });
608
- const given = (typeof spec === "object" && spec !== null ? spec : {});
609
- const { image, network, labels } = given;
610
- if (typeof image !== "string" || image.trim() === "")
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 && gpuRefused.length === 0 && typeof image === "string" && image !== DAYTONA_DEFAULT_SNAPSHOT && image !== gpuSnapshot) {
640
- refuse("image", `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`);
641
- }
642
- for (const [field, value] of Object.entries(given)) {
643
- if (SPEC_FIELDS.has(field) || value === undefined)
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
- async create(spec, context) {
657
- const signal = context?.signal;
658
- const refusals = this.check(spec);
659
- if (refusals.length > 0)
660
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
661
- let daemon;
662
- try {
663
- daemon = readFileSync(this.#daemonPath);
664
- }
665
- catch {
666
- return fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
667
- }
668
- const sha256 = createHash("sha256").update(daemon).digest("hex");
669
- if (signal?.aborted)
670
- return fail("aborted", "create was aborted before Daytona was called");
671
- const name = `computer-${randomBytes(6).toString("hex")}`;
672
- const deadline = new Date(Date.now() + runLifetimeMs(spec)).toISOString();
673
- const archil = archilOf(spec);
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;
674
183
  const body = {
675
- name,
676
- // A GPU sandbox is made from the provider's GPU snapshot (check() took "default" or that name). Otherwise
184
+ name: req.name,
677
185
  // "default" sends no snapshot, and Daytona makes the sandbox from its default snapshot.
678
- ...(spec.gpu !== undefined ? { snapshot: this.#gpu.snapshot } : spec.image === DAYTONA_DEFAULT_SNAPSHOT ? {} : { snapshot: spec.image }),
679
- // An Archil computer carries its mount as a label: kind and source, never the token.
680
- 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 },
681
188
  env: {},
682
189
  public: false,
683
190
  // A GPU sandbox runs in region earth alone, whatever the provider's target.
684
- ...(spec.gpu !== undefined ? { target: DAYTONA_GPU_REGION } : this.#target === undefined ? {} : { target: this.#target }),
685
- ttlMinutes: Math.max(1, Math.ceil(runLifetimeMs(spec) / 60_000)),
191
+ ...(gpu ? { target: DAYTONA_GPU_REGION } : this.#target === undefined ? {} : { target: this.#target }),
192
+ ttlMinutes: Math.max(1, Math.ceil((req.lifetimeMs ?? 0) / 60_000)),
686
193
  autoStopInterval: this.#autoStop,
687
- // A GPU sandbox's stop deletes it (no pause, no snapshot), so it is asked for and read back as deleted at stop:
688
- // autoDeleteInterval 0 is Daytona's ephemeral (its SDK's ephemeral sets it; CreateSandbox has no ephemeral field).
689
- autoDeleteInterval: this.#autoDeleteFor(spec.gpu !== undefined),
690
- // An Archil computer's root reaches Archil: Daytona's network is open, and init's own namespace (loopback alone)
691
- // holds the tools to none.
692
- ...(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",
693
198
  // No resource field (cpu, gpu, gpuType, memory, disk): a snapshot carries its own, and Daytona refuses a create that
694
199
  // names a snapshot and sends any (400 "Cannot specify Sandbox resources when using a snapshot"). A GPU computer's
695
- // GPU is daytona-gpu's, held in the read-back.
200
+ // GPU is the snapshot's, held in the read-back.
696
201
  };
697
- const posted = await this.#rest.json("POST", this.#rest.sandbox(), { json: body, timeoutMs: this.#timeouts.createMs }, signal);
698
- const made = posted.ok ? posted.value : undefined;
699
- if (!posted.ok || typeof made?.id !== "string") {
700
- // A create Daytona refused with a 4xx made nothing. One that failed otherwise, or was aborted, may still have made
701
- // the sandbox: it goes by its name, which is this provider's.
702
- const refused = !posted.ok && ["invalid", "denied", "limit", "not_found"].includes(posted.error.code);
703
- const removed = refused ? ok(undefined) : await this.#delete(name);
704
- const left = removed.ok ? "" : `; a sandbox named ${name} may be left (${removed.error.message}), which Daytona ends by ${deadline}`;
705
- if (!posted.ok)
706
- return fail(posted.error.code, `${posted.error.code === "aborted" ? "create was aborted" : "Daytona did not create the sandbox"}: ${posted.error.message}${left}`);
707
- return vendorFail("daytona", `POST /sandbox: no sandbox id in the answer${left}`);
708
- }
709
- const ref = { id: made.id, name };
710
- // From here the sandbox exists: every step takes the caller's signal, and a failure or an abort deletes it.
711
- const prepared = await this.#prepare(spec, ref, made, deadline, daemon, sha256, signal);
712
- if (signal?.aborted)
713
- return this.#abandon(ref, { code: "aborted", message: "create was aborted" }, signal);
714
- if (prepared.ok)
715
- return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
716
- return this.#abandon(ref, prepared.error, signal);
717
- }
718
- async #abandon(ref, error, signal) {
719
- // The delete itself is never signalled: it is sent even after an abort. The wait for the sandbox to go takes the
720
- // caller's signal, as Modal's terminate does, so an aborted create returns once the delete is sent.
721
- const deleted = await this.#delete(ref.id);
722
- const removed = deleted.ok ? await this.#settle(ref, "gone", "delete", signal) : deleted;
723
- const after = removed.ok
724
- ? "was deleted"
725
- : deleted.ok && removed.error.code === "aborted"
726
- ? "was sent a delete, and the wait for it to go was aborted; Daytona ends it at its TTL if the delete did not take"
727
- : `could not be deleted (${removed.error.message}); Daytona ends it at its TTL`;
728
- return fail(error.code, `the computer ${ref.name} ${after}: ${error.message}`);
729
- }
730
- /** Everything between the create's answer and a computer that passed the drift check. */
731
- async #prepare(spec, ref, made, deadline, daemon, sha256, signal) {
732
- const started = await this.#waitStarted(made, signal);
733
- if (!started.ok)
734
- return started;
735
- const sb = started.value;
736
- const archil = archilOf(spec);
737
- // An Archil computer's network at Daytona is open for root; init's own namespace holds the tools to the spec's none.
738
- const vendor = sandboxDrift(archil ? { ...spec, network: "open" } : spec, sb, this.#sandboxExpected(deadline, spec.gpu !== undefined));
739
- if (vendor.length > 0)
740
- return fail("refused", `it did not match its spec: ${vendor.join("; ")}`);
741
- const toolbox = await this.#toolbox(sb, signal);
742
- if (!toolbox.ok)
743
- return toolbox;
744
- const staging = `${STAGING}${randomBytes(8).toString("hex")}`;
745
- const uploaded = await this.#upload(toolbox.value, staging, daemon, signal);
746
- if (!uploaded.ok)
747
- return fail(uploaded.error.code, `the daemon's upload was refused: ${uploaded.error.message}`);
748
- // Init's flags are built here (childCommands): every remote computer, an Archil one included, starts init with
749
- // --own-network, init and every tool in a network namespace of their own, loopback alone; the archil client and
750
- // serve, run as root through the toolbox, stay in the computer's namespace, which reaches Archil.
751
- const commands = daytonaCommands({ staging, deadline, user: `${this.#uid}:${this.#gid}` });
752
- const install = await this.#execute(toolbox.value, commands.install, signal);
753
- if (!install.ok)
754
- return install;
755
- if (install.value.exitCode !== 0)
756
- return fail("refused", `installing the daemon failed (exit ${install.value.exitCode}): ${install.value.result.trim().slice(0, 500)}`);
757
- const read = /^sha256 ([0-9a-f]{64})$/m.exec(install.value.result)?.[1];
758
- if (read !== sha256)
759
- return fail("refused", `it did not match its spec: daemon: uploaded sha256 ${sha256}, the installed binary reads back ${show(read)}`);
760
- // Who installed it, for the create's notes: root, or the snapshot's user through passwordless sudo (daytona-gpu's).
761
- const installer = installerOf(install.value.result);
762
- // The run's folder, mounted before init starts, so no tool program runs before it is there.
763
- let epoch;
764
- if (archil) {
765
- const labels = spec.labels ?? {};
766
- const claim = epochOf(labels);
767
- epoch = claim.ok ? claim.value : undefined;
768
- const run = labels[RUN_LABEL];
769
- const mounted = await archilMount({
770
- root: this.#root(toolbox.value),
771
- mount: archil,
772
- self: ref,
773
- releaseOlder: () => releaseOlder(this, run, epoch, signal ? { signal } : {}),
774
- timeoutMs: this.#timeouts.execMs,
775
- ...(this.#archilEgress ? { egress: this.#archilEgress } : {}),
776
- ...(signal ? { signal } : {}),
777
- });
778
- if (!mounted.ok)
779
- return mounted;
780
- }
781
- const session = await this.#rest.call("POST", `${toolbox.value}/process/session`, { json: { sessionId: INIT_SESSION } }, signal);
782
- if (!session.ok)
783
- return fail(session.error.code, `starting the daemon: ${session.error.message}`);
784
- const init = await this.#rest.json("POST", `${toolbox.value}/process/session/${INIT_SESSION}/exec`, { json: { command: commands.init, runAsync: true, suppressInputEcho: true } }, signal);
785
- if (!init.ok)
786
- return fail(init.error.code, `starting the daemon: ${init.error.message}`);
787
- const initId = init.value?.cmdId;
788
- const opened = await this.#open(sb, toolbox.value, signal);
789
- if (!opened.ok) {
790
- if (opened.error.code === "aborted")
791
- return opened;
792
- const why = typeof initId === "string" ? await this.#initLog(toolbox.value, initId) : "";
793
- return fail(opened.error.code, `the daemon did not answer: ${opened.error.message}${why ? `; init wrote: ${why}` : ""}`);
794
- }
795
- const daemonFound = await daemonDrift(opened.value, this.#daemonExpected(), this.#timeouts.helloMs, signal);
796
- const mountRead = archil ? await this.#mountReadBack(opened.value.client, epoch, archil, signal) : undefined;
797
- await opened.value.close();
798
- if (!daemonFound.ok)
799
- return daemonFound;
800
- if (daemonFound.value.length > 0)
801
- return fail("refused", `it did not match its spec: ${daemonFound.value.join("; ")}`);
802
- if (archil && mountRead !== undefined) {
803
- if (!mountRead.ok)
804
- return mountRead;
805
- const want = readBackOf(archil, epoch);
806
- if (JSON.stringify(mountRead.value) !== JSON.stringify(want)) {
807
- return fail("refused", `it did not match its spec: mount: declared ${show(want)}, read back ${show(mountRead.value ?? "nothing")}`);
808
- }
809
- }
810
- const listed = await this.#waitListed(ref.id, signal);
811
- return listed.ok ? ok(installer === undefined ? [] : [installer]) : listed;
812
- }
813
- /**
814
- * What an Archil computer mounts at /workspace, read back through its computerd: the mount table, and whether the
815
- * resident serve answers (exclusive), under `epoch`, the computer's label.
816
- */
817
- #mountReadBack(client, epoch, recorded, signal) {
818
- 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;
819
232
  }
820
233
  /**
821
- * The toolbox as the Archil mount's root channel: argv run as root (the snapshot's user is root, never sudo), in a
822
- * session of its own, its stdin, when given, sent as the session command's input with no echo; its exit code polled
823
- * 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.
824
236
  */
825
- #root(toolbox) {
826
- return {
827
- run: async (argv, { stdin, timeoutMs, signal }) => {
828
- const sessionId = `agentrun-archil-${randomBytes(8).toString("hex")}`;
829
- const session = `${toolbox}/process/session/${sessionId}`;
830
- const made = await this.#rest.call("POST", `${toolbox}/process/session`, { json: { sessionId } }, signal);
831
- if (!made.ok)
832
- return made;
833
- try {
834
- const ran = await this.#rest.json("POST", `${session}/exec`, { json: { command: shellCommand(ROOT_RUN, argv), runAsync: true, suppressInputEcho: true } }, signal);
835
- if (!ran.ok)
836
- return ran;
837
- const commandId = ran.value?.cmdId;
838
- if (typeof commandId !== "string")
839
- return vendorFail("daytona", "POST exec: no command id in the answer");
840
- const command = `${session}/command/${encodeURIComponent(commandId)}`;
841
- if (stdin !== undefined) {
842
- // Its words never carry stdin: it is the disk's token.
843
- const sent = await this.#rest.call("POST", `${command}/input`, { json: { data: stdin } }, signal);
844
- if (!sent.ok)
845
- return fail(sent.error.code, `the command's stdin could not be sent (${sent.error.code})`);
846
- }
847
- const end = Date.now() + timeoutMs;
848
- let exitCode;
849
- while (exitCode === undefined) {
850
- const read = await this.#rest.json("GET", session, { retry: true }, signal);
851
- if (!read.ok)
852
- return read;
853
- const found = (read.value?.commands ?? []).find((one) => one.id === commandId);
854
- if (typeof found?.exitCode === "number")
855
- exitCode = found.exitCode;
856
- else if (Date.now() >= end)
857
- return fail("timeout", `the root command did not end within ${Math.round(timeoutMs / 1000)} s`);
858
- else
859
- await sleep(this.#timeouts.pollMs, signal);
860
- if (signal?.aborted)
861
- return fail("aborted", "the root command's wait was aborted");
862
- }
863
- const logs = await this.#rest.call("GET", `${command}/logs`, {}, signal);
864
- return ok({ exitCode, output: logs.ok ? logText(logs.value.bytes).trim().slice(-2000) : "" });
865
- }
866
- finally {
867
- await this.#rest.call("DELETE", session, {});
868
- }
869
- },
870
- };
871
- }
872
- #sandboxExpected(deadline, gpu = false) {
873
- return { deadline, sandboxClass: this.#class, autoStopInterval: this.#autoStop, autoDeleteInterval: this.#autoDeleteFor(gpu), gpu: this.#gpu };
874
- }
875
- /** The autoDeleteInterval a sandbox is made and read back with: 0 for a GPU sandbox, which a stop deletes; else the option's. */
876
- #autoDeleteFor(gpu) {
877
- return gpu ? 0 : this.#autoDelete;
878
- }
879
- #daemonExpected() {
880
- const { kind, groups } = this.capabilities();
881
- return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: this.#arch, kind, groups };
882
- }
883
- async #waitStarted(made, signal) {
884
- const end = Date.now() + this.#timeouts.startMs;
885
- let current = made;
886
- for (let first = true;; first = false) {
887
- // The create's answer may leave fields out, as a listing does: the drift check reads the sandbox's own read.
888
- if (!first && current?.state === "started")
889
- return ok(current);
890
- if (current === undefined || GONE.has(current.state ?? "") || current.state === "error" || current.state === "build_failed") {
891
- const reason = current?.errorReason ? `: ${current.errorReason}` : "";
892
- return vendorFail("daytona", `the sandbox went to ${current?.state ?? "deleted"} while starting${reason}`);
893
- }
894
- if (!first && Date.now() >= end)
895
- return fail("timeout", `the sandbox did not start within ${this.#timeouts.startMs / 1000} s (state ${current.state})`);
896
- if (!first)
897
- await sleep(this.#timeouts.pollMs, signal);
898
- if (signal?.aborted)
899
- return fail("aborted", "create was aborted while the sandbox started");
900
- const next = await this.#rest.get(made.id, signal);
901
- if (!next.ok)
902
- return next;
903
- current = next.value;
904
- }
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));
905
241
  }
906
242
  /**
907
- * Daytona's label listing trails a create (measured 0.7 to 1.6 s, with flaps), and list() must show a
908
- * computer once create returns: create waits until the listing has shown it, without a miss, for listedStableMs.
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.
909
246
  */
910
- async #waitListed(id, signal) {
911
- const end = Date.now() + this.#timeouts.listedMs;
912
- let streak;
913
- for (let hits = 0;;) {
914
- const listed = await this.#listOwn(signal);
915
- if (!listed.ok)
916
- return listed;
917
- if (listed.value.some((sb) => sb.id === id)) {
918
- streak ??= Date.now();
919
- hits++;
920
- if (hits >= LISTED_ROUNDS && Date.now() - streak >= this.#timeouts.listedStableMs)
921
- return ok(undefined);
922
- }
923
- else {
924
- streak = undefined;
925
- hits = 0;
926
- }
927
- if (Date.now() >= end)
928
- return fail("timeout", `the computer was not listed steadily within ${this.#timeouts.listedMs / 1000} s of its creation`);
929
- await sleep(Math.min(LISTED_POLL_MS, this.#timeouts.pollMs), signal);
930
- if (signal?.aborted)
931
- return fail("aborted", "create was aborted while it waited for the listing");
932
- }
933
- }
934
- async #toolbox(sb, signal) {
935
- let proxy = sb.toolboxProxyUrl;
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;
936
274
  if (typeof proxy !== "string" || proxy === "") {
937
- const found = await this.#rest.json("GET", this.#rest.sandbox(sb.id, "/toolbox-proxy-url"), { retry: true }, signal);
938
- if (!found.ok)
939
- return found;
940
- 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;
941
277
  }
942
278
  let url;
943
279
  try {
944
280
  url = new URL(proxy ?? "");
945
281
  }
946
282
  catch {
947
- return vendorFail("daytona", `Daytona gave no toolbox URL for ${sb.id}`);
283
+ throw new Error(`Daytona gave no toolbox URL for ${id}`);
948
284
  }
949
285
  if (url.protocol !== "https:")
950
- return vendorFail("daytona", `the toolbox URL Daytona gave is not https (${url.protocol}), so the key is not sent to it`);
951
- return ok(`${url.href.replace(/\/+$/, "")}/${encodeURIComponent(sb.id)}`);
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;
952
290
  }
953
291
  /**
954
292
  * A file's bytes to `path` in the sandbox: files/upload-v2, else files/upload. An older toolbox, as a self-hosted
@@ -956,608 +294,225 @@ export class DaytonaProvider {
956
294
  * has no files/upload-v2 and answers it 404; its files/upload takes the same form (a path query, the bytes as
957
295
  * "file"). A 404 alone moves to the older route, so a refusal of any other kind is never sent twice.
958
296
  */
959
- async #upload(toolbox, path, bytes, signal) {
297
+ async upload(id, path, bytes, ctx) {
298
+ const toolbox = await this.#toolbox(id, ctx.signal);
960
299
  const query = new URLSearchParams({ path });
961
300
  const send = (route, answerStatus) => {
962
301
  const form = new FormData();
963
302
  form.append("file", new Blob([new Uint8Array(bytes)]), "computerd");
964
- return this.#rest.call("POST", `${toolbox}/${route}?${query}`, { form, retry: true, timeoutMs: this.#timeouts.uploadMs, ...(answerStatus === undefined ? {} : { answerStatus }) }, signal);
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);
965
304
  };
966
- const current = await send("files/upload-v2", 404);
967
- if (!current.ok || current.value.status !== 404)
968
- return current;
969
- const missing = `POST ${new URL(`${toolbox}/files/upload-v2`).pathname}: 404 ${decoder.decode(current.value.bytes).replace(/\s+/g, " ").trim().slice(0, 300)}`;
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)}`;
970
309
  const older = await send("files/upload");
971
- return older.ok ? older : fail(older.error.code, `${missing}, then ${older.error.message}`);
972
- }
973
- async #execute(toolbox, command, signal) {
974
- const seconds = Math.ceil(this.#timeouts.execMs / 1000);
975
- const ran = await this.#rest.json("POST", `${toolbox}/process/execute`, { json: { command, timeout: seconds }, timeoutMs: this.#timeouts.execMs + 15_000 }, signal);
976
- if (!ran.ok)
977
- return ran;
978
- const value = ran.value;
979
- 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}`);
980
312
  }
981
- /** What init wrote to stderr, for the words of a daemon that did not start. Best effort: empty when it cannot be read. */
982
- async #initLog(toolbox, commandId) {
983
- const logs = await this.#rest.call("GET", `${toolbox}/process/session/${INIT_SESSION}/command/${encodeURIComponent(commandId)}/logs`, {});
984
- if (!logs.ok)
985
- return "";
986
- const bytes = Buffer.from(logs.value.bytes);
987
- const parsed = parseJson(bytes);
988
- if (typeof parsed?.stderr === "string")
989
- return parsed.stderr.trim().slice(-500);
990
- return bytes
991
- .toString("utf8")
992
- .split("\n")
993
- .filter((line) => line.startsWith("\x02\x02\x02"))
994
- .map((line) => line.slice(3))
995
- .join("\n")
996
- .trim()
997
- .slice(-500);
998
- }
999
- /** One connection to the daemon, after hello, unchecked: a session of its own running the bridge. */
1000
- async #open(sb, toolbox, signal) {
1001
- 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")}`;
1002
324
  const session = `${toolbox}/process/session/${sessionId}`;
1003
- const made = await this.#rest.call("POST", `${toolbox}/process/session`, { json: { sessionId } }, signal);
1004
- if (!made.ok)
1005
- return made;
1006
- const removeSession = async () => {
1007
- await this.#rest.call("DELETE", session, {});
1008
- };
1009
- 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);
1010
329
  const commandId = ran.ok ? ran.value?.cmdId : undefined;
1011
330
  if (!ran.ok || typeof commandId !== "string") {
1012
331
  await removeSession();
1013
- return ran.ok ? vendorFail("daytona", "POST exec: no command id in the answer") : ran;
332
+ throw ran.ok ? new Error("POST exec: no command id in the answer") : new HostError(ran.error.code, ran.error.message);
1014
333
  }
1015
334
  const command = `${session}/command/${encodeURIComponent(commandId)}`;
1016
- const logs = `${command.replace(/^https:/, "wss:")}/logs?follow=true`;
1017
335
  let socket;
1018
336
  try {
1019
- socket = this.#webSocket(logs, { headers: this.#rest.headers(), protocols: [] });
337
+ socket = this.#webSocket(`${command.replace(/^https:/, "wss:")}/logs?follow=true`, { headers: this.#headers, protocols: [] });
1020
338
  }
1021
339
  catch (error) {
1022
340
  await removeSession();
1023
- return vendorFail("daytona", `opening the log stream: ${error.message}`);
1024
- }
1025
- const stream = sessionStream(socket, async (data) => {
1026
- const sent = await this.#rest.call("POST", `${command}/input`, { json: { data } });
1027
- return sent.ok ? ok(undefined) : sent;
1028
- });
1029
- const client = new DaemonClient(stream);
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
+ };
1030
368
  let closed;
1031
- const close = () => (closed ??= (async () => {
1032
- client.close();
1033
- socket.close(1000);
1034
- await removeSession();
1035
- })());
1036
- const bound = AbortSignal.timeout(this.#timeouts.helloMs);
1037
- const either = signal ? AbortSignal.any([signal, bound]) : bound;
1038
- // The stream's open raced against the bound; the abort listener is removed once the race is decided, so no connect
1039
- // leaves one behind on its signal.
1040
- let onAbort = () => { };
1041
- const aborted = new Promise((done) => {
1042
- onAbort = () => done(fail("aborted", ""));
1043
- if (either.aborted)
1044
- onAbort();
1045
- else
1046
- 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);
1047
381
  });
1048
- const opened = await Promise.race([stream.open, aborted]);
1049
- either.removeEventListener("abort", onAbort);
1050
- const timedOut = () => fail("timeout", `the daemon in ${sb.name ?? sb.id} did not answer hello within ${this.#timeouts.helloMs / 1000} s`);
1051
- if (!opened.ok) {
1052
- await close();
1053
- if (signal?.aborted)
1054
- return fail("aborted", `connecting to ${sb.name ?? sb.id} was aborted`);
1055
- return opened.error.code === "aborted" ? timedOut() : opened;
1056
- }
1057
- const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: either });
1058
- if (!hello.ok) {
1059
- await close();
1060
- if (signal?.aborted)
1061
- return fail("aborted", `hello to the daemon in ${sb.name ?? sb.id} was aborted`);
1062
- if (hello.error.code === "aborted")
1063
- return timedOut();
1064
- if (hello.error.code !== "gone")
1065
- return hello;
1066
- return vendorFail("daytona", `cannot reach the daemon in ${sb.name ?? sb.id}: ${stream.stderr() || hello.error.message}`);
1067
- }
1068
- return ok({ client, hello: hello.value, close });
1069
- }
1070
- /** A sandbox this provider made, by its ref; not_found for one that is gone or another's. */
1071
- async #own(ref, signal) {
1072
- const found = await this.#rest.get(ref.id, signal);
1073
- if (!found.ok)
1074
- return found;
1075
- const sb = found.value;
1076
- if (!ours(sb) || sb.name !== ref.name || going(sb))
1077
- return fail("not_found", `no Daytona computer is ${ref.name} (${ref.id})`);
1078
- return ok(sb);
1079
- }
1080
- /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a sandbox has no screen. */
1081
- watch(ref, handlers, options) {
1082
- return daemonWatch(this, ref, handlers, options);
1083
- }
1084
- async connect(ref) {
1085
- if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
1086
- return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
1087
- const found = await this.#own(ref);
1088
- if (!found.ok)
1089
- return found;
1090
- if (found.value.state !== "started")
1091
- return fail("refused", `${ref.name} is ${found.value.state ?? "in no state Daytona reports"}, not started: its daemon does not run`);
1092
- const toolbox = await this.#toolbox(found.value);
1093
- if (!toolbox.ok)
1094
- return toolbox;
1095
- const opened = await this.#open(found.value, toolbox.value);
1096
- if (!opened.ok)
1097
- return opened;
1098
- const { kind, groups } = this.capabilities();
1099
- const drifted = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: this.#arch, fence: true });
1100
- // An Archil computer's client syncs the run's folder after every call that may change it, before it answers.
1101
- if (drifted.length === 0)
1102
- return recordedMount(found.value.labels) ? ok({ ...opened.value, client: syncingClient(opened.value.client) }) : opened;
1103
- await opened.value.close();
1104
- return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drifted.join("; ")}`);
1105
- }
1106
- async attach(ref, { signal } = {}) {
1107
- const given = (typeof ref === "object" && ref !== null ? ref : {});
1108
- if ((given.id === undefined) === (given.labels === undefined))
1109
- return fail("invalid", "attach takes { id } or { labels }, one of them");
1110
- if (given.id !== undefined) {
1111
- const id = given.id;
1112
- if (typeof id !== "string" || id === "" || id.includes("/"))
1113
- return fail("invalid", `${String(id)} is not a Daytona sandbox's id or a computer's name`);
1114
- const found = await this.#rest.get(id, signal);
1115
- if (!found.ok)
1116
- return found;
1117
- const sb = found.value;
1118
- if (!ours(sb) || (sb.id !== id && sb.name !== id) || going(sb))
1119
- return fail("not_found", `no Daytona computer has the id ${id}`);
1120
- return this.#attached(sb, signal);
1121
- }
1122
- const problem = filterProblem(given.labels);
1123
- if (problem)
1124
- return fail("invalid", problem);
1125
- const labels = given.labels;
1126
- if (Object.keys(labels).length === 0)
1127
- return fail("invalid", "attach by labels needs at least one label");
1128
- const listed = await this.list(labels, { signal });
1129
- if (!listed.ok)
1130
- return listed;
1131
- const words = JSON.stringify(labels);
1132
- if (listed.value.length === 0)
1133
- return fail("not_found", `no Daytona computer has the labels ${words}`);
1134
- if (listed.value.length > 1)
1135
- return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
1136
- const match = listed.value[0].ref;
1137
- const found = await this.#own(match, signal);
1138
- if (!found.ok)
1139
- return found.error.code === "not_found" ? fail("not_found", `no Daytona computer has the labels ${words}`) : found;
1140
- return this.#attached(found.value, signal);
1141
- }
1142
- /**
1143
- * The drift check of a computer attach did not make: its spec read back from Daytona and held to what check()
1144
- * allows, the sandbox as at create, and, when it runs, its daemon. One that drifts is refused and left as it is.
1145
- */
1146
- async #attached(sb, signal) {
1147
- const ref = { id: sb.id, name: sb.name };
1148
- const found = [];
1149
- const deadline = deadlineOf(sb);
1150
- if (deadline === undefined)
1151
- found.push(`deadline: the label ${DEADLINE_LABEL} reads ${show(sb.labels?.[DEADLINE_LABEL])}, not the ISO time create writes`);
1152
- else if (deadline.getTime() > Date.now() + MAX_LIFETIME_MS + 60_000)
1153
- found.push(`deadline: ${deadline.toISOString()} is past the 30 days create allows`);
1154
- const network = networkOf(sb);
1155
- if (typeof network === "object" && "other" in network)
1156
- found.push(`network: ${network.other}, which this provider never makes`);
1157
- // An Archil computer's Daytona network is open, for root to reach Archil; its spec's network is the tools', none.
1158
- const archilComputer = recordedMount(sb.labels) !== undefined;
1159
- if (archilComputer && network !== "open")
1160
- found.push(`network: an Archil computer's Daytona network is open, for root to reach Archil; read back ${policyWords(network)}`);
1161
- // The caller's labels: none of the provider's own, which are read back above (the mount's label by recordedMount).
1162
- const labels = Object.fromEntries(Object.entries(sb.labels ?? {}).filter(([key]) => key !== COMPUTER_LABEL && !key.startsWith(`${COMPUTER_LABEL}.`) && key !== ARCHIL_MOUNT_LABEL));
1163
- // The image create was asked for, from its label; a computer made before the label was written reports its snapshot.
1164
- const asked = sb.labels?.[IMAGE_LABEL];
1165
- const specNetwork = archilComputer || (typeof network === "object" && "other" in network) ? "none" : network;
1166
- // The GPUs Daytona reports, held to what check() allows: a type this provider declares, a count up to its max.
1167
- const gpu = isWhole(sb.gpu) && sb.gpu > 0 ? { type: String(sb.gpuType), count: sb.gpu } : undefined;
1168
- const spec = { image: asked ?? sb.snapshot, lifetimeMs: 1, network: specNetwork, labels, ...(gpu === undefined ? {} : { gpu }) };
1169
- found.push(...this.check(spec).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
1170
- const vendor = sandboxDrift(spec, sb, this.#sandboxExpected(sb.labels?.[DEADLINE_LABEL] ?? "", gpu !== undefined));
1171
- found.push(...vendor.filter((line) => !line.startsWith("network:") &&
1172
- !line.startsWith(`label ${DEADLINE_LABEL}`) &&
1173
- !(asked === undefined && line.startsWith(`label ${IMAGE_LABEL}`)) &&
1174
- !(deadline === undefined && line.startsWith("autoDestroyAt"))));
1175
- let user = `${this.#uid}:${this.#gid}`;
1176
- let workdir;
1177
- let kind;
1178
- // An Archil computer: its mount read back from inside it. Daytona's network is open for root, so the tools' is
1179
- // init's own namespace, which the daemon's drift check reads back (lo alone, or attach refuses): "none".
1180
- const recorded = recordedMount(sb.labels);
1181
- let mount;
1182
- const toolsNetwork = recorded ? "none" : spec.network;
1183
- if (sb.state === "started") {
1184
- const toolbox = await this.#toolbox(sb, signal);
1185
- if (!toolbox.ok)
1186
- return toolbox;
1187
- const opened = await this.#open(sb, toolbox.value, signal);
1188
- if (!opened.ok)
1189
- return opened;
1190
- const daemonFound = await daemonDrift(opened.value, this.#daemonExpected(), this.#timeouts.helloMs, signal);
1191
- const claim = epochOf(sb.labels);
1192
- const mountRead = recorded ? await this.#mountReadBack(opened.value.client, claim.ok ? claim.value : undefined, recorded, signal) : undefined;
1193
- await opened.value.close();
1194
- if (!daemonFound.ok)
1195
- return daemonFound;
1196
- found.push(...daemonFound.value);
1197
- workdir = WORK;
1198
- kind = opened.value.hello.kind;
1199
- if (mountRead !== undefined) {
1200
- if (!mountRead.ok)
1201
- return mountRead;
1202
- mount = mountRead.value;
1203
- // Held to the whole read-back the label and the epoch make (exclusive included), as Modal and E2B hold it.
1204
- if (recorded !== undefined)
1205
- found.push(...mountDrift(readBackOf({ ...recorded, token: "" }, claim.ok ? claim.value : undefined), mount));
1206
- }
1207
- }
1208
- if (found.length > 0)
1209
- 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("; ")}`);
1210
- return ok({
1211
- ...ref,
1212
- spec: {
1213
- image: spec.image,
1214
- ...(typeof sb.snapshot === "string" ? { snapshot: sb.snapshot } : {}),
1215
- user,
1216
- network: toolsNetwork,
1217
- ...(mount === undefined ? {} : { mount }),
1218
- ...(isWhole(sb.cpu) ? { cpus: sb.cpu } : {}),
1219
- ...(isWhole(sb.memory) ? { memoryMb: sb.memory * 1024 } : {}),
1220
- ...(workdir === undefined ? {} : { workdir }),
1221
- ...(deadline === undefined ? {} : { deadline }),
1222
- ...(kind === undefined ? {} : { kind }),
1223
- ...(gpu === undefined ? {} : { gpu }),
1224
- },
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();
1225
388
  });
1226
- }
1227
- /** Every sandbox with this provider's label, all pages: one label query. */
1228
- async #listOwn(signal) {
1229
- const found = [];
1230
- const seen = new Set();
1231
- let cursor;
1232
- for (let page = 0; page < MAX_PAGES; page++) {
1233
- const query = new URLSearchParams({ labels: JSON.stringify({ [COMPUTER_LABEL]: "1" }), limit: "100" });
1234
- if (cursor !== undefined)
1235
- query.set("cursor", cursor);
1236
- const answer = await this.#rest.json("GET", `${this.#rest.sandbox()}?${query}`, { retry: true }, signal);
1237
- if (!answer.ok)
1238
- return answer;
1239
- const value = answer.value;
1240
- const items = Array.isArray(value) ? value : Array.isArray(value?.items) ? value.items : undefined;
1241
- if (items === undefined)
1242
- return vendorFail("daytona", "GET /sandbox: the listing is not a page of sandboxes");
1243
- found.push(...items);
1244
- const next = Array.isArray(value) ? undefined : value?.nextCursor;
1245
- if (typeof next !== "string" || next === "")
1246
- return ok(found);
1247
- if (seen.has(next))
1248
- return vendorFail("daytona", `GET /sandbox: the listing's cursor ${next} came back twice`);
1249
- seen.add(next);
1250
- cursor = next;
1251
- }
1252
- return vendorFail("daytona", `GET /sandbox: the listing ran past ${MAX_PAGES} pages`);
1253
- }
1254
- /**
1255
- * For the sweep after a live run: every sandbox Daytona lists with agentrun.computer=1, whatever its name or state, as
1256
- * Daytona reports it, with its labels (the sweep deletes only a conformance run's). list() keeps only this provider's
1257
- * computers; this keeps everything the label query returns.
1258
- */
1259
- async listLabelled({ signal } = {}) {
1260
- const listed = await this.#listOwn(signal);
1261
- if (!listed.ok)
1262
- return listed;
1263
- return ok(listed.value
1264
- .filter((sb) => typeof sb?.id === "string")
1265
- .map((sb) => ({ id: sb.id, ...(typeof sb.name === "string" ? { name: sb.name } : {}), ...(typeof sb.state === "string" ? { state: sb.state } : {}), labels: { ...(sb.labels ?? {}) } })));
1266
- }
1267
- /** For the sweep: GET /sandbox/{id} once, retried as every read is, and the status Daytona answered (404: none). */
1268
- async probe(id, { signal } = {}) {
1269
- if (typeof id !== "string" || id === "" || id.includes("/"))
1270
- return fail("invalid", `${String(id)} is not a Daytona sandbox's id`);
1271
- const answer = await this.#rest.call("GET", this.#rest.sandbox(id), { retry: true, anyStatus: true }, signal);
1272
- if (!answer.ok)
1273
- return answer;
1274
- const state = parseJson(answer.value.bytes)?.state;
1275
- return ok({ status: answer.value.status, ...(typeof state === "string" ? { state } : {}) });
1276
- }
1277
- /**
1278
- * Settings' test: one page of the account's sandboxes by the provider's own label, which makes nothing. The count is
1279
- * read from the listing, with no read of each sandbox: a busy account answers as fast, and one sandbox's read never
1280
- * fails a working key. A further page is "or more".
1281
- */
1282
- async testConnection({ signal } = {}) {
1283
- const query = new URLSearchParams({ labels: JSON.stringify({ [COMPUTER_LABEL]: "1" }), limit: "100" });
1284
- const answer = await this.#rest.json("GET", `${this.#rest.sandbox()}?${query}`, { retry: true }, signal);
1285
- if (!answer.ok)
1286
- return countTested("Daytona", answer);
1287
- const value = answer.value;
1288
- const items = Array.isArray(value) ? value : Array.isArray(value?.items) ? value.items : undefined;
1289
- if (items === undefined)
1290
- return countTested("Daytona", vendorFail("daytona", "GET /sandbox: the listing is not a page of sandboxes"));
1291
- const next = Array.isArray(value) ? undefined : value?.nextCursor;
1292
- return countTested("Daytona", ok({ count: items.filter((item) => ours(item) && !going(item)).length, more: typeof next === "string" && next !== "" }));
1293
- }
1294
- async list(labels, { signal } = {}) {
1295
- const problem = filterProblem(labels);
1296
- if (problem)
1297
- return fail("invalid", problem);
1298
- const listed = await this.#listOwn(signal);
1299
- if (!listed.ok)
1300
- return listed;
1301
- const infos = [];
1302
- for (const item of listed.value) {
1303
- if (!ours(item) || going(item))
1304
- continue;
1305
- if (!Object.entries(labels).every(([key, value]) => item.labels?.[key] === value))
1306
- continue;
1307
- let sb = item;
1308
- // A listing may leave the network out: the sandbox's own read says.
1309
- if (item.networkBlockAll === undefined) {
1310
- const read = await this.#rest.get(item.id, signal);
1311
- if (!read.ok)
1312
- return read;
1313
- if (read.value === undefined)
1314
- continue;
1315
- sb = read.value;
1316
- }
1317
- // An Archil computer: its mount as labelled, under its epoch label, and its tools' network, init's own namespace
1318
- // (create held its daemon to lo alone; attach and network() read it back from inside). Daytona's own report is
1319
- // open, for root to reach Archil.
1320
- const recorded = recordedMount(sb.labels);
1321
- const claim = epochOf(sb.labels);
1322
- const mount = recorded ? readBackOf({ ...recorded, token: "" }, claim.ok ? claim.value : undefined) : undefined;
1323
- const network = recorded ? "none" : networkOf(sb);
1324
- infos.push({ ref: { id: sb.id, name: sb.name }, labels: { ...(sb.labels ?? {}) }, deadline: deadlineOf(sb), state: stateOf(sb), network, ...(mount ? { mount } : {}) });
1325
- }
1326
- return ok(infos);
1327
- }
1328
- async network(ref, policy, { signal } = {}) {
1329
- if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
1330
- return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
1331
- if (policy !== undefined) {
1332
- const problem = this.check({ image: "-", lifetimeMs: 1, network: policy }).find((refusal) => refusal.field === "network");
1333
- if (problem)
1334
- return fail("invalid", problem.message);
1335
- }
1336
- const found = await this.#own(ref, signal);
1337
- if (!found.ok)
1338
- return found;
1339
- // An Archil computer: Daytona's network is open for root, so the tools' network is read back from the daemon, init's
1340
- // own namespace: "none" while it holds lo alone. It takes no other policy.
1341
- if (recordedMount(found.value.labels)) {
1342
- if (policy !== undefined && policy !== "none")
1343
- return fail("refused", `${ref.name} has an Archil mount: its tools' network is none, init's own namespace, and it takes no other`);
1344
- return this.#toolsNetwork(found.value, signal);
1345
- }
1346
- const current = networkOf(found.value);
1347
- if (policy === undefined || samePolicy(current, policy))
1348
- return ok(current);
1349
- const changed = await this.#setNetwork(ref, policy, signal);
1350
- // Read back whatever the change's answer: one that timed out may still have been applied. Never signalled, so an
1351
- // aborted change is still checked.
1352
- const after = await this.#own(ref);
1353
- // What the network is now is not known, whatever the change answered: it is made safe.
1354
- if (!after.ok) {
1355
- const answered = changed.ok ? "" : ` (the change itself answered: ${changed.error.message})`;
1356
- return this.#makeSafe(ref, after.error.code, `network ${policyWords(policy)} could not be read back after the change: ${after.error.message}${answered}`);
1357
- }
1358
- const read = networkOf(after.value);
1359
- if (samePolicy(read, policy))
1360
- return ok(read);
1361
- if (!(typeof current === "object" && "other" in current) && samePolicy(read, current)) {
1362
- return changed.ok ? fail("refused", `Daytona did not apply network ${policyWords(policy)}: ${ref.name} still reads back ${policyWords(read)}`) : this.#refusedChange(policy, changed.error);
1363
- }
1364
- // Never wider: a change Daytona applied otherwise is put back, or, failing that, the network is blocked.
1365
- if (typeof current === "string" || "allow" in current) {
1366
- const back = await this.#setNetwork(ref, current);
1367
- const again = back.ok ? await this.#own(ref) : back;
1368
- if (again.ok && samePolicy(networkOf(again.value), current)) {
1369
- return fail("refused", `Daytona did not apply network ${policyWords(policy)} (it read back ${policyWords(read)}), so ${ref.name} is back on ${policyWords(current)}`);
1370
- }
1371
- }
1372
- return this.#makeSafe(ref, "refused", `Daytona did not apply network ${policyWords(policy)} (it read back ${policyWords(read)})`);
1373
- }
1374
- /** The network of a computer's programs, read back as their user sees it (computerd probe): "none" while lo alone. */
1375
- async #toolsNetwork(sb, signal) {
1376
- if (sb.state !== "started")
1377
- return fail("refused", `${sb.name ?? sb.id} is ${sb.state ?? "in no state Daytona reports"}, so its daemon cannot read its network back`);
1378
- const toolbox = await this.#toolbox(sb, signal);
1379
- if (!toolbox.ok)
1380
- return toolbox;
1381
- const opened = await this.#open(sb, toolbox.value, signal);
1382
- if (!opened.ok)
1383
- 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
+ };
1384
404
  try {
1385
- const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(this.#timeouts.helloMs)]) : AbortSignal.timeout(this.#timeouts.helloMs);
1386
- const drift = await readOwnNetwork(opened.value.client, this.#timeouts.helloMs, bounded);
1387
- if (!drift.ok)
1388
- return drift;
1389
- return ok(drift.value.length === 0 ? "none" : { other: drift.value.join("; ") });
1390
- }
1391
- finally {
1392
- await opened.value.close();
405
+ const failed = await Promise.race([open, bound.promise]);
406
+ if (failed !== undefined)
407
+ throw new Error(failed);
1393
408
  }
1394
- }
1395
- /**
1396
- * A computer whose network is wider than asked, or not known, is blocked (none), and the block read back: Daytona may
1397
- * answer a POST it does not apply. One that does not read back none is deleted. Never signalled, as every step after a
1398
- * change is, so an aborted call still leaves the computer safe. Always a failure, in words: why, then what was done.
1399
- */
1400
- async #makeSafe(ref, code, why) {
1401
- const blocked = await this.#setNetwork(ref, "none");
1402
- const again = blocked.ok ? await this.#own(ref) : undefined;
1403
- if (again?.ok && samePolicy(networkOf(again.value), "none"))
1404
- return fail(code, `${why}, so ${ref.name}'s network was blocked (none) and read back none`);
1405
- const how = !blocked.ok
1406
- ? `blocking it (none) failed: ${blocked.error.message}`
1407
- : again !== undefined && !again.ok
1408
- ? `blocking it (none) could not be read back: ${again.error.message}`
1409
- : `blocking it (none) read back ${policyWords(networkOf(again.value))}`;
1410
- const removed = await this.release(ref, "delete");
1411
- 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}`}`);
1412
- }
1413
- #refusedChange(policy, error) {
1414
- if (error.code === "aborted" || error.code === "timeout")
1415
- return fail(error.code, `the change to network ${policyWords(policy)} did not complete: ${error.message}`);
1416
- const code = error.code === "invalid" || error.code === "denied" ? "refused" : error.code;
1417
- return fail(code, `Daytona refused the change to network ${policyWords(policy)}: ${error.message}`);
1418
- }
1419
- async #setNetwork(ref, policy, signal) {
1420
- const body = networkBody(policy);
1421
- if (body === undefined)
1422
- return fail("invalid", `network ${policyWords(policy)} is not one Daytona can hold`);
1423
- return this.#rest.json("POST", this.#rest.sandbox(ref.id, "/network-settings"), { json: body }, signal);
1424
- }
1425
- /**
1426
- * Daytona answers a delete or a stop before the sandbox is gone or stopped, and its listing trails both: release
1427
- * returns once Daytona reads the computer as release left it, or fails naming the last state it read.
1428
- */
1429
- async release(ref, how, { signal } = {}) {
1430
- if (!NAME.test(ref?.name ?? "") || typeof ref?.id !== "string" || ref.id === "")
1431
- return fail("invalid", `${ref?.name} is not a Daytona computer's ref ({ id, name: computer-<12 hex digits> })`);
1432
- if (how !== "stop" && how !== "delete")
1433
- return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1434
- const found = await this.#rest.get(ref.id, signal);
1435
- if (!found.ok)
1436
- return found;
1437
- const sb = found.value;
1438
- if (sb === undefined)
1439
- return ok(undefined);
1440
- // Already going (a second delete, or Daytona's own end): only the wait is left. Daytona renames a sandbox it
1441
- // destroys, so the name is not held to the ref's here.
1442
- if (going(sb))
1443
- return this.#settle(ref, "gone", how, signal);
1444
- if (!ours(sb) || sb.name !== ref.name)
1445
- 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`);
1446
- const letGo = recordedMount(sb.labels) && sb.state === "started" ? await this.#letGo(sb, signal) : ok(undefined);
1447
- 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));
1448
- if (!letGo.ok && released.ok)
1449
- this.#onNote?.({ computer: ref.name, note: `${ref.name} was ${how === "stop" ? "stopped" : "deleted"}, and ${letGo.error.message}` });
1450
- return released;
1451
- }
1452
- /**
1453
- * An Archil computer lets its folder go before it is stopped or deleted: a final sync through its computerd (when it
1454
- * answers), then checkin as root. Neither stops the release: every call that changed the folder synced before it
1455
- * answered, and a hold left behind is revoked by the run's next claim. What did not go cleanly is said through onNote.
1456
- */
1457
- async #letGo(sb, signal) {
1458
- const toolbox = await this.#toolbox(sb, signal);
1459
- if (!toolbox.ok)
1460
- return fail(toolbox.error.code, `the run's folder was not let go: the toolbox could not be reached (${toolbox.error.message})`);
1461
- const opened = await this.#open(sb, toolbox.value, signal);
1462
- try {
1463
- 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;
1464
412
  }
1465
413
  finally {
1466
- if (opened.ok)
1467
- await opened.value.close();
1468
- }
1469
- }
1470
- async #stop(ref, sb, signal) {
1471
- if (!STOPPED.has(sb.state ?? "")) {
1472
- const stopped = await this.#rest.call("POST", this.#rest.sandbox(sb.id, "/stop"), {}, signal);
1473
- if (!stopped.ok && stopped.error.code !== "invalid" && stopped.error.code !== "not_found")
1474
- return stopped;
1475
- }
1476
- // With autoDeleteInterval 0, Daytona deletes a sandbox as it stops: such a stop is done once the computer is gone. A
1477
- // GPU sandbox is one of those whatever the option (its stop deletes it).
1478
- const deletes = this.#autoDeleteFor(isWhole(sb.gpu) && sb.gpu > 0) === 0;
1479
- return this.#settle(ref, deletes ? "gone" : "stopped", "stop", signal);
1480
- }
1481
- /**
1482
- * Waits, through waitUntil, until Daytona reads the sandbox as wanted, twice running, by its own read and by the
1483
- * listing alike: "gone" is a 404 and no listed computer; "stopped" is stopped (or gone) and listed stopped (or not at
1484
- * all, when gone). Pauses double from pollMs to 5 s, bounded by goneMs or stopMs and the caller's signal. A stop not
1485
- * under way (neither stopping nor stopped) is asked for again. A failed read or listing, or a sandbox gone to error,
1486
- * ends the wait with that error.
1487
- */
1488
- async #settle(ref, want, how, signal) {
1489
- let agreed = 0;
1490
- let last = "unread";
1491
- const read = async (readSignal) => {
1492
- const got = await this.#rest.get(ref.id, readSignal);
1493
- if (!got.ok) {
1494
- if (got.error.code === "aborted")
1495
- return { last };
1496
- return { failed: fail(got.error.code, `release ${how} of ${ref.name}: reading it back failed (${got.error.message}); it last read ${last}`) };
1497
- }
1498
- const sb = got.value;
1499
- last = stateWords(sb);
1500
- if (sb !== undefined && (sb.state === "error" || sb.state === "build_failed") && sb.desiredState !== "destroyed") {
1501
- return { failed: vendorFail("daytona", `release ${how} of ${ref.name}: it went to ${sb.state}${sb.errorReason ? `: ${sb.errorReason}` : ""}`) };
1502
- }
1503
- const gone = sb === undefined || sb.state === "destroyed";
1504
- const reached = gone ? "gone" : want === "stopped" && STOPPED.has(sb.state ?? "") ? "stopped" : undefined;
1505
- if (reached === undefined) {
1506
- agreed = 0;
1507
- if (how === "stop" && sb !== undefined && !going(sb) && !LEAVING.has(sb.state ?? "")) {
1508
- const again = await this.#rest.call("POST", this.#rest.sandbox(ref.id, "/stop"), {}, readSignal);
1509
- if (!again.ok && again.error.code !== "invalid" && again.error.code !== "not_found" && again.error.code !== "aborted")
1510
- 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}`);
1511
439
  }
1512
- return { last };
1513
- }
1514
- const listed = await this.#listOwn(readSignal);
1515
- if (!listed.ok) {
1516
- if (listed.error.code === "aborted")
1517
- return { last };
1518
- return { failed: fail(listed.error.code, `release ${how} of ${ref.name}: the listing failed (${listed.error.message}); it last read ${last}`) };
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);
1519
448
  }
1520
- const item = listed.value.find((one) => one.id === ref.id);
1521
- const shown = item === undefined || !ours(item) || going(item) ? undefined : stateOf(item);
1522
- if (reached === "gone" ? shown === undefined : shown === "stopped")
1523
- return ++agreed >= LISTED_ROUNDS ? { settled: true } : { last };
1524
- agreed = 0;
1525
- last = `${last}, listed ${shown ?? "not at all"}`;
1526
- return { last };
1527
449
  };
1528
- const { pollMs, stopMs, goneMs } = this.#timeouts;
1529
- const waited = await waitUntil(read, (state) => !("last" in state), {
1530
- boundMs: how === "stop" ? stopMs : goneMs,
1531
- signal,
1532
- minMs: Math.min(pollMs, RELEASE_POLL_MAX_MS),
1533
- maxMs: RELEASE_POLL_MAX_MS,
1534
- what: `${ref.name} to be ${want} after its release ${how}`,
1535
- describe: (state) => ("last" in state ? `Daytona read it ${state.last}` : "done"),
1536
- });
1537
- if (!waited.ok)
1538
- return waited;
1539
- return "failed" in waited.value ? waited.value.failed : ok(undefined);
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
+ };
1540
471
  }
1541
- /**
1542
- * Deletes a sandbox and makes sure it is going: a DELETE that fails counts as done only when the
1543
- * sandbox is gone or being destroyed; a forced stop comes before the last attempt. Never signalled: a delete that
1544
- * cleans up after an abort must outlive it.
1545
- */
1546
- async #delete(idOrName) {
1547
- let failure;
1548
- for (let attempt = 1; attempt <= DELETE_ATTEMPTS; attempt++) {
1549
- const removed = await this.#rest.call("DELETE", this.#rest.sandbox(idOrName), { retry: true, timeoutMs: this.#timeouts.deleteMs });
1550
- if (removed.ok || removed.error.code === "not_found")
1551
- return ok(undefined);
1552
- failure = removed.error;
1553
- const found = await this.#rest.get(idOrName);
1554
- if (found.ok && (found.value === undefined || GONE.has(found.value.state ?? "")))
1555
- return ok(undefined);
1556
- if (attempt === DELETE_ATTEMPTS - 1)
1557
- await this.#rest.call("POST", this.#rest.sandbox(idOrName, "/stop?force=true"), { timeoutMs: this.#timeouts.deleteMs });
1558
- if (attempt < DELETE_ATTEMPTS)
1559
- await sleep(this.#timeouts.retryMs);
1560
- }
1561
- return { ok: false, error: failure ?? { code: "vendor", vendor: "daytona", message: `could not delete ${idOrName}` } };
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 });
1562
517
  }
1563
518
  }