@howaboua/pi-browser 0.0.15 → 0.0.17

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @howaboua/pi-browser
2
2
 
3
+ ## 0.0.17
4
+
5
+ - On Linux, `start` uses the graphical desktop's configured default browser instead of falling back to Chromium. `CDP_BROWSER` still overrides browser selection.
6
+
7
+ ## 0.0.16
8
+
9
+ - Shortened browser timeout and tab-creation errors. They say what may have happened and what to check before retrying.
10
+
3
11
  ## 0.0.15
4
12
 
5
13
  - Browser settings clarify which listed host runs locally and where to set the Node.js executable for SSH hosts.
package/README.md CHANGED
@@ -10,7 +10,7 @@ The extension is the TypeScript counterpart of Pi Codex's browser custom tool. I
10
10
  pi install npm:@howaboua/pi-browser
11
11
  ```
12
12
 
13
- Requires Pi 1.0.0 or newer, Node.js 22.19 or newer, and a Chrome-family browser with remote debugging enabled at `chrome://inspect/#remote-debugging`.
13
+ Requires the latest Pi release, Node.js 22.19 or newer, and a Chrome-family browser with remote debugging enabled at `chrome://inspect/#remote-debugging`.
14
14
 
15
15
  Pi Codex 3.0.52 or newer is optional. Without it, Browser remains a normal top-level Pi tool. Do not load Pi Codex's example `browser.toml` custom tool alongside this extension.
16
16
 
@@ -50,7 +50,9 @@ The browser tool is unavailable to the agent, while voice startup and `/browser`
50
50
 
51
51
  The tool discovers CDP through `CDP_PORT`, port 9222, or `DevToolsActivePort`. Set `CDP_PORT_FILE` for a non-standard port file.
52
52
 
53
- The `start` action runs on the selected host and can launch Chromium through a Linux systemd user session. Override the executable with `CDP_BROWSER` and the profile with `CDP_PROFILE_DIRECTORY`. On other systems, start the browser normally with remote debugging enabled.
53
+ The `start` action reuses a browser already listening on the configured CDP port. On Linux with a systemd user session, it uses `xdg-settings` to find the graphical desktop's default browser on the selected host. Over SSH, the host's systemd user session must know the graphical desktop environment. The action uses the browser's desktop launch command without creating a separate profile. A browser that does not support CDP may open, but the action reports success only when CDP responds.
54
+
55
+ Set `CDP_BROWSER` to explicitly choose a compatible executable and `CDP_PROFILE_DIRECTORY` to select a profile. If automatic startup is unsupported or the browser does not expose CDP, start the browser normally and enable remote debugging.
54
56
 
55
57
  ## Boundaries
56
58
 
@@ -12,7 +12,7 @@ import { spawn as spawn3 } from "node:child_process";
12
12
  import { chmod, lstat as lstat2, mkdir as mkdir4, rm as rm4 } from "node:fs/promises";
13
13
  import { createConnection, createServer } from "node:net";
14
14
  import { tmpdir as tmpdir2 } from "node:os";
15
- import { dirname as dirname2, join as join6 } from "node:path";
15
+ import { dirname as dirname2, join as join7 } from "node:path";
16
16
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
17
17
 
18
18
  // src/cdp/actions/key.ts
@@ -635,7 +635,7 @@ function loadBrowserRoutes(path, currentHostname = hostname()) {
635
635
 
636
636
  // src/browser/runtime.ts
637
637
  import { randomUUID } from "node:crypto";
638
- import { join as join5 } from "node:path";
638
+ import { join as join6 } from "node:path";
639
639
 
640
640
  // src/cdp/serial.ts
641
641
  function waitForTurn(promise, signal) {
@@ -841,10 +841,10 @@ function cdpTimeoutAttempts(method) {
841
841
  function timeoutError(method, attempts) {
842
842
  const seconds = CDP_TIMEOUT_MS / 1000;
843
843
  if (attempts > 1) {
844
- return new Error(`Chrome did not answer ${method} after two ${seconds}s attempts. The tab may be unresponsive or suspended.`);
844
+ return new Error(`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`);
845
845
  }
846
846
  if (method === "Runtime.evaluate") {
847
- return new Error(`Chrome did not answer Runtime.evaluate within ${seconds}s. The expression or awaited promise may still be running; check its effect before retrying.`);
847
+ return new Error(`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`);
848
848
  }
849
849
  return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
850
850
  }
@@ -1342,7 +1342,7 @@ class BrowserTabs {
1342
1342
  try {
1343
1343
  response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
1344
1344
  } catch (error) {
1345
- throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
1345
+ throw new Error(`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`);
1346
1346
  }
1347
1347
  if (typeof response["targetId"] !== "string")
1348
1348
  throw new Error("Chrome did not return a new tab target; run tabs before retrying");
@@ -1350,7 +1350,7 @@ class BrowserTabs {
1350
1350
  try {
1351
1351
  await this.remember(created);
1352
1352
  } catch (error) {
1353
- throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
1353
+ throw new Error(`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`);
1354
1354
  }
1355
1355
  return created;
1356
1356
  }, signal);
@@ -1821,7 +1821,7 @@ function browserHelp(hosts = []) {
1821
1821
  type: "ref_id text id?; id focuses",
1822
1822
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
1823
1823
  press: "ref_id key; focused element, e.g. Enter or Control+a",
1824
- wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
1824
+ wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
1825
1825
  screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
1826
1826
  navigate: "ref_id url",
1827
1827
  html: "ref_id id?|selector?",
@@ -3036,18 +3036,172 @@ function boundSnapshot(page) {
3036
3036
 
3037
3037
  // src/browser/launcher.ts
3038
3038
  import { spawn } from "node:child_process";
3039
+ import { isAbsolute as isAbsolute2 } from "node:path";
3040
+
3041
+ // src/browser/default-browser.ts
3042
+ import { constants } from "node:fs";
3043
+ import { access, readdir as readdir3, readFile as readFile2, stat as stat2 } from "node:fs/promises";
3044
+ import { homedir as homedir3 } from "node:os";
3045
+ import { isAbsolute, join as join4 } from "node:path";
3046
+ var RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
3047
+ async function missingIsUndefined(operation) {
3048
+ try {
3049
+ return await operation;
3050
+ } catch (error) {
3051
+ if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
3052
+ return;
3053
+ }
3054
+ throw error;
3055
+ }
3056
+ }
3057
+ async function desktopFiles(directory, id) {
3058
+ const entries = await missingIsUndefined(readdir3(directory, { withFileTypes: true }));
3059
+ const paths = [];
3060
+ for (const entry of entries ?? []) {
3061
+ const path = join4(directory, entry.name);
3062
+ if (entry.name === id && !entry.isDirectory()) {
3063
+ paths.push(path);
3064
+ } else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
3065
+ paths.push(...await desktopFiles(path, id.slice(entry.name.length + 1)));
3066
+ }
3067
+ }
3068
+ return paths;
3069
+ }
3070
+ async function findDesktopFile(id, env) {
3071
+ const userData = env["XDG_DATA_HOME"];
3072
+ const home = env["HOME"];
3073
+ const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share").split(":").filter(isAbsolute);
3074
+ const roots = [
3075
+ userData && isAbsolute(userData) ? userData : join4(home && isAbsolute(home) ? home : homedir3(), ".local/share"),
3076
+ ...systemData
3077
+ ];
3078
+ for (const root of roots) {
3079
+ const [path, ambiguous] = await desktopFiles(join4(root, "applications"), id);
3080
+ if (ambiguous)
3081
+ throw new Error("the desktop ID is ambiguous");
3082
+ if (path)
3083
+ return path;
3084
+ }
3085
+ throw new Error("the desktop entry was not found");
3086
+ }
3087
+ function desktopEntry(source) {
3088
+ const entry = new Map;
3089
+ let inDesktopEntry = false;
3090
+ for (const line of source.split(/\r?\n/)) {
3091
+ const trimmed = line.trim();
3092
+ if (trimmed.startsWith("[")) {
3093
+ if (inDesktopEntry)
3094
+ break;
3095
+ inDesktopEntry = trimmed === "[Desktop Entry]";
3096
+ } else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
3097
+ const equals = trimmed.indexOf("=");
3098
+ if (equals < 1)
3099
+ throw new Error("invalid desktop entry");
3100
+ const key = trimmed.slice(0, equals).trimEnd();
3101
+ if (entry.has(key))
3102
+ throw new Error("duplicate desktop entry key");
3103
+ entry.set(key, trimmed.slice(equals + 1).trimStart());
3104
+ }
3105
+ }
3106
+ return entry;
3107
+ }
3108
+ function desktopString(value) {
3109
+ const escapes = {
3110
+ s: " ",
3111
+ n: `
3112
+ `,
3113
+ t: "\t",
3114
+ r: "\r",
3115
+ "\\": "\\"
3116
+ };
3117
+ return value.replace(/\\(.|$)/g, (_match, char) => {
3118
+ const replacement = escapes[char];
3119
+ if (replacement === undefined)
3120
+ throw new Error("invalid desktop entry escape");
3121
+ return replacement;
3122
+ });
3123
+ }
3124
+ function execArguments(line) {
3125
+ const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
3126
+ const args = [];
3127
+ let hasInputField = false;
3128
+ for (let remaining = desktopString(line).trim();remaining; ) {
3129
+ const match = word.exec(remaining)?.[0];
3130
+ if (match === undefined)
3131
+ throw new Error("unsupported desktop Exec quoting");
3132
+ remaining = remaining.slice(match.length).trimStart();
3133
+ word.lastIndex = 0;
3134
+ if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
3135
+ if (hasInputField)
3136
+ throw new Error("multiple desktop Exec input fields");
3137
+ hasInputField = true;
3138
+ continue;
3139
+ }
3140
+ const unquoted = match.startsWith('"') ? match.slice(1, -1).replace(/\\(.)/gs, "$1") : match;
3141
+ args.push(unquoted.replace(/%%|%/g, (percent) => {
3142
+ if (percent === "%%")
3143
+ return "%";
3144
+ throw new Error("unsupported desktop Exec field code");
3145
+ }));
3146
+ }
3147
+ return args;
3148
+ }
3149
+ async function executablePath(executable, env) {
3150
+ const candidates = isAbsolute(executable) ? [executable] : executable.includes("/") ? [] : (env["PATH"] ?? "/usr/bin:/bin").split(":").filter(isAbsolute).map((directory) => join4(directory, executable));
3151
+ for (const path of candidates) {
3152
+ try {
3153
+ await access(path, constants.X_OK);
3154
+ if ((await stat2(path)).isFile())
3155
+ return path;
3156
+ } catch {}
3157
+ }
3158
+ return;
3159
+ }
3160
+ async function resolveDefaultBrowser(id, env) {
3161
+ if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
3162
+ throw new Error("Could not determine the configured default browser. " + RECOVERY);
3163
+ }
3164
+ try {
3165
+ const path = await findDesktopFile(id, env);
3166
+ if (!(await stat2(path)).isFile())
3167
+ throw new Error("invalid desktop entry file");
3168
+ const entry = desktopEntry(await readFile2(path, "utf8"));
3169
+ if (entry.get("Type") !== "Application" || entry.get("Hidden") === "true" || entry.get("Terminal") === "true" || entry.get("DBusActivatable") === "true") {
3170
+ throw new Error("the desktop entry does not use direct application startup");
3171
+ }
3172
+ const [command, ...args] = execArguments(entry.get("Exec") ?? "");
3173
+ if (!command || command.includes("=")) {
3174
+ throw new Error("the desktop entry has no valid executable");
3175
+ }
3176
+ const executable = await executablePath(command, env);
3177
+ const tryExec = desktopString(entry.get("TryExec") ?? "");
3178
+ if (!executable || tryExec && !await executablePath(tryExec, env)) {
3179
+ throw new Error("the desktop executable is unavailable");
3180
+ }
3181
+ const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
3182
+ if (workingDirectory && !isAbsolute(workingDirectory)) {
3183
+ throw new Error("the desktop working directory is not absolute");
3184
+ }
3185
+ return { executable, args, workingDirectory };
3186
+ } catch (error) {
3187
+ throw new Error('Cannot start the default browser "' + id + '": ' + (error instanceof Error ? error.message : String(error)) + ". " + RECOVERY, { cause: error });
3188
+ }
3189
+ }
3190
+
3191
+ // src/browser/launcher.ts
3039
3192
  var BROWSER_START_TIMEOUT_MS = 1e4;
3040
3193
  var BROWSER_UNIT = "chrome-cdp-browser.service";
3041
3194
  var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
3042
3195
  function abortReason(signal) {
3043
3196
  return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
3044
3197
  }
3045
- function runProcess(command, args, signal) {
3198
+ function runProcess(command, args, signal, env) {
3046
3199
  if (signal?.aborted)
3047
3200
  return Promise.reject(abortReason(signal));
3048
3201
  return new Promise((resolveValue, reject) => {
3049
3202
  const child = spawn(command, args, {
3050
- stdio: ["ignore", "pipe", "pipe"]
3203
+ stdio: ["ignore", "pipe", "pipe"],
3204
+ env
3051
3205
  });
3052
3206
  let stdout = "";
3053
3207
  let stderr = "";
@@ -3125,7 +3279,114 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
3125
3279
  }
3126
3280
  await sleep(100, signal);
3127
3281
  }
3128
- throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}`);
3282
+ throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`);
3283
+ }
3284
+ function hasGraphicalDesktop(env) {
3285
+ return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
3286
+ }
3287
+ async function graphicalEnvironment(signal) {
3288
+ if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
3289
+ return { ...process.env };
3290
+ }
3291
+ const result = await runProcess("busctl", [
3292
+ "--user",
3293
+ "--json=short",
3294
+ "get-property",
3295
+ "org.freedesktop.systemd1",
3296
+ "/org/freedesktop/systemd1",
3297
+ "org.freedesktop.systemd1.Manager",
3298
+ "Environment"
3299
+ ], signal);
3300
+ if (result.code !== 0)
3301
+ throw new Error("systemd user environment unavailable");
3302
+ const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
3303
+ if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
3304
+ throw new Error("Invalid systemd user environment");
3305
+ }
3306
+ const entries = [];
3307
+ for (const assignment of reply["data"]) {
3308
+ if (typeof assignment !== "string")
3309
+ throw new Error("Invalid systemd environment variable");
3310
+ const equals = assignment.indexOf("=");
3311
+ if (equals <= 0)
3312
+ throw new Error("Invalid systemd environment variable");
3313
+ entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
3314
+ }
3315
+ const env = Object.fromEntries(entries);
3316
+ if (!hasGraphicalDesktop(env))
3317
+ throw new Error("systemd has no graphical desktop environment");
3318
+ return env;
3319
+ }
3320
+ async function configuredDefaultBrowser(signal) {
3321
+ const timeout = AbortSignal.timeout(5000);
3322
+ const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
3323
+ let env;
3324
+ try {
3325
+ env = await graphicalEnvironment(lookupSignal);
3326
+ } catch (error) {
3327
+ signal?.throwIfAborted();
3328
+ throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
3329
+ }
3330
+ delete env["BROWSER"];
3331
+ let id;
3332
+ try {
3333
+ const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
3334
+ if (result.code !== 0)
3335
+ throw new Error(result.stderr || `exit ${result.code}`);
3336
+ id = result.stdout;
3337
+ } catch (error) {
3338
+ signal?.throwIfAborted();
3339
+ throw new Error("Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
3340
+ }
3341
+ return resolveDefaultBrowser(id, env);
3342
+ }
3343
+ async function browserLaunchCommand(host, port, signal) {
3344
+ const switches = new Map([
3345
+ ["--remote-debugging-address", host],
3346
+ ["--remote-debugging-port", port]
3347
+ ]);
3348
+ const profile = process.env["CDP_PROFILE_DIRECTORY"];
3349
+ if (profile)
3350
+ switches.set("--profile-directory", profile);
3351
+ const override = process.env["CDP_BROWSER"];
3352
+ if (override === "") {
3353
+ throw new Error("CDP_BROWSER must name a compatible executable.");
3354
+ }
3355
+ const desktop = override ? {
3356
+ executable: override,
3357
+ args: ["about:blank"],
3358
+ workingDirectory: undefined
3359
+ } : await configuredDefaultBrowser(signal);
3360
+ const fromDesktop = new Set;
3361
+ for (const arg of desktop.args) {
3362
+ if (arg === "--") {
3363
+ throw new Error("The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.");
3364
+ }
3365
+ const [name = ""] = arg.split("=", 1);
3366
+ const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
3367
+ const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
3368
+ const configured = switches.get(key);
3369
+ if (key === "--remote-debugging-pipe" || configured !== undefined && configured !== value) {
3370
+ throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
3371
+ }
3372
+ if (key === "--user-data-dir" && !isAbsolute2(value) && !desktop.workingDirectory) {
3373
+ throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
3374
+ }
3375
+ fromDesktop.add(key);
3376
+ }
3377
+ const args = [
3378
+ ...override ? [] : desktop.args,
3379
+ ...[...switches].filter(([key]) => !fromDesktop.has(key)).map(([key, value]) => `${key}=${value}`),
3380
+ ...override ? desktop.args : []
3381
+ ];
3382
+ const literalExecutable = desktop.executable.includes("$");
3383
+ return [
3384
+ ...desktop.workingDirectory ? [`--property=WorkingDirectory=${desktop.workingDirectory}`] : [],
3385
+ ...literalExecutable ? ["--expand-environment=no"] : [],
3386
+ "--",
3387
+ desktop.executable,
3388
+ ...literalExecutable ? args : args.map((arg) => arg.replaceAll("$", () => "$$"))
3389
+ ];
3129
3390
  }
3130
3391
  async function unitExists(systemctl, signal) {
3131
3392
  const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
@@ -3156,7 +3417,7 @@ async function startBrowser(signal) {
3156
3417
  }
3157
3418
  const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
3158
3419
  const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
3159
- const browser = process.env["CDP_BROWSER"] ?? "/usr/bin/chromium";
3420
+ let launchCommand;
3160
3421
  let lastLaunchError = "";
3161
3422
  for (let attempt = 0;attempt < 3; attempt++) {
3162
3423
  const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
@@ -3166,24 +3427,15 @@ async function startBrowser(signal) {
3166
3427
  if (state === "timeout") {
3167
3428
  throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
3168
3429
  }
3430
+ launchCommand ??= await browserLaunchCommand(host, port, signal);
3169
3431
  await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
3170
- const browserArgs = [
3171
- `--remote-debugging-address=${host}`,
3172
- `--remote-debugging-port=${port}`
3173
- ];
3174
- const profile = process.env["CDP_PROFILE_DIRECTORY"];
3175
- if (profile) {
3176
- browserArgs.push(`--profile-directory=${profile}`);
3177
- }
3178
- browserArgs.push("about:blank");
3179
3432
  const launched = await runProcess(systemdRun, [
3180
3433
  "--user",
3181
3434
  "--unit=chrome-cdp-browser",
3182
3435
  "--collect",
3183
3436
  "--property=Type=exec",
3184
3437
  "--property=Restart=no",
3185
- browser,
3186
- ...browserArgs
3438
+ ...launchCommand
3187
3439
  ], signal);
3188
3440
  if (launched.code === 0) {
3189
3441
  await waitForDebugEndpoint(signal);
@@ -3303,10 +3555,10 @@ class BrowserOperationExecutor {
3303
3555
 
3304
3556
  // src/browser/remote.ts
3305
3557
  import { mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
3306
- import { basename as basename2, join as join4 } from "node:path";
3558
+ import { basename as basename2, join as join5 } from "node:path";
3307
3559
 
3308
3560
  // src/browser/remote-helper.ts
3309
- import { readFile as readFile2 } from "node:fs/promises";
3561
+ import { readFile as readFile3 } from "node:fs/promises";
3310
3562
  import { fileURLToPath } from "node:url";
3311
3563
 
3312
3564
  // src/browser/remote-process.ts
@@ -3458,7 +3710,7 @@ async function readHelperSource() {
3458
3710
  let lastError;
3459
3711
  for (const path of candidates) {
3460
3712
  try {
3461
- return await readFile2(path, "utf8");
3713
+ return await readFile3(path, "utf8");
3462
3714
  } catch (error) {
3463
3715
  lastError = error;
3464
3716
  }
@@ -3506,7 +3758,7 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
3506
3758
  throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
3507
3759
  }
3508
3760
  await mkdir3(artifactDirectory(), { recursive: true, mode: 448 });
3509
- const localFile = join4(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
3761
+ const localFile = join5(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
3510
3762
  const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
3511
3763
  if (copied.code !== 0) {
3512
3764
  throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
@@ -3645,7 +3897,7 @@ class BrowserRuntime {
3645
3897
  let session = this.localSessions.get(ownerId);
3646
3898
  if (session)
3647
3899
  return session;
3648
- const cdp = new BrowserCdpSession(ownerId, join5(artifactDirectory(), "tabs"));
3900
+ const cdp = new BrowserCdpSession(ownerId, join6(artifactDirectory(), "tabs"));
3649
3901
  session = {
3650
3902
  activeCalls: 0,
3651
3903
  cdp,
@@ -3680,8 +3932,8 @@ var IS_WINDOWS2 = process.platform === "win32";
3680
3932
  function workerSocketPath(workerId) {
3681
3933
  if (IS_WINDOWS2)
3682
3934
  return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
3683
- const directory = process.env["XDG_RUNTIME_DIR"] ? join6(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join6(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
3684
- return join6(directory, `worker-${workerId}.sock`);
3935
+ const directory = process.env["XDG_RUNTIME_DIR"] ? join7(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join7(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
3936
+ return join7(directory, `worker-${workerId}.sock`);
3685
3937
  }
3686
3938
  async function ensureWorkerSocketDirectory(workerId) {
3687
3939
  if (IS_WINDOWS2)
@@ -0,0 +1,7 @@
1
+ interface DesktopBrowser {
2
+ executable: string;
3
+ args: string[];
4
+ workingDirectory: string | undefined;
5
+ }
6
+ export declare function resolveDefaultBrowser(id: string, env: NodeJS.ProcessEnv): Promise<DesktopBrowser>;
7
+ export {};
@@ -0,0 +1,181 @@
1
+ import { constants } from "node:fs";
2
+ import { access, readdir, readFile, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join } from "node:path";
5
+ const RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
6
+ async function missingIsUndefined(operation) {
7
+ try {
8
+ return await operation;
9
+ }
10
+ catch (error) {
11
+ if (error &&
12
+ typeof error === "object" &&
13
+ "code" in error &&
14
+ (error.code === "ENOENT" || error.code === "ENOTDIR")) {
15
+ return undefined;
16
+ }
17
+ throw error;
18
+ }
19
+ }
20
+ async function desktopFiles(directory, id) {
21
+ const entries = await missingIsUndefined(readdir(directory, { withFileTypes: true }));
22
+ const paths = [];
23
+ for (const entry of entries ?? []) {
24
+ const path = join(directory, entry.name);
25
+ if (entry.name === id && !entry.isDirectory()) {
26
+ paths.push(path);
27
+ }
28
+ else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
29
+ // Nested entries derive their IDs by replacing '/' with '-'.
30
+ paths.push(...(await desktopFiles(path, id.slice(entry.name.length + 1))));
31
+ }
32
+ }
33
+ return paths;
34
+ }
35
+ async function findDesktopFile(id, env) {
36
+ const userData = env["XDG_DATA_HOME"];
37
+ const home = env["HOME"];
38
+ const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share")
39
+ .split(":")
40
+ .filter(isAbsolute);
41
+ const roots = [
42
+ userData && isAbsolute(userData)
43
+ ? userData
44
+ : join(home && isAbsolute(home) ? home : homedir(), ".local/share"),
45
+ ...systemData,
46
+ ];
47
+ for (const root of roots) {
48
+ const [path, ambiguous] = await desktopFiles(join(root, "applications"), id);
49
+ if (ambiguous)
50
+ throw new Error("the desktop ID is ambiguous");
51
+ if (path)
52
+ return path;
53
+ }
54
+ throw new Error("the desktop entry was not found");
55
+ }
56
+ function desktopEntry(source) {
57
+ const entry = new Map();
58
+ let inDesktopEntry = false;
59
+ for (const line of source.split(/\r?\n/)) {
60
+ const trimmed = line.trim();
61
+ if (trimmed.startsWith("[")) {
62
+ if (inDesktopEntry)
63
+ break;
64
+ inDesktopEntry = trimmed === "[Desktop Entry]";
65
+ }
66
+ else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
67
+ const equals = trimmed.indexOf("=");
68
+ if (equals < 1)
69
+ throw new Error("invalid desktop entry");
70
+ const key = trimmed.slice(0, equals).trimEnd();
71
+ if (entry.has(key))
72
+ throw new Error("duplicate desktop entry key");
73
+ entry.set(key, trimmed.slice(equals + 1).trimStart());
74
+ }
75
+ }
76
+ return entry;
77
+ }
78
+ function desktopString(value) {
79
+ const escapes = {
80
+ s: " ",
81
+ n: "\n",
82
+ t: "\t",
83
+ r: "\r",
84
+ "\\": "\\",
85
+ };
86
+ return value.replace(/\\(.|$)/g, (_match, char) => {
87
+ const replacement = escapes[char];
88
+ if (replacement === undefined)
89
+ throw new Error("invalid desktop entry escape");
90
+ return replacement;
91
+ });
92
+ }
93
+ function execArguments(line) {
94
+ // Desktop Entry quoting is not shell quoting. Accept literal words and
95
+ // whole double-quoted arguments only; leave nonliteral launchers unsupported.
96
+ const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
97
+ const args = [];
98
+ let hasInputField = false;
99
+ for (let remaining = desktopString(line).trim(); remaining;) {
100
+ const match = word.exec(remaining)?.[0];
101
+ if (match === undefined)
102
+ throw new Error("unsupported desktop Exec quoting");
103
+ remaining = remaining.slice(match.length).trimStart();
104
+ word.lastIndex = 0;
105
+ if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
106
+ if (hasInputField)
107
+ throw new Error("multiple desktop Exec input fields");
108
+ hasInputField = true;
109
+ continue; // No URL or file was requested.
110
+ }
111
+ const unquoted = match.startsWith('"')
112
+ ? match.slice(1, -1).replace(/\\(.)/gs, "$1")
113
+ : match;
114
+ args.push(unquoted.replace(/%%|%/g, (percent) => {
115
+ if (percent === "%%")
116
+ return "%";
117
+ throw new Error("unsupported desktop Exec field code");
118
+ }));
119
+ }
120
+ return args;
121
+ }
122
+ async function executablePath(executable, env) {
123
+ const candidates = isAbsolute(executable)
124
+ ? [executable]
125
+ : executable.includes("/")
126
+ ? []
127
+ : (env["PATH"] ?? "/usr/bin:/bin")
128
+ .split(":")
129
+ .filter(isAbsolute)
130
+ .map((directory) => join(directory, executable));
131
+ for (const path of candidates) {
132
+ try {
133
+ await access(path, constants.X_OK);
134
+ if ((await stat(path)).isFile())
135
+ return path;
136
+ }
137
+ catch {
138
+ // Keep looking on PATH when a candidate isn't executable.
139
+ }
140
+ }
141
+ return undefined;
142
+ }
143
+ export async function resolveDefaultBrowser(id, env) {
144
+ if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
145
+ throw new Error("Could not determine the configured default browser. " + RECOVERY);
146
+ }
147
+ try {
148
+ const path = await findDesktopFile(id, env);
149
+ if (!(await stat(path)).isFile())
150
+ throw new Error("invalid desktop entry file");
151
+ const entry = desktopEntry(await readFile(path, "utf8"));
152
+ if (entry.get("Type") !== "Application" ||
153
+ entry.get("Hidden") === "true" ||
154
+ entry.get("Terminal") === "true" ||
155
+ entry.get("DBusActivatable") === "true") {
156
+ throw new Error("the desktop entry does not use direct application startup");
157
+ }
158
+ const [command, ...args] = execArguments(entry.get("Exec") ?? "");
159
+ if (!command || command.includes("=")) {
160
+ throw new Error("the desktop entry has no valid executable");
161
+ }
162
+ const executable = await executablePath(command, env);
163
+ const tryExec = desktopString(entry.get("TryExec") ?? "");
164
+ if (!executable || (tryExec && !(await executablePath(tryExec, env)))) {
165
+ throw new Error("the desktop executable is unavailable");
166
+ }
167
+ const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
168
+ if (workingDirectory && !isAbsolute(workingDirectory)) {
169
+ throw new Error("the desktop working directory is not absolute");
170
+ }
171
+ return { executable, args, workingDirectory };
172
+ }
173
+ catch (error) {
174
+ throw new Error('Cannot start the default browser "' +
175
+ id +
176
+ '": ' +
177
+ (error instanceof Error ? error.message : String(error)) +
178
+ ". " +
179
+ RECOVERY, { cause: error });
180
+ }
181
+ }
@@ -21,7 +21,7 @@ export function browserHelp(hosts = []) {
21
21
  type: "ref_id text id?; id focuses",
22
22
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
23
23
  press: "ref_id key; focused element, e.g. Enter or Control+a",
24
- wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
24
+ wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
25
25
  screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
26
26
  navigate: "ref_id url",
27
27
  html: "ref_id id?|selector?",