@howaboua/pi-durable-browser 0.11.0 → 0.13.0

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/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { Type } from "typebox";
5
5
  // packages/browser/src/browser/artifact-store.ts
6
6
  import {
7
7
  mkdir,
8
+ open,
8
9
  readdir,
9
10
  readFile,
10
11
  rm,
@@ -23,6 +24,23 @@ function nodeArtifactStore(directory) {
23
24
  await mkdir(directory, { recursive: true, mode: 448 });
24
25
  await writeFile(path(name), data, { mode: 384 });
25
26
  },
27
+ async readWindow(name, offset, length) {
28
+ const file = await open(path(name), "r");
29
+ try {
30
+ const { size } = await file.stat();
31
+ const data = Buffer.alloc(Math.min(Math.max(0, size - offset), length));
32
+ let used = 0;
33
+ while (used < data.length) {
34
+ const { bytesRead } = await file.read(data, used, data.length - used, offset + used);
35
+ if (!bytesRead)
36
+ break;
37
+ used += bytesRead;
38
+ }
39
+ return { size, data: data.subarray(0, used) };
40
+ } finally {
41
+ await file.close();
42
+ }
43
+ },
26
44
  async read(name) {
27
45
  return readFile(path(name), "utf8");
28
46
  },
@@ -52,6 +70,16 @@ async function environmentArtifactStore(env, directory, context) {
52
70
  getOrThrow(await env.createDir(root, { recursive: true }, context));
53
71
  getOrThrow(await env.writeFile(path(name), data, context));
54
72
  },
73
+ async readWindow(name, offset, length) {
74
+ const file = getOrThrow(await env.openBinaryReader(path(name), { noFollow: true }, context));
75
+ try {
76
+ const { size } = getOrThrow(await file.info(context));
77
+ const data = offset >= size ? new Uint8Array : getOrThrow(await file.read(offset, Math.min(size - offset, length), context));
78
+ return { size, data };
79
+ } finally {
80
+ await file.close(context);
81
+ }
82
+ },
55
83
  async read(name) {
56
84
  return getOrThrow(await env.readTextFile(path(name), context));
57
85
  },
@@ -631,7 +659,7 @@ function parseBrowserRequest(input) {
631
659
 
632
660
  // packages/browser/src/browser/runtime.ts
633
661
  import { randomUUID } from "node:crypto";
634
- import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
662
+ import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
635
663
 
636
664
  // packages/browser/src/cdp/serial.ts
637
665
  function waitForTurn(promise, signal) {
@@ -840,10 +868,10 @@ function cdpTimeoutAttempts(method) {
840
868
  function timeoutError(method, attempts) {
841
869
  const seconds = CDP_TIMEOUT_MS / 1000;
842
870
  if (attempts > 1) {
843
- return new Error(`Chrome did not answer ${method} after two ${seconds}s attempts. The tab may be unresponsive or suspended.`);
871
+ return new Error(`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`);
844
872
  }
845
873
  if (method === "Runtime.evaluate") {
846
- 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.`);
874
+ return new Error(`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`);
847
875
  }
848
876
  return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
849
877
  }
@@ -1348,7 +1376,7 @@ class BrowserTabs {
1348
1376
  try {
1349
1377
  response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
1350
1378
  } catch (error) {
1351
- throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
1379
+ throw new Error(`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`);
1352
1380
  }
1353
1381
  if (typeof response["targetId"] !== "string")
1354
1382
  throw new Error("Chrome did not return a new tab target; run tabs before retrying");
@@ -1356,7 +1384,7 @@ class BrowserTabs {
1356
1384
  try {
1357
1385
  await this.remember(created);
1358
1386
  } catch (error) {
1359
- throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
1387
+ throw new Error(`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`);
1360
1388
  }
1361
1389
  return created;
1362
1390
  }, signal);
@@ -1635,18 +1663,33 @@ class BrowserCdpSession {
1635
1663
  var RESULT_TTL_MS = 60 * 60 * 1000;
1636
1664
  var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
1637
1665
  var TEXT_BUDGET_BYTES = 32000;
1638
- function chunkForJson(value, offset = 0, budget = TEXT_BUDGET_BYTES) {
1666
+ function chunkForJson(value, offset = 0) {
1639
1667
  let bytes = 2;
1640
1668
  let end = offset;
1641
- for (const character of value.slice(offset)) {
1642
- const next = Buffer.byteLength(JSON.stringify(character)) - 2;
1643
- if (bytes + next > budget)
1669
+ while (end < value.length) {
1670
+ const point = value.codePointAt(end) ?? 0;
1671
+ const next = jsonCharacterBytes(point);
1672
+ if (bytes + next > TEXT_BUDGET_BYTES)
1644
1673
  break;
1645
1674
  bytes += next;
1646
- end += character.length;
1675
+ end += point > 65535 ? 2 : 1;
1647
1676
  }
1648
1677
  return { text: value.slice(offset, end), end };
1649
1678
  }
1679
+ function jsonCharacterBytes(point) {
1680
+ if (point < 32) {
1681
+ return point === 8 || point === 9 || point === 10 || point === 12 || point === 13 ? 2 : 6;
1682
+ }
1683
+ if (point === 34 || point === 92)
1684
+ return 2;
1685
+ if (point < 128)
1686
+ return 1;
1687
+ if (point < 2048)
1688
+ return 2;
1689
+ if (point >= 55296 && point <= 57343)
1690
+ return 6;
1691
+ return point <= 65535 ? 3 : 4;
1692
+ }
1650
1693
 
1651
1694
  class BrowserArtifacts {
1652
1695
  store;
@@ -1665,7 +1708,7 @@ class BrowserArtifacts {
1665
1708
  async prune(now = Date.now()) {
1666
1709
  let removed = 0;
1667
1710
  for (const entry of await this.store.entries()) {
1668
- if (!/^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(entry.name))
1711
+ if (!/^(?:result-[a-f0-9-]{36}\.(?:txt|utf16le)|browser-.*\.png)$/.test(entry.name))
1669
1712
  continue;
1670
1713
  const age = entry.name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
1671
1714
  if (now - entry.mtimeMs > age) {
@@ -1680,7 +1723,10 @@ class BrowserArtifacts {
1680
1723
  if (chunk.end >= value.length)
1681
1724
  return { ...base, [field]: value };
1682
1725
  const handle = crypto.randomUUID();
1683
- await this.store.write(`result-${handle}.txt`, value);
1726
+ if (this.store.readWindow)
1727
+ await this.store.write(`result-${handle}.utf16le`, Buffer.from(value, "utf16le"));
1728
+ else
1729
+ await this.store.write(`result-${handle}.txt`, value);
1684
1730
  return {
1685
1731
  ...base,
1686
1732
  [field]: chunk.text,
@@ -1691,36 +1737,54 @@ class BrowserArtifacts {
1691
1737
  };
1692
1738
  }
1693
1739
  async readCachedResult(request) {
1694
- let value;
1695
- try {
1696
- value = await this.store.read(`result-${request.handle}.txt`);
1697
- } catch (error) {
1698
- if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "not_found")) {
1699
- throw new Error(`result handle not found: ${request.handle}; check the host or rerun the original action`);
1740
+ const { offset, handle } = request;
1741
+ let name = `result-${handle}.utf16le`;
1742
+ let page;
1743
+ if (this.store.readWindow) {
1744
+ try {
1745
+ const { data, size } = await this.store.readWindow(name, offset * 2, 2 * (TEXT_BUDGET_BYTES - 1));
1746
+ if (size % 2 || data.length !== Math.min(2 * (TEXT_BUDGET_BYTES - 1), Math.max(0, size - offset * 2)))
1747
+ throw new Error("Cached result is incomplete; rerun the original action");
1748
+ const chunk = chunkForJson(Buffer.from(data).toString("utf16le"));
1749
+ page = { length: size / 2, end: offset + chunk.end, text: chunk.text };
1750
+ } catch (error) {
1751
+ if (!missing2(error))
1752
+ throw error;
1700
1753
  }
1701
- throw error;
1702
- }
1703
- if (request.offset > value.length) {
1704
- throw new Error(`offset ${request.offset} exceeds result length ${value.length}`);
1705
1754
  }
1706
- const chunk = chunkForJson(value, request.offset);
1707
- const complete = chunk.end >= value.length;
1708
- if (complete) {
1709
- await this.store.remove(`result-${request.handle}.txt`);
1755
+ if (!page) {
1756
+ name = `result-${handle}.txt`;
1757
+ let value;
1758
+ try {
1759
+ value = await this.store.read(name);
1760
+ } catch (error) {
1761
+ if (!missing2(error))
1762
+ throw error;
1763
+ throw new Error(`result handle not found: ${handle}; check the host or rerun the original action`);
1764
+ }
1765
+ page = { ...chunkForJson(value, offset), length: value.length };
1710
1766
  }
1767
+ if (offset > page.length)
1768
+ throw new Error(`offset ${offset} exceeds result length ${page.length}`);
1769
+ const complete = page.end >= page.length;
1770
+ if (complete)
1771
+ await this.store.remove(name);
1711
1772
  return {
1712
- handle: request.handle,
1713
- offset: request.offset,
1714
- text: chunk.text,
1773
+ handle,
1774
+ offset,
1775
+ text: page.text,
1715
1776
  complete,
1716
- ...complete ? {} : { next_offset: chunk.end }
1777
+ ...complete ? {} : { next_offset: page.end }
1717
1778
  };
1718
1779
  }
1719
1780
  async discardCachedResult(handle) {
1720
- await this.store.remove(`result-${handle}.txt`);
1781
+ await Promise.all(["utf16le", "txt"].map((ext) => this.store.remove(`result-${handle}.${ext}`)));
1721
1782
  return { discarded: handle };
1722
1783
  }
1723
1784
  }
1785
+ function missing2(error) {
1786
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "not_found");
1787
+ }
1724
1788
 
1725
1789
  // packages/browser/src/browser/help.ts
1726
1790
  function browserHelp(hosts = []) {
@@ -1728,11 +1792,11 @@ function browserHelp(hosts = []) {
1728
1792
  return {
1729
1793
  input: "{action,...fields}",
1730
1794
  ...routed ? {
1731
- host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`
1795
+ host: `${hosts.join("|")} optional; user-named host→all calls; refs/handles stay with host`
1732
1796
  } : {},
1733
- refs: "tabs -> open; keep ref_id/id/cursors with their result",
1734
- safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1735
- batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
1797
+ refs: "tabs→open; ref_id/id/cursors stay with result",
1798
+ safety: "MUST ask before unfamiliar low-trust navigation or consequential action unless authorised. MUST NOT close shared browser",
1799
+ batch: "Independent only: {action_name:[{...fields}],...}; nonempty arrays; root host/response_length; omit item action",
1736
1800
  actions: {
1737
1801
  tabs: "query? offset? owned_only? -> ref_id title url owned",
1738
1802
  open: "ref_id lineno? | url; new tabs open in background",
@@ -1743,8 +1807,8 @@ function browserHelp(hosts = []) {
1743
1807
  type: "ref_id text id?; id focuses",
1744
1808
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
1745
1809
  press: "ref_id key; focused element, e.g. Enter or Control+a",
1746
- wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
1747
- screenshot: "ref_id id?|selector? -> file; brings tab to foreground",
1810
+ wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
1811
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
1748
1812
  navigate: "ref_id url",
1749
1813
  html: "ref_id id?|selector?",
1750
1814
  evaluate: "ref_id expression",
@@ -1756,7 +1820,7 @@ function browserHelp(hosts = []) {
1756
1820
  read_result: "handle offset",
1757
1821
  discard_result: "handle"
1758
1822
  },
1759
- continue: "next_lineno/next_offset; response_length=short|medium|long"
1823
+ continue: "next_lineno/next_offset; open(ref_id)/find: response_length=short|medium|long"
1760
1824
  };
1761
1825
  }
1762
1826
 
@@ -2957,18 +3021,172 @@ function boundSnapshot(page) {
2957
3021
 
2958
3022
  // packages/browser/src/browser/launcher.ts
2959
3023
  import { spawn } from "node:child_process";
3024
+ import { isAbsolute as isAbsolute3 } from "node:path";
3025
+
3026
+ // packages/browser/src/browser/default-browser.ts
3027
+ import { constants } from "node:fs";
3028
+ import { access, readdir as readdir3, readFile as readFile2, stat as stat2 } from "node:fs/promises";
3029
+ import { homedir as homedir2 } from "node:os";
3030
+ import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
3031
+ var RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
3032
+ async function missingIsUndefined(operation) {
3033
+ try {
3034
+ return await operation;
3035
+ } catch (error) {
3036
+ if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
3037
+ return;
3038
+ }
3039
+ throw error;
3040
+ }
3041
+ }
3042
+ async function desktopFiles(directory, id) {
3043
+ const entries = await missingIsUndefined(readdir3(directory, { withFileTypes: true }));
3044
+ const paths = [];
3045
+ for (const entry of entries ?? []) {
3046
+ const path = join3(directory, entry.name);
3047
+ if (entry.name === id && !entry.isDirectory()) {
3048
+ paths.push(path);
3049
+ } else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
3050
+ paths.push(...await desktopFiles(path, id.slice(entry.name.length + 1)));
3051
+ }
3052
+ }
3053
+ return paths;
3054
+ }
3055
+ async function findDesktopFile(id, env) {
3056
+ const userData = env["XDG_DATA_HOME"];
3057
+ const home = env["HOME"];
3058
+ const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share").split(":").filter(isAbsolute2);
3059
+ const roots = [
3060
+ userData && isAbsolute2(userData) ? userData : join3(home && isAbsolute2(home) ? home : homedir2(), ".local/share"),
3061
+ ...systemData
3062
+ ];
3063
+ for (const root of roots) {
3064
+ const [path, ambiguous] = await desktopFiles(join3(root, "applications"), id);
3065
+ if (ambiguous)
3066
+ throw new Error("the desktop ID is ambiguous");
3067
+ if (path)
3068
+ return path;
3069
+ }
3070
+ throw new Error("the desktop entry was not found");
3071
+ }
3072
+ function desktopEntry(source) {
3073
+ const entry = new Map;
3074
+ let inDesktopEntry = false;
3075
+ for (const line of source.split(/\r?\n/)) {
3076
+ const trimmed = line.trim();
3077
+ if (trimmed.startsWith("[")) {
3078
+ if (inDesktopEntry)
3079
+ break;
3080
+ inDesktopEntry = trimmed === "[Desktop Entry]";
3081
+ } else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
3082
+ const equals = trimmed.indexOf("=");
3083
+ if (equals < 1)
3084
+ throw new Error("invalid desktop entry");
3085
+ const key = trimmed.slice(0, equals).trimEnd();
3086
+ if (entry.has(key))
3087
+ throw new Error("duplicate desktop entry key");
3088
+ entry.set(key, trimmed.slice(equals + 1).trimStart());
3089
+ }
3090
+ }
3091
+ return entry;
3092
+ }
3093
+ function desktopString(value) {
3094
+ const escapes = {
3095
+ s: " ",
3096
+ n: `
3097
+ `,
3098
+ t: "\t",
3099
+ r: "\r",
3100
+ "\\": "\\"
3101
+ };
3102
+ return value.replace(/\\(.|$)/g, (_match, char) => {
3103
+ const replacement = escapes[char];
3104
+ if (replacement === undefined)
3105
+ throw new Error("invalid desktop entry escape");
3106
+ return replacement;
3107
+ });
3108
+ }
3109
+ function execArguments(line) {
3110
+ const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
3111
+ const args = [];
3112
+ let hasInputField = false;
3113
+ for (let remaining = desktopString(line).trim();remaining; ) {
3114
+ const match = word.exec(remaining)?.[0];
3115
+ if (match === undefined)
3116
+ throw new Error("unsupported desktop Exec quoting");
3117
+ remaining = remaining.slice(match.length).trimStart();
3118
+ word.lastIndex = 0;
3119
+ if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
3120
+ if (hasInputField)
3121
+ throw new Error("multiple desktop Exec input fields");
3122
+ hasInputField = true;
3123
+ continue;
3124
+ }
3125
+ const unquoted = match.startsWith('"') ? match.slice(1, -1).replace(/\\(.)/gs, "$1") : match;
3126
+ args.push(unquoted.replace(/%%|%/g, (percent) => {
3127
+ if (percent === "%%")
3128
+ return "%";
3129
+ throw new Error("unsupported desktop Exec field code");
3130
+ }));
3131
+ }
3132
+ return args;
3133
+ }
3134
+ async function executablePath(executable, env) {
3135
+ const candidates = isAbsolute2(executable) ? [executable] : executable.includes("/") ? [] : (env["PATH"] ?? "/usr/bin:/bin").split(":").filter(isAbsolute2).map((directory) => join3(directory, executable));
3136
+ for (const path of candidates) {
3137
+ try {
3138
+ await access(path, constants.X_OK);
3139
+ if ((await stat2(path)).isFile())
3140
+ return path;
3141
+ } catch {}
3142
+ }
3143
+ return;
3144
+ }
3145
+ async function resolveDefaultBrowser(id, env) {
3146
+ if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
3147
+ throw new Error("Could not determine the configured default browser. " + RECOVERY);
3148
+ }
3149
+ try {
3150
+ const path = await findDesktopFile(id, env);
3151
+ if (!(await stat2(path)).isFile())
3152
+ throw new Error("invalid desktop entry file");
3153
+ const entry = desktopEntry(await readFile2(path, "utf8"));
3154
+ if (entry.get("Type") !== "Application" || entry.get("Hidden") === "true" || entry.get("Terminal") === "true" || entry.get("DBusActivatable") === "true") {
3155
+ throw new Error("the desktop entry does not use direct application startup");
3156
+ }
3157
+ const [command, ...args] = execArguments(entry.get("Exec") ?? "");
3158
+ if (!command || command.includes("=")) {
3159
+ throw new Error("the desktop entry has no valid executable");
3160
+ }
3161
+ const executable = await executablePath(command, env);
3162
+ const tryExec = desktopString(entry.get("TryExec") ?? "");
3163
+ if (!executable || tryExec && !await executablePath(tryExec, env)) {
3164
+ throw new Error("the desktop executable is unavailable");
3165
+ }
3166
+ const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
3167
+ if (workingDirectory && !isAbsolute2(workingDirectory)) {
3168
+ throw new Error("the desktop working directory is not absolute");
3169
+ }
3170
+ return { executable, args, workingDirectory };
3171
+ } catch (error) {
3172
+ throw new Error('Cannot start the default browser "' + id + '": ' + (error instanceof Error ? error.message : String(error)) + ". " + RECOVERY, { cause: error });
3173
+ }
3174
+ }
3175
+
3176
+ // packages/browser/src/browser/launcher.ts
2960
3177
  var BROWSER_START_TIMEOUT_MS = 1e4;
2961
3178
  var BROWSER_UNIT = "chrome-cdp-browser.service";
2962
3179
  var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
2963
3180
  function abortReason(signal) {
2964
3181
  return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
2965
3182
  }
2966
- function runProcess(command, args, signal) {
3183
+ function runProcess(command, args, signal, env) {
2967
3184
  if (signal?.aborted)
2968
3185
  return Promise.reject(abortReason(signal));
2969
3186
  return new Promise((resolveValue, reject) => {
2970
3187
  const child = spawn(command, args, {
2971
- stdio: ["ignore", "pipe", "pipe"]
3188
+ stdio: ["ignore", "pipe", "pipe"],
3189
+ env
2972
3190
  });
2973
3191
  let stdout = "";
2974
3192
  let stderr = "";
@@ -3053,7 +3271,114 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
3053
3271
  }
3054
3272
  await sleep(100, signal);
3055
3273
  }
3056
- throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}`);
3274
+ 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.`);
3275
+ }
3276
+ function hasGraphicalDesktop(env) {
3277
+ return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
3278
+ }
3279
+ async function graphicalEnvironment(signal) {
3280
+ if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
3281
+ return { ...process.env };
3282
+ }
3283
+ const result = await runProcess("busctl", [
3284
+ "--user",
3285
+ "--json=short",
3286
+ "get-property",
3287
+ "org.freedesktop.systemd1",
3288
+ "/org/freedesktop/systemd1",
3289
+ "org.freedesktop.systemd1.Manager",
3290
+ "Environment"
3291
+ ], signal);
3292
+ if (result.code !== 0)
3293
+ throw new Error("systemd user environment unavailable");
3294
+ const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
3295
+ if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
3296
+ throw new Error("Invalid systemd user environment");
3297
+ }
3298
+ const entries = [];
3299
+ for (const assignment of reply["data"]) {
3300
+ if (typeof assignment !== "string")
3301
+ throw new Error("Invalid systemd environment variable");
3302
+ const equals = assignment.indexOf("=");
3303
+ if (equals <= 0)
3304
+ throw new Error("Invalid systemd environment variable");
3305
+ entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
3306
+ }
3307
+ const env = Object.fromEntries(entries);
3308
+ if (!hasGraphicalDesktop(env))
3309
+ throw new Error("systemd has no graphical desktop environment");
3310
+ return env;
3311
+ }
3312
+ async function configuredDefaultBrowser(signal) {
3313
+ const timeout = AbortSignal.timeout(5000);
3314
+ const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
3315
+ let env;
3316
+ try {
3317
+ env = await graphicalEnvironment(lookupSignal);
3318
+ } catch (error) {
3319
+ signal?.throwIfAborted();
3320
+ throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
3321
+ }
3322
+ delete env["BROWSER"];
3323
+ let id;
3324
+ try {
3325
+ const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
3326
+ if (result.code !== 0)
3327
+ throw new Error(result.stderr || `exit ${result.code}`);
3328
+ id = result.stdout;
3329
+ } catch (error) {
3330
+ signal?.throwIfAborted();
3331
+ 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 });
3332
+ }
3333
+ return resolveDefaultBrowser(id, env);
3334
+ }
3335
+ async function browserLaunchCommand(host, port, signal) {
3336
+ const switches = new Map([
3337
+ ["--remote-debugging-address", host],
3338
+ ["--remote-debugging-port", port]
3339
+ ]);
3340
+ const profile = process.env["CDP_PROFILE_DIRECTORY"];
3341
+ if (profile)
3342
+ switches.set("--profile-directory", profile);
3343
+ const override = process.env["CDP_BROWSER"];
3344
+ if (override === "") {
3345
+ throw new Error("CDP_BROWSER must name a compatible executable.");
3346
+ }
3347
+ const desktop = override ? {
3348
+ executable: override,
3349
+ args: ["about:blank"],
3350
+ workingDirectory: undefined
3351
+ } : await configuredDefaultBrowser(signal);
3352
+ const fromDesktop = new Set;
3353
+ for (const arg of desktop.args) {
3354
+ if (arg === "--") {
3355
+ 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.");
3356
+ }
3357
+ const [name = ""] = arg.split("=", 1);
3358
+ const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
3359
+ const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
3360
+ const configured = switches.get(key);
3361
+ if (key === "--remote-debugging-pipe" || configured !== undefined && configured !== value) {
3362
+ throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
3363
+ }
3364
+ if (key === "--user-data-dir" && !isAbsolute3(value) && !desktop.workingDirectory) {
3365
+ throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
3366
+ }
3367
+ fromDesktop.add(key);
3368
+ }
3369
+ const args = [
3370
+ ...override ? [] : desktop.args,
3371
+ ...[...switches].filter(([key]) => !fromDesktop.has(key)).map(([key, value]) => `${key}=${value}`),
3372
+ ...override ? desktop.args : []
3373
+ ];
3374
+ const literalExecutable = desktop.executable.includes("$");
3375
+ return [
3376
+ ...desktop.workingDirectory ? [`--property=WorkingDirectory=${desktop.workingDirectory}`] : [],
3377
+ ...literalExecutable ? ["--expand-environment=no"] : [],
3378
+ "--",
3379
+ desktop.executable,
3380
+ ...literalExecutable ? args : args.map((arg) => arg.replaceAll("$", () => "$$"))
3381
+ ];
3057
3382
  }
3058
3383
  async function unitExists(systemctl, signal) {
3059
3384
  const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
@@ -3084,7 +3409,7 @@ async function startBrowser(signal) {
3084
3409
  }
3085
3410
  const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
3086
3411
  const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
3087
- const browser = process.env["CDP_BROWSER"] ?? "/usr/bin/chromium";
3412
+ let launchCommand;
3088
3413
  let lastLaunchError = "";
3089
3414
  for (let attempt = 0;attempt < 3; attempt++) {
3090
3415
  const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
@@ -3094,24 +3419,15 @@ async function startBrowser(signal) {
3094
3419
  if (state === "timeout") {
3095
3420
  throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
3096
3421
  }
3422
+ launchCommand ??= await browserLaunchCommand(host, port, signal);
3097
3423
  await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
3098
- const browserArgs = [
3099
- `--remote-debugging-address=${host}`,
3100
- `--remote-debugging-port=${port}`
3101
- ];
3102
- const profile = process.env["CDP_PROFILE_DIRECTORY"];
3103
- if (profile) {
3104
- browserArgs.push(`--profile-directory=${profile}`);
3105
- }
3106
- browserArgs.push("about:blank");
3107
3424
  const launched = await runProcess(systemdRun, [
3108
3425
  "--user",
3109
3426
  "--unit=chrome-cdp-browser",
3110
3427
  "--collect",
3111
3428
  "--property=Type=exec",
3112
3429
  "--property=Restart=no",
3113
- browser,
3114
- ...browserArgs
3430
+ ...launchCommand
3115
3431
  ], signal);
3116
3432
  if (launched.code === 0) {
3117
3433
  await waitForDebugEndpoint(signal);
@@ -3232,11 +3548,11 @@ class BrowserOperationExecutor {
3232
3548
  }
3233
3549
 
3234
3550
  // packages/browser/src/browser/remote.ts
3235
- import { mkdir as mkdir3, mkdtemp, readFile as readFile3, rm as rm3 } from "node:fs/promises";
3236
- import { join as join3 } from "node:path";
3551
+ import { mkdir as mkdir3, mkdtemp, readFile as readFile4, rm as rm3 } from "node:fs/promises";
3552
+ import { join as join4 } from "node:path";
3237
3553
 
3238
3554
  // packages/browser/src/browser/remote-helper.ts
3239
- import { readFile as readFile2 } from "node:fs/promises";
3555
+ import { readFile as readFile3 } from "node:fs/promises";
3240
3556
  import { fileURLToPath } from "node:url";
3241
3557
 
3242
3558
  // packages/browser/src/browser/remote-process.ts
@@ -3381,7 +3697,7 @@ async function readHelperSource() {
3381
3697
  let lastError;
3382
3698
  for (const path of candidates) {
3383
3699
  try {
3384
- return await readFile2(path, "utf8");
3700
+ return await readFile3(path, "utf8");
3385
3701
  } catch (error) {
3386
3702
  lastError = error;
3387
3703
  }
@@ -3423,8 +3739,8 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
3423
3739
  throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
3424
3740
  }
3425
3741
  await mkdir3(stateDirectory, { recursive: true, mode: 448 });
3426
- const staging = await mkdtemp(join3(stateDirectory, "scp-"));
3427
- const localFile = join3(staging, "screenshot.png");
3742
+ const staging = await mkdtemp(join4(stateDirectory, "scp-"));
3743
+ const localFile = join4(staging, "screenshot.png");
3428
3744
  try {
3429
3745
  const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
3430
3746
  if (copied.code !== 0) {
@@ -3435,7 +3751,7 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
3435
3751
  throw new Error(removed.stderr || removed.stdout || "copied screenshot but could not remove remote artifact");
3436
3752
  }
3437
3753
  const target = artifacts.screenshotTarget({ ref_id: host });
3438
- await target.write(await readFile3(localFile));
3754
+ await target.write(await readFile4(localFile));
3439
3755
  return target.file;
3440
3756
  } finally {
3441
3757
  await rm3(staging, { recursive: true, force: true });
@@ -3578,7 +3894,7 @@ class BrowserRuntime {
3578
3894
  config;
3579
3895
  constructor(config) {
3580
3896
  this.config = config;
3581
- if (!isAbsolute2(config.stateDirectory))
3897
+ if (!isAbsolute4(config.stateDirectory))
3582
3898
  throw new Error("Native browser stateDirectory must be absolute");
3583
3899
  this.routes = config.routes ?? new BrowserRoutes;
3584
3900
  this.hosts = this.routes.names;
@@ -3673,7 +3989,7 @@ class BrowserRuntime {
3673
3989
  let session = this.localSessions.get(ownerId);
3674
3990
  if (session)
3675
3991
  return session;
3676
- const cdp = new BrowserCdpSession(ownerId, join4(this.config.stateDirectory, "tabs"), this.config.discover);
3992
+ const cdp = new BrowserCdpSession(ownerId, join5(this.config.stateDirectory, "tabs"), this.config.discover);
3677
3993
  session = {
3678
3994
  activeCalls: 0,
3679
3995
  cdp,
@@ -3701,17 +4017,17 @@ class BrowserRuntime {
3701
4017
  }
3702
4018
  // packages/browser/src/browser/config-store.ts
3703
4019
  import { randomUUID as randomUUID2 } from "node:crypto";
3704
- import { mkdir as mkdir4, readFile as readFile4, rename, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
3705
- import { basename, dirname, isAbsolute as isAbsolute3, join as join5 } from "node:path";
4020
+ import { mkdir as mkdir4, readFile as readFile5, rename, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
4021
+ import { basename, dirname, isAbsolute as isAbsolute5, join as join6 } from "node:path";
3706
4022
  function createBrowserRouteConfigFileStore(path) {
3707
- if (!isAbsolute3(path) || !basename(path))
4023
+ if (!isAbsolute5(path) || !basename(path))
3708
4024
  throw new Error("Browser route config path must name an absolute file");
3709
4025
  const directory = dirname(path);
3710
4026
  return {
3711
4027
  id: path,
3712
4028
  async read() {
3713
4029
  try {
3714
- return await readFile4(path, "utf8");
4030
+ return await readFile5(path, "utf8");
3715
4031
  } catch (error) {
3716
4032
  if (isCode(error, "ENOENT"))
3717
4033
  return;
@@ -3724,7 +4040,7 @@ function createBrowserRouteConfigFileStore(path) {
3724
4040
  return;
3725
4041
  }
3726
4042
  await mkdir4(directory, { recursive: true });
3727
- const temporary = join5(directory, `.${basename(path)}.${process.pid}.${randomUUID2()}.tmp`);
4043
+ const temporary = join6(directory, `.${basename(path)}.${process.pid}.${randomUUID2()}.tmp`);
3728
4044
  try {
3729
4045
  await writeFile3(temporary, text, {
3730
4046
  encoding: "utf8",
@@ -3776,6 +4092,17 @@ var GROK_STATE = String.raw`(() => {
3776
4092
  const listening = !muted && mode === 'voice' && /^listening(?: ·|$)/.test(status) && status.includes(' · browser microphone connected');
3777
4093
  return {state: detail || muted ? 'error' : listening ? 'listening' : button && !button.disabled && mode === 'voice' ? 'ready' : 'waiting', status, detail: muted ? 'Microphone is muted. Unmute it in the voice page.' : detail};
3778
4094
  })()`;
4095
+ var LIVE_STATE = String.raw`(() => {
4096
+ const button = document.querySelector('#start');
4097
+ const surface = document.querySelector('#surface');
4098
+ const status = document.querySelector('#status')?.textContent?.trim() || '';
4099
+ const detail = document.querySelector('#error')?.textContent?.trim() || '';
4100
+ const conversation = document.querySelector('#mode')?.value === 'voice';
4101
+ const muted = document.querySelector('#mute')?.getAttribute('aria-pressed') === 'true';
4102
+ const ready = surface?.dataset.audioReady === 'true';
4103
+ const listening = ready && conversation && !muted && status === 'listening';
4104
+ return {state: detail || (ready && muted) ? 'error' : listening ? 'listening' : !surface?.disabled && button && !button.disabled && conversation ? 'ready' : 'waiting', status, detail: ready && muted ? 'Microphone is muted. Unmute it in the voice page.' : detail};
4105
+ })()`;
3779
4106
  function pageState(result) {
3780
4107
  if (typeof result["value"] !== "string")
3781
4108
  throw new Error("Voice page did not return its audio status");
@@ -3790,7 +4117,7 @@ async function startBrowserVoice(options, config) {
3790
4117
  if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647)
3791
4118
  throw new Error("Voice browser timeout must fit a positive signed 32-bit millisecond timer");
3792
4119
  assertHttpUrl(options.url);
3793
- if (!["codex", "gippity", "grok"].includes(options.provider))
4120
+ if (options.provider !== undefined && !["openai", "gemini", "codex", "gippity", "grok", "live"].includes(options.provider))
3794
4121
  throw new Error("Unsupported voice page provider");
3795
4122
  const timeout = AbortSignal.timeout(timeoutMs);
3796
4123
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
@@ -3798,12 +4125,16 @@ async function startBrowserVoice(options, config) {
3798
4125
  let refId;
3799
4126
  let observed = { state: "waiting", status: "", detail: "" };
3800
4127
  let clicked = false;
4128
+ const resultUrl = new URL(options.url);
4129
+ const pairing = options.provider === "live" ? new URLSearchParams(resultUrl.hash.slice(1)).get("pair") : null;
4130
+ if (options.provider === "live")
4131
+ resultUrl.hash = "";
3801
4132
  const result = (state, detail = observed.detail) => ({
3802
4133
  state,
3803
- url: options.url,
4134
+ url: options.provider === "live" ? resultUrl.href : options.url,
3804
4135
  ...refId ? { refId } : {},
3805
4136
  status: observed.status,
3806
- detail
4137
+ detail: pairing ? detail.replaceAll(pairing, "[voice pairing token]") : detail
3807
4138
  });
3808
4139
  try {
3809
4140
  const browser = new BrowserRuntime(config);
@@ -3812,14 +4143,20 @@ async function startBrowserVoice(options, config) {
3812
4143
  operations: [operation],
3813
4144
  ...options.host ? { host: options.host } : {}
3814
4145
  }, { signal });
3815
- const opened = await execute({ action: "open", url: options.url });
4146
+ const pageUrl = new URL(options.url);
4147
+ if (options.provider === "live" && pageUrl.pathname === "/")
4148
+ pageUrl.searchParams.set("bundled", "1");
4149
+ const opened = await execute({
4150
+ action: "open",
4151
+ url: options.provider === "live" ? pageUrl.href : options.url
4152
+ });
3816
4153
  if (opened["owned"] !== true || typeof opened["ref_id"] !== "string")
3817
4154
  throw new Error("Browser did not confirm ownership of the new voice tab");
3818
4155
  refId = opened["ref_id"];
3819
4156
  await execute({
3820
4157
  action: "wait",
3821
4158
  ref_id: refId,
3822
- selector: options.provider === "grok" ? "#start" : "#voice",
4159
+ selector: options.provider === "live" ? "#surface #start" : options.provider === "grok" ? "#voice, #start" : "#voice",
3823
4160
  timeout_ms: timeoutMs
3824
4161
  });
3825
4162
  while (true) {
@@ -3827,7 +4164,7 @@ async function startBrowserVoice(options, config) {
3827
4164
  observed = pageState(await execute({
3828
4165
  action: "evaluate",
3829
4166
  ref_id: refId,
3830
- expression: options.provider === "grok" ? GROK_STATE : CONVERSATION_STATE
4167
+ expression: options.provider === "live" ? LIVE_STATE : options.provider === "grok" ? `document.querySelector("#voice") ? ${CONVERSATION_STATE} : ${GROK_STATE}` : CONVERSATION_STATE
3831
4168
  }));
3832
4169
  if (observed.state === "listening")
3833
4170
  return result("listening");
@@ -3838,7 +4175,7 @@ async function startBrowserVoice(options, config) {
3838
4175
  await execute({
3839
4176
  action: "click",
3840
4177
  ref_id: refId,
3841
- selector: options.provider === "grok" ? "#start" : "#voice"
4178
+ selector: options.provider === "live" ? "#surface #start" : options.provider === "grok" ? "#voice, body:not(:has(#voice)) #start" : "#voice"
3842
4179
  });
3843
4180
  }
3844
4181
  await sleep(200, signal);