@parcha/agentrun-computer 0.1.0-beta.33 → 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.
Files changed (59) hide show
  1. package/README.md +169 -15
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +6 -3
  4. package/dist/browserbase.d.ts +3 -1
  5. package/dist/browserbase.js +3 -1
  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/cases/gpu.d.ts +2 -0
  13. package/dist/conformance/cases/gpu.js +108 -0
  14. package/dist/conformance/cases/health.js +83 -3
  15. package/dist/conformance/cases/index.js +2 -0
  16. package/dist/conformance/cases/mount.d.ts +8 -1
  17. package/dist/conformance/cases/mount.js +4 -3
  18. package/dist/conformance/cases/provider.js +14 -0
  19. package/dist/conformance/cli.js +46 -7
  20. package/dist/conformance/local.d.ts +30 -0
  21. package/dist/conformance/local.js +36 -0
  22. package/dist/conformance/report.js +10 -5
  23. package/dist/conformance/runner.js +45 -13
  24. package/dist/conformance/types.d.ts +63 -16
  25. package/dist/daytona.d.ts +32 -3
  26. package/dist/daytona.js +96 -24
  27. package/dist/docker.d.ts +3 -1
  28. package/dist/docker.js +11 -3
  29. package/dist/drift.d.ts +3 -1
  30. package/dist/drift.js +9 -0
  31. package/dist/e2b.d.ts +3 -1
  32. package/dist/e2b.js +7 -4
  33. package/dist/index.d.ts +4 -2
  34. package/dist/index.js +4 -2
  35. package/dist/isolation.d.ts +0 -2
  36. package/dist/isolation.js +0 -16
  37. package/dist/kernel.d.ts +3 -1
  38. package/dist/kernel.js +3 -1
  39. package/dist/kinds.d.ts +10 -4
  40. package/dist/kinds.js +26 -6
  41. package/dist/labels.d.ts +6 -0
  42. package/dist/labels.js +26 -1
  43. package/dist/local-supervisor.d.ts +51 -0
  44. package/dist/local-supervisor.js +221 -0
  45. package/dist/local.d.ts +89 -0
  46. package/dist/local.js +472 -0
  47. package/dist/modal.d.ts +31 -4
  48. package/dist/modal.js +90 -30
  49. package/dist/orgo.d.ts +3 -1
  50. package/dist/orgo.js +14 -27
  51. package/dist/phone-harness.d.ts +3 -1
  52. package/dist/phone-harness.js +7 -4
  53. package/dist/protocol.d.ts +20 -0
  54. package/dist/protocol.js +9 -0
  55. package/dist/provider.d.ts +63 -3
  56. package/dist/provider.js +28 -0
  57. package/dist/providers.d.ts +7 -1
  58. package/dist/providers.js +1 -0
  59. package/package.json +1 -1
package/dist/kinds.js CHANGED
@@ -7,9 +7,9 @@
7
7
  // The default images are values: each from the provider module that owns it. Those modules import this one for types
8
8
  // alone, so this is no import cycle.
9
9
  import { BROWSER_IMAGE } from "./browser.js";
10
- import { DAYTONA_DEFAULT_SNAPSHOT } from "./daytona.js";
10
+ import { DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU } from "./daytona.js";
11
11
  import { E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE } from "./e2b.js";
12
- import { MODAL_DEFAULT_IMAGE } from "./modal.js";
12
+ import { MODAL_DEFAULT_IMAGE, MODAL_GPU } from "./modal.js";
13
13
  import { ORGO_BASE_IMAGE } from "./orgo.js";
14
14
  import { PHONE_IMAGE } from "./phone-harness.js";
15
15
  export const SETTING_KINDS = {
@@ -47,16 +47,18 @@ export function kindOf(capabilities) {
47
47
  }
48
48
  const SANDBOX = { kind: "linux", groups: ["exec", "files", "processes"] };
49
49
  const LINUX_DESKTOP = { kind: "desktop", groups: ["exec", "files", "processes", "screen", "input.pointer", "input.keys"] };
50
+ /** A provider's GPU capability as its configuration carries it: a deep copy of the module's own. */
51
+ const gpuOf = (gpu) => structuredClone(gpu);
50
52
  /** An entry with its kinds derived from its capabilities. */
51
53
  function entry(fields) {
52
54
  return { ...fields, kinds: SETTING_KIND_NAMES.filter((kind) => fields.capabilities.some((one) => serves(one, kind))) };
53
55
  }
54
56
  /**
55
57
  * Every provider Settings offers, each with its provider file in the registry;
56
- * a unit test then holds each to its module (CAPABILITIES, MOUNT). daytona, modal and e2b take archil mounts.
58
+ * a unit test then holds each to its module (CAPABILITIES, MOUNT, NETWORK). daytona, modal and e2b take archil mounts.
57
59
  */
58
60
  export const PROVIDERS = [
59
- entry({ id: "docker", label: "Docker", keys: [], mounts: ["bind"], metered: false, capabilities: [SANDBOX, LINUX_DESKTOP] }),
61
+ entry({ id: "docker", label: "Docker", keys: [], mounts: ["bind"], network: ["none", "open", "allow"], metered: false, capabilities: [SANDBOX, LINUX_DESKTOP] }),
60
62
  entry({
61
63
  id: "daytona",
62
64
  label: "Daytona",
@@ -66,8 +68,9 @@ export const PROVIDERS = [
66
68
  { name: "DAYTONA_TARGET", required: false },
67
69
  ],
68
70
  mounts: ["archil"],
71
+ network: ["none"],
69
72
  metered: true,
70
- capabilities: [SANDBOX],
73
+ capabilities: [{ ...SANDBOX, gpu: gpuOf(DAYTONA_GPU) }],
71
74
  defaultImage: { sandbox: DAYTONA_DEFAULT_SNAPSHOT },
72
75
  }),
73
76
  entry({
@@ -78,8 +81,9 @@ export const PROVIDERS = [
78
81
  { name: "MODAL_TOKEN_SECRET", required: true },
79
82
  ],
80
83
  mounts: ["archil"],
84
+ network: ["none"],
81
85
  metered: true,
82
- capabilities: [SANDBOX],
86
+ capabilities: [{ ...SANDBOX, gpu: gpuOf(MODAL_GPU) }],
83
87
  defaultImage: { sandbox: MODAL_DEFAULT_IMAGE },
84
88
  }),
85
89
  entry({
@@ -87,6 +91,7 @@ export const PROVIDERS = [
87
91
  label: "E2B",
88
92
  keys: [{ name: "E2B_API_KEY", required: true }],
89
93
  mounts: ["archil"],
94
+ network: ["none"],
90
95
  metered: true,
91
96
  capabilities: [SANDBOX, LINUX_DESKTOP],
92
97
  defaultImage: { sandbox: E2B_BASE_TEMPLATE, desktop: E2B_DESKTOP_TEMPLATE },
@@ -96,6 +101,7 @@ export const PROVIDERS = [
96
101
  label: "Orgo",
97
102
  keys: [{ name: "ORGO_API_KEY", required: true }],
98
103
  mounts: [],
104
+ network: ["none"],
99
105
  metered: true,
100
106
  capabilities: [LINUX_DESKTOP],
101
107
  defaultImage: { desktop: ORGO_BASE_IMAGE },
@@ -105,6 +111,7 @@ export const PROVIDERS = [
105
111
  label: "Phone harness",
106
112
  keys: [{ name: "PHONE_HARNESS_API_KEY", required: true }],
107
113
  mounts: [],
114
+ network: ["open"],
108
115
  metered: true,
109
116
  capabilities: [{ kind: "android", groups: ["screen", "input.touch", "input.keys", "apps", "apps.ui_tree"] }],
110
117
  defaultImage: { phone: PHONE_IMAGE },
@@ -117,6 +124,7 @@ export const PROVIDERS = [
117
124
  { name: "BROWSERBASE_PROJECT_ID", required: true },
118
125
  ],
119
126
  mounts: [],
127
+ network: ["open"],
120
128
  metered: true,
121
129
  capabilities: [{ kind: "browser", groups: ["cdp", "stream"] }],
122
130
  defaultImage: { browser: BROWSER_IMAGE },
@@ -126,8 +134,20 @@ export const PROVIDERS = [
126
134
  label: "Kernel",
127
135
  keys: [{ name: "KERNEL_API_KEY", required: true }],
128
136
  mounts: [],
137
+ network: ["open"],
129
138
  metered: true,
130
139
  capabilities: [{ kind: "browser", groups: ["cdp", "stream"] }],
131
140
  defaultImage: { browser: BROWSER_IMAGE },
132
141
  }),
142
+ // This machine's Chrome: no key, nothing billed, no live view (a person watching runs it headed).
143
+ entry({
144
+ id: "local",
145
+ label: "Local Chrome",
146
+ keys: [],
147
+ mounts: [],
148
+ network: ["open", "allow"],
149
+ metered: false,
150
+ capabilities: [{ kind: "browser", groups: ["cdp"] }],
151
+ defaultImage: { browser: BROWSER_IMAGE },
152
+ }),
133
153
  ];
package/dist/labels.d.ts CHANGED
@@ -5,6 +5,12 @@ export { epochProblem };
5
5
  export declare const RUN_LABEL = "agentrun.run";
6
6
  /** The claim epoch of the run's runner that made the computer, in decimal. */
7
7
  export declare const EPOCH_LABEL = "agentrun.epoch";
8
+ /** The run label's hash (runHash), listed in place of RUN_LABEL by a provider that keeps only the hash and is listed
9
+ * with no run label to match. */
10
+ export declare const RUN_HASH_LABEL = "agentrun.run.hash";
11
+ /** The run label's hash, as a provider keeps it where the run itself doesn't fit (a computer's name): base32 of its
12
+ * sha256, lower case, 16 letters. */
13
+ export declare function runHash(run: string): string;
8
14
  /**
9
15
  * Why run is not a run id, in words, or undefined when it is one: a non-empty string with no NUL byte. That is the
10
16
  * strictest rule the providers share for a label's value (Docker, Daytona and Modal each refuse only a NUL), so every
package/dist/labels.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // The run and its claim epoch, as two labels every computer of a run carries. The claim epoch is the one fence for runs
2
2
  // and computers: a new claim is epoch + 1, and it releases every computer of the run labelled with a lower epoch
3
- // (releaseOlder, in janitor.ts). Both names live here alone.
3
+ // (releaseOlder, in janitor.ts). Both names live here alone, with the run label's hash: a provider whose computers keep
4
+ // only that (Orgo's names) lists it under RUN_HASH_LABEL, so a caller can still tell whose run a computer is.
5
+ import { createHash } from "node:crypto";
4
6
  import { epochProblem } from "./mount.js";
5
7
  import { fail, ok } from "./result.js";
6
8
  export { epochProblem };
@@ -8,6 +10,29 @@ export { epochProblem };
8
10
  export const RUN_LABEL = "agentrun.run";
9
11
  /** The claim epoch of the run's runner that made the computer, in decimal. */
10
12
  export const EPOCH_LABEL = "agentrun.epoch";
13
+ /** The run label's hash (runHash), listed in place of RUN_LABEL by a provider that keeps only the hash and is listed
14
+ * with no run label to match. */
15
+ export const RUN_HASH_LABEL = "agentrun.run.hash";
16
+ /** The run label's hash, as a provider keeps it where the run itself doesn't fit (a computer's name): base32 of its
17
+ * sha256, lower case, 16 letters. */
18
+ export function runHash(run) {
19
+ const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
20
+ const bytes = createHash("sha256").update(run, "utf8").digest();
21
+ let bits = 0;
22
+ let value = 0;
23
+ let out = "";
24
+ for (const byte of bytes) {
25
+ value = (value << 8) | byte;
26
+ bits += 8;
27
+ while (bits >= 5 && out.length < 16) {
28
+ out += alphabet[(value >>> (bits - 5)) & 31];
29
+ bits -= 5;
30
+ }
31
+ if (out.length >= 16)
32
+ break;
33
+ }
34
+ return out;
35
+ }
11
36
  /** An epoch as a label holds it: decimal digits, no sign, no leading zero, no space. */
12
37
  const EPOCH_TEXT = /^(?:0|[1-9][0-9]*)$/;
13
38
  /**
@@ -0,0 +1,51 @@
1
+ /** The browser's record, written by local.ts before the supervisor starts: the label a list finds it by. */
2
+ export declare const BROWSER_FILE = "browser.json";
3
+ /** What the supervisor writes once Chrome answers: the pids and ports a connect and a release read. */
4
+ export declare const STATE_FILE = "state.json";
5
+ /** The supervisor's own pid, written as it starts. */
6
+ export declare const SUPERVISOR_FILE = "supervisor.pid";
7
+ /** Chrome's pid, written as soon as it is spawned: a release finds a Chrome whose supervisor died before it answered. */
8
+ export declare const CHROME_PID_FILE = "chrome.pid";
9
+ /** Chrome's profile, fresh per browser. */
10
+ export declare const PROFILE_DIR = "profile";
11
+ /** The egress proxy's socket: short, since a Unix socket's path holds 107 bytes at most. */
12
+ export declare const EGRESS_SOCKET_FILE = "e.sock";
13
+ export declare const CHROME_LOG = "chrome.log";
14
+ export declare const EGRESS_LOG = "egress.log";
15
+ /** 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). */
16
+ export declare const BROWSER_MAX_TUNNELS = 128;
17
+ export declare const BROWSER_MAX_CONNECTIONS = 100000;
18
+ /** How long Chrome has to answer on its debugging port. */
19
+ export declare const READY_MS = 20000;
20
+ /** What local.ts writes in browser.json. */
21
+ export interface BrowserRecord {
22
+ provider: "local";
23
+ id: string;
24
+ labels: Record<string, string>;
25
+ /** ISO times. */
26
+ created: string;
27
+ deadline: string;
28
+ executablePath: string;
29
+ /** Every argument but the fence, the profile, the debugging port and the page: CHROME_FLAGS, headless, the window. */
30
+ args: string[];
31
+ /** The spec's allowlist (parseAllow's), when its network is one: the proxy reaches only these hosts. Absent: open. */
32
+ allow?: string[];
33
+ }
34
+ /** What the supervisor writes in state.json. */
35
+ export interface BrowserState {
36
+ supervisor: number;
37
+ pid: number;
38
+ port: number;
39
+ /** The browser's DevTools path, /devtools/browser/<id>: with the port, the CDP URL. */
40
+ path: string;
41
+ relay: number;
42
+ }
43
+ /** The line the supervisor writes on stdout: ready, or why not. */
44
+ export type SupervisorLine = {
45
+ ready: true;
46
+ } | {
47
+ failed: string;
48
+ sandbox?: boolean;
49
+ };
50
+ /** Supervises the browser in `dir` until it ends; the process exits then. */
51
+ export declare function supervise(dir: string, out: (line: SupervisorLine) => void): Promise<never>;
@@ -0,0 +1,221 @@
1
+ // One local browser's supervisor: a detached Node process of its own per browser (local.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.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.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
+ }
@@ -0,0 +1,89 @@
1
+ import type { KindCapabilities } from "./kinds.js";
2
+ import type { MountKind } from "./mount.js";
3
+ import type { AttachedComputer, CallContext, ComputerCapabilities, ComputerConnection, ComputerInfo, ComputerProvider, ComputerRef, ComputerSpec, CreatedComputer, NetworkForm, NetworkPolicy, NetworkSpec, Refusal } from "./provider.js";
4
+ import { type Result } from "./result.js";
5
+ /** The longest a local browser lives: a day, as pi-browser's local Chrome. */
6
+ export declare const LOCAL_MAX_LIFETIME_MS: number;
7
+ /** A browser takes no mount. */
8
+ export declare const MOUNT: readonly MountKind[];
9
+ /** The networks a local browser runs on, through its egress proxy: public addresses ("open"), or only the hosts of a list
10
+ * ("allow"), public ones still. It cannot have none: a browser with no network has nothing to do. */
11
+ export declare const NETWORK: readonly NetworkForm[];
12
+ /** A spec's network as this browser's proxy takes it: open (no list), a list (parseAllow's), or why it can't. */
13
+ export declare function browserNetworkOf(network: unknown): {
14
+ allow?: string[];
15
+ } | {
16
+ problem: string;
17
+ };
18
+ /** The one configuration it offers: a browser with a CDP target. No live view: a person watching runs it headed. */
19
+ export declare const CAPABILITIES: readonly KindCapabilities[];
20
+ export interface LocalBrowserOptions {
21
+ /** The Chrome or Chromium to run; default the one findChrome finds in `env`, then in the usual places. */
22
+ executablePath?: string;
23
+ /**
24
+ * Where CHROME_PATH, PI_BROWSER_CHROME and PATH are read when no executablePath is given: the host's environment, which
25
+ * it passes (serve passes its own). The library reads none.
26
+ */
27
+ env?: Readonly<Record<string, string | undefined>>;
28
+ /** Shows the window, for a person watching on this machine; default headless. */
29
+ headed?: boolean;
30
+ /** Where the browsers' directories go; default <tmpdir>/agentrun-local-browser-<uid>. Made 0700, and refused when another user can write it. */
31
+ root?: string;
32
+ /** The user this process runs as: a test's seam. */
33
+ uid?: number;
34
+ }
35
+ /** Computers that are this machine's Chrome. */
36
+ export declare class LocalBrowserProvider implements ComputerProvider {
37
+ #private;
38
+ readonly id = "local";
39
+ readonly version: string;
40
+ readonly root: string;
41
+ constructor({ executablePath, env, headed, root, uid }?: LocalBrowserOptions);
42
+ /**
43
+ * A browser: our supervisor ends it at its deadline, and list reads that deadline, so the janitor sweeps one whose
44
+ * supervisor is gone (lifetime janitor); it reaches public addresses only, through its egress proxy (network open), or
45
+ * only a list's hosts among them (network allow);
46
+ * it runs on this host, as this user, isolated by Chrome's sandbox alone (isolation host).
47
+ */
48
+ capabilities(): ComputerCapabilities;
49
+ /** The Chrome this provider runs: the option's, else one found; null when there is none. */
50
+ executable(): string | null;
51
+ check(spec: ComputerSpec): Refusal[];
52
+ /** Starts Chrome under a supervisor of its own, waits until its DevTools socket answers, and hands back its ref. */
53
+ create(spec: ComputerSpec, { signal }?: {
54
+ signal?: AbortSignal;
55
+ }): Promise<Result<CreatedComputer>>;
56
+ /**
57
+ * Settings' test: finds the Chrome and starts it once, headless, on a blank page, with its sandbox on (chrome.ts
58
+ * checkChrome), with a proxy that reaches nothing. No browser is kept and no key is read; no Chrome, root, or a Chrome
59
+ * that cannot start its sandbox is said in words.
60
+ */
61
+ testConnection(_context?: CallContext): Promise<Result<{
62
+ detail: string;
63
+ }>>;
64
+ /** Every browser with these labels: running while its Chrome runs, stopped once it does not (its files not yet removed). */
65
+ list(labels: Record<string, string>, _context?: CallContext): Promise<Result<ComputerInfo[]>>;
66
+ attach(ref: {
67
+ id: string;
68
+ } | {
69
+ labels: Record<string, string>;
70
+ }, _context?: CallContext): Promise<Result<AttachedComputer>>;
71
+ /** 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. */
72
+ network(ref: ComputerRef, policy?: NetworkSpec, _context?: CallContext): Promise<Result<NetworkPolicy>>;
73
+ /**
74
+ * The browser's DevTools URL, ws://127.0.0.1:<port>/devtools/browser/<id>, once the socket on that port answers with
75
+ * the path this browser's Chrome wrote; and a client that answers hello and ping. The URL bears no secret, but the
76
+ * socket takes any local client: it is the browser.
77
+ */
78
+ connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
79
+ /**
80
+ * Ends the browser and removes its files: its supervisor is asked to end it (SIGTERM), and whatever is left once it
81
+ * has gone (a supervisor already gone, a Chrome it did not end) is ended and removed here. A browser already gone is
82
+ * released; done means its directory is gone.
83
+ */
84
+ release(ref: ComputerRef, how: "stop" | "delete", _context?: CallContext): Promise<Result<void>>;
85
+ }
86
+ /** The provider, built from its options alone: no key, and no environment read but the `env` it is given. */
87
+ export declare function create(options?: LocalBrowserOptions): LocalBrowserProvider;
88
+ /** The conformance CLI's module for the local browser: its live switch, its image and its notes. */
89
+ export declare const conformance: () => Promise<typeof import("./conformance/local.js")>;