@parcha/agentrun-computer 0.1.0-beta.33 → 0.1.0-beta.35

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 (112) hide show
  1. package/README.md +308 -36
  2. package/dist/browser.d.ts +13 -14
  3. package/dist/browser.js +22 -17
  4. package/dist/browserbase.d.ts +3 -3
  5. package/dist/browserbase.js +16 -11
  6. package/dist/child.d.ts +2 -0
  7. package/dist/child.js +13 -2
  8. package/dist/chrome.d.ts +73 -0
  9. package/dist/chrome.js +224 -0
  10. package/dist/computerd-linux-amd64 +0 -0
  11. package/dist/computerd-linux-arm64 +0 -0
  12. package/dist/conformance/browserbase.js +1 -1
  13. package/dist/conformance/cases/gpu.d.ts +2 -0
  14. package/dist/conformance/cases/gpu.js +108 -0
  15. package/dist/conformance/cases/health.js +83 -3
  16. package/dist/conformance/cases/index.js +2 -0
  17. package/dist/conformance/cases/mount.d.ts +8 -1
  18. package/dist/conformance/cases/mount.js +4 -3
  19. package/dist/conformance/cases/provider.js +92 -3
  20. package/dist/conformance/cli.js +46 -7
  21. package/dist/conformance/daytona.js +2 -1
  22. package/dist/conformance/e2b.js +2 -1
  23. package/dist/conformance/fixture.js +24 -2
  24. package/dist/conformance/kernel.js +1 -1
  25. package/dist/conformance/kind.js +2 -1
  26. package/dist/conformance/local-chrome.d.ts +30 -0
  27. package/dist/conformance/local-chrome.js +36 -0
  28. package/dist/conformance/orgo.d.ts +11 -5
  29. package/dist/conformance/orgo.js +37 -8
  30. package/dist/conformance/phone-harness.js +2 -1
  31. package/dist/conformance/report.js +13 -7
  32. package/dist/conformance/runner.js +68 -18
  33. package/dist/conformance/types.d.ts +78 -18
  34. package/dist/conformance/types.js +10 -0
  35. package/dist/conformance/windows-fixture.d.ts +1 -0
  36. package/dist/conformance/windows-fixture.js +37 -0
  37. package/dist/daytona.d.ts +4 -6
  38. package/dist/daytona.js +97 -52
  39. package/dist/descriptor.d.ts +94 -0
  40. package/dist/descriptor.js +81 -0
  41. package/dist/descriptors/browserbase.d.ts +24 -0
  42. package/dist/descriptors/browserbase.js +18 -0
  43. package/dist/descriptors/daytona.d.ts +62 -0
  44. package/dist/descriptors/daytona.js +49 -0
  45. package/dist/descriptors/docker.d.ts +12 -0
  46. package/dist/descriptors/docker.js +17 -0
  47. package/dist/descriptors/e2b.d.ts +22 -0
  48. package/dist/descriptors/e2b.js +19 -0
  49. package/dist/descriptors/index.d.ts +229 -0
  50. package/dist/descriptors/index.js +19 -0
  51. package/dist/descriptors/kernel.d.ts +20 -0
  52. package/dist/descriptors/kernel.js +15 -0
  53. package/dist/descriptors/local-chrome.d.ts +17 -0
  54. package/dist/descriptors/local-chrome.js +21 -0
  55. package/dist/descriptors/modal.d.ts +50 -0
  56. package/dist/descriptors/modal.js +38 -0
  57. package/dist/descriptors/orgo.d.ts +88 -0
  58. package/dist/descriptors/orgo.js +44 -0
  59. package/dist/descriptors/phone-harness.d.ts +28 -0
  60. package/dist/descriptors/phone-harness.js +20 -0
  61. package/dist/descriptors/shared.d.ts +7 -0
  62. package/dist/descriptors/shared.js +6 -0
  63. package/dist/desktop.d.ts +4 -4
  64. package/dist/desktop.js +4 -4
  65. package/dist/docker/egress.d.ts +1 -1
  66. package/dist/docker/image.js +17 -15
  67. package/dist/docker/inspect.d.ts +147 -0
  68. package/dist/docker/inspect.js +335 -0
  69. package/dist/docker.d.ts +6 -4
  70. package/dist/docker.js +53 -41
  71. package/dist/drift.d.ts +6 -146
  72. package/dist/drift.js +14 -334
  73. package/dist/e2b.d.ts +2 -6
  74. package/dist/e2b.js +19 -22
  75. package/dist/index.d.ts +9 -10
  76. package/dist/index.js +14 -10
  77. package/dist/isolation.d.ts +0 -2
  78. package/dist/isolation.js +2 -18
  79. package/dist/janitor.d.ts +18 -1
  80. package/dist/janitor.js +67 -19
  81. package/dist/kernel.d.ts +3 -3
  82. package/dist/kernel.js +19 -14
  83. package/dist/kinds.d.ts +56 -30
  84. package/dist/kinds.js +19 -97
  85. package/dist/labels.d.ts +18 -0
  86. package/dist/labels.js +65 -2
  87. package/dist/local-chrome.d.ts +86 -0
  88. package/dist/local-chrome.js +475 -0
  89. package/dist/local-supervisor.d.ts +51 -0
  90. package/dist/local-supervisor.js +221 -0
  91. package/dist/modal.d.ts +15 -7
  92. package/dist/modal.js +83 -39
  93. package/dist/mount-archil.js +4 -4
  94. package/dist/orgo-channel.js +16 -13
  95. package/dist/orgo-desktop.d.ts +153 -0
  96. package/dist/orgo-desktop.js +1614 -0
  97. package/dist/orgo-names.d.ts +52 -0
  98. package/dist/orgo-names.js +84 -0
  99. package/dist/orgo.d.ts +18 -13
  100. package/dist/orgo.js +54 -128
  101. package/dist/phone-harness.d.ts +4 -8
  102. package/dist/phone-harness.js +48 -46
  103. package/dist/protocol.d.ts +20 -0
  104. package/dist/protocol.js +9 -0
  105. package/dist/provider.d.ts +151 -10
  106. package/dist/provider.js +70 -0
  107. package/dist/providers.d.ts +22 -17
  108. package/dist/providers.js +14 -16
  109. package/dist/result.d.ts +11 -1
  110. package/dist/result.js +11 -0
  111. package/dist/test-connection.js +2 -2
  112. package/package.json +42 -2
@@ -0,0 +1,221 @@
1
+ // One local browser's supervisor: a detached Node process of its own per browser (local-chrome.ts starts it), so the browser
2
+ // outlives neither its deadline nor its release, whatever becomes of the process that made it. It reads the browser's
3
+ // directory (browser.json), starts the browser's egress proxy (docker/egress-proxy.ts: with no list, every public host
4
+ // and nothing else; with the record's list, only its hosts, public ones still) on a Unix socket in that directory, with
5
+ // a relay on an ephemeral loopback port in front of it
6
+ // (Chrome takes a proxy over TCP alone; the relay passes each connection to the socket unread, the proxy decides), then
7
+ // starts Chrome behind that fence (chrome.ts chromeFence) with a fresh profile in the directory and a debugging port
8
+ // Chrome picks on 127.0.0.1. Once Chrome's DevTools socket answers it writes state.json and one line on stdout, which
9
+ // local-chrome.ts waits for; a Chrome that never does is reported on that line in words and nothing is left.
10
+ //
11
+ // It then ends the browser (Chrome's whole process group, the proxy, the relay, Chrome's singleton socket directory and
12
+ // the browser's directory) at the first of: the deadline in browser.json, SIGTERM (a release), or Chrome's own exit. So a
13
+ // run that crashes leaves no Chrome past its deadline, and none that can reach the network once its supervisor is gone:
14
+ // the relay goes with it. The relay and the proxy are the browser's only way out (chromeFence), and they live here, so a
15
+ // browser made by one process is driven from another with its fence intact.
16
+ import { spawn } from "node:child_process";
17
+ import { closeSync, createWriteStream, openSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { rm } from "node:fs/promises";
19
+ import { connect, createServer } from "node:net";
20
+ import { join, resolve } from "node:path";
21
+ import { alive, chromeFence, killTree, NO_SANDBOX, ownDebugger, answeringPath, singletonDir } from "./chrome.js";
22
+ import { startEgressProxy } from "./docker/egress-proxy.js";
23
+ import { isCommand } from "./entry.js";
24
+ /** The browser's record, written by local-chrome.ts before the supervisor starts: the label a list finds it by. */
25
+ export const BROWSER_FILE = "browser.json";
26
+ /** What the supervisor writes once Chrome answers: the pids and ports a connect and a release read. */
27
+ export const STATE_FILE = "state.json";
28
+ /** The supervisor's own pid, written as it starts. */
29
+ export const SUPERVISOR_FILE = "supervisor.pid";
30
+ /** Chrome's pid, written as soon as it is spawned: a release finds a Chrome whose supervisor died before it answered. */
31
+ export const CHROME_PID_FILE = "chrome.pid";
32
+ /** Chrome's profile, fresh per browser. */
33
+ export const PROFILE_DIR = "profile";
34
+ /** The egress proxy's socket: short, since a Unix socket's path holds 107 bytes at most. */
35
+ export const EGRESS_SOCKET_FILE = "e.sock";
36
+ export const CHROME_LOG = "chrome.log";
37
+ export const EGRESS_LOG = "egress.log";
38
+ /** How much of the proxy's decisions are kept: a long session's log stops there. */
39
+ const EGRESS_LOG_BYTES = 1024 * 1024;
40
+ /** Connections open at once, and in all: Chrome holds up to 32 sockets to one proxy, and a page opens one to each host it loads from (#1718's numbers). */
41
+ export const BROWSER_MAX_TUNNELS = 128;
42
+ export const BROWSER_MAX_CONNECTIONS = 100_000;
43
+ /** Where the relay to the proxy listens: this machine's loopback, which the proxy itself refuses. */
44
+ const RELAY_HOST = "127.0.0.1"; // key-gate: loopback-rule the local Chrome's relay to its egress proxy listens here
45
+ /** How long Chrome has to answer on its debugging port. */
46
+ export const READY_MS = 20_000;
47
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
48
+ /** The last lines Chrome wrote to its log, control characters dropped, each line at most 300 characters. */
49
+ function chromeTail(dir) {
50
+ let whole = "";
51
+ try {
52
+ whole = readFileSync(join(dir, CHROME_LOG), "utf8");
53
+ }
54
+ catch {
55
+ return "";
56
+ }
57
+ // A tail that starts inside a line drops that partial line.
58
+ return whole
59
+ .slice(-4096)
60
+ .split("\n")
61
+ .slice(whole.length > 4096 ? 1 : 0)
62
+ .map((line) => line.replace(/[\0-\x08\x0b-\x1f\x7f]/g, "").slice(0, 300))
63
+ .filter((line) => line.trim() !== "")
64
+ .slice(-10)
65
+ .join("\n");
66
+ }
67
+ /** Supervises the browser in `dir` until it ends; the process exits then. */
68
+ export async function supervise(dir, out) {
69
+ // First, so a release while Chrome still starts finds this process to end.
70
+ writeFileSync(join(dir, SUPERVISOR_FILE), String(process.pid), { mode: 0o600 });
71
+ const record = JSON.parse(readFileSync(join(dir, BROWSER_FILE), "utf8"));
72
+ const profile = join(dir, PROFILE_DIR);
73
+ let child;
74
+ let ending;
75
+ const open = new Set();
76
+ const log = createWriteStream(join(dir, EGRESS_LOG), { flags: "a", mode: 0o600 });
77
+ let logged = 0;
78
+ const proxy = await startEgressProxy({
79
+ socketPath: join(dir, EGRESS_SOCKET_FILE),
80
+ maxTunnels: BROWSER_MAX_TUNNELS,
81
+ maxConnections: BROWSER_MAX_CONNECTIONS,
82
+ ...(record.allow ? { allow: record.allow } : {}),
83
+ log: (line) => {
84
+ if (logged > EGRESS_LOG_BYTES)
85
+ return;
86
+ logged += line.length + 1;
87
+ log.write(`${line}\n`);
88
+ },
89
+ });
90
+ const relay = createServer((client) => {
91
+ const upstream = connect(join(dir, EGRESS_SOCKET_FILE));
92
+ for (const socket of [client, upstream]) {
93
+ open.add(socket);
94
+ socket.once("close", () => open.delete(socket));
95
+ socket.on("error", () => {
96
+ client.destroy();
97
+ upstream.destroy();
98
+ });
99
+ }
100
+ client.pipe(upstream).pipe(client);
101
+ });
102
+ /** Ends the browser: Chrome's group, then the relay and the proxy, then every file of the browser's. */
103
+ const end = (code) => (ending ??= (async () => {
104
+ if (child?.pid !== undefined && child.exitCode === null && child.signalCode === null) {
105
+ killTree(child.pid);
106
+ const gone = child;
107
+ await Promise.race([new Promise((done) => gone.once("exit", done)), sleep(5_000)]);
108
+ }
109
+ await new Promise((done) => {
110
+ relay.close(() => done());
111
+ for (const socket of open)
112
+ socket.destroy();
113
+ });
114
+ await proxy.close().catch(() => undefined);
115
+ log.end();
116
+ const socketDir = await singletonDir(profile);
117
+ if (socketDir)
118
+ await rm(socketDir, { recursive: true, force: true }).catch(() => undefined);
119
+ // A browser's last writes can land in its profile after the kill: the removal is tried again.
120
+ for (let attempt = 0; attempt < 5; attempt++) {
121
+ try {
122
+ await rm(dir, { recursive: true, force: true });
123
+ break;
124
+ }
125
+ catch {
126
+ await sleep(100 * (attempt + 1));
127
+ }
128
+ }
129
+ process.exit(code);
130
+ })());
131
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
132
+ process.on(signal, () => void end(0));
133
+ try {
134
+ await new Promise((done, failed) => relay.once("error", failed).listen(0, RELAY_HOST, () => done()));
135
+ }
136
+ catch (error) {
137
+ out({ failed: `the local browser's relay to its egress proxy could not listen on loopback (${error.message})` });
138
+ return end(1);
139
+ }
140
+ const relayPort = relay.address().port;
141
+ const stderr = openSync(join(dir, CHROME_LOG), "a", 0o600);
142
+ try {
143
+ const args = [...record.args, ...chromeFence(`http://${RELAY_HOST}:${relayPort}`), `--user-data-dir=${profile}`, "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", "about:blank"]; // key-gate: loopback-rule the local Chrome's DevTools socket listens on loopback alone
144
+ child = spawn(record.executablePath, args, {
145
+ stdio: ["ignore", "ignore", stderr],
146
+ detached: true,
147
+ });
148
+ // Before anything waits: a supervisor killed while Chrome starts leaves its pid for the release.
149
+ if (child.pid !== undefined)
150
+ writeFileSync(join(dir, CHROME_PID_FILE), String(child.pid), { mode: 0o600 });
151
+ }
152
+ catch (error) {
153
+ out({ failed: `Chrome could not be started (${error.message})` });
154
+ return end(1);
155
+ }
156
+ finally {
157
+ closeSync(stderr);
158
+ }
159
+ let exited;
160
+ let ready = false;
161
+ child.once("error", (error) => void (exited ??= `Chrome could not be started (${error.message})`));
162
+ child.once("exit", (code, signal) => {
163
+ exited ??= `Chrome exited before it opened its debugging port (${signal ?? code})`;
164
+ // Once ready, Chrome's own exit ends the browser: there is nothing left to drive.
165
+ if (ready)
166
+ void end(0);
167
+ });
168
+ const deadline = Date.parse(record.deadline);
169
+ for (const until = Date.now() + READY_MS;; await sleep(100)) {
170
+ if (exited !== undefined) {
171
+ const tail = chromeTail(dir);
172
+ const sandbox = /No usable sandbox|sandbox/i.test(tail) || child.signalCode === "SIGABRT";
173
+ out({ failed: `${sandbox ? NO_SANDBOX : exited}${tail ? `; Chrome said:\n${tail}` : ""}`, ...(sandbox ? { sandbox: true } : {}) });
174
+ return end(1);
175
+ }
176
+ const own = await ownDebugger(profile);
177
+ if (own && (await answeringPath(own.port)) === own.path) {
178
+ const state = { supervisor: process.pid, pid: child.pid, port: own.port, path: own.path, relay: relayPort };
179
+ try {
180
+ writeFileSync(join(dir, STATE_FILE), JSON.stringify(state), { mode: 0o600 });
181
+ }
182
+ catch (error) {
183
+ out({ failed: `the local browser's state could not be written (${error.message})` });
184
+ return end(1);
185
+ }
186
+ ready = true;
187
+ break;
188
+ }
189
+ if (Date.now() > until) {
190
+ out({ failed: `Chrome did not open its debugging port within ${READY_MS / 1000} s` });
191
+ return end(1);
192
+ }
193
+ }
194
+ // The deadline: from browser.json, so a browser whose maker is gone still ends then. setTimeout holds 24.8 days at most, past every lifetime here.
195
+ setTimeout(() => void end(0), Math.max(0, deadline - Date.now()));
196
+ // A Chrome that went between the ready check and here: its exit handler saw ready false.
197
+ if (!alive(child.pid) || child.exitCode !== null || child.signalCode !== null)
198
+ return end(0);
199
+ out({ ready: true });
200
+ return new Promise(() => undefined);
201
+ }
202
+ // Run as a script (`node local-supervisor.js <dir>`), not when imported.
203
+ if (isCommand(import.meta)) {
204
+ const dir = process.argv[2];
205
+ const out = (line) => {
206
+ try {
207
+ process.stdout.write(`${JSON.stringify(line)}\n`);
208
+ }
209
+ catch {
210
+ /* the maker stopped listening */
211
+ }
212
+ };
213
+ if (dir === undefined)
214
+ process.exit(2);
215
+ // The maker reads one line and lets go of the pipe: a later write to it fails, and nothing here depends on it.
216
+ process.stdout.on("error", () => undefined);
217
+ supervise(resolve(dir), out).catch((error) => {
218
+ out({ failed: `the local browser's supervisor failed (${error instanceof Error ? error.message : String(error)})` });
219
+ void rm(resolve(dir), { recursive: true, force: true }).finally(() => process.exit(1));
220
+ });
221
+ }
package/dist/modal.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { KindCapabilities } from "./kinds.js";
2
2
  import { type MountKind } from "./mount.js";
3
3
  import { type ProviderNote } from "./mount-archil.js";
4
- import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal } from "./provider.js";
4
+ import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
5
5
  import { type Result } from "./result.js";
6
6
  import { type ScreenWatch, type ScreenWatchHandlers, type WatchOptions } from "./screen-watch.js";
7
7
  /** The App sandboxes are made in (modal-client@64880502:js/src/app.ts:32-61). */
@@ -14,7 +14,10 @@ export interface ModalImage {
14
14
  }
15
15
  /** What sandboxes.create is given: every field is one of the SDK's SandboxCreateParams (js/src/sandbox.ts:356-474). */
16
16
  export interface ModalCreateParams {
17
- runtime: "vm";
17
+ /** vm, or gvisor for a GPU computer: Modal offers GPUs on gVisor only. */
18
+ runtime: ModalRuntime;
19
+ /** The GPUs, as the SDK takes them ("T4", "A100-80GB:4"): a GPU computer only. */
20
+ gpu?: string;
18
21
  command: string[];
19
22
  timeoutMs: number;
20
23
  workdir: string;
@@ -98,6 +101,11 @@ export interface ModalTimeouts {
98
101
  releaseMs: number;
99
102
  /** The first pause between two of those polls; the pauses double up to 5 s. */
100
103
  releasePollMs: number;
104
+ /**
105
+ * How long a create whose sandbox Modal says is shutting down on its own (its command, init, exited) waits for poll to
106
+ * read it finished, to give the command's exit code and words in its failure.
107
+ */
108
+ endedMs: number;
101
109
  /** Each root step of an Archil mount through exec (the preflight, mount or revoke, serve), and its checkin at release. */
102
110
  mountMs: number;
103
111
  }
@@ -134,10 +142,10 @@ export interface ModalProviderOptions {
134
142
  }
135
143
  /** The mount kinds a Modal computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
136
144
  export declare const MOUNT: readonly MountKind[];
137
- /** The machine kind and groups of its one configuration: a linux computer. */
145
+ /** The runtime a Modal sandbox runs under: vm, or gvisor for a GPU computer (Modal offers GPUs on gVisor only). */
146
+ export type ModalRuntime = "vm" | "gvisor";
147
+ /** The machine kind, groups and GPUs of its one configuration (its descriptor's): a linux computer, with GPUs when asked. */
138
148
  export declare const CAPABILITIES: readonly KindCapabilities[];
139
- /** A registry tag for linux/amd64 that Modal can pull: the default when a setting names no image. */
140
- export declare const MODAL_DEFAULT_IMAGE = "debian:bookworm-slim";
141
149
  /** The SDK's default server (modal-client@64880502:js/src/config.ts:143). */
142
150
  export declare const MODAL_DEFAULT_SERVER_URL = "https://api.modal.com:443";
143
151
  /** What modalClient gives the SDK's ModalClient: the token, explicitly, so the SDK fills none of it in. */
@@ -234,7 +242,7 @@ export interface UntilFinishedOptions {
234
242
  */
235
243
  export declare function untilFinished(poll: () => Promise<number | null>, { name, boundMs, callMs, minMs, maxMs, signal }: UntilFinishedOptions): Promise<Result<void>>;
236
244
  /**
237
- * Computers that are Modal sandboxes on the VM runtime. The daemon is uploaded right after create, streamed through an
245
+ * Computers that are Modal sandboxes on the VM runtime, or on gVisor with a GPU. The daemon is uploaded right after create, streamed through an
238
246
  * exec's stdin, while the sandbox's command, a small sh entrypoint, waits for it and then becomes `computerd init`; or,
239
247
  * with daemonImage, it comes in as a layer of the computer's image (COPY --from) and is the command itself. A
240
248
  * connection is `computerd stdio` through exec, so a computer with network none is still reached, and needs no network
@@ -298,5 +306,5 @@ export declare class ModalProvider implements ComputerProvider {
298
306
  * loses nothing (every call that changed it synced, and the next claim revokes the hold), so it is said through
299
307
  * onNote, and the release succeeds once the sandbox is gone.
300
308
  */
301
- release(ref: ComputerRef, how: "stop" | "delete", { signal }?: CallContext): Promise<Result<void>>;
309
+ release(ref: ComputerRef, how: ReleaseHow, { signal }?: CallContext): Promise<Result<void>>;
302
310
  }
package/dist/modal.js CHANGED
@@ -1,4 +1,4 @@
1
- // The Modal provisioner, VM runtime only: every call through the host's own Modal JS SDK client, of which this package
1
+ // The Modal provisioner, on the VM runtime, and on gVisor for a GPU computer (Modal's one GPU runtime): every call through the host's own Modal JS SDK client, of which this package
2
2
  // names only the slice it uses (ModalSdk) and imports nothing. Every SDK fact below is cited in the README's Modal
3
3
  // section, from modal-client@64880502 (js/src) and Modal's docs.
4
4
  import { createHash, randomBytes } from "node:crypto";
@@ -6,23 +6,28 @@ import { readFileSync } from "node:fs";
6
6
  import { Readable, Writable } from "node:stream";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { DaemonClient } from "./client.js";
9
+ import { MODAL, MODAL_DEFAULT_IMAGE, MODAL_GPU } from "./descriptors/modal.js";
9
10
  import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, WORK, } from "./drift.js";
10
11
  import { OWN_NETWORK_ONLY, probeOwnNetworkDrift, TOOL_USER } from "./isolation.js";
11
12
  import { releaseOlder } from "./janitor.js";
12
13
  import { EPOCH_LABEL, epochOf, RUN_LABEL } from "./labels.js";
13
14
  import { checkMount, readBackOf } from "./mount.js";
14
15
  import { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilMount, archilRefusals, archilRelease, claimEpoch, mountDrift, readArchilMount, recordedArchil as recordedArchilOf, syncingClient, } from "./mount-archil.js";
15
- import { checkLifetime, } from "./provider.js";
16
- import { fail, ok } from "./result.js";
16
+ import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
17
+ import { failFor, ok, vendorFail } from "./result.js";
17
18
  import { daemonWatch } from "./screen-watch.js";
18
19
  import { connectionError } from "./test-connection.js";
19
20
  import { waitUntil } from "./wait.js";
21
+ /** This module's failures: one with code vendor names Modal. */
22
+ const fail = failFor("modal");
20
23
  /** The mount kinds a Modal computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
21
- export const MOUNT = ["archil"];
22
- /** The machine kind and groups of its one configuration: a linux computer. */
23
- export const CAPABILITIES = [{ kind: "linux", groups: ["exec", "files", "processes"] }];
24
- /** A registry tag for linux/amd64 that Modal can pull: the default when a setting names no image. */
25
- export const MODAL_DEFAULT_IMAGE = "debian:bookworm-slim";
24
+ export const MOUNT = MODAL.mounts;
25
+ /** A copy of its descriptor's MODAL_GPU, so no caller can change the provider's own. */
26
+ const modalGpuCapability = () => ({ ...MODAL_GPU, types: [...MODAL_GPU.types], mounts: [] });
27
+ /** A GPU as the SDK takes it: the type, then :count past one ("T4", "H100:8"). */
28
+ const modalGpu = ({ type, count }) => (count === 1 ? type : `${type}:${count}`);
29
+ /** The machine kind, groups and GPUs of its one configuration (its descriptor's): a linux computer, with GPUs when asked. */
30
+ export const CAPABILITIES = MODAL.capabilities;
26
31
  /** The SDK's default server (modal-client@64880502:js/src/config.ts:143). */
27
32
  export const MODAL_DEFAULT_SERVER_URL = "https://api.modal.com:443";
28
33
  /** Not a literal, so no type checker or bundler resolves the SDK from this package. */
@@ -137,6 +142,7 @@ const DEFAULT_TIMEOUTS = {
137
142
  uploadMs: 300_000,
138
143
  releaseMs: 120_000,
139
144
  releasePollMs: 500,
145
+ endedMs: 30_000,
140
146
  mountMs: 120_000,
141
147
  };
142
148
  /** The user an Archil computer's tools run as: the image's agentrun-tool, with no sudo and no capability. */
@@ -221,7 +227,8 @@ const HOLD_SCRIPT = [
221
227
  /**
222
228
  * Init's arguments, after the daemon's path: the one place they are built, for the image route's command and the
223
229
  * entrypoint alike. Init and every tool run in a network namespace of their own, loopback alone (--own-network), an
224
- * Archil computer's too: its archil client and serve run through exec as root, outside it.
230
+ * Archil computer's too: its archil client and serve run through exec as root, outside it. Init makes it itself, or, on
231
+ * gVisor (a GPU computer's runtime), where root may not, inside a user namespace; hello says which (fence).
225
232
  */
226
233
  function initArgs({ deadline, user }) {
227
234
  return ["init", "--deadline", deadline, "--user", user, "--own-network"];
@@ -246,7 +253,7 @@ export function modalCommands({ deadline = "", user = TOOL_USER, waitSeconds = 3
246
253
  const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1111]:443", "1.1.1.1:53/udp", "[2606:4700:4700::1111]:53/udp"];
247
254
  /** How long close waits for the stdio bridge to exit once its stdin has ended. Modal has no kill for an exec. */
248
255
  const CLOSE_WAIT_MS = 5_000;
249
- const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "pids", "labels", "workdir", "user", "mount"]);
256
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "pids", "labels", "workdir", "user", "mount", "gpu"]);
250
257
  const NUL = "a NUL byte cannot be passed to Modal";
251
258
  const FIXED = "a Modal computer's network is fixed at create: Modal cannot update the policy of a sandbox made with blockNetwork, and updates only an allowlist set at create; create a new computer";
252
259
  const STOP = "Modal has no stop that keeps a sandbox: terminate is a sandbox's only end, and a sandbox that has finished cannot run again; release it with delete";
@@ -290,7 +297,11 @@ function codeOf(error) {
290
297
  // gRPC's UNAUTHENTICATED and PERMISSION_DENIED: a token Modal refused.
291
298
  if (code === 16 || code === 7)
292
299
  return "denied";
293
- return "modal";
300
+ // gRPC's FAILED_PRECONDITION on an exec: the sandbox is ending on its own ("Modal Sandbox is shutting down", from
301
+ // TaskExecStart, when its command, init, has exited). Gone, so create waits to read why.
302
+ if (code === 9)
303
+ return "gone";
304
+ return "vendor";
294
305
  }
295
306
  /** Settles with the promise's result, or a timeout or abort in words once ms pass or signal aborts. */
296
307
  function race(promise, what, ms, signal) {
@@ -454,8 +465,12 @@ function probeDrift(probe, expected) {
454
465
  const user = `${probe.uid}:${probe.gid}`;
455
466
  if (expected.user !== undefined && user !== expected.user)
456
467
  found.push(`user: declared ${expected.user}, read back ${user} (the uid:gid the daemon's programs run as)`);
457
- if (/gvisor/i.test(probe.kernel))
468
+ // The probe's kernel is the only runtime read-back: gVisor exactly for a GPU computer, a VM's kernel for every other.
469
+ const gvisor = /gvisor/i.test(probe.kernel);
470
+ if (expected.runtime === "vm" && gvisor)
458
471
  found.push(`runtime: declared vm, read back gVisor (the kernel reports ${JSON.stringify(probe.kernel)})`);
472
+ if (expected.runtime === "gvisor" && !gvisor)
473
+ found.push(`runtime: declared gVisor (a GPU computer), read back another kernel (${JSON.stringify(probe.kernel)})`);
459
474
  if (expected.network === "none")
460
475
  found.push(...probeNetworkDrift(probe));
461
476
  // Its own network: the live interfaces lo alone (a kernel's quiet tunnels are none), and none it could bring up.
@@ -474,7 +489,7 @@ function tagDrift(given, read) {
474
489
  return found;
475
490
  }
476
491
  /**
477
- * Computers that are Modal sandboxes on the VM runtime. The daemon is uploaded right after create, streamed through an
492
+ * Computers that are Modal sandboxes on the VM runtime, or on gVisor with a GPU. The daemon is uploaded right after create, streamed through an
478
493
  * exec's stdin, while the sandbox's command, a small sh entrypoint, waits for it and then becomes `computerd init`; or,
479
494
  * with daemonImage, it comes in as a layer of the computer's image (COPY --from) and is the command itself. A
480
495
  * connection is `computerd stdio` through exec, so a computer with network none is still reached, and needs no network
@@ -558,7 +573,7 @@ export class ModalProvider {
558
573
  return {
559
574
  kind: "linux",
560
575
  lifetime: "vendor",
561
- network: ["none"],
576
+ network: [...MODAL.network],
562
577
  networkReadBack: false,
563
578
  isolation: "vm",
564
579
  os: "linux",
@@ -570,12 +585,15 @@ export class ModalProvider {
570
585
  release: ["delete"],
571
586
  mount: [...MOUNT],
572
587
  vendorAgentPorts: [],
588
+ // A GPU computer runs on gVisor, Modal's one GPU runtime (gpu.isolation): isolation vm is every other computer's.
589
+ gpu: modalGpuCapability(),
573
590
  };
574
591
  }
575
- /** What hello must report: this package's version, the kind and groups declared, and Modal's one architecture. */
592
+ /** What hello must report: this package's version, the kind and groups declared, Modal's one architecture, and the
593
+ * fence init --own-network holds its programs behind (either way: hello says which, and create notes it). */
576
594
  #expected() {
577
595
  const { kind, groups } = this.capabilities();
578
- return { version: VERSION, kind, groups, arch: "amd64" };
596
+ return { version: VERSION, kind, groups, arch: "amd64", fence: true };
579
597
  }
580
598
  check(spec) {
581
599
  const refusals = [];
@@ -587,7 +605,7 @@ export class ModalProvider {
587
605
  }
588
606
  else if (image.includes("\0"))
589
607
  refuse("image", NUL);
590
- refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
608
+ refusals.push(...checkTenure(given, this.capabilities(), "Modal"));
591
609
  if (network === "open" || (typeof network === "object" && network !== null && "allow" in network))
592
610
  refuse("network", OWN_NETWORK_ONLY);
593
611
  else if (network !== "none")
@@ -620,13 +638,13 @@ export class ModalProvider {
620
638
  if (archil && user !== undefined && !isRootUser(user) && userOf(user) !== ARCHIL_USER) {
621
639
  refuse("user", `a computer with an Archil mount runs its tools as agentrun-tool, ${ARCHIL_USER}, the user its image makes with no way to root; leave user unset or ask for ${ARCHIL_USER}`);
622
640
  }
641
+ // A GPU computer runs on gVisor, Modal's one GPU runtime, where the Archil client's FUSE mount is not yet proven:
642
+ // its gpu.mounts is empty, so checkGpu refuses a GPU with a mount.
643
+ refusals.push(...checkGpu(given.gpu, this.capabilities(), mount));
623
644
  for (const [field, value] of Object.entries(given)) {
624
645
  if (SPEC_FIELDS.has(field) || value === undefined)
625
646
  continue;
626
- if (field === "gpu")
627
- refuse(field, "this provider makes VM computers, and Modal offers GPUs on the gVisor runtime only");
628
- else
629
- refuse(field, `a Modal computer does not support ${field}`);
647
+ refuse(field, `a Modal computer does not support ${field}`);
630
648
  }
631
649
  return refusals;
632
650
  }
@@ -651,7 +669,7 @@ export class ModalProvider {
651
669
  if (!app.ok)
652
670
  return app;
653
671
  const name = `computer-${randomBytes(6).toString("hex")}`;
654
- const deadline = new Date(Date.now() + spec.lifetimeMs).toISOString();
672
+ const deadline = new Date(Date.now() + runLifetimeMs(spec)).toISOString();
655
673
  // An Archil mount is made under the run's claim (check() held the spec to both labels), for the tool user alone.
656
674
  const archil = spec.mount?.kind === "archil" ? { mount: spec.mount, run: spec.labels?.[RUN_LABEL], epoch: claimEpoch(spec.labels) } : undefined;
657
675
  const user = archil === undefined ? (userOf(spec.user) ?? this.#user) : ARCHIL_USER;
@@ -665,8 +683,10 @@ export class ModalProvider {
665
683
  cpus,
666
684
  memoryMb,
667
685
  workdir,
668
- runtime: "vm",
686
+ // Modal offers GPUs on gVisor only: a GPU computer's runtime, read back by the probe's kernel like a VM's.
687
+ runtime: spec.gpu === undefined ? "vm" : "gvisor",
669
688
  ...(archil === undefined ? {} : { mount: readBackOf(archil.mount, archil.epoch) }),
689
+ ...(spec.gpu === undefined ? {} : { gpu: { type: spec.gpu.type, count: spec.gpu.count } }),
670
690
  };
671
691
  const tags = { ...spec.labels, [COMPUTER_LABEL]: "1", [NAME_TAG]: name, [DEADLINE_LABEL]: deadline, [SPEC_TAG]: JSON.stringify(recorded) };
672
692
  // With daemonImage the daemon comes in as a layer of the computer's own image, there before the command starts.
@@ -700,10 +720,11 @@ export class ModalProvider {
700
720
  : modalCommands({ deadline, user, waitSeconds: Math.ceil(waitMs / 1000), home: WORK, ...(gate === undefined ? {} : { gate }) }).entrypoint;
701
721
  const cpuLimit = cpus / CPUS_PER_CORE;
702
722
  const params = {
703
- runtime: "vm",
723
+ runtime: recorded.runtime,
724
+ ...(spec.gpu === undefined ? {} : { gpu: modalGpu(spec.gpu) }),
704
725
  command,
705
726
  // Modal ends the sandbox at its timeout: the lifetime, in the whole seconds the SDK takes.
706
- timeoutMs: Math.ceil(spec.lifetimeMs / 1000) * 1000,
727
+ timeoutMs: Math.ceil(runLifetimeMs(spec) / 1000) * 1000,
707
728
  workdir,
708
729
  cpu: Math.min(CPU_REQUEST, cpuLimit),
709
730
  cpuLimit,
@@ -751,17 +772,22 @@ export class ModalProvider {
751
772
  if (checked.ok)
752
773
  return ok(checked.value.length > 0 ? { ...ref, notes: checked.value } : ref);
753
774
  // Read before the terminate, which would end it with its own code: whether the sandbox's command had already ended.
754
- const why = await this.#endedWords(sandbox, archil?.mount.token, signal);
775
+ // A sandbox Modal says is ending on its own (gone) is waited for, bounded, so its command's exit and words are read.
776
+ const why = await this.#endedWords(sandbox, name, archil?.mount.token, checked.error.code === "gone", signal);
755
777
  await letGo();
756
778
  const after = await this.#terminate(sandbox, name, signal);
757
779
  return fail(checked.error.code, `the computer ${name} ${after}: ${checked.error.message}${why}`);
758
780
  }
759
781
  /**
760
782
  * When a create's sandbox has already finished, its command's exit code and the tail of its output (stdout, then
761
- * stderr; the token, if any, cut), in words to append; nothing while it runs or when that cannot be read.
783
+ * stderr; the token, if any, cut), in words to append; nothing while it runs or when that cannot be read. With
784
+ * `ending` (Modal said the sandbox is shutting down), first waits up to endedMs for poll to read it finished: Modal
785
+ * ends a sandbox asynchronously, and poll reads null until then, so its command's words would be lost.
762
786
  */
763
- async #endedWords(sandbox, token, signal) {
764
- const { callMs } = this.#timeouts;
787
+ async #endedWords(sandbox, name, token, ending, signal) {
788
+ const { callMs, endedMs, releasePollMs } = this.#timeouts;
789
+ if (ending)
790
+ await untilFinished(() => sandbox.poll(), { name, boundMs: endedMs, callMs, minMs: Math.min(releasePollMs, RELEASE_POLL_MAX_MS), maxMs: RELEASE_POLL_MAX_MS, signal });
765
791
  const polled = await call("poll of the sandbox", () => sandbox.poll(), callMs, signal);
766
792
  if (!polled.ok || polled.value === null)
767
793
  return "";
@@ -905,10 +931,14 @@ export class ModalProvider {
905
931
  const found = [
906
932
  ...tagDrift(tags, read.value),
907
933
  ...helloDrift(inside.value.hello, this.#expected()),
908
- ...probeDrift(inside.value.probe, { user: recorded.user, network: recorded.network }),
934
+ ...probeDrift(inside.value.probe, { user: recorded.user, network: recorded.network, runtime: recorded.runtime }),
909
935
  ...(archil === undefined ? [] : mountDrift(archil.expected, inside.value.mount)),
910
936
  ];
911
- return found.length === 0 ? ok(probeNotes(inside.value.probe, recorded.network)) : fail("refused", `it did not match its spec: ${found.join("; ")}`);
937
+ if (found.length > 0)
938
+ return fail("refused", `it did not match its spec: ${found.join("; ")}`);
939
+ // Which way init fenced its programs, as hello read it back: said once a way other than the plain one was taken.
940
+ const fence = inside.value.hello.fence === "userns-netns" ? [`fence: userns-netns: init made its programs' network namespace inside a user namespace of its own, as root on ${recorded.runtime} may not make one itself`] : [];
941
+ return ok([...probeNotes(inside.value.probe, recorded.network), ...fence]);
912
942
  }
913
943
  /** One connection's hello and the probe through it, and an Archil computer's mount read back, the connection closed after. */
914
944
  async #inside(sandbox, name, signal, patient = false, archil) {
@@ -1098,7 +1128,7 @@ export class ModalProvider {
1098
1128
  return fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(totalMs)}`);
1099
1129
  if (hello.error.code !== "gone")
1100
1130
  return hello;
1101
- return { ...fail("modal", `cannot reach the daemon in ${name}: ${stderr.trim() || hello.error.message}`), notListening: true };
1131
+ return { ...vendorFail("modal", `cannot reach the daemon in ${name}: ${stderr.trim() || hello.error.message}`), notListening: true };
1102
1132
  }
1103
1133
  return ok({ client, hello: hello.value, close });
1104
1134
  }
@@ -1160,10 +1190,12 @@ export class ModalProvider {
1160
1190
  if (typeof recorded === "string")
1161
1191
  found.push(recorded);
1162
1192
  else {
1163
- if (recorded.runtime !== "vm")
1164
- found.push(`runtime: the tag ${SPEC_TAG} says ${show(recorded.runtime)}; this provider makes vm computers`);
1165
- const { image, network, cpus, memoryMb, workdir, user } = recorded;
1166
- const refusals = this.check({ image, lifetimeMs: 1, network, cpus, memoryMb, workdir, user });
1193
+ // gvisor exactly for a GPU computer, vm for every other: anything else this provider never makes.
1194
+ const runtime = recorded.gpu === undefined ? "vm" : "gvisor";
1195
+ if (recorded.runtime !== runtime)
1196
+ found.push(`runtime: the tag ${SPEC_TAG} says ${show(recorded.runtime)}; this provider makes ${runtime} computers ${recorded.gpu === undefined ? "with no GPU" : "with a GPU"}`);
1197
+ const { image, network, cpus, memoryMb, workdir, user, gpu } = recorded;
1198
+ const refusals = this.check({ image, lifetimeMs: 1, network, cpus, memoryMb, workdir, user, ...(gpu === undefined ? {} : { gpu }) });
1167
1199
  found.push(...refusals.map(({ field, message }) => `${field}: ${message}, as recorded at create`));
1168
1200
  // No exec in a computer whose user is root: the bridge would run what that user could have replaced.
1169
1201
  if (isRootUser(user))
@@ -1176,18 +1208,30 @@ export class ModalProvider {
1176
1208
  const { hello, probe, mount } = inside.value;
1177
1209
  found.push(...helloDrift(hello, this.#expected()));
1178
1210
  if (typeof recorded !== "string")
1179
- found.push(...probeDrift(probe, { user: recorded.user, network: recorded.network }));
1211
+ found.push(...probeDrift(probe, { user: recorded.user, network: recorded.network, runtime: recorded.runtime }));
1180
1212
  // The mount read back from inside is the one the spec tag records, under the computer's epoch label.
1181
1213
  if (archil !== undefined)
1182
1214
  found.push(...mountDrift(archil.expected, mount));
1183
1215
  if (found.length > 0 || typeof recorded === "string" || deadline === undefined) {
1184
1216
  return fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
1185
1217
  }
1186
- const { image, network, cpus, memoryMb, workdir } = recorded;
1218
+ const { image, network, cpus, memoryMb, workdir, gpu } = recorded;
1187
1219
  const notes = probeNotes(probe, network);
1188
1220
  return ok({
1189
1221
  ...ref,
1190
- spec: { image, user: `${probe.uid}:${probe.gid}`, network, cpus, memoryMb, workdir, deadline, kind: hello.kind, ...(archil === undefined || mount === undefined ? {} : { mount }) },
1222
+ spec: {
1223
+ image,
1224
+ user: `${probe.uid}:${probe.gid}`,
1225
+ network,
1226
+ cpus,
1227
+ memoryMb,
1228
+ workdir,
1229
+ deadline,
1230
+ kind: hello.kind,
1231
+ ...(archil === undefined || mount === undefined ? {} : { mount }),
1232
+ // Modal reads no GPU back: what create recorded, on a computer the probe read as gVisor, Modal's GPU runtime.
1233
+ ...(gpu === undefined ? {} : { gpu }),
1234
+ },
1191
1235
  ...(notes.length > 0 ? { notes } : {}),
1192
1236
  });
1193
1237
  }
@@ -11,7 +11,7 @@ import { createHash } from "node:crypto";
11
11
  import { readFileSync } from "node:fs";
12
12
  import { EPOCH_LABEL, epochOf, RUN_LABEL, runProblem } from "./labels.js";
13
13
  import { readBackOf, WORKSPACE } from "./mount.js";
14
- import { fail, ok } from "./result.js";
14
+ import { fail, failAs, ok } from "./result.js";
15
15
  /** Where the image has the root helper, root:root 0755. */
16
16
  export const ARCHIL_HELPER = "/usr/local/sbin/agentrun-archil";
17
17
  /** The user computerd runs every tool as in a computer with an Archil mount: no sudo, no capability, no token. */
@@ -173,7 +173,7 @@ export async function archilMount({ root, mount, self: computer, releaseOlder, t
173
173
  const step = async (argv, what, stdin) => {
174
174
  const ran = await root.run(argv, { timeoutMs, ...(stdin === undefined ? {} : { stdin }), ...(signal ? { signal } : {}) });
175
175
  if (!ran.ok)
176
- return fail(ran.error.code, `archil ${what} in the computer could not run: ${scrub(ran.error.message, mount.token)}`);
176
+ return failAs(ran.error, `archil ${what} in the computer could not run: ${scrub(ran.error.message, mount.token)}`);
177
177
  return ran;
178
178
  };
179
179
  const failed = (what, ran, code = "refused") => fail(code, `archil ${what} in the computer failed (exit ${ran.exitCode}): ${scrub(ran.output, mount.token)}`);
@@ -186,7 +186,7 @@ export async function archilMount({ root, mount, self: computer, releaseOlder, t
186
186
  }
187
187
  const older = await releaseOlder();
188
188
  if (!older.ok)
189
- return fail(older.error.code, `the takeover could not release the run's lower epochs, so nothing was revoked or mounted: ${older.error.message}`);
189
+ return failAs(older.error, `the takeover could not release the run's lower epochs, so nothing was revoked or mounted: ${older.error.message}`);
190
190
  const twinsOf = (kept) => kept.filter((ref) => ref.id !== computer.id).map((ref) => ref.name);
191
191
  const twins = twinsOf(older.value.kept);
192
192
  // Right before any force, the run's listing is read again: a higher epoch made since (two creates of one run
@@ -194,7 +194,7 @@ export async function archilMount({ root, mount, self: computer, releaseOlder, t
194
194
  const beforeForce = async () => {
195
195
  const again = await releaseOlder();
196
196
  if (!again.ok)
197
- return fail(again.error.code, `the run's computers, listed again right before the force, stop it, so nothing was revoked: ${again.error.message}`);
197
+ return failAs(again.error, `the run's computers, listed again right before the force, stop it, so nothing was revoked: ${again.error.message}`);
198
198
  const late = twinsOf(again.value.kept);
199
199
  if (late.length > 0)
200
200
  return fail("refused", `the run has ${late.join(", ")} at this claim's same epoch, listed right before the force: a create never forces off a computer of its own epoch, so nothing was revoked`);