@parcha/agentrun-computer 0.1.0-beta.32 → 0.1.0-beta.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +190 -26
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +6 -3
- package/dist/browserbase.d.ts +3 -1
- package/dist/browserbase.js +3 -1
- package/dist/child.d.ts +2 -0
- package/dist/child.js +13 -2
- package/dist/chrome.d.ts +73 -0
- package/dist/chrome.js +224 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/cases/gpu.d.ts +2 -0
- package/dist/conformance/cases/gpu.js +108 -0
- package/dist/conformance/cases/health.js +83 -3
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/isolation.js +6 -0
- package/dist/conformance/cases/mount.d.ts +8 -1
- package/dist/conformance/cases/mount.js +4 -3
- package/dist/conformance/cases/provider.js +14 -0
- package/dist/conformance/cli.js +46 -7
- package/dist/conformance/daytona-sweep.js +17 -9
- package/dist/conformance/e2b-sweep.js +17 -10
- package/dist/conformance/local.d.ts +30 -0
- package/dist/conformance/local.js +36 -0
- package/dist/conformance/modal-sweep.js +32 -9
- package/dist/conformance/report.js +10 -5
- package/dist/conformance/runner.js +45 -13
- package/dist/conformance/types.d.ts +63 -16
- package/dist/daytona.d.ts +35 -4
- package/dist/daytona.js +113 -27
- package/dist/docker.d.ts +9 -1
- package/dist/docker.js +92 -7
- package/dist/drift.d.ts +3 -1
- package/dist/drift.js +9 -0
- package/dist/e2b.d.ts +6 -2
- package/dist/e2b.js +10 -6
- package/dist/index.d.ts +4 -2
- package/dist/index.js +4 -2
- package/dist/isolation.d.ts +0 -2
- package/dist/isolation.js +0 -16
- package/dist/kernel.d.ts +3 -1
- package/dist/kernel.js +3 -1
- package/dist/kinds.d.ts +10 -4
- package/dist/kinds.js +26 -6
- package/dist/labels.d.ts +6 -0
- package/dist/labels.js +26 -1
- package/dist/local-supervisor.d.ts +51 -0
- package/dist/local-supervisor.js +221 -0
- package/dist/local.d.ts +89 -0
- package/dist/local.js +472 -0
- package/dist/modal.d.ts +31 -4
- package/dist/modal.js +90 -30
- package/dist/orgo.d.ts +3 -1
- package/dist/orgo.js +14 -27
- package/dist/phone-harness.d.ts +3 -1
- package/dist/phone-harness.js +7 -4
- package/dist/protocol.d.ts +20 -0
- package/dist/protocol.js +9 -0
- package/dist/provider.d.ts +63 -3
- package/dist/provider.js +28 -0
- package/dist/providers.d.ts +7 -1
- package/dist/providers.js +1 -0
- package/package.json +1 -1
package/dist/local.js
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
// The local browser as a computer of kind browser: this machine's own Chrome or Chromium, with no key and no vendor.
|
|
2
|
+
// Each computer is one Chrome with a fresh throwaway profile, started headless (or headed, for a person watching) with
|
|
3
|
+
// its DevTools socket on a port Chrome picks on 127.0.0.1; connect hands over that socket's ws:// URL, which a driver
|
|
4
|
+
// dials. Each runs under a supervisor of its own (local-supervisor.ts), a detached Node process that holds the browser's
|
|
5
|
+
// egress proxy and ends the browser at its deadline, at its release, or when Chrome exits, so a run that crashes leaves
|
|
6
|
+
// no Chrome behind.
|
|
7
|
+
//
|
|
8
|
+
// Its fence and its sandbox rule are PR #1718's: Chrome's own sandbox is always on (a start as root, or on a machine
|
|
9
|
+
// where Chrome cannot start its sandbox, is refused in words, never retried without it), and every request Chrome makes
|
|
10
|
+
// goes through the egress proxy, which reaches public addresses only, checked after its lookup: this machine's loopback
|
|
11
|
+
// and its other services, private networks, link-local and a cloud's metadata address are each refused (chrome.ts
|
|
12
|
+
// chromeFence). Chrome resolves no name itself, speaks no QUIC and sends WebRTC over no UDP. A spec's network is "open"
|
|
13
|
+
// (every public host) or { allow: [...] }: then the proxy reaches only the listed names and CIDRs, on ports 80 and 443,
|
|
14
|
+
// and refuses every other host by name before any lookup; the public-address rule holds for a listed host too.
|
|
15
|
+
//
|
|
16
|
+
// What it does not fence: the DevTools socket has no auth, so any process of this machine that finds its port can drive
|
|
17
|
+
// the browser; and the browser is a process of this machine, as the user AgentRun runs as, isolated by Chrome's sandbox
|
|
18
|
+
// alone. It is for local and development use.
|
|
19
|
+
//
|
|
20
|
+
// Files: one directory per browser under the root (default <tmpdir>/agentrun-local-browser-<uid>, 0700), named by the
|
|
21
|
+
// browser's id: browser.json (its labels and deadline, which list and attach read), supervisor.pid, state.json (Chrome's
|
|
22
|
+
// pid and port, once it answers), the profile, the proxy's socket and two logs. A release removes all of it.
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import { randomBytes } from "node:crypto";
|
|
25
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
26
|
+
import { lstat, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
27
|
+
import { tmpdir } from "node:os";
|
|
28
|
+
import { join, resolve } from "node:path";
|
|
29
|
+
import { fileURLToPath } from "node:url";
|
|
30
|
+
import { BROWSER_IMAGE, browserClient, browserHello, carries, labelsProblem } from "./browser.js";
|
|
31
|
+
import { alive, answeringPath, CHROME_FLAGS, checkChrome, findChrome, killTree, NO_CHROME, AS_ROOT, runsWith, singletonDir } from "./chrome.js";
|
|
32
|
+
import { parseAllow } from "./docker/egress-proxy.js";
|
|
33
|
+
import { BROWSER_FILE, CHROME_PID_FILE, EGRESS_SOCKET_FILE, PROFILE_DIR, READY_MS, STATE_FILE, SUPERVISOR_FILE } from "./local-supervisor.js";
|
|
34
|
+
import { checkLifetime } from "./provider.js";
|
|
35
|
+
import { fail, ok } from "./result.js";
|
|
36
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
37
|
+
const SUPERVISOR = fileURLToPath(new URL("./local-supervisor.js", import.meta.url));
|
|
38
|
+
/** The longest a local browser lives: a day, as pi-browser's local Chrome. */
|
|
39
|
+
export const LOCAL_MAX_LIFETIME_MS = 24 * 60 * 60_000;
|
|
40
|
+
/** The window a local browser opens with. */
|
|
41
|
+
const WINDOW = "--window-size=1280,800";
|
|
42
|
+
/** A Unix socket's path holds 107 bytes; a root whose browsers' sockets would not fit is refused. */
|
|
43
|
+
const SOCKET_PATH_MAX = 107;
|
|
44
|
+
/** How long a release waits for the supervisor, then for Chrome, to end. */
|
|
45
|
+
const END_MS = 10_000;
|
|
46
|
+
/** A browser takes no mount. */
|
|
47
|
+
export const MOUNT = [];
|
|
48
|
+
/** The networks a local browser runs on, through its egress proxy: public addresses ("open"), or only the hosts of a list
|
|
49
|
+
* ("allow"), public ones still. It cannot have none: a browser with no network has nothing to do. */
|
|
50
|
+
export const NETWORK = ["open", "allow"];
|
|
51
|
+
/** A spec's network as this browser's proxy takes it: open (no list), a list (parseAllow's), or why it can't. */
|
|
52
|
+
export function browserNetworkOf(network) {
|
|
53
|
+
if (network === "open")
|
|
54
|
+
return {};
|
|
55
|
+
const given = typeof network === "object" && network !== null ? network.allow : undefined;
|
|
56
|
+
if (!Array.isArray(given) || !given.every((entry) => typeof entry === "string"))
|
|
57
|
+
return { problem: `a local browser reaches public addresses through its egress proxy: network is "open" or { allow: [names and CIDRs] }, not ${JSON.stringify(network)}` };
|
|
58
|
+
let allow;
|
|
59
|
+
try {
|
|
60
|
+
allow = parseAllow(given);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
return { problem: error.message };
|
|
64
|
+
}
|
|
65
|
+
if (allow.length === 0)
|
|
66
|
+
return { problem: 'a local browser\'s allowlist needs at least one name or CIDR; for every public host ask for "open"' };
|
|
67
|
+
return { allow };
|
|
68
|
+
}
|
|
69
|
+
/** What browser.json keeps of a checked spec's network: its list, when it has one. */
|
|
70
|
+
const networkRecord = (network) => {
|
|
71
|
+
const net = browserNetworkOf(network);
|
|
72
|
+
return "problem" in net ? {} : net;
|
|
73
|
+
};
|
|
74
|
+
/** A browser's network as list, attach and network() read it back from browser.json. */
|
|
75
|
+
const networkRead = (record) => (record.allow ? { allow: [...record.allow] } : "open");
|
|
76
|
+
/** The one configuration it offers: a browser with a CDP target. No live view: a person watching runs it headed. */
|
|
77
|
+
export const CAPABILITIES = [{ kind: "browser", groups: ["cdp"] }];
|
|
78
|
+
const ID = /^lb-[0-9a-f]{16}$/;
|
|
79
|
+
const idProblem = (id) => (typeof id === "string" && ID.test(id) ? undefined : `${typeof id === "string" ? JSON.stringify(id) : String(id)} is not a local browser's id`);
|
|
80
|
+
const refOf = (id) => ({ id, name: id });
|
|
81
|
+
const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels"]);
|
|
82
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
83
|
+
const readJson = async (file) => {
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
/** Computers that are this machine's Chrome. */
|
|
92
|
+
export class LocalBrowserProvider {
|
|
93
|
+
id = "local";
|
|
94
|
+
version = VERSION;
|
|
95
|
+
#executablePath;
|
|
96
|
+
#env;
|
|
97
|
+
#headed;
|
|
98
|
+
#uid;
|
|
99
|
+
root;
|
|
100
|
+
constructor({ executablePath, env = {}, headed = false, root, uid = process.getuid?.() } = {}) {
|
|
101
|
+
this.#executablePath = executablePath === "" ? undefined : executablePath;
|
|
102
|
+
this.#env = env;
|
|
103
|
+
this.#headed = headed;
|
|
104
|
+
this.#uid = uid;
|
|
105
|
+
// Absolute once, here: Chrome is given its profile by the supervisor's absolute path, and a liveness check or a
|
|
106
|
+
// release matches that path exactly, so a relative root would read a running Chrome as gone.
|
|
107
|
+
this.root = resolve(root ?? join(tmpdir(), `agentrun-local-browser-${uid ?? "user"}`));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A browser: our supervisor ends it at its deadline, and list reads that deadline, so the janitor sweeps one whose
|
|
111
|
+
* supervisor is gone (lifetime janitor); it reaches public addresses only, through its egress proxy (network open), or
|
|
112
|
+
* only a list's hosts among them (network allow);
|
|
113
|
+
* it runs on this host, as this user, isolated by Chrome's sandbox alone (isolation host).
|
|
114
|
+
*/
|
|
115
|
+
capabilities() {
|
|
116
|
+
return {
|
|
117
|
+
kind: "browser",
|
|
118
|
+
lifetime: "janitor",
|
|
119
|
+
network: [...NETWORK],
|
|
120
|
+
isolation: "host",
|
|
121
|
+
os: "linux",
|
|
122
|
+
daemon: "none",
|
|
123
|
+
groups: [...CAPABILITIES[0].groups],
|
|
124
|
+
maxLifetimeMs: LOCAL_MAX_LIFETIME_MS,
|
|
125
|
+
release: ["delete"],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** The Chrome this provider runs: the option's, else one found; null when there is none. */
|
|
129
|
+
executable() {
|
|
130
|
+
return this.#executablePath ?? findChrome(this.#env);
|
|
131
|
+
}
|
|
132
|
+
/** Why no browser can start on this machine, in words; none when one can (before the sandbox check, which starts Chrome). */
|
|
133
|
+
#machineRefusals() {
|
|
134
|
+
if (this.#uid === 0)
|
|
135
|
+
return [{ field: "host", message: AS_ROOT }];
|
|
136
|
+
const executable = this.executable();
|
|
137
|
+
if (executable === null)
|
|
138
|
+
return [{ field: "image", message: NO_CHROME }];
|
|
139
|
+
if (!existsSync(executable))
|
|
140
|
+
return [{ field: "image", message: `the executablePath ${executable} does not exist: ${NO_CHROME}` }];
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
check(spec) {
|
|
144
|
+
const refusals = [];
|
|
145
|
+
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
146
|
+
const { image, lifetimeMs, network, labels } = given;
|
|
147
|
+
if (image !== BROWSER_IMAGE)
|
|
148
|
+
refusals.push({ field: "image", message: `a local browser is this machine's Chrome: image is "${BROWSER_IMAGE}", not ${JSON.stringify(image)}` });
|
|
149
|
+
refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
|
|
150
|
+
const net = browserNetworkOf(network);
|
|
151
|
+
if ("problem" in net)
|
|
152
|
+
refusals.push({ field: "network", message: net.problem });
|
|
153
|
+
if (labels !== undefined) {
|
|
154
|
+
const problem = labelsProblem(labels);
|
|
155
|
+
if (problem)
|
|
156
|
+
refusals.push({ field: "labels", message: problem });
|
|
157
|
+
}
|
|
158
|
+
for (const [field, value] of Object.entries(given)) {
|
|
159
|
+
if (!SPEC_FIELDS.has(field) && value !== undefined)
|
|
160
|
+
refusals.push({ field, message: `a local browser does not take ${field}` });
|
|
161
|
+
}
|
|
162
|
+
return [...refusals, ...this.#machineRefusals()];
|
|
163
|
+
}
|
|
164
|
+
/** The root, made 0700 if it is not there; refused when it is not a directory of this user's that no one else can write. */
|
|
165
|
+
async #ensureRoot() {
|
|
166
|
+
try {
|
|
167
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
168
|
+
const info = await lstat(this.root);
|
|
169
|
+
if (!info.isDirectory())
|
|
170
|
+
return fail("invalid", `the local browser's root ${this.root} is not a directory`);
|
|
171
|
+
if (process.platform !== "win32") {
|
|
172
|
+
if (this.#uid !== undefined && info.uid !== this.#uid)
|
|
173
|
+
return fail("refused", `the local browser's root ${this.root} belongs to another user: set the root option to a directory of your own`);
|
|
174
|
+
if ((info.mode & 0o022) !== 0)
|
|
175
|
+
return fail("refused", `the local browser's root ${this.root} is writable by other users: make it 0700, or set the root option to another directory`);
|
|
176
|
+
}
|
|
177
|
+
return ok(undefined);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
return fail("invalid", `the local browser's root ${this.root} could not be made (${error.code ?? error.message})`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** Starts Chrome under a supervisor of its own, waits until its DevTools socket answers, and hands back its ref. */
|
|
184
|
+
async create(spec, { signal } = {}) {
|
|
185
|
+
const refusals = this.check(spec);
|
|
186
|
+
if (refusals.length > 0)
|
|
187
|
+
return fail(refusals.some((r) => r.field === "image" && r.message.endsWith(NO_CHROME)) ? "not_found" : "refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
188
|
+
if (signal?.aborted)
|
|
189
|
+
return fail("aborted", "create was aborted before Chrome was started");
|
|
190
|
+
const rooted = await this.#ensureRoot();
|
|
191
|
+
if (!rooted.ok)
|
|
192
|
+
return rooted;
|
|
193
|
+
const id = `lb-${randomBytes(8).toString("hex")}`;
|
|
194
|
+
const dir = join(this.root, id);
|
|
195
|
+
if (Buffer.byteLength(join(dir, EGRESS_SOCKET_FILE)) > SOCKET_PATH_MAX)
|
|
196
|
+
return fail("invalid", `the local browser's root ${this.root} is too long for a Unix socket under it: set the root option to a shorter directory`);
|
|
197
|
+
const now = Date.now();
|
|
198
|
+
const record = {
|
|
199
|
+
provider: "local",
|
|
200
|
+
id,
|
|
201
|
+
labels: { ...spec.labels },
|
|
202
|
+
created: new Date(now).toISOString(),
|
|
203
|
+
deadline: new Date(now + spec.lifetimeMs).toISOString(),
|
|
204
|
+
executablePath: this.executable(),
|
|
205
|
+
args: [...CHROME_FLAGS, ...(this.#headed ? [] : ["--headless=new"]), WINDOW],
|
|
206
|
+
...networkRecord(spec.network),
|
|
207
|
+
};
|
|
208
|
+
try {
|
|
209
|
+
await mkdir(join(dir, PROFILE_DIR), { recursive: true, mode: 0o700 });
|
|
210
|
+
await writeFile(join(dir, BROWSER_FILE), JSON.stringify(record), { mode: 0o600, flag: "wx" });
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
214
|
+
return fail("invalid", `the local browser's directory could not be made under ${this.root} (${error.code ?? error.message})`);
|
|
215
|
+
}
|
|
216
|
+
// A stop that came while the directory was made: nothing is started, and the directory goes.
|
|
217
|
+
if (signal?.aborted) {
|
|
218
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
219
|
+
return fail("aborted", "create was aborted before Chrome was started");
|
|
220
|
+
}
|
|
221
|
+
let child;
|
|
222
|
+
try {
|
|
223
|
+
child = spawn(process.execPath, [SUPERVISOR, dir], { detached: true, stdio: ["ignore", "pipe", "ignore"] });
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
227
|
+
return fail("invalid", `the local browser's supervisor could not be started (${error.message})`);
|
|
228
|
+
}
|
|
229
|
+
const exited = new Promise((done) => child.once("exit", () => done()));
|
|
230
|
+
const line = await new Promise((done) => {
|
|
231
|
+
let text = "";
|
|
232
|
+
const timer = setTimeout(() => finish("timeout"), READY_MS + 10_000);
|
|
233
|
+
const abort = () => finish("aborted");
|
|
234
|
+
const finish = (value) => {
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
signal?.removeEventListener("abort", abort);
|
|
237
|
+
done(value);
|
|
238
|
+
};
|
|
239
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
240
|
+
// An abort that fired before the listener was added fires no event: it is read here, and the supervisor is ended below.
|
|
241
|
+
if (signal?.aborted)
|
|
242
|
+
abort();
|
|
243
|
+
child.once("error", () => finish("exited"));
|
|
244
|
+
child.once("exit", () => finish("exited"));
|
|
245
|
+
child.stdout?.on("data", (chunk) => {
|
|
246
|
+
text += chunk.toString("utf8");
|
|
247
|
+
const at = text.indexOf("\n");
|
|
248
|
+
if (at < 0)
|
|
249
|
+
return;
|
|
250
|
+
try {
|
|
251
|
+
finish(JSON.parse(text.slice(0, at)));
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
finish("exited");
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
child.stdout?.destroy();
|
|
259
|
+
if (typeof line === "object" && "ready" in line) {
|
|
260
|
+
child.unref();
|
|
261
|
+
return ok(refOf(id));
|
|
262
|
+
}
|
|
263
|
+
// Not ready: the supervisor ends what it started; a release makes sure, and nothing of this browser is left.
|
|
264
|
+
let timer;
|
|
265
|
+
await Promise.race([exited, new Promise((done) => (timer = setTimeout(done, END_MS)))]);
|
|
266
|
+
clearTimeout(timer);
|
|
267
|
+
const released = await this.release(refOf(id), "delete");
|
|
268
|
+
child.unref();
|
|
269
|
+
const left = released.ok ? "" : `; ${released.error.message}`;
|
|
270
|
+
if (line === "aborted")
|
|
271
|
+
return fail("aborted", `create was aborted while Chrome started; it was ended${left}`);
|
|
272
|
+
if (line === "timeout")
|
|
273
|
+
return fail("timeout", `the local browser's supervisor did not answer within ${(READY_MS + 10_000) / 1000} s; it was ended${left}`);
|
|
274
|
+
if (line === "exited")
|
|
275
|
+
return fail("gone", `the local browser's supervisor ended before Chrome answered${left}`);
|
|
276
|
+
const code = line.sandbox ? "refused" : /did not open its debugging port within/.test(line.failed) ? "timeout" : "gone";
|
|
277
|
+
return fail(code, `${line.failed}${left}`);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Settings' test: finds the Chrome and starts it once, headless, on a blank page, with its sandbox on (chrome.ts
|
|
281
|
+
* checkChrome), with a proxy that reaches nothing. No browser is kept and no key is read; no Chrome, root, or a Chrome
|
|
282
|
+
* that cannot start its sandbox is said in words.
|
|
283
|
+
*/
|
|
284
|
+
async testConnection(_context = {}) {
|
|
285
|
+
const refused = this.#machineRefusals();
|
|
286
|
+
if (refused.length > 0)
|
|
287
|
+
return fail(refused[0]?.field === "host" ? "refused" : "not_found", refused[0].message);
|
|
288
|
+
// A Chrome found or named is started once with its sandbox on: what a create would do, with nothing kept.
|
|
289
|
+
const checked = await checkChrome(this.executable(), this.#uid === undefined ? {} : { uid: this.#uid });
|
|
290
|
+
if (!checked.ok)
|
|
291
|
+
return checked;
|
|
292
|
+
return ok({ detail: `${checked.value} starts here with its sandbox on: no key is needed` });
|
|
293
|
+
}
|
|
294
|
+
#dir(id) {
|
|
295
|
+
return join(this.root, id);
|
|
296
|
+
}
|
|
297
|
+
async #record(id) {
|
|
298
|
+
const record = await readJson(join(this.#dir(id), BROWSER_FILE));
|
|
299
|
+
return record?.provider === "local" && record.id === id ? record : undefined;
|
|
300
|
+
}
|
|
301
|
+
/** Chrome's state, when the Chrome it names still runs on this browser's profile. */
|
|
302
|
+
async #live(id) {
|
|
303
|
+
const state = await readJson(join(this.#dir(id), STATE_FILE));
|
|
304
|
+
if (!state || !Number.isInteger(state.pid) || !Number.isInteger(state.port) || typeof state.path !== "string")
|
|
305
|
+
return undefined;
|
|
306
|
+
return runsWith(state.pid, `--user-data-dir=${join(this.#dir(id), PROFILE_DIR)}`) ? state : undefined;
|
|
307
|
+
}
|
|
308
|
+
/** Every browser of this provider's root with these labels, each with whether its Chrome still runs. */
|
|
309
|
+
async #browsers(labels) {
|
|
310
|
+
const problem = labelsProblem(labels);
|
|
311
|
+
if (problem)
|
|
312
|
+
return fail("invalid", problem);
|
|
313
|
+
let names;
|
|
314
|
+
try {
|
|
315
|
+
names = await readdir(this.root);
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
if (error.code === "ENOENT")
|
|
319
|
+
return ok([]);
|
|
320
|
+
return fail("invalid", `the local browser's root ${this.root} could not be read (${error.code ?? error.message})`);
|
|
321
|
+
}
|
|
322
|
+
const found = [];
|
|
323
|
+
for (const name of names.filter((one) => ID.test(one)).sort()) {
|
|
324
|
+
const record = await this.#record(name);
|
|
325
|
+
if (!record || !carries(record.labels, labels))
|
|
326
|
+
continue;
|
|
327
|
+
found.push({ record, running: (await this.#live(name)) !== undefined });
|
|
328
|
+
}
|
|
329
|
+
return ok(found);
|
|
330
|
+
}
|
|
331
|
+
/** Every browser with these labels: running while its Chrome runs, stopped once it does not (its files not yet removed). */
|
|
332
|
+
async list(labels, _context = {}) {
|
|
333
|
+
const found = await this.#browsers(labels);
|
|
334
|
+
if (!found.ok)
|
|
335
|
+
return found;
|
|
336
|
+
return ok(found.value.map(({ record, running }) => {
|
|
337
|
+
const deadline = new Date(record.deadline);
|
|
338
|
+
return { ref: refOf(record.id), labels: { ...record.labels }, deadline: Number.isNaN(deadline.getTime()) ? undefined : deadline, state: running ? "running" : "stopped", network: networkRead(record) };
|
|
339
|
+
}));
|
|
340
|
+
}
|
|
341
|
+
#attached(record) {
|
|
342
|
+
const deadline = new Date(record.deadline);
|
|
343
|
+
const user = `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`;
|
|
344
|
+
return { ...refOf(record.id), spec: { image: BROWSER_IMAGE, user, network: networkRead(record), kind: "browser", ...(Number.isNaN(deadline.getTime()) ? {} : { deadline }) } };
|
|
345
|
+
}
|
|
346
|
+
async attach(ref, _context = {}) {
|
|
347
|
+
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
348
|
+
if ((given.id === undefined) === (given.labels === undefined))
|
|
349
|
+
return fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
350
|
+
if (given.id !== undefined) {
|
|
351
|
+
const problem = idProblem(given.id);
|
|
352
|
+
if (problem)
|
|
353
|
+
return fail("invalid", problem);
|
|
354
|
+
const id = given.id;
|
|
355
|
+
const record = await this.#record(id);
|
|
356
|
+
if (!record)
|
|
357
|
+
return fail("not_found", `no local browser has the id ${id}`);
|
|
358
|
+
if (!(await this.#live(id)))
|
|
359
|
+
return fail("gone", `the local browser ${id} no longer runs: only a running browser is attached to`);
|
|
360
|
+
return ok(this.#attached(record));
|
|
361
|
+
}
|
|
362
|
+
const labels = given.labels;
|
|
363
|
+
const found = await this.#browsers(labels);
|
|
364
|
+
if (!found.ok)
|
|
365
|
+
return found;
|
|
366
|
+
const running = found.value.filter((one) => one.running);
|
|
367
|
+
const words = JSON.stringify(labels);
|
|
368
|
+
if (running.length === 0)
|
|
369
|
+
return fail("not_found", `no running local browser has the labels ${words}`);
|
|
370
|
+
if (running.length > 1)
|
|
371
|
+
return fail("invalid", `${running.length} local browsers have the labels ${words}: ${running.map((one) => one.record.id).join(", ")}`);
|
|
372
|
+
return ok(this.#attached(running[0].record));
|
|
373
|
+
}
|
|
374
|
+
/** The network it was made with (open, or its list), read back; its proxy is started with it, so a change is refused in words. */
|
|
375
|
+
async network(ref, policy, _context = {}) {
|
|
376
|
+
const problem = idProblem(ref?.id);
|
|
377
|
+
if (problem)
|
|
378
|
+
return fail("invalid", problem);
|
|
379
|
+
const record = await this.#record(ref.id);
|
|
380
|
+
if (!record)
|
|
381
|
+
return fail("not_found", `no local browser has the id ${ref.id}`);
|
|
382
|
+
const now = networkRead(record);
|
|
383
|
+
const asked = policy === undefined ? undefined : browserNetworkOf(policy);
|
|
384
|
+
// The same network, a list's entries in any order, is no change.
|
|
385
|
+
const same = (a, b) => JSON.stringify(a.allow ? [...a.allow].sort() : null) === JSON.stringify(b.allow ? [...b.allow].sort() : null);
|
|
386
|
+
if (asked !== undefined && ("problem" in asked || !same(asked, networkRecord(now))))
|
|
387
|
+
return fail("refused", `a local browser's network is set when it starts, by its egress proxy; it is ${JSON.stringify(now)} and cannot be set to ${JSON.stringify(policy)}`);
|
|
388
|
+
return (await this.#live(ref.id)) ? ok(now) : fail("gone", `the local browser ${ref.id} no longer runs`);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* The browser's DevTools URL, ws://127.0.0.1:<port>/devtools/browser/<id>, once the socket on that port answers with
|
|
392
|
+
* the path this browser's Chrome wrote; and a client that answers hello and ping. The URL bears no secret, but the
|
|
393
|
+
* socket takes any local client: it is the browser.
|
|
394
|
+
*/
|
|
395
|
+
async connect(ref) {
|
|
396
|
+
const id = ref?.id;
|
|
397
|
+
const problem = idProblem(id);
|
|
398
|
+
if (problem)
|
|
399
|
+
return fail("invalid", problem);
|
|
400
|
+
if (!(await this.#record(id)))
|
|
401
|
+
return fail("not_found", `no local browser has the id ${id}`);
|
|
402
|
+
const state = await this.#live(id);
|
|
403
|
+
if (!state)
|
|
404
|
+
return fail("gone", `the local browser ${id} no longer runs`);
|
|
405
|
+
if ((await answeringPath(state.port)) !== state.path)
|
|
406
|
+
return fail("gone", `the local browser ${id}'s DevTools socket on port ${state.port} does not answer as its Chrome`);
|
|
407
|
+
const url = `ws://127.0.0.1:${state.port}${state.path}`; // key-gate: loopback-rule the local Chrome's own DevTools socket
|
|
408
|
+
const hello = browserHello(VERSION, this.capabilities().groups);
|
|
409
|
+
const client = browserClient(hello, async () => ok((await this.#live(id)) !== undefined));
|
|
410
|
+
return ok({ client, hello, cdp: { url }, close: async () => client.close() });
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Ends the browser and removes its files: its supervisor is asked to end it (SIGTERM), and whatever is left once it
|
|
414
|
+
* has gone (a supervisor already gone, a Chrome it did not end) is ended and removed here. A browser already gone is
|
|
415
|
+
* released; done means its directory is gone.
|
|
416
|
+
*/
|
|
417
|
+
async release(ref, how, _context = {}) {
|
|
418
|
+
if (how !== "delete")
|
|
419
|
+
return fail("refused", `a local browser is released with "delete"; it cannot be stopped and kept, so ${String(how)} is refused and the browser is left as it is`);
|
|
420
|
+
const id = ref?.id;
|
|
421
|
+
const problem = idProblem(id);
|
|
422
|
+
if (problem)
|
|
423
|
+
return fail("invalid", problem);
|
|
424
|
+
const dir = this.#dir(id);
|
|
425
|
+
if (!(await lstat(dir).then(() => true, () => false)))
|
|
426
|
+
return ok(undefined);
|
|
427
|
+
const supervisor = Number((await readFile(join(dir, SUPERVISOR_FILE), "utf8").catch(() => "")).trim());
|
|
428
|
+
if (runsWith(supervisor, dir)) {
|
|
429
|
+
try {
|
|
430
|
+
process.kill(supervisor, "SIGTERM");
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
/* gone already */
|
|
434
|
+
}
|
|
435
|
+
for (const until = Date.now() + END_MS; runsWith(supervisor, dir) && Date.now() < until;)
|
|
436
|
+
await sleep(50);
|
|
437
|
+
}
|
|
438
|
+
// Chrome's pid as the supervisor wrote it at the spawn (chrome.pid), and once Chrome answered (state.json): a
|
|
439
|
+
// supervisor killed before Chrome answered leaves only the first.
|
|
440
|
+
const state = await readJson(join(dir, STATE_FILE));
|
|
441
|
+
const spawned = Number((await readFile(join(dir, CHROME_PID_FILE), "utf8").catch(() => "")).trim());
|
|
442
|
+
const marker = `--user-data-dir=${join(dir, PROFILE_DIR)}`;
|
|
443
|
+
for (const pid of new Set([state?.pid, spawned].filter((one) => Number.isInteger(one) && one > 0))) {
|
|
444
|
+
if (!runsWith(pid, marker))
|
|
445
|
+
continue;
|
|
446
|
+
killTree(pid);
|
|
447
|
+
for (const until = Date.now() + END_MS; runsWith(pid, marker) && alive(pid) && Date.now() < until;)
|
|
448
|
+
await sleep(50);
|
|
449
|
+
}
|
|
450
|
+
const socketDir = await singletonDir(join(dir, PROFILE_DIR));
|
|
451
|
+
if (socketDir)
|
|
452
|
+
await rm(socketDir, { recursive: true, force: true }).catch(() => undefined);
|
|
453
|
+
let error;
|
|
454
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
455
|
+
try {
|
|
456
|
+
await rm(dir, { recursive: true, force: true });
|
|
457
|
+
return ok(undefined);
|
|
458
|
+
}
|
|
459
|
+
catch (caught) {
|
|
460
|
+
error = caught;
|
|
461
|
+
await sleep(100 * (attempt + 1));
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return fail("invalid", `the local browser ${id} was ended but its directory ${dir} could not be removed (${error.code ?? String(error)}): it may hold the session's cookies, so remove it by hand`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
/** The provider, built from its options alone: no key, and no environment read but the `env` it is given. */
|
|
468
|
+
export function create(options = {}) {
|
|
469
|
+
return new LocalBrowserProvider(options ?? {});
|
|
470
|
+
}
|
|
471
|
+
/** The conformance CLI's module for the local browser: its live switch, its image and its notes. */
|
|
472
|
+
export const conformance = () => import("./conformance/local.js");
|
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 GpuCapability, type NetworkForm, type NetworkPolicy, type NetworkSpec, type Refusal } 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
|
-
|
|
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,7 +142,26 @@ 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
|
|
145
|
+
/** The network a Modal computer's programs get: none, a network of their own (isolation.ts OWN_NETWORK_ONLY). */
|
|
146
|
+
export declare const NETWORK: readonly NetworkForm[];
|
|
147
|
+
/** The runtime a Modal sandbox runs under: vm, or gvisor for a GPU computer (Modal offers GPUs on gVisor only). */
|
|
148
|
+
export type ModalRuntime = "vm" | "gvisor";
|
|
149
|
+
/**
|
|
150
|
+
* The GPU types Modal takes, by its own names (guide/gpu, 11-10): "A100" is the 40 GB one, "A100-40GB" its explicit
|
|
151
|
+
* name. Its "H100!" and "B200+" variants (no upgrade to an H200; a B200 or B300) are not offered: what a computer gets
|
|
152
|
+
* should be what it asked for.
|
|
153
|
+
*/
|
|
154
|
+
export declare const MODAL_GPU_TYPES: readonly ["T4", "L4", "A10", "L40S", "A100", "A100-40GB", "A100-80GB", "RTX-PRO-6000", "H100", "H200", "B200", "B300"];
|
|
155
|
+
/** The most GPUs Modal gives one container: 8 (guide/gpu; an A10 container takes at most 4, which Modal refuses in words past). */
|
|
156
|
+
export declare const MODAL_GPU_MAX = 8;
|
|
157
|
+
/**
|
|
158
|
+
* The GPUs Modal offers, as capabilities().gpu and CAPABILITIES declare them: on gVisor, Modal's one GPU runtime;
|
|
159
|
+
* preemptible, as Modal may end a GPU container to free capacity; no mount yet, the Archil client's FUSE mount not
|
|
160
|
+
* being proven on gVisor; and the loopback fence made inside a user namespace, as gVisor's root may not make a network
|
|
161
|
+
* namespace itself (a live probe, 11-11: unshare -n refused, unshare -Urn allowed).
|
|
162
|
+
*/
|
|
163
|
+
export declare const MODAL_GPU: Readonly<GpuCapability>;
|
|
164
|
+
/** The machine kind, groups and GPUs of its one configuration: a linux computer, with GPUs when asked. */
|
|
138
165
|
export declare const CAPABILITIES: readonly KindCapabilities[];
|
|
139
166
|
/** A registry tag for linux/amd64 that Modal can pull: the default when a setting names no image. */
|
|
140
167
|
export declare const MODAL_DEFAULT_IMAGE = "debian:bookworm-slim";
|
|
@@ -234,7 +261,7 @@ export interface UntilFinishedOptions {
|
|
|
234
261
|
*/
|
|
235
262
|
export declare function untilFinished(poll: () => Promise<number | null>, { name, boundMs, callMs, minMs, maxMs, signal }: UntilFinishedOptions): Promise<Result<void>>;
|
|
236
263
|
/**
|
|
237
|
-
* Computers that are Modal sandboxes on the VM runtime. The daemon is uploaded right after create, streamed through an
|
|
264
|
+
* 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
265
|
* exec's stdin, while the sandbox's command, a small sh entrypoint, waits for it and then becomes `computerd init`; or,
|
|
239
266
|
* with daemonImage, it comes in as a layer of the computer's image (COPY --from) and is the command itself. A
|
|
240
267
|
* connection is `computerd stdio` through exec, so a computer with network none is still reached, and needs no network
|