@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
package/dist/browser.js CHANGED
@@ -3,10 +3,10 @@
3
3
  // URL, which a driver dials. That URL and the live view's are secrets: they live in memory (a UrlStore), and never reach
4
4
  // a ref, a list, an error's words or a report.
5
5
  import { randomBytes } from "node:crypto";
6
- import { checkLifetime } from "./provider.js";
7
- import { fail, ok } from "./result.js";
8
- /** The one image a browser computer runs: the vendor's own Chromium. */
9
- export const BROWSER_IMAGE = "chromium";
6
+ import { PROTOCOL_VERSION } from "./protocol.js";
7
+ import { checkGpu, checkLifetime } from "./provider.js";
8
+ import { errorOf, fail, ok } from "./result.js";
9
+ import { BROWSER_IMAGE } from "./descriptors/shared.js";
10
10
  /** A key's or a value's longest, in characters: what both vendors keep of a metadata entry. */
11
11
  const MAX_LABEL = 256;
12
12
  export const memoryUrls = () => {
@@ -15,24 +15,27 @@ export const memoryUrls = () => {
15
15
  };
16
16
  export const DEFAULT_CONFIRM = { polls: 6, intervalMs: 500 };
17
17
  export const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
- /** A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. */
19
- export function vendorFail(code, message, cause) {
20
- const failed = fail(code, message);
18
+ /**
19
+ * A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. With
20
+ * code vendor, vendor (the provider's id) names whose.
21
+ */
22
+ export function causedFail(code, message, cause, vendor) {
23
+ const failed = { ok: false, error: errorOf(code, message, vendor) };
21
24
  if (cause !== undefined && !failed.ok)
22
25
  Object.defineProperty(failed.error, "cause", { value: cause, enumerable: false });
23
26
  return failed;
24
27
  }
25
- /** The error a vendor call threw, behind a failure vendorFail made; undefined for any other. */
28
+ /** The error a vendor call threw, behind a failure causedFail made; undefined for any other. */
26
29
  export const causeOf = (result) => (result.ok ? undefined : result.error.cause);
27
- /** The code a vendor's HTTP status reads as. */
28
- export function statusCode(status, vendor) {
30
+ /** The code a vendor's HTTP status reads as: one of ours, or vendor. */
31
+ export function statusCode(status) {
29
32
  if (status === 401 || status === 403)
30
33
  return "denied";
31
34
  if (status === 404)
32
35
  return "not_found";
33
36
  if (status === 429)
34
37
  return "limit";
35
- return vendor;
38
+ return "vendor";
36
39
  }
37
40
  /** Why labels are not ones a browser provider writes into a vendor's metadata, in words; undefined when they are. */
38
41
  export function labelsProblem(labels) {
@@ -106,7 +109,7 @@ export async function recoverCreate(what, find, release, sleep) {
106
109
  }
107
110
  return words.join("; ");
108
111
  }
109
- const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels"]);
112
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "gpu"]);
110
113
  /**
111
114
  * The checks every browser provider makes before a vendor call: the image is chromium, the lifetime is within the
112
115
  * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, and no field a
@@ -132,6 +135,8 @@ export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
132
135
  else if (Object.hasOwn(labels, CREATE_LABEL))
133
136
  refusals.push({ field: "labels", message: `the label ${CREATE_LABEL} is the provider's own: each create writes it, so a lost create finds its browser` });
134
137
  }
138
+ // A browser declares no gpu: one asked is refused, in the words every provider shares.
139
+ refusals.push(...checkGpu(given.gpu, capabilities));
135
140
  for (const [field, value] of Object.entries(given)) {
136
141
  if (!SPEC_FIELDS.has(field) && value !== undefined)
137
142
  refusals.push({ field, message: `a ${vendor} browser does not take ${field}` });
@@ -139,7 +144,7 @@ export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
139
144
  return refusals;
140
145
  }
141
146
  /** hello for a browser: the provider's version, linux, kind browser and its groups. The vendor reports no arch. */
142
- export const browserHello = (version, groups) => ({ version, os: "linux", kind: "browser", arch: "unknown", groups: [...groups] });
147
+ export const browserHello = (version, groups) => ({ protocol: PROTOCOL_VERSION, version, os: "linux", kind: "browser", arch: "unknown", groups: [...groups] });
143
148
  /**
144
149
  * The client of a browser's connection: it answers hello, and ping from the vendor's own read of the session (gone
145
150
  * once it has ended); any other method is unsupported, in words, since a browser is driven over CDP.
@@ -213,15 +218,15 @@ export const plainCode = (code) => (typeof code === "string" && /^[a-z][a-z_.-]{
213
218
  const isAbort = (error) => error?.name === "AbortError";
214
219
  /**
215
220
  * A vendor call's thrown error as a result: aborted, or the code its status reads as, in words that name the call and the
216
- * status alone. The error itself rides along as the failure's hidden cause (vendorFail).
221
+ * status alone. The error itself rides along as the failure's hidden cause (causedFail). vendor is the provider's id.
217
222
  */
218
223
  export function vendorFailure(vendor, name, call, error) {
219
224
  if (isAbort(error))
220
- return vendorFail("aborted", `${name} ${call} was aborted`, error);
225
+ return causedFail("aborted", `${name} ${call} was aborted`, error, vendor);
221
226
  const status = error?.status;
222
- const code = typeof status === "number" ? statusCode(status, vendor) : vendor;
227
+ const code = typeof status === "number" ? statusCode(status) : "vendor";
223
228
  const words = error instanceof BrowserVendorError ? error.message : typeof status === "number" ? `${name} ${call} answered ${status}` : `${name} ${call} failed`;
224
- return vendorFail(code, words, error);
229
+ return causedFail(code, words, error, vendor);
225
230
  }
226
231
  /**
227
232
  * Why a vendor's CDP URL is not one to hand a driver, in words that never carry it; undefined when it is. It must be wss:
@@ -1,7 +1,7 @@
1
1
  import { type BrowserStream, type ReleaseConfirm, type UrlStore } from "./browser.js";
2
2
  import type { KindCapabilities } from "./kinds.js";
3
3
  import type { MountKind } from "./mount.js";
4
- import type { AttachedComputer, CallContext, ComputerCapabilities, ComputerConnection, ComputerInfo, ComputerProvider, ComputerRef, ComputerSpec, CreatedComputer, NetworkPolicy, NetworkSpec, 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
  export declare const BROWSERBASE_API_URL = "https://api.browserbase.com";
7
7
  /** The domain a Browserbase CDP URL is on (wss://connect.browserbase.com, read live 11-08): cdpUrlProblem holds it there. */
@@ -18,7 +18,7 @@ export declare const labelKey: (metadataKey: string) => string;
18
18
  export declare function browserbaseLabelsProblem(labels: unknown): string | undefined;
19
19
  /** A browser takes no mount. */
20
20
  export declare const MOUNT: readonly MountKind[];
21
- /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
21
+ /** The one configuration it offers, its descriptor's: a browser with a CDP target and a live view. */
22
22
  export declare const CAPABILITIES: readonly KindCapabilities[];
23
23
  /** A session as Browserbase answers it; only what the provider reads. */
24
24
  export interface BrowserbaseSession {
@@ -124,7 +124,7 @@ export declare class BrowserbaseProvider implements ComputerProvider {
124
124
  */
125
125
  connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
126
126
  /** Asks Browserbase to release the session and waits until it reads as ended; one already ended or unknown is released. */
127
- release(ref: ComputerRef, how: "stop" | "delete", { signal }?: CallContext): Promise<Result<void>>;
127
+ release(ref: ComputerRef, how: ReleaseHow, { signal }?: CallContext): Promise<Result<void>>;
128
128
  /** The session's live view, which takes input: a view-only one is refused, never handed over as one. */
129
129
  stream(ref: ComputerRef, options?: {
130
130
  viewOnly?: boolean;
@@ -15,9 +15,14 @@
15
15
  // label key of letters, digits and dots alone, so no label key holds an "_" and the mapping is one to one; a value with
16
16
  // ' or \ is refused too, since list's query quotes it.
17
17
  import { readFileSync } from "node:fs";
18
- import { cdpUrlProblem, BROWSER_IMAGE, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, httpsBase, idProblem, labelsOf, labelsProblem, memoryUrls, queryable, recoverCreate, releaseConfirmed, restCall, vendorFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
19
- import { fail, ok } from "./result.js";
18
+ import { BROWSERBASE } from "./descriptors/browserbase.js";
19
+ import { BROWSER_IMAGE } from "./descriptors/shared.js";
20
+ import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, httpsBase, idProblem, labelsOf, labelsProblem, memoryUrls, queryable, recoverCreate, releaseConfirmed, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
21
+ import { runLifetimeMs, } from "./provider.js";
22
+ import { failFor, ok, vendorFail } from "./result.js";
20
23
  import { connectionError } from "./test-connection.js";
24
+ /** This module's failures: one with code vendor names Browserbase. */
25
+ const fail = failFor("browserbase");
21
26
  const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
22
27
  const NAME = "Browserbase";
23
28
  export const BROWSERBASE_API_URL = "https://api.browserbase.com";
@@ -56,9 +61,9 @@ export function browserbaseLabelsProblem(labels) {
56
61
  return undefined;
57
62
  }
58
63
  /** A browser takes no mount. */
59
- export const MOUNT = [];
60
- /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
61
- export const CAPABILITIES = [{ kind: "browser", groups: ["cdp", "stream"] }];
64
+ export const MOUNT = BROWSERBASE.mounts;
65
+ /** The one configuration it offers, its descriptor's: a browser with a CDP target and a live view. */
66
+ export const CAPABILITIES = BROWSERBASE.capabilities;
62
67
  /** Browserbase's v1 REST API over fetch: the default api. */
63
68
  export function browserbaseRest({ apiKey, apiUrl = BROWSERBASE_API_URL, projectId, fetch: fetcher = fetch }) {
64
69
  const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Browserbase API URL"), headers: { "X-BB-API-Key": apiKey } };
@@ -138,7 +143,7 @@ export class BrowserbaseProvider {
138
143
  return {
139
144
  kind: "browser",
140
145
  lifetime: "vendor",
141
- network: ["open"],
146
+ network: [...BROWSERBASE.network],
142
147
  isolation: "vm",
143
148
  os: "linux",
144
149
  daemon: "none",
@@ -171,7 +176,7 @@ export class BrowserbaseProvider {
171
176
  const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
172
177
  const body = {
173
178
  ...settings,
174
- timeout: Math.ceil(spec.lifetimeMs / 1000),
179
+ timeout: Math.ceil(runLifetimeMs(spec) / 1000),
175
180
  keepAlive: true,
176
181
  userMetadata: toMetadata(written),
177
182
  ...(this.#projectId ? { projectId: this.#projectId } : {}),
@@ -185,16 +190,16 @@ export class BrowserbaseProvider {
185
190
  if (failed.ok || !createUncertain(error))
186
191
  return failed;
187
192
  // The session may have been made though its answer never came: found by its create label, never made again.
188
- return vendorFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed));
193
+ return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed), "browserbase");
189
194
  }
190
195
  if (idProblem(made?.id, NAME) !== undefined) {
191
- return fail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(written)}`);
196
+ return vendorFail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(written)}`);
192
197
  }
193
198
  const unusable = cdpUrlProblem(made.connectUrl, NAME, CDP_DOMAIN);
194
199
  if (unusable !== undefined) {
195
200
  // The session is made and billed (keepAlive, up to its timeout): released here, not left to a later sweep.
196
201
  const released = await this.release(refOf(made), "delete");
197
- return fail("browserbase", `Browserbase POST /v1/sessions made a session with no CDP URL to hand over: ${unusable}; ${released.ok ? "the session was released" : `the session was not released (${released.error.code}), and its labels let a sweep find it`}`);
202
+ return vendorFail("browserbase", `Browserbase POST /v1/sessions made a session with no CDP URL to hand over: ${unusable}; ${released.ok ? "the session was released" : `the session was not released (${released.error.code}), and its labels let a sweep find it`}`);
198
203
  }
199
204
  this.#urls.set(made.id, made.connectUrl);
200
205
  return ok(refOf(made));
@@ -342,7 +347,7 @@ export class BrowserbaseProvider {
342
347
  // Whatever held it (create, a read, a host's url store), a URL a driver would dial is wss: on Browserbase's own domain.
343
348
  const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
344
349
  if (unusable !== undefined)
345
- return fail("browserbase", `the Browserbase session ${id} is not handed over: ${unusable}`);
350
+ return vendorFail("browserbase", `the Browserbase session ${id} is not handed over: ${unusable}`);
346
351
  this.#urls.set(id, url);
347
352
  const hello = browserHello(VERSION, this.capabilities().groups);
348
353
  const client = browserClient(hello, (signal) => this.#alive(id, signal));
package/dist/child.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { ComputerCapabilities, ComputerConnection } from "./provider.js";
2
2
  import { type Result } from "./result.js";
3
+ /** Who ran install, from its output's `installer <uid> <name>[ sudo]` line, in words; undefined when it has none. */
4
+ export declare function installerOf(output: string): string | undefined;
3
5
  /** One string for a shell: `sh -c '<script>' sh '<arg>' ...`, every word quoted. */
4
6
  export declare const shellCommand: (script: string, args: readonly string[]) => string;
5
7
  export interface ChildCommandOptions {
package/dist/child.js CHANGED
@@ -15,7 +15,7 @@ const ROOT = 'p=; [ "$(id -u)" = 0 ] || p="sudo -n"';
15
15
  * coreutils alike; a trailing `.` (an SELinux label) is allowed, a `+` (an ACL) is not. */
16
16
  const HELD = 'held() { x=$1; while :; do set -- $(ls -ldn "$x" 2>/dev/null); case "$1" in ?????[!w]??[!w]?|?????[!w]??[!w]?.) ;; *) false ;; esac && [ "$3" = 0 ] || { echo "the daemon at $d is not root\'s alone: $x is ${1:-missing}, owner ${3:-none}"; return 1; }; [ "$x" = / ] && return 0; x=${x%/*}; x=${x:-/}; done; }';
17
17
  /** Installs the uploaded daemon root-owned and read-only to its user, makes its home and socket directory (init gives
18
- * them to the daemon's user), and prints the installed binary's sha256. As root, or through passwordless sudo; else
18
+ * them to the daemon's user), and prints who installed it and the installed binary's sha256. As root, or through passwordless sudo; else
19
19
  * it says why. The daemon's directory is made root's (0755) even when the image already had it, a stale entry at
20
20
  * the daemon's path is removed first, and the whole path is held to `held` before and after; a path another user can
21
21
  * change is refused with nothing installed. Every tool is in BusyBox and in coreutils alike: no privilege tool of the
@@ -31,8 +31,18 @@ const INSTALL_SCRIPT = [
31
31
  '$p mkdir -p "$b" "$h" "$r" && $p chown 0:0 "$b" && $p chmod 0755 "$b" && $p rm -f "$d" && $p install -m 0755 -o 0 -g 0 "$s" "$d" || { echo "installing the daemon at $d failed"; exit 5; }',
32
32
  'held "$d" || exit 6',
33
33
  'rm -f "$s"',
34
+ // Who installed it: the sandbox user's uid and name, and "sudo" when through passwordless sudo (installerOf).
35
+ 'echo "installer $(id -u) $(id -un 2>/dev/null || echo unnamed)${p:+ sudo}"',
34
36
  'echo "sha256 $($p sha256sum "$d" | cut -c1-64)"',
35
37
  ].join("\n");
38
+ /** Who ran install, from its output's `installer <uid> <name>[ sudo]` line, in words; undefined when it has none. */
39
+ export function installerOf(output) {
40
+ const found = /^installer (\d+) (\S+)( sudo)?$/m.exec(output);
41
+ if (found === null)
42
+ return undefined;
43
+ const [, uid, name, sudo] = found;
44
+ return `the daemon was installed by ${name} (uid ${uid})${sudo ? ", through passwordless sudo" : ", as root"}`;
45
+ }
36
46
  /** Starts init, the long-lived command, as root in a clean environment from its home: `init --user` gives HOME and the
37
47
  * socket's directory to the daemon's user, sets no_new_privs and empties every capability set on every thread, and
38
48
  * becomes that user with no groups. `--own-network` first cuts init and its programs off from the vendor's agent beside
@@ -79,7 +89,8 @@ const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value)
79
89
  * working directory and binary. Each read is bounded by timeoutMs and the caller's signal.
80
90
  */
81
91
  export async function daemonDrift(connection, expected, timeoutMs, signal) {
82
- const found = helloDrift(connection.hello, { version: expected.version, kind: expected.kind, groups: expected.groups, arch: expected.arch });
92
+ // childCommands starts init with --own-network: hello must say which fence holds its programs.
93
+ const found = helloDrift(connection.hello, { version: expected.version, kind: expected.kind, groups: expected.groups, arch: expected.arch, fence: true });
83
94
  const bounded = () => (signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs));
84
95
  const status = await connection.client.call("files.read", { path: "/proc/self/status" }, { signal: bounded() });
85
96
  if (!status.ok)
@@ -0,0 +1,73 @@
1
+ import { type Result } from "./result.js";
2
+ /** The environment names a Chrome is found by: pi-browser's own, then the common one. */
3
+ export declare const CHROME_ENV: readonly ["PI_BROWSER_CHROME", "CHROME_PATH"];
4
+ /**
5
+ * The Chrome or Chromium on this machine: the one PI_BROWSER_CHROME or CHROME_PATH names in `env`, else the first on
6
+ * env.PATH, else the first of the usual install places; null when there is none. `env` is the caller's: the library
7
+ * reads none.
8
+ */
9
+ export declare function findChrome(env?: Readonly<Record<string, string | undefined>>, exists?: (file: string) => boolean): string | null;
10
+ /** What to do when there is no Chrome, in words: what to install, and the settings that point at one. */
11
+ export declare const NO_CHROME = "no Chrome or Chromium was found on this machine: install Google Chrome or Chromium (on Debian or Ubuntu, `apt install chromium` or Google's google-chrome-stable package), or name the executable with the provider's executablePath option, or CHROME_PATH (or PI_BROWSER_CHROME) in the environment the host passes as its env option";
12
+ /**
13
+ * The switches every local Chrome starts with, beside the fence, its profile and its debugging port: no first-run
14
+ * screens, no sign-in or sync, no background traffic of Chrome's own (component updates, field trials, safe-browsing
15
+ * pings), no keychain prompt, no sound.
16
+ */
17
+ export declare const CHROME_FLAGS: readonly string[];
18
+ /**
19
+ * The arguments that hold a local Chrome to its egress proxy at `proxy` (an http URL of a loopback port, the relay to
20
+ * the proxy, which decides): every request through the proxy, loopback too (`<-loopback>` takes away the bypass Chrome
21
+ * gives it by default), so this machine's own services, private networks, link-local and a cloud's metadata address are
22
+ * each refused by the proxy after its lookup; no name or address resolved by Chrome itself but the proxy's, so a request
23
+ * a page sends around the proxy reaches nothing; no QUIC, which goes around an HTTP proxy; and WebRTC on no UDP but the
24
+ * proxy's, which carries none, so no ICE candidate is gathered and no STUN packet leaves. That last is
25
+ * `--webrtc-ip-handling-policy`: Chrome 155 and 156 ignore the `--force-` spelling (#1718 measured a STUN server on
26
+ * loopback sent its binding requests under it). From #1718's chromeFence, less the bypass it kept for the DevTools guard
27
+ * Stagehand's extension dialled: nothing in this browser reaches its own DevTools socket.
28
+ */
29
+ export declare function chromeFence(proxy: string): string[];
30
+ /** Signal 0 only asks; EPERM means the process exists under another user. */
31
+ export declare const alive: (pid: number) => boolean;
32
+ /** Whether `pid` leads its own process group (a detached child does); null where there is no /proc to ask. */
33
+ export declare function leadsOwnGroup(pid: number): boolean | null;
34
+ /**
35
+ * Kills `pid` and its group. A pid reaches here from a file a restart reads back: `kill(-1)` signals every process the
36
+ * user can, `kill(0)` this process's own group, so neither a pid below 2 nor our own is ever signalled, and a negative
37
+ * pid (a whole group) only for a process that leads one.
38
+ */
39
+ export declare function killTree(pid: number, io?: {
40
+ kill?: (pid: number, signal: NodeJS.Signals) => void;
41
+ leadsGroup?: (pid: number) => boolean | null;
42
+ }, signal?: NodeJS.Signals): void;
43
+ /**
44
+ * Whether `pid` is a process whose command line holds `marker` (a Chrome's `--user-data-dir=<profile>`, a supervisor's
45
+ * directory), so a pid read back from a file never names a recycled process. Where there is no /proc to ask (macOS),
46
+ * whether it is alive.
47
+ */
48
+ export declare function runsWith(pid: number, marker: string): boolean;
49
+ /** The port and browser path a Chrome on `profile` wrote to its DevToolsActivePort: only that Chrome writes it there. */
50
+ export declare function ownDebugger(profile: string): Promise<{
51
+ port: number;
52
+ path: string;
53
+ } | null>;
54
+ /** The browser path the DevTools socket on `port` answers /json/version with, or null; bounded, so a socket that takes the connection and never answers holds no one. */
55
+ export declare function answeringPath(port: number, timeoutMs?: number): Promise<string | null>;
56
+ /** Chrome's singleton socket directory under the temp directory outlives every Chrome exit; the profile's link names it. */
57
+ export declare function singletonDir(profile: string): Promise<string | null>;
58
+ /** What a start whose Chrome could not start its sandbox is told: never to turn it off, which nothing here can. */
59
+ export declare const NO_SANDBOX = "this machine's Chrome could not start its sandbox, and the local browser never runs Chrome without it, so no browser was started: on Ubuntu 23.10 and later give this Chrome an AppArmor profile that allows it user namespaces, or use a Chrome whose setuid sandbox helper is installed (Google's package installs one)";
60
+ /** What a start as root is told: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. */
61
+ export declare const AS_ROOT = "the local browser does not start Chrome as root: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. Run AgentRun as a user that is not root";
62
+ /** How long the sandbox check may take: one headless Chrome that loads a blank page and exits. */
63
+ export declare const CHECK_MS = 30000;
64
+ /**
65
+ * Whether the Chrome at `path` starts here with its sandbox on: an executable file, a user that is not root, and one
66
+ * headless start on a blank page (`--dump-dom about:blank`) in a profile of its own that goes with it, with a proxy no
67
+ * name or address reaches, so nothing leaves the machine. ok with the resolved path; refused in words that never offer
68
+ * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam).
69
+ */
70
+ export declare function checkChrome(path: string, { uid, timeoutMs }?: {
71
+ uid?: number;
72
+ timeoutMs?: number;
73
+ }): Promise<Result<string>>;
package/dist/chrome.js ADDED
@@ -0,0 +1,224 @@
1
+ // Launching a Chrome on this machine, the pieces the local browser (local-chrome.ts, local-supervisor.ts) is made of. Moved
2
+ // here from pi-browser, which starts its own local Chrome (packages/pi-browser/src/providers/chrome-args.ts findChrome, and
3
+ // src/providers/cdp.ts alive, leadsOwnGroup, killTree, ownDebugger and singletonDir), so pi-browser can import them back
4
+ // once it depends on this package; and the fence and sandbox check of PR #1718's local Chrome for serve
5
+ // (packages/serve/src/local-chrome.ts chromeFence and checkChrome), less what was there for Stagehand's extension.
6
+ //
7
+ // The library reads no environment: where pi-browser read CHROME_PATH and PATH from process.env, findChrome takes the
8
+ // environment it is given.
9
+ import { spawn } from "node:child_process";
10
+ import { constants, existsSync, readFileSync } from "node:fs";
11
+ import { access, mkdtemp, readFile, readlink, rm, stat } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
14
+ import { fail, ok } from "./result.js";
15
+ /** The names a Chrome or Chromium goes by on a Linux PATH. */
16
+ const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
17
+ /** Where a Chrome is installed when no PATH names it: Linux's packages, macOS's and Windows' installers. */
18
+ const FIXED = [
19
+ "/usr/bin/google-chrome",
20
+ "/usr/bin/chromium",
21
+ "/usr/bin/chromium-browser",
22
+ "/opt/google/chrome/chrome",
23
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
24
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
25
+ ];
26
+ /** The environment names a Chrome is found by: pi-browser's own, then the common one. */
27
+ export const CHROME_ENV = ["PI_BROWSER_CHROME", "CHROME_PATH"];
28
+ /**
29
+ * The Chrome or Chromium on this machine: the one PI_BROWSER_CHROME or CHROME_PATH names in `env`, else the first on
30
+ * env.PATH, else the first of the usual install places; null when there is none. `env` is the caller's: the library
31
+ * reads none.
32
+ */
33
+ export function findChrome(env = {}, exists = existsSync) {
34
+ for (const name of CHROME_ENV) {
35
+ const named = env[name];
36
+ if (named && exists(named))
37
+ return named;
38
+ }
39
+ const onPath = (env.PATH ?? "")
40
+ .split(delimiter)
41
+ .filter(Boolean)
42
+ .flatMap((dir) => LINUX_NAMES.map((name) => join(dir, name)));
43
+ return [...onPath, ...FIXED].find((file) => exists(file)) ?? null;
44
+ }
45
+ /** What to do when there is no Chrome, in words: what to install, and the settings that point at one. */
46
+ export const NO_CHROME = "no Chrome or Chromium was found on this machine: install Google Chrome or Chromium (on Debian or Ubuntu, `apt install chromium` or Google's google-chrome-stable package), or name the executable with the provider's executablePath option, or CHROME_PATH (or PI_BROWSER_CHROME) in the environment the host passes as its env option";
47
+ /**
48
+ * The switches every local Chrome starts with, beside the fence, its profile and its debugging port: no first-run
49
+ * screens, no sign-in or sync, no background traffic of Chrome's own (component updates, field trials, safe-browsing
50
+ * pings), no keychain prompt, no sound.
51
+ */
52
+ export const CHROME_FLAGS = [
53
+ "--no-first-run",
54
+ "--no-default-browser-check",
55
+ "--disable-background-networking",
56
+ "--disable-component-update",
57
+ "--disable-sync",
58
+ "--disable-default-apps",
59
+ "--disable-client-side-phishing-detection",
60
+ "--disable-domain-reliability",
61
+ "--metrics-recording-only",
62
+ "--password-store=basic",
63
+ "--use-mock-keychain",
64
+ "--mute-audio",
65
+ "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,AutofillServerCommunication",
66
+ ];
67
+ /**
68
+ * The arguments that hold a local Chrome to its egress proxy at `proxy` (an http URL of a loopback port, the relay to
69
+ * the proxy, which decides): every request through the proxy, loopback too (`<-loopback>` takes away the bypass Chrome
70
+ * gives it by default), so this machine's own services, private networks, link-local and a cloud's metadata address are
71
+ * each refused by the proxy after its lookup; no name or address resolved by Chrome itself but the proxy's, so a request
72
+ * a page sends around the proxy reaches nothing; no QUIC, which goes around an HTTP proxy; and WebRTC on no UDP but the
73
+ * proxy's, which carries none, so no ICE candidate is gathered and no STUN packet leaves. That last is
74
+ * `--webrtc-ip-handling-policy`: Chrome 155 and 156 ignore the `--force-` spelling (#1718 measured a STUN server on
75
+ * loopback sent its binding requests under it). From #1718's chromeFence, less the bypass it kept for the DevTools guard
76
+ * Stagehand's extension dialled: nothing in this browser reaches its own DevTools socket.
77
+ */
78
+ export function chromeFence(proxy) {
79
+ const { hostname, port } = new URL(proxy);
80
+ return [
81
+ `--proxy-server=${proxy}`,
82
+ "--proxy-bypass-list=<-loopback>",
83
+ `--host-resolver-rules=MAP ${hostname}:${port} ${hostname}:${port}, MAP * ~NOTFOUND`,
84
+ "--disable-quic",
85
+ "--webrtc-ip-handling-policy=disable_non_proxied_udp",
86
+ ];
87
+ }
88
+ /** Signal 0 only asks; EPERM means the process exists under another user. */
89
+ export const alive = (pid) => {
90
+ try {
91
+ process.kill(pid, 0);
92
+ return true;
93
+ }
94
+ catch (error) {
95
+ return error.code === "EPERM";
96
+ }
97
+ };
98
+ /** Whether `pid` leads its own process group (a detached child does); null where there is no /proc to ask. */
99
+ export function leadsOwnGroup(pid) {
100
+ if (process.platform !== "linux")
101
+ return null;
102
+ try {
103
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
104
+ // pid (comm) state ppid pgrp ...: the name may hold spaces and brackets, so the fields are counted from its last ")".
105
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[2]) === pid;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ /**
112
+ * Kills `pid` and its group. A pid reaches here from a file a restart reads back: `kill(-1)` signals every process the
113
+ * user can, `kill(0)` this process's own group, so neither a pid below 2 nor our own is ever signalled, and a negative
114
+ * pid (a whole group) only for a process that leads one.
115
+ */
116
+ export function killTree(pid, io = {}, signal = "SIGKILL") {
117
+ if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid)
118
+ return;
119
+ const kill = io.kill ?? ((target, how) => process.kill(target, how));
120
+ if ((io.leadsGroup ?? leadsOwnGroup)(pid) !== false) {
121
+ try {
122
+ return kill(-pid, signal);
123
+ }
124
+ catch {
125
+ /* no such group: the process alone */
126
+ }
127
+ }
128
+ try {
129
+ kill(pid, signal);
130
+ }
131
+ catch {
132
+ /* already gone */
133
+ }
134
+ }
135
+ /**
136
+ * Whether `pid` is a process whose command line holds `marker` (a Chrome's `--user-data-dir=<profile>`, a supervisor's
137
+ * directory), so a pid read back from a file never names a recycled process. Where there is no /proc to ask (macOS),
138
+ * whether it is alive.
139
+ */
140
+ export function runsWith(pid, marker) {
141
+ if (!Number.isInteger(pid) || pid <= 1)
142
+ return false;
143
+ if (process.platform !== "linux")
144
+ return alive(pid);
145
+ try {
146
+ // Chrome rewrites its own process title: its arguments then read as one string, joined by spaces.
147
+ const words = ` ${readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ")} `;
148
+ return words.includes(` ${marker} `);
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
154
+ /** The port and browser path a Chrome on `profile` wrote to its DevToolsActivePort: only that Chrome writes it there. */
155
+ export async function ownDebugger(profile) {
156
+ const [port, browser] = (await readFile(join(profile, "DevToolsActivePort"), "utf8").catch(() => "")).split("\n");
157
+ return /^\d+$/.test(port ?? "") && browser?.startsWith("/devtools/browser/") ? { port: Number(port), path: browser.trim() } : null;
158
+ }
159
+ /** The browser path the DevTools socket on `port` answers /json/version with, or null; bounded, so a socket that takes the connection and never answers holds no one. */
160
+ export async function answeringPath(port, timeoutMs = 2_000) {
161
+ try {
162
+ const reply = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeoutMs) }); // key-gate: loopback-rule the local Chrome's own DevTools socket
163
+ const url = (await reply.json()).webSocketDebuggerUrl;
164
+ return typeof url === "string" ? new URL(url).pathname : null;
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ /** Chrome's singleton socket directory under the temp directory outlives every Chrome exit; the profile's link names it. */
171
+ export async function singletonDir(profile) {
172
+ const socket = await readlink(join(profile, "SingletonSocket")).catch(() => null);
173
+ const dir = socket && basename(socket) === "SingletonSocket" ? dirname(socket) : null;
174
+ return dir && /^\.?(org\.chromium\.Chromium|com\.google\.Chrome)\.[A-Za-z0-9]{6}$/.test(basename(dir)) ? dir : null;
175
+ }
176
+ /** What a start whose Chrome could not start its sandbox is told: never to turn it off, which nothing here can. */
177
+ export const NO_SANDBOX = "this machine's Chrome could not start its sandbox, and the local browser never runs Chrome without it, so no browser was started: on Ubuntu 23.10 and later give this Chrome an AppArmor profile that allows it user namespaces, or use a Chrome whose setuid sandbox helper is installed (Google's package installs one)";
178
+ /** What a start as root is told: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. */
179
+ export const AS_ROOT = "the local browser does not start Chrome as root: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. Run AgentRun as a user that is not root";
180
+ /** How long the sandbox check may take: one headless Chrome that loads a blank page and exits. */
181
+ export const CHECK_MS = 30_000;
182
+ /**
183
+ * Whether the Chrome at `path` starts here with its sandbox on: an executable file, a user that is not root, and one
184
+ * headless start on a blank page (`--dump-dom about:blank`) in a profile of its own that goes with it, with a proxy no
185
+ * name or address reaches, so nothing leaves the machine. ok with the resolved path; refused in words that never offer
186
+ * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam).
187
+ */
188
+ export async function checkChrome(path, { uid = process.getuid?.(), timeoutMs = CHECK_MS } = {}) {
189
+ const at = resolve(path);
190
+ const runs = (await stat(at).then((info) => info.isFile(), () => false)) && (await access(at, constants.X_OK).then(() => true, () => false));
191
+ if (!runs)
192
+ return fail("not_found", `${at} is not an executable file: name a Chrome or Chromium binary with the executablePath option, or leave it out to look in the usual places`);
193
+ if (uid === 0)
194
+ return fail("refused", AS_ROOT);
195
+ // A short directory: Chrome's singleton socket must stay within a Unix socket's 107 bytes.
196
+ const dir = await mkdtemp(join(existsSync("/tmp") ? "/tmp" : tmpdir(), "agentrun-chrome-check-"));
197
+ const profile = join(dir, "profile");
198
+ try {
199
+ const said = await new Promise((done) => {
200
+ const child = spawn(at, ["--headless=new", `--user-data-dir=${profile}`, "--no-first-run", "--proxy-server=http://agentrun-check.invalid:9", "--host-resolver-rules=MAP * ~NOTFOUND", "--dump-dom", "about:blank"], {
201
+ stdio: ["ignore", "ignore", "pipe"],
202
+ timeout: timeoutMs,
203
+ killSignal: "SIGKILL",
204
+ });
205
+ let stderr = "";
206
+ child.stderr.on("data", (chunk) => void (stderr = (stderr + chunk).slice(-8_192)));
207
+ child.once("error", (error) => done({ code: null, signal: null, stderr: error.message }));
208
+ child.once("exit", (code, signal) => done({ code, signal, stderr }));
209
+ });
210
+ if (said.code === 0)
211
+ return ok(at);
212
+ // Chrome's own words name the sandbox and go on to offer --no-sandbox: only the first are passed on.
213
+ if (/No usable sandbox|sandbox/i.test(said.stderr))
214
+ return fail("refused", `${at} did not start with its sandbox on (No usable sandbox): ${NO_SANDBOX}`);
215
+ const why = said.signal ? `it ended on ${said.signal}` : `it exited ${said.code ?? "without starting"}`;
216
+ return fail("refused", `${at} did not start here (${why}), so no local browser can start on it`);
217
+ }
218
+ finally {
219
+ const socket = await singletonDir(profile);
220
+ if (socket)
221
+ await rm(socket, { recursive: true, force: true }).catch(() => undefined);
222
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
223
+ }
224
+ }
Binary file
Binary file
@@ -4,7 +4,7 @@
4
4
  // reads no environment: this module reads its own COMPUTER_BROWSERBASE_* names (never BROWSERBASE_API_KEY, which may
5
5
  // hold another project's key) and passes each to create() as its option. The live switch is checked first, before any
6
6
  // other setting is read. The run makes one session, shared by every case, and releases it.
7
- import { BROWSER_IMAGE } from "../browser.js";
7
+ import { BROWSER_IMAGE } from "../descriptors/shared.js";
8
8
  import { create } from "../browserbase.js";
9
9
  /** The environment this module reads, by name, each for the option its comment names, and the live switch. */
10
10
  export const BROWSERBASE_ENV = {
@@ -0,0 +1,2 @@
1
+ import type { Case } from "../types.js";
2
+ export declare const gpuCases: Case[];