@generativereality/browser-automation 0.6.1 → 0.7.2

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
@@ -1,17 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
4
- import { createServer } from "node:net";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
6
+ import { createConnection, createServer } from "node:net";
5
7
  import { homedir, tmpdir } from "node:os";
6
8
  import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
7
- import { accessSync, appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
8
9
  import { execFileSync, spawn, spawnSync } from "node:child_process";
9
10
  import consola, { consola as consola$1 } from "consola";
10
11
  import { fileURLToPath } from "node:url";
11
12
  //#region package.json
12
13
  var name = "@generativereality/browser-automation";
13
- var version = "0.6.1";
14
- var description = "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.";
14
+ var version = "0.7.2";
15
+ var description = "Let many Claude Code sessions use your own signed-in Chrome at once, each in its own tab, without stealing your screen. Daemonless CLI over per-target CDP: persistent profile and extensions, no MCP server, nothing long-lived to crash.";
15
16
  var package_default = {
16
17
  name,
17
18
  version,
@@ -40,7 +41,11 @@ var package_default = {
40
41
  "cdp",
41
42
  "chrome-devtools-protocol",
42
43
  "playwright-alternative",
43
- "ai-agents"
44
+ "ai-agents",
45
+ "chrome",
46
+ "claude-code-plugin",
47
+ "parallel-agents",
48
+ "cli"
44
49
  ],
45
50
  author: "motin",
46
51
  license: "MIT",
@@ -256,6 +261,78 @@ function cdpHost() {
256
261
  return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
257
262
  }
258
263
  /**
264
+ * Pipe or port.
265
+ *
266
+ * The port is reachable by every process on the machine and has no
267
+ * authentication, so anything local could drive this user's signed-in browser.
268
+ * The pipe is not reachable at all except through the broker's socket, which
269
+ * lives in a 0700 directory under ~ and is itself 0600.
270
+ *
271
+ * Port stays only where somebody asked for it: `BROWSER_AUTOMATION_CDP` names one
272
+ * explicitly (a browser somebody else started, the test fakes). It does not
273
+ * apply to a login context, which is always this CLI's own Chrome, on its own
274
+ * broker. Windows and contexts were on the port until 0.7.0.
275
+ */
276
+ function usesPipe() {
277
+ if (activeContext()) return true;
278
+ return !process.env.BROWSER_AUTOMATION_CDP;
279
+ }
280
+ function baseDir() {
281
+ return process.env.BROWSER_AUTOMATION_HOME || join(homedir(), ".browser-automation");
282
+ }
283
+ /**
284
+ * The broker's directory: state file, lock, broker and Chrome logs, and (macOS,
285
+ * Linux) the socket. 0700. A login context's is its own folder, beside its profile.
286
+ */
287
+ function brokerDir() {
288
+ const ctx = activeContext();
289
+ return ctx ? join(contextsDir(), ctx.name) : baseDir();
290
+ }
291
+ /** The state file a broker writes once it serves: pids, profile, and where it listens. */
292
+ function brokerStatePath(dir = brokerDir()) {
293
+ return join(dir, "broker.json");
294
+ }
295
+ /**
296
+ * Where the broker for the active Chrome listens.
297
+ *
298
+ * macOS and Linux: a Unix socket in the broker's 0700 directory. Its path is
299
+ * capped at 104 bytes on macOS, and a context's folder can be longer than that
300
+ * allows (a 64-character name), so a long one gets a short socket in a 0700
301
+ * folder of its own, named after the directory it stands for.
302
+ *
303
+ * Windows: a named pipe. Named pipes have no directory to protect them, so the
304
+ * broker picks a random name when it starts and records it in its state file,
305
+ * which only this user can read. Nobody else can guess the name, so nobody can
306
+ * create it first and wait for us to connect, and the pipe's default ACL keeps
307
+ * other accounts from opening it for writing. Measured on Windows 11 ARM64
308
+ * (Node 22, 2026-10-27): full control for this user, SYSTEM and Administrators;
309
+ * Read only for Everyone and Anonymous, which drives nothing: a read-only
310
+ * connection cannot send the line that attaches it, and each connection is its
311
+ * own pipe instance. Before a broker has written its state, this is a name that
312
+ * answers nothing.
313
+ */
314
+ function socketPath() {
315
+ if (process.env.BROWSER_AUTOMATION_SOCKET && !activeContext()) return process.env.BROWSER_AUTOMATION_SOCKET;
316
+ const dir = brokerDir();
317
+ if (process.platform === "win32") {
318
+ try {
319
+ const st = JSON.parse(readFileSync(brokerStatePath(dir), "utf8"));
320
+ if (typeof st.socket === "string" && st.socket.startsWith("\\\\.\\pipe\\")) return st.socket;
321
+ } catch {}
322
+ return "\\\\.\\pipe\\browser-automation-not-running";
323
+ }
324
+ const p = join(dir, "cdp.sock");
325
+ if (Buffer.byteLength(p) <= 100) return p;
326
+ return join(baseDir(), "sockets", `${createHash("sha256").update(dir).digest("hex").slice(0, 16)}.sock`);
327
+ }
328
+ /** What to call the browser we are driving, in messages. */
329
+ function endpointLabel() {
330
+ return usesPipe() ? `the browser behind ${socketPath()}` : cdpHost();
331
+ }
332
+ /** Endpoints handed around in place of webSocketDebuggerUrl when on the pipe. */
333
+ const PIPE_BROWSER = "pipe:browser";
334
+ const pipePage = (targetId) => `pipe:target:${targetId}`;
335
+ /**
259
336
  * Ports for login contexts, decided here like every other port. A block well
260
337
  * above the per-user range (BASE_PORT … BASE_PORT+999), so a context can never
261
338
  * land on another account's Chrome. The first free one not already given to a
@@ -283,7 +360,7 @@ async function allocateContextPort(taken) {
283
360
  var TargetGoneError = class extends Error {
284
361
  targetId;
285
362
  constructor(targetId) {
286
- super(`target ${targetId} not found on ${cdpHost()} (tab closed or Chrome restarted)`);
363
+ super(`target ${targetId} not found on ${endpointLabel()} (tab closed or Chrome restarted)`);
287
364
  this.targetId = targetId;
288
365
  this.name = "TargetGoneError";
289
366
  }
@@ -294,10 +371,23 @@ async function httpJson(path) {
294
371
  return await res.json();
295
372
  }
296
373
  async function browserWsUrl() {
374
+ if (usesPipe()) return PIPE_BROWSER;
297
375
  return (await httpJson("/json/version")).webSocketDebuggerUrl;
298
376
  }
377
+ /** `Browser.getVersion`, from either transport. Throws when nothing answers. */
378
+ async function browserVersion(timeout = 5e3) {
379
+ if (!usesPipe()) return { product: (await httpJson("/json/version")).Browser };
380
+ return withBrowser((s) => s.send("Browser.getVersion", {}, timeout), timeout);
381
+ }
299
382
  async function listTargets() {
300
- return httpJson("/json/list");
383
+ if (!usesPipe()) return httpJson("/json/list");
384
+ return (await withBrowser((s) => s.send("Target.getTargets"))).targetInfos.filter((t) => t.type !== "browser_ui" && t.type !== "browser").map((t) => ({
385
+ id: t.targetId,
386
+ type: t.type,
387
+ title: t.title,
388
+ url: t.url,
389
+ webSocketDebuggerUrl: pipePage(t.targetId)
390
+ }));
301
391
  }
302
392
  async function listPageTargets() {
303
393
  return (await listTargets()).filter((t) => t.type === "page");
@@ -306,8 +396,10 @@ async function listPageTargets() {
306
396
  async function targetWsUrl(targetId) {
307
397
  return (await listTargets()).find((t) => t.id === targetId)?.webSocketDebuggerUrl ?? null;
308
398
  }
309
- /** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser). */
399
+ /** Open a CDP session to an arbitrary webSocketDebuggerUrl (page or browser), or
400
+ * to a `pipe:` endpoint from this module, which goes through the broker. */
310
401
  function connect(wsUrl, { timeout = 15e3 } = {}) {
402
+ if (wsUrl.startsWith("pipe:")) return connectPipe(wsUrl, timeout);
311
403
  return new Promise((resolve, reject) => {
312
404
  const ws = new WebSocket(wsUrl);
313
405
  let nextId = 1;
@@ -378,6 +470,109 @@ function connect(wsUrl, { timeout = 15e3 } = {}) {
378
470
  });
379
471
  });
380
472
  }
473
+ /**
474
+ * One connection to the broker, bound to one target (or to the browser).
475
+ *
476
+ * The broker speaks CDP's own JSON, one message per line, after a one-line
477
+ * handshake naming what to attach to. It answers the handshake once the session
478
+ * exists, so a tab that has gone fails here, as a closed tab's WebSocket would.
479
+ */
480
+ function connectPipe(endpoint, timeout) {
481
+ const attach = endpoint === PIPE_BROWSER ? { attach: "browser" } : {
482
+ attach: "target",
483
+ targetId: endpoint.slice(12)
484
+ };
485
+ return new Promise((resolve, reject) => {
486
+ const sock = createConnection(socketPath());
487
+ let nextId = 1;
488
+ let ready = false;
489
+ let buf = "";
490
+ const pending = /* @__PURE__ */ new Map();
491
+ const listeners = /* @__PURE__ */ new Map();
492
+ const fail = (e) => {
493
+ for (const p of pending.values()) p.reject(e);
494
+ pending.clear();
495
+ };
496
+ const openTimer = setTimeout(() => {
497
+ sock.destroy();
498
+ reject(/* @__PURE__ */ new Error(`CDP connect timeout ${timeout}ms to ${socketPath()}`));
499
+ }, timeout);
500
+ sock.setEncoding("utf8");
501
+ sock.on("connect", () => sock.write(JSON.stringify(attach) + "\n"));
502
+ sock.on("data", (chunk) => {
503
+ buf += chunk;
504
+ let nl;
505
+ while ((nl = buf.indexOf("\n")) >= 0) {
506
+ const line = buf.slice(0, nl);
507
+ buf = buf.slice(nl + 1);
508
+ let msg;
509
+ try {
510
+ msg = JSON.parse(line);
511
+ } catch {
512
+ continue;
513
+ }
514
+ if (!ready) {
515
+ clearTimeout(openTimer);
516
+ if (msg.error) {
517
+ sock.destroy();
518
+ reject(new Error(String(msg.error)));
519
+ return;
520
+ }
521
+ ready = true;
522
+ resolve(session);
523
+ continue;
524
+ }
525
+ if (typeof msg.id === "number" && pending.has(msg.id)) {
526
+ const p = pending.get(msg.id);
527
+ pending.delete(msg.id);
528
+ if (msg.error) p.reject(/* @__PURE__ */ new Error(`${p.method}: ${msg.error.message ?? JSON.stringify(msg.error)}`));
529
+ else p.resolve(msg.result);
530
+ } else if (msg.method) for (const cb of listeners.get(msg.method) ?? []) cb(msg.params);
531
+ }
532
+ });
533
+ sock.on("error", (e) => {
534
+ clearTimeout(openTimer);
535
+ const err = e?.code === "ENOENT" || e?.code === "ECONNREFUSED" ? /* @__PURE__ */ new Error(`no browser on ${socketPath()} — run: browser-automation launch`) : /* @__PURE__ */ new Error(`socket error on ${socketPath()}: ${e?.message ?? e}`);
536
+ if (!ready) reject(err);
537
+ fail(err);
538
+ });
539
+ sock.on("close", () => fail(/* @__PURE__ */ new Error("the browser connection closed (tab closed or Chrome quit)")));
540
+ const session = {
541
+ send(method, params = {}, timeoutMs = 3e4) {
542
+ return new Promise((res, rej) => {
543
+ const id = nextId++;
544
+ const t = setTimeout(() => {
545
+ if (pending.delete(id)) rej(/* @__PURE__ */ new Error(`CDP ${method} timed out after ${timeoutMs}ms`));
546
+ }, timeoutMs);
547
+ pending.set(id, {
548
+ resolve: (v) => {
549
+ clearTimeout(t);
550
+ res(v);
551
+ },
552
+ reject: (e) => {
553
+ clearTimeout(t);
554
+ rej(e);
555
+ },
556
+ method
557
+ });
558
+ sock.write(JSON.stringify({
559
+ id,
560
+ method,
561
+ params
562
+ }) + "\n");
563
+ });
564
+ },
565
+ on(method, cb) {
566
+ const arr = listeners.get(method) ?? [];
567
+ arr.push(cb);
568
+ listeners.set(method, arr);
569
+ },
570
+ close() {
571
+ sock.end();
572
+ }
573
+ };
574
+ });
575
+ }
381
576
  /** Run `fn` against a session bound to a single page target, then close it. */
382
577
  async function withPage(targetId, fn) {
383
578
  const wsUrl = await targetWsUrl(targetId);
@@ -620,7 +815,7 @@ function resolveProfile() {
620
815
  };
621
816
  }
622
817
  /** Is any Chrome of ours running with this --user-data-dir? */
623
- function inUse(dir) {
818
+ function profileInUse(dir) {
624
819
  try {
625
820
  execFileSync("pgrep", [
626
821
  "-u",
@@ -652,7 +847,7 @@ function migrateProfile() {
652
847
  dir: legacy,
653
848
  detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
654
849
  };
655
- if (inUse(legacy)) return {
850
+ if (profileInUse(legacy)) return {
656
851
  outcome: "in-use",
657
852
  dir: legacy,
658
853
  detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
@@ -763,7 +958,19 @@ const SITE_DATA = new Set([
763
958
  "Device Bound Sessions",
764
959
  "Device Bound Sessions-journal",
765
960
  "passkey_enclave_state",
766
- join("Service Worker", "CacheStorage")
961
+ join("Service Worker", "CacheStorage"),
962
+ ...[
963
+ "Cookies",
964
+ "Cookies-journal",
965
+ "Network Persistent State",
966
+ "Reporting and NEL",
967
+ "Reporting and NEL-journal",
968
+ "Trust Tokens",
969
+ "Trust Tokens-journal",
970
+ "Device Bound Sessions",
971
+ "Device Bound Sessions-journal",
972
+ "SCT Auditing Pending Reports"
973
+ ].map((f) => join("Network", f))
767
974
  ]);
768
975
  function keep(src, root, mode) {
769
976
  const rel = relative(root, src);
@@ -1326,202 +1533,995 @@ async function ensureRenderer(targetId, { grace, budget, allowWake = !process.en
1326
1533
  };
1327
1534
  }
1328
1535
  //#endregion
1329
- //#region src/core/renderer-health.ts
1330
- /** First attempt's budget. Later attempts double it. */
1331
- const DEFAULT_TIMEOUT = 5e3;
1332
- /** How many times we ask before we are willing to call a browser broken. */
1333
- const DEFAULT_ATTEMPTS = 3;
1334
- /** Breathing room between attempts — a browser mid-GC deserves a second look. */
1335
- const RETRY_PAUSE = 400;
1336
- /**
1337
- * The verdict, from the probe and the corroborations — and from nothing else.
1338
- *
1339
- * Pure, and separate from the probing, because this is the decision that was
1340
- * wrong: every failure used to become 'wedged' by default. Now 'wedged'
1341
- * requires `rendezvous === false`, which is the only thing that has ever
1342
- * actually meant it.
1343
- */
1344
- function rendererVerdict(outcome, e) {
1345
- if (outcome === "ok") return "healthy";
1346
- if (e?.rendezvous === false) return "wedged";
1347
- if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
1348
- return "unknown";
1349
- }
1350
- /**
1351
- * Create a throwaway tab, make its renderer prove it is alive, close it.
1352
- *
1353
- * Three things changed after 2026-09-11, and each of them is load-bearing:
1354
- *
1355
- * 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
1356
- * tool opens tabs AND gets the same wake treatment. A probe that is harsher
1357
- * on itself than `goto` is on a real tab reports failures `goto` would not
1358
- * have had.
1359
- * 2. It retries with a doubling budget. One 5s timeout is not evidence of a
1360
- * permanent condition; it is evidence of 5 seconds.
1361
- * 3. It stops early when the Mach name is ABSENT — the one state where more
1362
- * waiting is genuinely pointless — so the real failure is still reported
1363
- * fast while a slow browser gets the benefit of the doubt.
1364
- */
1365
- async function probeRenderer({ timeout, attempts } = {}) {
1366
- const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
1367
- const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
1368
- const started = Date.now();
1369
- let pageTargets = 0;
1370
- try {
1371
- pageTargets = (await listPageTargets()).length;
1372
- } catch {}
1373
- const tries = [];
1374
- let evidence;
1375
- for (let i = 0; i < maxAttempts; i++) {
1376
- const budget = base * 2 ** i;
1377
- tries.push(await probeOnce(budget));
1378
- if (tries[tries.length - 1].outcome === "ok") return finish({
1379
- ok: true,
1380
- started,
1381
- pageTargets,
1382
- tries,
1383
- evidence
1384
- });
1385
- evidence ??= gatherEvidence();
1386
- if (evidence.rendezvous === false) break;
1387
- if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
1388
- }
1389
- return finish({
1390
- ok: false,
1391
- started,
1392
- pageTargets,
1393
- tries,
1394
- evidence
1395
- });
1536
+ //#region src/core/broker.ts
1537
+ function statePath(dir) {
1538
+ return join(dir, "broker.json");
1396
1539
  }
1397
- function finish({ ok, started, pageTargets, tries, evidence }) {
1398
- const last = tries[tries.length - 1];
1399
- const health = {
1400
- ok,
1401
- ms: Date.now() - started,
1402
- pageTargets,
1403
- reason: last?.reason,
1404
- outcome: last?.outcome ?? "error",
1405
- verdict: rendererVerdict(last?.outcome ?? "error", evidence),
1406
- attempts: tries,
1407
- evidence
1408
- };
1409
- recordProbe(health);
1410
- return health;
1540
+ const windows = process.platform === "win32";
1541
+ /** A named pipe nobody can predict, so nobody can create it before we do. */
1542
+ function windowsPipeName() {
1543
+ return `\\\\.\\pipe\\browser-automation-${randomUUID()}`;
1411
1544
  }
1412
- /** One create -> ensure -> close cycle. */
1413
- async function probeOnce(budget) {
1414
- const started = Date.now();
1415
- let targetId;
1416
- try {
1417
- targetId = await createTab("about:blank", { timeout: budget });
1418
- } catch (e) {
1419
- return {
1420
- outcome: "error",
1421
- budget,
1422
- ms: Date.now() - started,
1423
- woke: false,
1424
- reason: `could not create a target at all: ${e?.message ?? e}`
1425
- };
1426
- }
1545
+ function servedSocket(dir) {
1427
1546
  try {
1428
- const r = await ensureRenderer(targetId, {
1429
- grace: budget,
1430
- budget
1431
- });
1432
- return {
1433
- outcome: r.outcome,
1434
- budget,
1435
- ms: Date.now() - started,
1436
- woke: r.woke,
1437
- reason: r.reason
1438
- };
1439
- } finally {
1440
- if (targetId) await closeTab(targetId).catch(() => {});
1547
+ return JSON.parse(readFileSync(statePath(dir), "utf8")).socket ?? null;
1548
+ } catch {
1549
+ return null;
1441
1550
  }
1442
1551
  }
1443
1552
  /**
1444
- * Ask an EXISTING target's renderer to prove it is alive.
1445
- *
1446
- * Kept returning `string | null` because that is what `gc` wants (a reason to
1447
- * print beside a tab it is about to close). New callers should prefer
1448
- * `askRenderer`, which says WHICH failure it was.
1553
+ * Chrome marks itself automated (navigator.webdriver = true, the
1554
+ * AutomationControlled Blink feature) whenever it is started with
1555
+ * --remote-debugging-pipe, as it does for --enable-automation and headless; the
1556
+ * port never did. Cloudflare's Turnstile refuses a browser with that mark however
1557
+ * often the person ticks the box, so from the move to the pipe (#34, 2026-10-27)
1558
+ * claude.ai and dash.cloudflare.com stopped passing in a Chrome that had passed
1559
+ * them for months. This is the person's own headed, signed-in browser, not a
1560
+ * test harness: switch the mark off and keep the pipe.
1449
1561
  */
1450
- async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
1451
- const r = await askRenderer(targetId, timeout);
1452
- return r.outcome === "ok" ? null : r.reason ?? r.outcome;
1562
+ const NO_AUTOMATION_MARK = "--disable-blink-features=AutomationControlled";
1563
+ /** The flags Chrome is started with. The profile flag is also how `ps` finds it. */
1564
+ function chromeArgs(profile, extra = []) {
1565
+ return [
1566
+ "--remote-debugging-pipe",
1567
+ NO_AUTOMATION_MARK,
1568
+ `--user-data-dir=${profile}`,
1569
+ "--no-first-run",
1570
+ "--no-default-browser-check",
1571
+ ...extra,
1572
+ "about:blank"
1573
+ ];
1453
1574
  }
1454
- /**
1455
- * The port we are actually talking to.
1456
- *
1457
- * NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
1458
- * arbitrary host:port, and everything here that shells out to `ps` or
1459
- * `launchctl` has to ask about THAT browser. Using the uid-derived port instead
1460
- * finds the user's default Chrome and cheerfully reports its health as if it
1461
- * were the one being driven — caught while testing this module against a second
1462
- * Chrome, where a perfectly healthy browser was accused of having lost a
1463
- * bootstrap name that in fact belonged to a different pid.
1464
- */
1465
- function targetPort() {
1466
- const explicit = process.env.BROWSER_AUTOMATION_CDP;
1467
- if (explicit) try {
1468
- const p = Number(new URL(explicit).port);
1469
- if (Number.isInteger(p) && p > 0) return p;
1470
- } catch {}
1471
- return cdpPort();
1575
+ /** Does something answer on this socket? Connect-and-close; no CDP. */
1576
+ function socketAnswers(socket, timeout = 1e3) {
1577
+ return new Promise((resolve) => {
1578
+ const s = createConnection(socket);
1579
+ const t = setTimeout(() => {
1580
+ s.destroy();
1581
+ resolve(false);
1582
+ }, timeout);
1583
+ s.on("connect", () => {
1584
+ clearTimeout(t);
1585
+ s.destroy();
1586
+ resolve(true);
1587
+ });
1588
+ s.on("error", () => {
1589
+ clearTimeout(t);
1590
+ resolve(false);
1591
+ });
1592
+ });
1472
1593
  }
1594
+ const alive$2 = (pid) => {
1595
+ try {
1596
+ process.kill(pid, 0);
1597
+ return true;
1598
+ } catch {
1599
+ return false;
1600
+ }
1601
+ };
1473
1602
  /**
1474
- * The browser process serving our port, and how many renderers it has.
1475
- *
1476
- * One `ps`, not one `pgrep` plus one `ps` per hit: on a Chrome with 40 children
1477
- * that was 41 forks to answer two questions, and it ran on the error path of a
1478
- * browser already thought to be struggling.
1603
+ * Become the one broker for this directory, or learn that another one is. Two
1604
+ * `launch` runs at once (two tabs both finding no browser) each start a broker,
1605
+ * and before either listens, the socket check below passes for both: both then
1606
+ * spawn Chrome on the same profile, one Chrome hands off to the other through
1607
+ * the profile lock and exits, and one broker's listen fails. An O_EXCL pid file
1608
+ * taken before Chrome is spawned leaves exactly one. A lock whose pid is gone
1609
+ * was left by a broker that died, and is taken over.
1479
1610
  *
1480
- * The executable check is not decoration. Matching on the command line alone
1481
- * (as `pgrep -f` does) hits any process that merely CONTAINS the debugging-port
1482
- * flag — the `grep` looking for it, or a shell running `browser-automation`
1483
- * with the flag as an argument. One of those, having no `--type=`, would have
1484
- * been reported as the browser pid, and its absent Mach name read as the
1485
- * permanent failure. Seen while writing this: a `ugrep` for the flag sat in
1486
- * `ps` output alongside the real Chrome.
1611
+ * The pid is written to a file of our own first and linked into place, so the
1612
+ * lock never exists without it. Created empty and written after, a broker that
1613
+ * read it in between found no pid, took it for a dead broker's, and took the
1614
+ * lock as well: two brokers, and the second one's listen failed.
1487
1615
  */
1488
- function chromeProcesses() {
1489
- const flag = `--remote-debugging-port=${targetPort()}`;
1490
- const uid = String(process.getuid?.() ?? -1);
1491
- let out;
1616
+ function takeLock(lock) {
1617
+ const mine = `${lock}.${process.pid}`;
1618
+ writeFileSync(mine, `${process.pid}\n`, { mode: 384 });
1492
1619
  try {
1493
- out = execFileSync("ps", ["-Ao", "pid=,uid=,command="], {
1494
- encoding: "utf8",
1495
- maxBuffer: 64 * 1024 * 1024,
1496
- stdio: [
1497
- "ignore",
1498
- "pipe",
1499
- "ignore"
1500
- ]
1620
+ for (let attempt = 0; attempt < 2; attempt++) try {
1621
+ linkSync(mine, lock);
1622
+ return true;
1623
+ } catch (e) {
1624
+ if (e.code !== "EEXIST") throw e;
1625
+ let pid = NaN;
1626
+ try {
1627
+ pid = Number.parseInt(readFileSync(lock, "utf8"), 10);
1628
+ } catch (r) {
1629
+ if (r.code !== "ENOENT") throw r;
1630
+ }
1631
+ if (Number.isInteger(pid) && pid > 0 && alive$2(pid)) return false;
1632
+ rmSync(lock, { force: true });
1633
+ }
1634
+ return false;
1635
+ } finally {
1636
+ rmSync(mine, { force: true });
1637
+ }
1638
+ }
1639
+ const sleep$5 = (ms) => new Promise((r) => setTimeout(r, ms));
1640
+ async function runBroker(o) {
1641
+ process.umask(63);
1642
+ const dir = o.dir;
1643
+ for (const d of windows ? [dir] : [dir, dirname(o.socket)]) {
1644
+ mkdirSync(d, {
1645
+ recursive: true,
1646
+ mode: 448
1501
1647
  });
1502
- } catch {
1503
- return {
1504
- browser: null,
1505
- renderers: null
1506
- };
1648
+ chmodSync(d, 448);
1507
1649
  }
1508
- let browser = null;
1509
- let renderers = 0;
1510
- for (const line of out.split("\n")) {
1511
- const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
1512
- if (!m) continue;
1513
- const [, pid, u, cmd] = m;
1514
- if (u !== uid || !cmd.includes(flag)) continue;
1515
- if (!/chrome|chromium|brave|msedge|thorium/i.test(cmd.split(" --")[0])) continue;
1516
- if (/--type=renderer\b/.test(cmd)) renderers++;
1517
- else if (!cmd.includes("--type=")) browser = Number(pid);
1650
+ const lock = join(dir, "broker.lock");
1651
+ if (!takeLock(lock)) {
1652
+ for (let i = 0; i < 240; i++) {
1653
+ const theirs = windows ? servedSocket(dir) : o.socket;
1654
+ if (theirs && await socketAnswers(theirs)) return;
1655
+ await sleep$5(250);
1656
+ }
1657
+ throw new Error(`another broker holds ${lock}, but nothing answered on ${o.socket} within 60s`);
1518
1658
  }
1519
- return {
1520
- browser,
1521
- renderers
1659
+ const releaseLock = () => {
1660
+ try {
1661
+ if (readFileSync(lock, "utf8").trim() === String(process.pid)) rmSync(lock, { force: true });
1662
+ } catch {}
1522
1663
  };
1523
- }
1524
- /** The pid of the browser process serving the port we are driving, if visible. */
1664
+ try {
1665
+ await serve(o, releaseLock);
1666
+ } finally {
1667
+ releaseLock();
1668
+ }
1669
+ }
1670
+ async function serve(o, releaseLock) {
1671
+ const dir = o.dir;
1672
+ if (!windows && existsSync(o.socket)) {
1673
+ if (await socketAnswers(o.socket)) throw new Error(`a broker is already serving ${o.socket}`);
1674
+ rmSync(o.socket, { force: true });
1675
+ }
1676
+ const logFd = openSync(o.log, "a", 384);
1677
+ const chrome = spawn(o.chrome, chromeArgs(o.profile, o.extraArgs), { stdio: [
1678
+ "ignore",
1679
+ logFd,
1680
+ logFd,
1681
+ "pipe",
1682
+ "pipe"
1683
+ ] });
1684
+ closeSync(logFd);
1685
+ const toChrome = chrome.stdio[3];
1686
+ const fromChrome = chrome.stdio[4];
1687
+ let nextId = 1;
1688
+ const relayed = /* @__PURE__ */ new Map();
1689
+ const own = /* @__PURE__ */ new Map();
1690
+ const bySession = /* @__PURE__ */ new Map();
1691
+ const clients = /* @__PURE__ */ new Set();
1692
+ const socks = /* @__PURE__ */ new Set();
1693
+ const toPipe = (msg) => toChrome.write(JSON.stringify(msg) + "\0");
1694
+ const ask = (method, params) => new Promise((resolve) => {
1695
+ const id = nextId++;
1696
+ own.set(id, resolve);
1697
+ toPipe({
1698
+ id,
1699
+ method,
1700
+ params
1701
+ });
1702
+ });
1703
+ const tell = (c, msg) => {
1704
+ if (!c.sock.destroyed) c.sock.write(JSON.stringify(msg) + "\n");
1705
+ };
1706
+ let buf = "";
1707
+ fromChrome.setEncoding("utf8");
1708
+ fromChrome.on("data", (chunk) => {
1709
+ buf += chunk;
1710
+ let end;
1711
+ while ((end = buf.indexOf("\0")) >= 0) {
1712
+ const raw = buf.slice(0, end);
1713
+ buf = buf.slice(end + 1);
1714
+ let msg;
1715
+ try {
1716
+ msg = JSON.parse(raw);
1717
+ } catch {
1718
+ continue;
1719
+ }
1720
+ if (typeof msg.id === "number") {
1721
+ const mine = own.get(msg.id);
1722
+ if (mine) {
1723
+ own.delete(msg.id);
1724
+ mine(msg);
1725
+ continue;
1726
+ }
1727
+ const r = relayed.get(msg.id);
1728
+ if (!r) continue;
1729
+ relayed.delete(msg.id);
1730
+ const { sessionId: _drop, ...rest } = msg;
1731
+ tell(r.client, {
1732
+ ...rest,
1733
+ id: r.id
1734
+ });
1735
+ continue;
1736
+ }
1737
+ if (msg.sessionId) {
1738
+ const c = bySession.get(msg.sessionId);
1739
+ if (c) tell(c, {
1740
+ method: msg.method,
1741
+ params: msg.params
1742
+ });
1743
+ continue;
1744
+ }
1745
+ if (msg.method === "Target.detachedFromTarget") {
1746
+ const c = bySession.get(msg.params?.sessionId);
1747
+ if (c) {
1748
+ bySession.delete(msg.params.sessionId);
1749
+ c.sessionId = null;
1750
+ c.sock.end();
1751
+ }
1752
+ }
1753
+ for (const c of clients) if (c.browser) tell(c, {
1754
+ method: msg.method,
1755
+ params: msg.params
1756
+ });
1757
+ }
1758
+ });
1759
+ const server = createServer((sock) => {
1760
+ socks.add(sock);
1761
+ sock.on("close", () => socks.delete(sock));
1762
+ const c = {
1763
+ sock,
1764
+ sessionId: null,
1765
+ browser: false
1766
+ };
1767
+ let attached = false;
1768
+ let pending = "";
1769
+ sock.setEncoding("utf8");
1770
+ sock.on("data", async (chunk) => {
1771
+ pending += chunk;
1772
+ let nl;
1773
+ while ((nl = pending.indexOf("\n")) >= 0) {
1774
+ const line = pending.slice(0, nl);
1775
+ pending = pending.slice(nl + 1);
1776
+ let msg;
1777
+ try {
1778
+ msg = JSON.parse(line);
1779
+ } catch {
1780
+ sock.destroy();
1781
+ return;
1782
+ }
1783
+ if (!attached) {
1784
+ attached = true;
1785
+ sock.pause();
1786
+ if (msg.attach === "browser") c.browser = true;
1787
+ else if (msg.attach === "target" && typeof msg.targetId === "string") {
1788
+ const r = await ask("Target.attachToTarget", {
1789
+ targetId: msg.targetId,
1790
+ flatten: true
1791
+ });
1792
+ if (sock.destroyed) {
1793
+ if (!r.error) toPipe({
1794
+ id: nextId++,
1795
+ method: "Target.detachFromTarget",
1796
+ params: { sessionId: r.result.sessionId }
1797
+ });
1798
+ return;
1799
+ }
1800
+ if (r.error) {
1801
+ tell(c, { error: `target ${msg.targetId}: ${r.error.message}` });
1802
+ sock.end();
1803
+ return;
1804
+ }
1805
+ c.sessionId = r.result.sessionId;
1806
+ bySession.set(c.sessionId, c);
1807
+ } else {
1808
+ tell(c, { error: "first line must be {\"attach\":\"browser\"} or {\"attach\":\"target\",\"targetId\":…}" });
1809
+ sock.end();
1810
+ return;
1811
+ }
1812
+ clients.add(c);
1813
+ tell(c, { attached: true });
1814
+ sock.resume();
1815
+ continue;
1816
+ }
1817
+ if (typeof msg.id !== "number" || typeof msg.method !== "string") continue;
1818
+ const id = nextId++;
1819
+ relayed.set(id, {
1820
+ client: c,
1821
+ id: msg.id
1822
+ });
1823
+ toPipe({
1824
+ id,
1825
+ method: msg.method,
1826
+ params: msg.params ?? {},
1827
+ ...c.sessionId ? { sessionId: c.sessionId } : {}
1828
+ });
1829
+ }
1830
+ });
1831
+ const gone = () => {
1832
+ if (!clients.delete(c)) return;
1833
+ for (const [id, r] of relayed) if (r.client === c) relayed.delete(id);
1834
+ if (c.sessionId) {
1835
+ bySession.delete(c.sessionId);
1836
+ toPipe({
1837
+ id: nextId++,
1838
+ method: "Target.detachFromTarget",
1839
+ params: { sessionId: c.sessionId }
1840
+ });
1841
+ }
1842
+ };
1843
+ sock.on("close", gone);
1844
+ sock.on("error", gone);
1845
+ });
1846
+ await new Promise((resolve, reject) => {
1847
+ server.once("error", reject);
1848
+ server.listen(o.socket, () => resolve());
1849
+ });
1850
+ if (!windows) chmodSync(o.socket, 384);
1851
+ const state = {
1852
+ brokerPid: process.pid,
1853
+ chromePid: chrome.pid ?? -1,
1854
+ profile: o.profile,
1855
+ socket: o.socket,
1856
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1857
+ };
1858
+ writeFileSync(statePath(dir), JSON.stringify(state, null, 2) + "\n", { mode: 384 });
1859
+ const cleanup = () => {
1860
+ server.close();
1861
+ for (const s of socks) s.destroy();
1862
+ if (!windows) rmSync(o.socket, { force: true });
1863
+ rmSync(statePath(dir), { force: true });
1864
+ releaseLock();
1865
+ };
1866
+ const stop = () => {
1867
+ toPipe({
1868
+ id: nextId++,
1869
+ method: "Browser.close",
1870
+ params: {}
1871
+ });
1872
+ setTimeout(() => toChrome.end(), 1e4).unref();
1873
+ setTimeout(() => chrome.kill("SIGKILL"), 2e4).unref();
1874
+ };
1875
+ process.on("SIGTERM", stop);
1876
+ process.on("SIGINT", stop);
1877
+ await new Promise((resolve) => {
1878
+ chrome.on("exit", () => resolve());
1879
+ chrome.on("error", (e) => {
1880
+ appendFileSync(o.log, `browser-automation broker: could not start ${o.chrome}: ${e.message}\n`);
1881
+ resolve();
1882
+ });
1883
+ });
1884
+ cleanup();
1885
+ }
1886
+ //#endregion
1887
+ //#region src/core/chrome-path.ts
1888
+ function executable(p) {
1889
+ try {
1890
+ if (!statSync(p).isFile()) return false;
1891
+ if (process.platform === "win32") return true;
1892
+ accessSync(p, constants.X_OK);
1893
+ return true;
1894
+ } catch {
1895
+ return false;
1896
+ }
1897
+ }
1898
+ const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
1899
+ function platformCandidates() {
1900
+ if (process.platform === "darwin") return [{
1901
+ path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
1902
+ source: "/Applications"
1903
+ }, {
1904
+ path: join(homedir(), "Applications", MAC_BINARY),
1905
+ source: "~/Applications"
1906
+ }];
1907
+ if (process.platform === "win32") {
1908
+ const out = [];
1909
+ const exe = join("Google", "Chrome", "Application", "chrome.exe");
1910
+ if (process.env.PROGRAMFILES) out.push({
1911
+ path: join(process.env.PROGRAMFILES, exe),
1912
+ source: "Program Files"
1913
+ });
1914
+ if (process.env["PROGRAMFILES(X86)"]) out.push({
1915
+ path: join(process.env["PROGRAMFILES(X86)"], exe),
1916
+ source: "Program Files (x86)"
1917
+ });
1918
+ if (process.env.LOCALAPPDATA) out.push({
1919
+ path: join(process.env.LOCALAPPDATA, exe),
1920
+ source: "%LOCALAPPDATA%"
1921
+ });
1922
+ return out;
1923
+ }
1924
+ const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
1925
+ return [
1926
+ "google-chrome",
1927
+ "google-chrome-stable",
1928
+ "chromium",
1929
+ "chromium-browser"
1930
+ ].flatMap((name) => dirs.map((d) => ({
1931
+ path: join(d, name),
1932
+ source: `PATH (${name})`
1933
+ })));
1934
+ }
1935
+ function chromeExecutable() {
1936
+ let ignored;
1937
+ for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
1938
+ const v = process.env[name];
1939
+ if (!v) continue;
1940
+ if (executable(v)) return {
1941
+ path: v,
1942
+ source: name
1943
+ };
1944
+ ignored ??= `${name}=${v} is not an executable file`;
1945
+ }
1946
+ const hit = platformCandidates().find((c) => executable(c.path));
1947
+ return hit ? {
1948
+ path: hit.path,
1949
+ source: hit.source,
1950
+ ignored
1951
+ } : {
1952
+ path: null,
1953
+ source: "not found",
1954
+ ignored
1955
+ };
1956
+ }
1957
+ /** Where we looked, for a "not found" message. */
1958
+ function chromeSearchDescription() {
1959
+ if (process.platform === "darwin") return "/Applications and ~/Applications";
1960
+ if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
1961
+ return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
1962
+ }
1963
+ //#endregion
1964
+ //#region src/core/launch-windows.ts
1965
+ const sleep$4 = (ms) => new Promise((r) => setTimeout(r, ms));
1966
+ /** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
1967
+ function windowsChromeExe() {
1968
+ return chromeExecutable().path;
1969
+ }
1970
+ /** Is anything answering CDP on this port? (The script's `is_up`.) */
1971
+ async function cdpUp(port) {
1972
+ try {
1973
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
1974
+ } catch {
1975
+ return false;
1976
+ }
1977
+ }
1978
+ /**
1979
+ * pid of OUR automation Chrome's browser process on this port, or 0.
1980
+ *
1981
+ * PowerShell for the command lines: Node cannot read another process's command
1982
+ * line on Windows, and `wmic` is gone from Windows 11 25H2.
1983
+ */
1984
+ function ourChromePid(port) {
1985
+ return ourChromeProcess(port)?.pid ?? 0;
1986
+ }
1987
+ /**
1988
+ * OUR Chrome's browser process on this port, with the profile it was started
1989
+ * on, or null. The command line comes back base64'd, so a profile path with
1990
+ * spaces or non-ASCII characters survives the console's code page.
1991
+ */
1992
+ function ourChromeProcess(port) {
1993
+ const script = [
1994
+ "$ProgressPreference = 'SilentlyContinue'",
1995
+ `$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
1996
+ "$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
1997
+ "$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
1998
+ " Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
1999
+ " Select-Object -First 1",
2000
+ "if ($b) { Write-Output ('BA-PID ' + [int]$b.ProcessId + ' ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($b.CommandLine))) } else { Write-Output 'BA-PID 0' }"
2001
+ ].join("\n");
2002
+ try {
2003
+ const out = execFileSync("powershell.exe", [
2004
+ "-NoProfile",
2005
+ "-NonInteractive",
2006
+ "-ExecutionPolicy",
2007
+ "Bypass",
2008
+ "-EncodedCommand",
2009
+ Buffer.from(script, "utf16le").toString("base64")
2010
+ ], {
2011
+ encoding: "utf8",
2012
+ stdio: [
2013
+ "ignore",
2014
+ "pipe",
2015
+ "ignore"
2016
+ ],
2017
+ timeout: 2e4,
2018
+ windowsHide: true
2019
+ });
2020
+ const m = /^BA-PID (\d+)(?: (\S+))?\s*$/m.exec(out);
2021
+ const pid = Number(m?.[1] ?? 0);
2022
+ if (!pid) return null;
2023
+ return {
2024
+ pid,
2025
+ profile: userDataDir(m?.[2] ? Buffer.from(m[2], "base64").toString("utf8") : "")
2026
+ };
2027
+ } catch {
2028
+ return null;
2029
+ }
2030
+ }
2031
+ /** --user-data-dir from a Windows command line, quoted ("--user-data-dir=C:\a b") or not. Pure. */
2032
+ function userDataDir(cmd) {
2033
+ const quoted = /"--user-data-dir=([^"]+)"/.exec(cmd) ?? /--user-data-dir="([^"]+)"/.exec(cmd);
2034
+ if (quoted) return quoted[1];
2035
+ return /--user-data-dir=(\S+)/.exec(cmd)?.[1] ?? null;
2036
+ }
2037
+ /**
2038
+ * Quit OUR Chrome on this port, from before the move to the pipe, through the
2039
+ * PORT (never closeBrowser(), which would address the pipe browser), and wait
2040
+ * for it to exit. taskkill only if it will not go.
2041
+ */
2042
+ async function stopPortChrome(port, quit, say) {
2043
+ const pid = ourChromePid(port);
2044
+ if (!pid) return;
2045
+ await quit().catch(() => {});
2046
+ for (let i = 0; i < 60 && alive$1(pid); i++) await sleep$4(250);
2047
+ if (alive$1(pid)) {
2048
+ say(`Chrome (pid ${pid}) did not exit within 15s of being asked to quit; ending it.`);
2049
+ try {
2050
+ execFileSync("taskkill", [
2051
+ "/PID",
2052
+ String(pid),
2053
+ "/T",
2054
+ "/F"
2055
+ ], { stdio: "ignore" });
2056
+ } catch {}
2057
+ for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
2058
+ }
2059
+ if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not starting another on its profile.`);
2060
+ }
2061
+ function alive$1(pid) {
2062
+ try {
2063
+ process.kill(pid, 0);
2064
+ return true;
2065
+ } catch {
2066
+ return false;
2067
+ }
2068
+ }
2069
+ /**
2070
+ * Quit OUR Chrome on this port and wait until it has really exited.
2071
+ *
2072
+ * CDP Browser.close first — Chrome's own quit, which flushes the profile that
2073
+ * holds the logins. On Windows the process does exit after it (unlike macOS,
2074
+ * where it lingers windowless). taskkill /F only if it will not go.
2075
+ */
2076
+ async function stopOurChrome(port, say) {
2077
+ const pid = ourChromePid(port);
2078
+ if (!pid) return await cdpUp(port) ? "not-ours" : "none";
2079
+ await closeBrowser().catch(() => {});
2080
+ for (let i = 0; i < 40 && alive$1(pid); i++) await sleep$4(250);
2081
+ if (alive$1(pid)) {
2082
+ say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
2083
+ try {
2084
+ execFileSync("taskkill", [
2085
+ "/PID",
2086
+ String(pid),
2087
+ "/T",
2088
+ "/F"
2089
+ ], { stdio: "ignore" });
2090
+ } catch {}
2091
+ for (let i = 0; i < 20 && alive$1(pid); i++) await sleep$4(250);
2092
+ }
2093
+ if (alive$1(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
2094
+ for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep$4(250);
2095
+ return "stopped";
2096
+ }
2097
+ /** Start the automation Chrome unless ours is already serving the port. */
2098
+ async function startChrome(port, profile, log) {
2099
+ if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
2100
+ const exe = windowsChromeExe();
2101
+ if (!exe) return { outcome: "no-chrome" };
2102
+ mkdirSync(profile, { recursive: true });
2103
+ mkdirSync(dirname(log), { recursive: true });
2104
+ try {
2105
+ if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
2106
+ } catch {}
2107
+ const fd = openSync(log, "a");
2108
+ spawn(exe, [
2109
+ `--remote-debugging-port=${port}`,
2110
+ `--user-data-dir=${profile}`,
2111
+ "--no-first-run",
2112
+ "--no-default-browser-check",
2113
+ "about:blank"
2114
+ ], {
2115
+ detached: true,
2116
+ stdio: [
2117
+ "ignore",
2118
+ fd,
2119
+ fd
2120
+ ]
2121
+ }).unref();
2122
+ const started = Date.now();
2123
+ for (let i = 0; i < 240; i++) {
2124
+ if (await cdpUp(port)) return {
2125
+ outcome: "launched",
2126
+ seconds: Math.round((Date.now() - started) / 1e3)
2127
+ };
2128
+ await sleep$4(250);
2129
+ }
2130
+ return {
2131
+ outcome: "timeout",
2132
+ log
2133
+ };
2134
+ }
2135
+ //#endregion
2136
+ //#region src/core/launch-pipe.ts
2137
+ const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
2138
+ function brokerLogPath() {
2139
+ return join(brokerDir(), "broker.log");
2140
+ }
2141
+ function brokerState() {
2142
+ try {
2143
+ return JSON.parse(readFileSync(brokerStatePath(), "utf8"));
2144
+ } catch {
2145
+ return null;
2146
+ }
2147
+ }
2148
+ function alive(pid) {
2149
+ if (!pid || pid < 1) return false;
2150
+ try {
2151
+ process.kill(pid, 0);
2152
+ return true;
2153
+ } catch {
2154
+ return false;
2155
+ }
2156
+ }
2157
+ /** A browser answers on the socket: the broker is there AND Chrome replies. */
2158
+ async function pipeUp(timeout = 3e3) {
2159
+ if (!await socketAnswers(socketPath(), timeout)) return false;
2160
+ return browserVersion(timeout).then(() => true, () => false);
2161
+ }
2162
+ /**
2163
+ * Is this user's Chrome from before the move still running on the port?
2164
+ *
2165
+ * It holds the profile, so a pipe Chrome cannot open it alongside — and it is
2166
+ * the very exposure the move exists to close. `launch` says so and stops;
2167
+ * `launch --restart` quits it.
2168
+ */
2169
+ function portChromeRunning() {
2170
+ if (process.platform === "win32") return ourChromeProcess(cdpPort()) !== null;
2171
+ try {
2172
+ execFileSync("pgrep", [
2173
+ "-u",
2174
+ String(process.getuid?.() ?? -1),
2175
+ "-f",
2176
+ "--",
2177
+ `--remote-debugging-port=${cdpPort()}`
2178
+ ], { stdio: "ignore" });
2179
+ return true;
2180
+ } catch {
2181
+ return false;
2182
+ }
2183
+ }
2184
+ /**
2185
+ * The --user-data-dir of this user's browser on the port, read off its command
2186
+ * line. The launch script's `--stop` waits for THAT profile's lock to go before
2187
+ * it escalates; given the wrong one it sees no lock, decides the profile is
2188
+ * released, and SIGKILLs a browser mid-flush.
2189
+ */
2190
+ function portChromeProfile() {
2191
+ if (process.platform === "win32") return ourChromeProcess(cdpPort())?.profile ?? null;
2192
+ let out;
2193
+ try {
2194
+ out = execFileSync("ps", ["-Ao", "uid=,command="], {
2195
+ encoding: "utf8",
2196
+ maxBuffer: 64 * 1024 * 1024,
2197
+ stdio: [
2198
+ "ignore",
2199
+ "pipe",
2200
+ "ignore"
2201
+ ]
2202
+ });
2203
+ } catch {
2204
+ return null;
2205
+ }
2206
+ const uid = String(process.getuid?.() ?? -1);
2207
+ for (const line of out.split("\n")) {
2208
+ const m = /^\s*(\d+)\s+(.*)$/.exec(line);
2209
+ if (!m || m[1] !== uid) continue;
2210
+ const cmd = m[2];
2211
+ if (!cmd.includes(`--remote-debugging-port=${cdpPort()}`) || cmd.includes("--type=")) continue;
2212
+ const d = /--user-data-dir=(.+?)(?= --|$)/.exec(cmd);
2213
+ if (d) return d[1];
2214
+ }
2215
+ return null;
2216
+ }
2217
+ /** Ask the browser on the port to quit the way its menu does, so it flushes its profile. */
2218
+ async function quitPortChrome() {
2219
+ const ws = (await (await fetch(`http://127.0.0.1:${cdpPort()}/json/version`, { signal: AbortSignal.timeout(2e3) })).json()).webSocketDebuggerUrl;
2220
+ const s = await connect(ws, { timeout: 3e3 });
2221
+ try {
2222
+ await s.send("Browser.close", {}, 3e3).catch(() => {});
2223
+ } finally {
2224
+ s.close();
2225
+ }
2226
+ }
2227
+ /** Start the broker detached, and wait until Chrome answers through it. */
2228
+ async function startBroker(chrome, profile, chromeLog) {
2229
+ const start = Date.now();
2230
+ mkdirSync(brokerDir(), {
2231
+ recursive: true,
2232
+ mode: 448
2233
+ });
2234
+ const logFd = openSync(brokerLogPath(), "a", 384);
2235
+ const ctx = activeContextName();
2236
+ const { BAC_CONTEXT: _project, ...env } = process.env;
2237
+ const child = spawn(process.execPath, [
2238
+ process.argv[1],
2239
+ "broker",
2240
+ "--chrome",
2241
+ chrome,
2242
+ "--profile",
2243
+ profile,
2244
+ "--log",
2245
+ chromeLog,
2246
+ ...ctx ? ["--context", ctx] : []
2247
+ ], {
2248
+ detached: true,
2249
+ stdio: [
2250
+ "ignore",
2251
+ logFd,
2252
+ logFd
2253
+ ],
2254
+ windowsHide: true,
2255
+ env
2256
+ });
2257
+ child.unref();
2258
+ for (let i = 0; i < 240; i++) {
2259
+ if (await pipeUp(1e3)) return {
2260
+ ok: true,
2261
+ seconds: Math.round((Date.now() - start) / 1e3)
2262
+ };
2263
+ if (child.exitCode !== null) break;
2264
+ await sleep$3(250);
2265
+ }
2266
+ return {
2267
+ ok: false,
2268
+ reason: `Chrome did not answer on ${socketPath()} within 60s.${refusedDevTools(chromeLog)} Broker log: ${brokerLogPath()}; Chrome's log: ${chromeLog}`
2269
+ };
2270
+ }
2271
+ /**
2272
+ * Chrome runs, but refused DevTools on the pipe, and says why only in its log.
2273
+ * It refuses remote debugging on its DEFAULT profile, and decides which that is
2274
+ * from its app-data folder: on Windows with USERPROFILE pointed elsewhere it
2275
+ * could not find that folder, took our profile for its default, and the launch
2276
+ * timed out with nothing else to go on (2026-10-27).
2277
+ */
2278
+ function refusedDevTools(chromeLog) {
2279
+ let tail = "";
2280
+ try {
2281
+ tail = readFileSync(chromeLog, "utf8").slice(-16384);
2282
+ } catch {
2283
+ return "";
2284
+ }
2285
+ if (!tail.includes("requires a non-default data directory")) return "";
2286
+ return ` Chrome refused DevTools: it took this profile for its default one ("DevTools remote debugging requires a non-default data directory"). It decides that from its own app-data folder, so this happens when it cannot find that folder: check that ${process.platform === "win32" ? "USERPROFILE and LOCALAPPDATA are" : "HOME is"} this account's own.`;
2287
+ }
2288
+ /**
2289
+ * Quit the pipe Chrome and wait for the broker to go, which is when Chrome has
2290
+ * exited and released the profile. Browser.close first, so the profile is
2291
+ * flushed; the broker's own SIGTERM path next; SIGKILL only after that.
2292
+ */
2293
+ async function stopBroker(log) {
2294
+ const st = brokerState();
2295
+ await closeBrowser().catch(() => {});
2296
+ const gone = () => !alive(st?.brokerPid) && !alive(st?.chromePid) && !existsSync(brokerStatePath());
2297
+ for (let i = 0; i < 60 && !gone(); i++) await sleep$3(250);
2298
+ if (gone()) return;
2299
+ if (alive(st?.brokerPid)) {
2300
+ log("Chrome did not quit within 15s of being asked; asking the broker to stop it.");
2301
+ process.kill(st.brokerPid, "SIGTERM");
2302
+ for (let i = 0; i < 100 && !gone(); i++) await sleep$3(250);
2303
+ }
2304
+ if (gone()) return;
2305
+ log("Still running after 40s; sending SIGKILL.");
2306
+ for (const pid of [st?.chromePid, st?.brokerPid]) if (alive(pid)) process.kill(pid, "SIGKILL");
2307
+ for (let i = 0; i < 20 && (alive(st?.chromePid) || alive(st?.brokerPid)); i++) await sleep$3(250);
2308
+ if (alive(st?.chromePid)) throw new Error(`Chrome (pid ${st?.chromePid}) would not exit, even on SIGKILL. Not relaunching on top of it.`);
2309
+ }
2310
+ //#endregion
2311
+ //#region src/core/renderer-health.ts
2312
+ /** First attempt's budget. Later attempts double it. */
2313
+ const DEFAULT_TIMEOUT = 5e3;
2314
+ /** How many times we ask before we are willing to call a browser broken. */
2315
+ const DEFAULT_ATTEMPTS = 3;
2316
+ /** Breathing room between attempts — a browser mid-GC deserves a second look. */
2317
+ const RETRY_PAUSE = 400;
2318
+ /**
2319
+ * The verdict, from the probe and the corroborations — and from nothing else.
2320
+ *
2321
+ * Pure, and separate from the probing, because this is the decision that was
2322
+ * wrong: every failure used to become 'wedged' by default. Now 'wedged'
2323
+ * requires `rendezvous === false`, which is the only thing that has ever
2324
+ * actually meant it.
2325
+ */
2326
+ function rendererVerdict(outcome, e) {
2327
+ if (outcome === "ok") return "healthy";
2328
+ if (e?.rendezvous === false) return "wedged";
2329
+ if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
2330
+ return "unknown";
2331
+ }
2332
+ /**
2333
+ * Create a throwaway tab, make its renderer prove it is alive, close it.
2334
+ *
2335
+ * Three things changed after 2026-09-11, and each of them is load-bearing:
2336
+ *
2337
+ * 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
2338
+ * tool opens tabs AND gets the same wake treatment. A probe that is harsher
2339
+ * on itself than `goto` is on a real tab reports failures `goto` would not
2340
+ * have had.
2341
+ * 2. It retries with a doubling budget. One 5s timeout is not evidence of a
2342
+ * permanent condition; it is evidence of 5 seconds.
2343
+ * 3. It stops early when the Mach name is ABSENT — the one state where more
2344
+ * waiting is genuinely pointless — so the real failure is still reported
2345
+ * fast while a slow browser gets the benefit of the doubt.
2346
+ */
2347
+ async function probeRenderer({ timeout, attempts } = {}) {
2348
+ const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
2349
+ const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
2350
+ const started = Date.now();
2351
+ let pageTargets = 0;
2352
+ try {
2353
+ pageTargets = (await listPageTargets()).length;
2354
+ } catch {}
2355
+ const tries = [];
2356
+ let evidence;
2357
+ for (let i = 0; i < maxAttempts; i++) {
2358
+ const budget = base * 2 ** i;
2359
+ tries.push(await probeOnce(budget));
2360
+ if (tries[tries.length - 1].outcome === "ok") return finish({
2361
+ ok: true,
2362
+ started,
2363
+ pageTargets,
2364
+ tries,
2365
+ evidence
2366
+ });
2367
+ evidence ??= gatherEvidence();
2368
+ if (evidence.rendezvous === false) break;
2369
+ if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
2370
+ }
2371
+ return finish({
2372
+ ok: false,
2373
+ started,
2374
+ pageTargets,
2375
+ tries,
2376
+ evidence
2377
+ });
2378
+ }
2379
+ function finish({ ok, started, pageTargets, tries, evidence }) {
2380
+ const last = tries[tries.length - 1];
2381
+ const health = {
2382
+ ok,
2383
+ ms: Date.now() - started,
2384
+ pageTargets,
2385
+ reason: last?.reason,
2386
+ outcome: last?.outcome ?? "error",
2387
+ verdict: rendererVerdict(last?.outcome ?? "error", evidence),
2388
+ attempts: tries,
2389
+ evidence
2390
+ };
2391
+ recordProbe(health);
2392
+ return health;
2393
+ }
2394
+ /** One create -> ensure -> close cycle. */
2395
+ async function probeOnce(budget) {
2396
+ const started = Date.now();
2397
+ let targetId;
2398
+ try {
2399
+ targetId = await createTab("about:blank", { timeout: budget });
2400
+ } catch (e) {
2401
+ return {
2402
+ outcome: "error",
2403
+ budget,
2404
+ ms: Date.now() - started,
2405
+ woke: false,
2406
+ reason: `could not create a target at all: ${e?.message ?? e}`
2407
+ };
2408
+ }
2409
+ try {
2410
+ const r = await ensureRenderer(targetId, {
2411
+ grace: budget,
2412
+ budget
2413
+ });
2414
+ return {
2415
+ outcome: r.outcome,
2416
+ budget,
2417
+ ms: Date.now() - started,
2418
+ woke: r.woke,
2419
+ reason: r.reason
2420
+ };
2421
+ } finally {
2422
+ if (targetId) await closeTab(targetId).catch(() => {});
2423
+ }
2424
+ }
2425
+ /**
2426
+ * Ask an EXISTING target's renderer to prove it is alive.
2427
+ *
2428
+ * Kept returning `string | null` because that is what `gc` wants (a reason to
2429
+ * print beside a tab it is about to close). New callers should prefer
2430
+ * `askRenderer`, which says WHICH failure it was.
2431
+ */
2432
+ async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
2433
+ const r = await askRenderer(targetId, timeout);
2434
+ return r.outcome === "ok" ? null : r.reason ?? r.outcome;
2435
+ }
2436
+ /**
2437
+ * The port we are actually talking to.
2438
+ *
2439
+ * NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
2440
+ * arbitrary host:port, and everything here that shells out to `ps` or
2441
+ * `launchctl` has to ask about THAT browser. Using the uid-derived port instead
2442
+ * finds the user's default Chrome and cheerfully reports its health as if it
2443
+ * were the one being driven — caught while testing this module against a second
2444
+ * Chrome, where a perfectly healthy browser was accused of having lost a
2445
+ * bootstrap name that in fact belonged to a different pid.
2446
+ */
2447
+ function targetPort() {
2448
+ const explicit = process.env.BROWSER_AUTOMATION_CDP;
2449
+ if (explicit) try {
2450
+ const p = Number(new URL(explicit).port);
2451
+ if (Number.isInteger(p) && p > 0) return p;
2452
+ } catch {}
2453
+ return cdpPort();
2454
+ }
2455
+ /**
2456
+ * The browser process serving our port, and how many renderers it has.
2457
+ *
2458
+ * One `ps`, not one `pgrep` plus one `ps` per hit: on a Chrome with 40 children
2459
+ * that was 41 forks to answer two questions, and it ran on the error path of a
2460
+ * browser already thought to be struggling.
2461
+ *
2462
+ * The executable check is not decoration. Matching on the command line alone
2463
+ * (as `pgrep -f` does) hits any process that merely CONTAINS the debugging-port
2464
+ * flag — the `grep` looking for it, or a shell running `browser-automation`
2465
+ * with the flag as an argument. One of those, having no `--type=`, would have
2466
+ * been reported as the browser pid, and its absent Mach name read as the
2467
+ * permanent failure. Seen while writing this: a `ugrep` for the flag sat in
2468
+ * `ps` output alongside the real Chrome.
2469
+ */
2470
+ function chromeProcesses() {
2471
+ const flag = `--remote-debugging-port=${targetPort()}`;
2472
+ const uid = String(process.getuid?.() ?? -1);
2473
+ let out;
2474
+ try {
2475
+ out = execFileSync("ps", ["-Ao", "pid=,ppid=,uid=,command="], {
2476
+ encoding: "utf8",
2477
+ maxBuffer: 64 * 1024 * 1024,
2478
+ stdio: [
2479
+ "ignore",
2480
+ "pipe",
2481
+ "ignore"
2482
+ ]
2483
+ });
2484
+ } catch {
2485
+ return {
2486
+ browser: null,
2487
+ renderers: null
2488
+ };
2489
+ }
2490
+ if (usesPipe()) {
2491
+ const st = brokerState();
2492
+ const browser = st && out.split("\n").some((l) => new RegExp(`^\\s*${st.chromePid}\\s`).test(l)) ? st.chromePid : null;
2493
+ if (browser === null) return {
2494
+ browser: null,
2495
+ renderers: null
2496
+ };
2497
+ let renderers = 0;
2498
+ for (const line of out.split("\n")) {
2499
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
2500
+ if (!m || m[3] !== uid || !/--type=renderer\b/.test(m[4])) continue;
2501
+ if (Number(m[2]) === browser || m[4].includes(`--user-data-dir=${st.profile}`)) renderers++;
2502
+ }
2503
+ return {
2504
+ browser,
2505
+ renderers
2506
+ };
2507
+ }
2508
+ let browser = null;
2509
+ let renderers = 0;
2510
+ for (const line of out.split("\n")) {
2511
+ const m = /^\s*(\d+)\s+\d+\s+(\d+)\s+(.*)$/.exec(line);
2512
+ if (!m) continue;
2513
+ const [, pid, u, cmd] = m;
2514
+ if (u !== uid || !cmd.includes(flag)) continue;
2515
+ if (!/chrome|chromium|brave|msedge|thorium/i.test(cmd.split(" --")[0])) continue;
2516
+ if (/--type=renderer\b/.test(cmd)) renderers++;
2517
+ else if (!cmd.includes("--type=")) browser = Number(pid);
2518
+ }
2519
+ return {
2520
+ browser,
2521
+ renderers
2522
+ };
2523
+ }
2524
+ /** The pid of the browser process serving the port we are driving, if visible. */
1525
2525
  function browserPid() {
1526
2526
  return chromeProcesses().browser;
1527
2527
  }
@@ -1561,7 +2561,9 @@ function gatherEvidence() {
1561
2561
  /** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
1562
2562
  function chromeLogPath() {
1563
2563
  const tmp = process.platform === "win32" ? tmpdir() : process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
1564
- return process.env.BROWSER_AUTOMATION_LOG || `${tmp}/chrome-${targetPort()}.log`;
2564
+ if (process.env.BROWSER_AUTOMATION_LOG) return process.env.BROWSER_AUTOMATION_LOG;
2565
+ if (usesPipe()) return join(brokerDir(), "chrome.log");
2566
+ return `${tmp}/chrome-${targetPort()}.log`;
1565
2567
  }
1566
2568
  function probeLogPath() {
1567
2569
  return process.env.BROWSER_AUTOMATION_PROBE_LOG || join(homedir(), ".browser-automation", "renderer-probes.jsonl");
@@ -1832,16 +2834,12 @@ function describeNotShown(outcome) {
1832
2834
  //#endregion
1833
2835
  //#region src/core/context-launch.ts
1834
2836
  async function reachable() {
1835
- try {
1836
- return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
1837
- } catch {
1838
- return false;
1839
- }
2837
+ return pipeUp(1500);
1840
2838
  }
1841
2839
  async function ensureContextChrome() {
1842
2840
  const ctx = activeContext();
1843
2841
  if (!ctx || await reachable()) return;
1844
- consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile, on :${ctx.port}. Whatever you sign in to or install there is kept.`);
2842
+ consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile. Whatever you sign in to or install there is kept.`);
1845
2843
  if (spawnSync(process.execPath, [
1846
2844
  process.argv[1],
1847
2845
  "launch",
@@ -2166,7 +3164,67 @@ function clickExpr(ref) {
2166
3164
  const el=__baFind(${r});
2167
3165
  if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
2168
3166
  el.scrollIntoView({block:'center',inline:'center'});
3167
+ const tag=el.tagName.toLowerCase();
3168
+ if(el.getAttribute('role')==='option'&&el.closest('[data-radix-select-viewport]')){
3169
+ el.focus({preventScroll:true});
3170
+ const k={key:'Enter',code:'Enter',keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,view:window};
3171
+ el.dispatchEvent(new KeyboardEvent('keydown',k));
3172
+ el.dispatchEvent(new KeyboardEvent('keyup',k));
3173
+ return {ok:true,tag,via:'keyboard'};
3174
+ }
3175
+ const b=el.getBoundingClientRect();
3176
+ const x=b.left+b.width/2,y=b.top+b.height/2;
3177
+ const o={bubbles:true,cancelable:true,composed:true,view:window,clientX:x,clientY:y,screenX:x,screenY:y,button:0,buttons:1,detail:1,pointerId:1,pointerType:'mouse',isPrimary:true};
3178
+ const up={...o,buttons:0};
3179
+ el.dispatchEvent(new PointerEvent('pointerover',o));
3180
+ el.dispatchEvent(new PointerEvent('pointerenter',{...o,bubbles:false,cancelable:false}));
3181
+ el.dispatchEvent(new MouseEvent('mouseover',o));
3182
+ const down=el.dispatchEvent(new PointerEvent('pointerdown',o));
3183
+ if(down&&el.dispatchEvent(new MouseEvent('mousedown',o))&&typeof el.focus==='function')el.focus({preventScroll:true});
3184
+ el.dispatchEvent(new PointerEvent('pointerup',up));
3185
+ if(down)el.dispatchEvent(new MouseEvent('mouseup',up));
2169
3186
  el.click();
3187
+ return {ok:true,tag};
3188
+ })()`;
3189
+ }
3190
+ const KEY_CODES = {
3191
+ Enter: 13,
3192
+ Escape: 27,
3193
+ Tab: 9,
3194
+ " ": 32,
3195
+ Backspace: 8,
3196
+ Delete: 46,
3197
+ ArrowUp: 38,
3198
+ ArrowDown: 40,
3199
+ ArrowLeft: 37,
3200
+ ArrowRight: 39,
3201
+ Home: 36,
3202
+ End: 35,
3203
+ PageUp: 33,
3204
+ PageDown: 34
3205
+ };
3206
+ function keyExpr(ref, key) {
3207
+ const r = JSON.stringify(ref);
3208
+ const name = key === "Space" ? " " : key;
3209
+ const keyCode = KEY_CODES[name] ?? (name.length === 1 ? name.toUpperCase().charCodeAt(0) : 0);
3210
+ const code = name === " " ? "Space" : /^[a-z]$/i.test(name) ? `Key${name.toUpperCase()}` : /^[0-9]$/.test(name) ? `Digit${name}` : name;
3211
+ return WALK + `(() => {
3212
+ const el=__baFind(${r});
3213
+ if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
3214
+ el.scrollIntoView({block:'center',inline:'center'});
3215
+ if(typeof el.focus==='function')el.focus({preventScroll:true});
3216
+ const t=document.activeElement&&el.contains(document.activeElement)?document.activeElement:el;
3217
+ const k={...${JSON.stringify({
3218
+ key: name,
3219
+ code,
3220
+ keyCode,
3221
+ which: keyCode,
3222
+ bubbles: true,
3223
+ cancelable: true,
3224
+ composed: true
3225
+ })},view:window};
3226
+ t.dispatchEvent(new KeyboardEvent('keydown',k));
3227
+ t.dispatchEvent(new KeyboardEvent('keyup',k));
2170
3228
  return {ok:true,tag:el.tagName.toLowerCase()};
2171
3229
  })()`;
2172
3230
  }
@@ -2336,7 +3394,7 @@ const snapshotCommand = define({
2336
3394
  });
2337
3395
  //#endregion
2338
3396
  //#region src/commands/click.ts
2339
- const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
3397
+ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
2340
3398
  const clickCommand = define({
2341
3399
  name: "click",
2342
3400
  description: "Click an element by ref (from the latest snapshot)",
@@ -2348,7 +3406,7 @@ const clickCommand = define({
2348
3406
  },
2349
3407
  trusted: {
2350
3408
  type: "boolean",
2351
- description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched el.click(). Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright. Use for widgets that demand isTrusted events AND animate in: artdeco dropdown menu items (LinkedIn More→Connect), Radix dropdown/popover triggers, cmdk comboboxes — which a default click, or an immediate trusted click on stale coordinates, only highlights without firing."
3409
+ description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched pointer + mouse sequence and el.click(). The default needs no focus and already drives Radix/headless-UI triggers and items; use this only for widgets that check isTrusted. Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright. Canonical case: artdeco dropdown menu items (LinkedIn More→Connect), which demand isTrusted and animate in, so a default click, or an immediate trusted click on stale coordinates, only highlights them without firing."
2352
3410
  }
2353
3411
  },
2354
3412
  async run(ctx) {
@@ -2377,7 +3435,7 @@ const clickCommand = define({
2377
3435
  while (Date.now() < focusDeadline) {
2378
3436
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
2379
3437
  if (f && f.f && f.v === "visible") break;
2380
- await sleep$3(50);
3438
+ await sleep$2(50);
2381
3439
  }
2382
3440
  let prev = null;
2383
3441
  let point = null;
@@ -2403,7 +3461,7 @@ const clickCommand = define({
2403
3461
  x: a.x,
2404
3462
  y: a.y
2405
3463
  };
2406
- await sleep$3(60);
3464
+ await sleep$2(60);
2407
3465
  }
2408
3466
  if (!point) {
2409
3467
  consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
@@ -2418,7 +3476,7 @@ const clickCommand = define({
2418
3476
  buttons: 0,
2419
3477
  pointerType: "mouse"
2420
3478
  });
2421
- await sleep$3(20);
3479
+ await sleep$2(20);
2422
3480
  await s.send("Input.dispatchMouseEvent", {
2423
3481
  type: "mousePressed",
2424
3482
  x,
@@ -2448,7 +3506,42 @@ const clickCommand = define({
2448
3506
  consola$1.error(r.err);
2449
3507
  process.exit(1);
2450
3508
  }
2451
- consola$1.success(`clicked ${ref} <${r.tag}>`);
3509
+ consola$1.success(`clicked ${ref} <${r.tag}>${r.via ? ` (${r.via})` : ""}`);
3510
+ }
3511
+ });
3512
+ //#endregion
3513
+ //#region src/commands/key.ts
3514
+ const keyCommand = define({
3515
+ name: "key",
3516
+ description: "Press one key on an element by ref: focus it, then dispatch keydown + keyup (Enter, Escape, ArrowDown, Space, a character…), without bringing the tab to the front",
3517
+ args: {
3518
+ ...targetArgs,
3519
+ ref: {
3520
+ type: "positional",
3521
+ description: "Element ref, e.g. e7"
3522
+ },
3523
+ key: {
3524
+ type: "positional",
3525
+ description: "An event.key name: Enter, Escape, Tab, ArrowDown, Space, or one character"
3526
+ }
3527
+ },
3528
+ async run(ctx) {
3529
+ const ref = ctx.positionals[1];
3530
+ const key = ctx.positionals[2];
3531
+ if (!ref || !isValidRef(ref)) {
3532
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
3533
+ process.exit(1);
3534
+ }
3535
+ if (!key) {
3536
+ consola$1.error("A key is required, e.g. `browser-automation key e7 Enter`");
3537
+ process.exit(1);
3538
+ }
3539
+ const r = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), keyExpr(ref, key));
3540
+ if (r.err) {
3541
+ consola$1.error(r.err);
3542
+ process.exit(1);
3543
+ }
3544
+ consola$1.success(`pressed ${key} on ${ref} <${r.tag}>`);
2452
3545
  }
2453
3546
  });
2454
3547
  //#endregion
@@ -2552,7 +3645,7 @@ const readCommand = define({
2552
3645
  });
2553
3646
  //#endregion
2554
3647
  //#region src/commands/focus.ts
2555
- const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
3648
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
2556
3649
  /**
2557
3650
  * Make a tab believe it is the visible one.
2558
3651
  *
@@ -2622,7 +3715,7 @@ const focusCommand = define({
2622
3715
  returnByValue: true
2623
3716
  })).result?.value ?? last;
2624
3717
  if (last.focused && last.visibility === "visible") break;
2625
- await sleep$2(50);
3718
+ await sleep$1(50);
2626
3719
  }
2627
3720
  return last;
2628
3721
  });
@@ -2988,7 +4081,7 @@ const uploadCommand = define({
2988
4081
  });
2989
4082
  //#endregion
2990
4083
  //#region src/commands/drop.ts
2991
- const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
4084
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2992
4085
  /** Resolve each path to absolute and verify it's an existing file. */
2993
4086
  function absFiles(paths) {
2994
4087
  return paths.map((p) => {
@@ -3090,7 +4183,7 @@ const dropCommand = define({
3090
4183
  while (Date.now() < focusDeadline) {
3091
4184
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
3092
4185
  if (f && f.f && f.v === "visible") break;
3093
- await sleep$1(50);
4186
+ await sleep(50);
3094
4187
  }
3095
4188
  let prev = null;
3096
4189
  let point = null;
@@ -3116,7 +4209,7 @@ const dropCommand = define({
3116
4209
  x: a.x,
3117
4210
  y: a.y
3118
4211
  };
3119
- await sleep$1(60);
4212
+ await sleep(60);
3120
4213
  }
3121
4214
  if (!point) {
3122
4215
  consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
@@ -3140,7 +4233,7 @@ const dropCommand = define({
3140
4233
  y,
3141
4234
  data
3142
4235
  });
3143
- await sleep$1(20);
4236
+ await sleep(20);
3144
4237
  await s.send("Input.dispatchDragEvent", {
3145
4238
  type: "drop",
3146
4239
  x,
@@ -3364,7 +4457,7 @@ const listCommand = define({
3364
4457
  if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
3365
4458
  if (sessions.length) consola$1.log("");
3366
4459
  const ctxName = activeContextName();
3367
- consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} (:${cdpPort()}) — address with -t <id> or -m <substr>`);
4460
+ consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} ${usesPipe() ? "" : ` (:${cdpPort()})`} — address with -t <id> or -m <substr>`);
3368
4461
  for (const t of targets) {
3369
4462
  const owner = sessions.find((s) => s.targetId === t.id);
3370
4463
  const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
@@ -3463,211 +4556,6 @@ function launchScriptPath() {
3463
4556
  return join(packageRoot(), "scripts", "launch-chrome.sh");
3464
4557
  }
3465
4558
  //#endregion
3466
- //#region src/core/chrome-path.ts
3467
- function executable(p) {
3468
- try {
3469
- if (!statSync(p).isFile()) return false;
3470
- if (process.platform === "win32") return true;
3471
- accessSync(p, constants.X_OK);
3472
- return true;
3473
- } catch {
3474
- return false;
3475
- }
3476
- }
3477
- const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
3478
- function platformCandidates() {
3479
- if (process.platform === "darwin") return [{
3480
- path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
3481
- source: "/Applications"
3482
- }, {
3483
- path: join(homedir(), "Applications", MAC_BINARY),
3484
- source: "~/Applications"
3485
- }];
3486
- if (process.platform === "win32") {
3487
- const out = [];
3488
- const exe = join("Google", "Chrome", "Application", "chrome.exe");
3489
- if (process.env.PROGRAMFILES) out.push({
3490
- path: join(process.env.PROGRAMFILES, exe),
3491
- source: "Program Files"
3492
- });
3493
- if (process.env["PROGRAMFILES(X86)"]) out.push({
3494
- path: join(process.env["PROGRAMFILES(X86)"], exe),
3495
- source: "Program Files (x86)"
3496
- });
3497
- if (process.env.LOCALAPPDATA) out.push({
3498
- path: join(process.env.LOCALAPPDATA, exe),
3499
- source: "%LOCALAPPDATA%"
3500
- });
3501
- return out;
3502
- }
3503
- const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
3504
- return [
3505
- "google-chrome",
3506
- "google-chrome-stable",
3507
- "chromium",
3508
- "chromium-browser"
3509
- ].flatMap((name) => dirs.map((d) => ({
3510
- path: join(d, name),
3511
- source: `PATH (${name})`
3512
- })));
3513
- }
3514
- function chromeExecutable() {
3515
- let ignored;
3516
- for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
3517
- const v = process.env[name];
3518
- if (!v) continue;
3519
- if (executable(v)) return {
3520
- path: v,
3521
- source: name
3522
- };
3523
- ignored ??= `${name}=${v} is not an executable file`;
3524
- }
3525
- const hit = platformCandidates().find((c) => executable(c.path));
3526
- return hit ? {
3527
- path: hit.path,
3528
- source: hit.source,
3529
- ignored
3530
- } : {
3531
- path: null,
3532
- source: "not found",
3533
- ignored
3534
- };
3535
- }
3536
- /** Where we looked, for a "not found" message. */
3537
- function chromeSearchDescription() {
3538
- if (process.platform === "darwin") return "/Applications and ~/Applications";
3539
- if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
3540
- return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
3541
- }
3542
- //#endregion
3543
- //#region src/core/launch-windows.ts
3544
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3545
- /** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
3546
- function windowsChromeExe() {
3547
- return chromeExecutable().path;
3548
- }
3549
- /** Is anything answering CDP on this port? (The script's `is_up`.) */
3550
- async function cdpUp(port) {
3551
- try {
3552
- return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
3553
- } catch {
3554
- return false;
3555
- }
3556
- }
3557
- /**
3558
- * pid of OUR automation Chrome's browser process on this port, or 0.
3559
- *
3560
- * PowerShell for the command lines: Node cannot read another process's command
3561
- * line on Windows, and `wmic` is gone from Windows 11 25H2.
3562
- */
3563
- function ourChromePid(port) {
3564
- const script = [
3565
- "$ProgressPreference = 'SilentlyContinue'",
3566
- `$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
3567
- "$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
3568
- "$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
3569
- " Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
3570
- " Select-Object -First 1 -ExpandProperty ProcessId",
3571
- "Write-Output ('BA-PID ' + [int]$b)"
3572
- ].join("\n");
3573
- try {
3574
- const out = execFileSync("powershell.exe", [
3575
- "-NoProfile",
3576
- "-NonInteractive",
3577
- "-ExecutionPolicy",
3578
- "Bypass",
3579
- "-EncodedCommand",
3580
- Buffer.from(script, "utf16le").toString("base64")
3581
- ], {
3582
- encoding: "utf8",
3583
- stdio: [
3584
- "ignore",
3585
- "pipe",
3586
- "ignore"
3587
- ],
3588
- timeout: 2e4,
3589
- windowsHide: true
3590
- });
3591
- return Number(/^BA-PID (\d+)\s*$/m.exec(out)?.[1] ?? 0);
3592
- } catch {
3593
- return 0;
3594
- }
3595
- }
3596
- function alive(pid) {
3597
- try {
3598
- process.kill(pid, 0);
3599
- return true;
3600
- } catch {
3601
- return false;
3602
- }
3603
- }
3604
- /**
3605
- * Quit OUR Chrome on this port and wait until it has really exited.
3606
- *
3607
- * CDP Browser.close first — Chrome's own quit, which flushes the profile that
3608
- * holds the logins. On Windows the process does exit after it (unlike macOS,
3609
- * where it lingers windowless). taskkill /F only if it will not go.
3610
- */
3611
- async function stopOurChrome(port, say) {
3612
- const pid = ourChromePid(port);
3613
- if (!pid) return await cdpUp(port) ? "not-ours" : "none";
3614
- await closeBrowser().catch(() => {});
3615
- for (let i = 0; i < 40 && alive(pid); i++) await sleep(250);
3616
- if (alive(pid)) {
3617
- say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
3618
- try {
3619
- execFileSync("taskkill", [
3620
- "/PID",
3621
- String(pid),
3622
- "/T",
3623
- "/F"
3624
- ], { stdio: "ignore" });
3625
- } catch {}
3626
- for (let i = 0; i < 20 && alive(pid); i++) await sleep(250);
3627
- }
3628
- if (alive(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
3629
- for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep(250);
3630
- return "stopped";
3631
- }
3632
- /** Start the automation Chrome unless ours is already serving the port. */
3633
- async function startChrome(port, profile, log) {
3634
- if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
3635
- const exe = windowsChromeExe();
3636
- if (!exe) return { outcome: "no-chrome" };
3637
- mkdirSync(profile, { recursive: true });
3638
- mkdirSync(dirname(log), { recursive: true });
3639
- try {
3640
- if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
3641
- } catch {}
3642
- const fd = openSync(log, "a");
3643
- spawn(exe, [
3644
- `--remote-debugging-port=${port}`,
3645
- `--user-data-dir=${profile}`,
3646
- "--no-first-run",
3647
- "--no-default-browser-check",
3648
- "about:blank"
3649
- ], {
3650
- detached: true,
3651
- stdio: [
3652
- "ignore",
3653
- fd,
3654
- fd
3655
- ]
3656
- }).unref();
3657
- const started = Date.now();
3658
- for (let i = 0; i < 240; i++) {
3659
- if (await cdpUp(port)) return {
3660
- outcome: "launched",
3661
- seconds: Math.round((Date.now() - started) / 1e3)
3662
- };
3663
- await sleep(250);
3664
- }
3665
- return {
3666
- outcome: "timeout",
3667
- log
3668
- };
3669
- }
3670
- //#endregion
3671
4559
  //#region src/commands/launch.ts
3672
4560
  const launchCommand = define({
3673
4561
  name: "launch",
@@ -3683,7 +4571,10 @@ const launchCommand = define({
3683
4571
  }
3684
4572
  },
3685
4573
  async run(ctx) {
3686
- if (process.platform === "win32") {
4574
+ if (usesPipe()) {
4575
+ if (!await launchPipe(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
4576
+ if (ctx.values.status) return;
4577
+ } else if (process.platform === "win32") {
3687
4578
  if (!await launchWindows(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
3688
4579
  if (ctx.values.status) return;
3689
4580
  } else {
@@ -3802,6 +4693,94 @@ async function launchWindows(statusOnly, restart) {
3802
4693
  return false;
3803
4694
  }
3804
4695
  }
4696
+ /** Two profile paths are the same folder (Windows paths ignore case and slash direction). */
4697
+ function sameDir(a, b) {
4698
+ if (process.platform !== "win32") return a === b;
4699
+ const n = (p) => resolve(p).toLowerCase();
4700
+ return n(a) === n(b);
4701
+ }
4702
+ /**
4703
+ * Chrome on the DevTools pipe, behind the broker: every platform, and every
4704
+ * login context (its own broker). Returns false on a failure that must stop
4705
+ * `launch` before the health check.
4706
+ */
4707
+ async function launchPipe(statusOnly, restart) {
4708
+ const sock = () => socketPath();
4709
+ const ctxName = activeContextName();
4710
+ const driveIt = `Drive it with: browser-automation goto -s <session>${ctxName ? ` --context ${ctxName} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`;
4711
+ if (statusOnly) {
4712
+ const up = await pipeUp();
4713
+ consola$1.log(up ? `Chrome is up on the pipe (${sock()})` : `Chrome is NOT running (nothing answers on ${sock()})`);
4714
+ return up;
4715
+ }
4716
+ if (portChromeRunning()) {
4717
+ const theirs = portChromeProfile();
4718
+ const mine = resolveProfile().dir;
4719
+ const where = `port ${cdpPort()}${theirs ? ` (profile ${theirs})` : ""}`;
4720
+ if (!theirs || !sameDir(theirs, mine)) consola$1.warn(`This account also has a browser listening on ${where}; anything on this computer can drive it. It is not this one, so it is left alone.`);
4721
+ else if (!restart) {
4722
+ consola$1.error(`This browser is still running on ${where}, from before the move to the pipe, and anything on this computer can drive it. Switch it over:\n browser-automation launch --restart\nThat quits it (closing its tabs; logins are kept) and starts it again on the pipe.`);
4723
+ return false;
4724
+ } else {
4725
+ consola$1.info(`Quitting this browser on ${where} to start it again on the pipe.`);
4726
+ if (process.platform === "win32") try {
4727
+ await stopPortChrome(cdpPort(), quitPortChrome, (s) => consola$1.warn(s));
4728
+ } catch (e) {
4729
+ consola$1.error(String(e?.message ?? e));
4730
+ return false;
4731
+ }
4732
+ else {
4733
+ await quitPortChrome().catch(() => {});
4734
+ if (spawnSync("bash", [
4735
+ launchScriptPath(),
4736
+ "--port",
4737
+ String(cdpPort()),
4738
+ "--stop",
4739
+ "--profile",
4740
+ theirs
4741
+ ], { stdio: "inherit" }).status !== 0) return false;
4742
+ }
4743
+ }
4744
+ }
4745
+ if (await pipeUp()) {
4746
+ if (!restart) {
4747
+ consola$1.log(`Already running on the pipe (${sock()}).`);
4748
+ consola$1.log(driveIt);
4749
+ return true;
4750
+ }
4751
+ const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
4752
+ consola$1.info(`Restarting Chrome — closing ${tabs ?? "?"} open tab(s).`);
4753
+ try {
4754
+ await stopBroker((s) => consola$1.warn(s));
4755
+ } catch (e) {
4756
+ consola$1.error(String(e?.message ?? e));
4757
+ return false;
4758
+ }
4759
+ }
4760
+ const m = migrateProfile();
4761
+ if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
4762
+ else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
4763
+ await personalizeIfNeeded();
4764
+ if (process.platform === "darwin" && m.dir === legacyProfileDir()) {
4765
+ consola$1.error(`The profile is still inside Chrome's own folder (${m.dir}), where macOS refuses a Chrome started with the DevTools pipe.${m.detail ? ` ${m.detail}` : ""}`);
4766
+ return false;
4767
+ }
4768
+ const chrome = chromeExecutable();
4769
+ if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
4770
+ if (!chrome.path) {
4771
+ consola$1.error("Chrome not found. Install it, or set BROWSER_AUTOMATION_CHROME to its binary.");
4772
+ return false;
4773
+ }
4774
+ const r = await startBroker(chrome.path, m.dir, chromeLogPath());
4775
+ if (!r.ok) {
4776
+ consola$1.error(r.reason);
4777
+ return false;
4778
+ }
4779
+ consola$1.log(`Chrome launched on the pipe in ${r.seconds}s (profile: ${m.dir}, ${process.platform === "win32" ? "pipe" : "socket"}: ${sock()}, log: ${chromeLogPath()})`);
4780
+ consola$1.log(`No debugging port is open: only this account can reach it, through the ${process.platform === "win32" ? "named pipe" : "socket"}.`);
4781
+ consola$1.log(driveIt);
4782
+ return true;
4783
+ }
3805
4784
  //#endregion
3806
4785
  //#region src/commands/doctor.ts
3807
4786
  /**
@@ -3838,7 +4817,10 @@ const doctorCommand = define({
3838
4817
  const bad = (m) => consola$1.log(` ✗ ${m}`);
3839
4818
  if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
3840
4819
  else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
3841
- consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
4820
+ if (usesPipe()) {
4821
+ consola$1.log(` • Transport: DevTools pipe, served on ${socketPath()} — no debugging port open`);
4822
+ if (portChromeRunning()) bad(`a Chrome of yours is still listening on port ${cdpPort()} (from before the pipe): anything on this computer can drive it. Switch it over: browser-automation launch --restart`);
4823
+ } else consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
3842
4824
  const profile = resolveProfile();
3843
4825
  consola$1.log(` • Profile: ${profile.dir}`);
3844
4826
  if (profile.source === "legacy") {
@@ -3850,7 +4832,13 @@ const doctorCommand = define({
3850
4832
  else bad(`Chrome binary: not found (looked in ${chromeSearchDescription()}) — \`launch\` cannot start one. Install Chrome, or set CHROME.`);
3851
4833
  if (chrome.ignored) consola$1.log(` ⚠ ignoring ${chrome.ignored}`);
3852
4834
  let version;
3853
- try {
4835
+ if (usesPipe()) try {
4836
+ ok(`Chrome reachable: ${(await browserVersion()).product}`);
4837
+ } catch {
4838
+ bad(`No browser on ${socketPath()} — run: browser-automation launch`);
4839
+ return;
4840
+ }
4841
+ else try {
3854
4842
  version = await (await fetch(`${cdpHost()}/json/version`)).json();
3855
4843
  if (!portIsOurs()) {
3856
4844
  bad(`something on port ${cdpPort()} is serving CDP (${version.Browser}) but this account did not start it — it is another user's Chrome, and anything you drive would happen in their browser. Quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port.`);
@@ -4045,6 +5033,38 @@ const profileCommand = define({
4045
5033
  }
4046
5034
  });
4047
5035
  //#endregion
5036
+ //#region src/commands/broker.ts
5037
+ const brokerCommand = define({
5038
+ name: "broker",
5039
+ description: "Internal: hold Chrome's DevTools pipe and serve it on this user's socket. `launch` starts it.",
5040
+ args: {
5041
+ chrome: {
5042
+ type: "string",
5043
+ description: "Chrome binary",
5044
+ required: true
5045
+ },
5046
+ profile: {
5047
+ type: "string",
5048
+ description: "--user-data-dir",
5049
+ required: true
5050
+ },
5051
+ log: {
5052
+ type: "string",
5053
+ description: "Chrome's stdout/stderr",
5054
+ required: true
5055
+ }
5056
+ },
5057
+ async run(ctx) {
5058
+ await runBroker({
5059
+ chrome: ctx.values.chrome,
5060
+ profile: ctx.values.profile,
5061
+ log: ctx.values.log,
5062
+ dir: brokerDir(),
5063
+ socket: process.platform === "win32" ? windowsPipeName() : socketPath()
5064
+ });
5065
+ }
5066
+ });
5067
+ //#endregion
4048
5068
  //#region src/commands/context.ts
4049
5069
  /** Run `fn` as if `name` (or, when undefined, the user's own automation Chrome) were the active context. */
4050
5070
  async function asChrome(name, fn) {
@@ -4058,7 +5078,9 @@ async function asChrome(name, fn) {
4058
5078
  else process.env.BROWSER_AUTOMATION_CONTEXT = saved;
4059
5079
  }
4060
5080
  }
5081
+ /** Is the active Chrome up? Over its pipe, or, for the person's own with BROWSER_AUTOMATION_CDP set, its port. */
4061
5082
  async function up() {
5083
+ if (usesPipe()) return pipeUp(1500);
4062
5084
  try {
4063
5085
  return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
4064
5086
  } catch {
@@ -4066,11 +5088,7 @@ async function up() {
4066
5088
  }
4067
5089
  }
4068
5090
  async function running(r) {
4069
- try {
4070
- return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
4071
- } catch {
4072
- return false;
4073
- }
5091
+ return asChrome(r.name, up);
4074
5092
  }
4075
5093
  /**
4076
5094
  * Login contexts (core/context-store.ts): a separate Chrome per extra account,
@@ -4078,7 +5096,7 @@ async function running(r) {
4078
5096
  */
4079
5097
  const contextCommand = define({
4080
5098
  name: "context",
4081
- description: "Login contexts — a separate Chrome (own profile, own port, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
5099
+ description: "Login contexts — a separate Chrome (own profile, own pipe, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
4082
5100
  args: { "delete-profile": {
4083
5101
  type: "boolean",
4084
5102
  description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
@@ -4094,9 +5112,9 @@ const contextCommand = define({
4094
5112
  const on = await up();
4095
5113
  const pid = on ? browserPid() : null;
4096
5114
  const users = sessions.filter((s) => (s.context ?? void 0) === name).map((s) => s.name);
4097
- return ` ${label.padEnd(22)} :${String(cdpPort()).padEnd(5)} [${on ? "running" : "stopped"}]${pid ? ` pid ${pid}` : ""}${color ? ` ${color} window` : ""}${name && name === project ? " ← BAC_CONTEXT" : ""}${users.length > 6 ? ` ${users.length} sessions` : users.length ? ` sessions: ${users.join(", ")}` : ""}`;
5115
+ return ` ${label.padEnd(22)} [${on ? "running" : "stopped"}]${pid ? ` pid ${pid}` : ""}${color ? ` ${color} window` : ""}${name && name === project ? " ← BAC_CONTEXT" : ""}${users.length > 6 ? ` ${users.length} sessions` : users.length ? ` sessions: ${users.join(", ")}` : ""}`;
4098
5116
  });
4099
- consola$1.log(`# Chromes driven by browser-automation — login contexts' profiles under ${contextsDir()}`);
5117
+ consola$1.log(`# Chromes driven by browser-automation, each on its own pipe — login contexts' profiles under ${contextsDir()}`);
4100
5118
  consola$1.log(await row("(your automation Chrome)", void 0, void 0));
4101
5119
  for (const r of all) consola$1.log(await row(r.name, r.name, r.color));
4102
5120
  if (!all.length) consola$1.log(" No login contexts yet. Open one with: browser-automation new -s <session> --context <name> <url>");
@@ -4153,6 +5171,7 @@ const subCommands = new Map([
4153
5171
  ["snapshot", snapshotCommand],
4154
5172
  ["snap", snapshotCommand],
4155
5173
  ["click", clickCommand],
5174
+ ["key", keyCommand],
4156
5175
  ["fill", fillCommand],
4157
5176
  ["read", readCommand],
4158
5177
  ["focus", focusCommand],
@@ -4174,6 +5193,7 @@ const subCommands = new Map([
4174
5193
  ["prune", gcCommand],
4175
5194
  ["port", portCommand],
4176
5195
  ["profile", profileCommand],
5196
+ ["broker", brokerCommand],
4177
5197
  ["context", contextCommand]
4178
5198
  ]);
4179
5199
  function withRealPositionals(cmd, real) {