@generativereality/browser-automation 0.4.12 → 0.4.14

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,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
4
- import { consola } from "consola";
4
+ import consola, { consola as consola$1 } from "consola";
5
5
  import { homedir } from "node:os";
6
6
  import { basename, dirname, extname, join, resolve } from "node:path";
7
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { execFileSync, spawnSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  //#region package.json
11
11
  var name = "@generativereality/browser-automation";
12
- var version = "0.4.12";
12
+ var version = "0.4.14";
13
13
  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
14
  var package_default = {
15
15
  name,
@@ -408,6 +408,22 @@ async function activateTab(targetId) {
408
408
  await s.send("Target.activateTarget", { targetId });
409
409
  });
410
410
  }
411
+ /**
412
+ * Ask Chrome to quit, the way its own menu does.
413
+ *
414
+ * `launch --restart` used to rely on SIGTERM, and on macOS 27 / Chrome 153 the
415
+ * browser process never exits on it: the DevTools port and helpers go, the
416
+ * process stays asleep. Measured 2026-09-23, every restart of every Chrome,
417
+ * however launched. The script then escalates to SIGKILL, which skips the
418
+ * profile flush that keeps the logins — so quit it properly first and leave the
419
+ * signals as the fallback. Resolves once the request is sent; the connection
420
+ * dropping as Chrome goes is the expected outcome, not an error.
421
+ */
422
+ async function closeBrowser() {
423
+ await withBrowser(async (s) => {
424
+ await s.send("Browser.close", {}, 3e3).catch(() => {});
425
+ }, 3e3);
426
+ }
411
427
  async function closeTab(targetId) {
412
428
  return withBrowser(async (s) => {
413
429
  return !!(await s.send("Target.closeTarget", { targetId })).success;
@@ -453,13 +469,37 @@ async function captureScreenshot(targetId, { fullPage = false } = {}) {
453
469
  });
454
470
  }
455
471
  /** Navigate a page target and wait for load (or timeout). */
456
- async function navigate(targetId, url, { timeout = 3e4 } = {}) {
472
+ /**
473
+ * How long to wait for a page's load event before giving up on confirming it.
474
+ *
475
+ * Read from the environment so the suite can exercise the give-up path without
476
+ * spending 30 real seconds on it. Deliberately NOT used by the test that checks
477
+ * a prompt exit: shrinking the timeout there would shrink the leak it exists to
478
+ * catch, and it would pass against the bug.
479
+ */
480
+ function navTimeout() {
481
+ const v = Number(process.env.BROWSER_AUTOMATION_NAV_TIMEOUT);
482
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : 3e4;
483
+ }
484
+ async function navigate(targetId, url, { timeout = navTimeout() } = {}) {
457
485
  return withPage(targetId, async (s) => {
458
486
  await s.send("Page.enable");
459
- const loaded = new Promise((resolve) => s.on("Page.loadEventFired", () => resolve()));
487
+ let seen = false;
488
+ const loaded = new Promise((resolve) => s.on("Page.loadEventFired", () => {
489
+ seen = true;
490
+ resolve();
491
+ }));
460
492
  const r = await s.send("Page.navigate", { url });
461
493
  if (r.errorText) throw new Error(`navigate failed: ${r.errorText}`);
462
- await Promise.race([loaded, new Promise((res) => setTimeout(res, timeout))]);
494
+ let timer;
495
+ try {
496
+ await Promise.race([loaded, new Promise((res) => {
497
+ timer = setTimeout(res, timeout);
498
+ })]);
499
+ } finally {
500
+ if (timer !== void 0) clearTimeout(timer);
501
+ }
502
+ return { loaded: seen };
463
503
  });
464
504
  }
465
505
  //#endregion
@@ -1073,7 +1113,7 @@ const newCommand = define({
1073
1113
  async run(ctx) {
1074
1114
  const name = ctx.values.session || defaultSessionName();
1075
1115
  const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
1076
- if (loadSession(name) && !ctx.values.force) consola.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
1116
+ if (loadSession(name) && !ctx.values.force) consola$1.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
1077
1117
  const targetId = await withRendererDiagnosis(() => createTab(url));
1078
1118
  saveSession({
1079
1119
  name,
@@ -1082,16 +1122,16 @@ const newCommand = define({
1082
1122
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
1083
1123
  });
1084
1124
  const r = await ensureRenderer(targetId);
1085
- if (r.woke) consola.warn(`[${name}] the new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.`);
1125
+ if (r.woke) consola$1.warn(`[${name}] the new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.`);
1086
1126
  if (!r.ok) {
1087
1127
  const health = await probeRenderer().catch(() => null);
1088
1128
  if (health && !health.ok) {
1089
- consola.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
1129
+ consola$1.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
1090
1130
  process.exit(1);
1091
1131
  }
1092
- consola.warn(`[${name}] tab ${targetId.slice(0, 12)}… did not answer yet (${r.reason ?? r.outcome}). Chrome can still create renderers, so this is likely transient — retry the next command.`);
1132
+ consola$1.warn(`[${name}] tab ${targetId.slice(0, 12)}… did not answer yet (${r.reason ?? r.outcome}). Chrome can still create renderers, so this is likely transient — retry the next command.`);
1093
1133
  }
1094
- consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
1134
+ consola$1.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
1095
1135
  }
1096
1136
  });
1097
1137
  //#endregion
@@ -1201,16 +1241,16 @@ const gotoCommand = define({
1201
1241
  async run(ctx) {
1202
1242
  const url = ctx.positionals[1];
1203
1243
  if (!url) {
1204
- consola.error("URL is required");
1244
+ consola$1.error("URL is required");
1205
1245
  process.exit(1);
1206
1246
  }
1207
1247
  const target = normalizeUrl(url);
1208
1248
  const opts = targetOpts(ctx.values);
1209
1249
  const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
1210
1250
  if (created) {
1211
- if ((await ensureRenderer(targetId)).woke) consola.warn("The new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.");
1251
+ if ((await ensureRenderer(targetId)).woke) consola$1.warn("The new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.");
1212
1252
  }
1213
- await withRendererDiagnosis(() => navigate(targetId, target));
1253
+ if (!(await withRendererDiagnosis(() => navigate(targetId, target))).loaded) consola$1.warn("No load event arrived, so the page may still be loading. The navigation itself was accepted; this is a statement about what could not be confirmed.");
1214
1254
  if (!opts.match && !opts.target) {
1215
1255
  const name = opts.session || defaultSessionName();
1216
1256
  saveSession({
@@ -1219,8 +1259,8 @@ const gotoCommand = define({
1219
1259
  url: target,
1220
1260
  createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
1221
1261
  });
1222
- consola.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
1223
- } else consola.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
1262
+ consola$1.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
1263
+ } else consola$1.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
1224
1264
  }
1225
1265
  });
1226
1266
  //#endregion
@@ -1486,18 +1526,18 @@ const snapshotCommand = define({
1486
1526
  return;
1487
1527
  }
1488
1528
  const overlayNote = snap.overlayCount ? ` (${snap.overlayCount} in an open overlay, listed first)` : "";
1489
- consola.log(`# ${snap.title}\n# ${snap.url}\n# ${snap.count} interactive elements${overlayNote}`);
1490
- if (snap.overlayText) consola.log(`# overlay: ${snap.overlayText}`);
1529
+ consola$1.log(`# ${snap.title}\n# ${snap.url}\n# ${snap.count} interactive elements${overlayNote}`);
1530
+ if (snap.overlayText) consola$1.log(`# overlay: ${snap.overlayText}`);
1491
1531
  for (const el of snap.elements) {
1492
1532
  const label = el.type ? `${el.role}[${el.type}]` : el.role;
1493
1533
  const st = el.state ? `[${el.state}] ` : "";
1494
- consola.log(`${el.ref.padEnd(5)} ${label.padEnd(18)} ${st}${el.name}`);
1534
+ consola$1.log(`${el.ref.padEnd(5)} ${label.padEnd(18)} ${st}${el.name}`);
1495
1535
  }
1496
1536
  }
1497
1537
  });
1498
1538
  //#endregion
1499
1539
  //#region src/commands/click.ts
1500
- const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
1540
+ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
1501
1541
  const clickCommand = define({
1502
1542
  name: "click",
1503
1543
  description: "Click an element by ref (from the latest snapshot)",
@@ -1515,7 +1555,7 @@ const clickCommand = define({
1515
1555
  async run(ctx) {
1516
1556
  const ref = ctx.positionals[1];
1517
1557
  if (!ref || !isValidRef(ref)) {
1518
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1558
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1519
1559
  process.exit(1);
1520
1560
  }
1521
1561
  const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
@@ -1538,7 +1578,7 @@ const clickCommand = define({
1538
1578
  while (Date.now() < focusDeadline) {
1539
1579
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
1540
1580
  if (f && f.f && f.v === "visible") break;
1541
- await sleep$1(50);
1581
+ await sleep$2(50);
1542
1582
  }
1543
1583
  let prev = null;
1544
1584
  let point = null;
@@ -1547,7 +1587,7 @@ const clickCommand = define({
1547
1587
  while (Date.now() < actDeadline) {
1548
1588
  const a = await evalIn(actionabilityExpr(ref));
1549
1589
  if (a?.err) {
1550
- consola.error(a.err);
1590
+ consola$1.error(a.err);
1551
1591
  process.exit(1);
1552
1592
  }
1553
1593
  const stable = prev !== null && Math.abs(prev.x - a.x) < .5 && Math.abs(prev.y - a.y) < .5;
@@ -1564,10 +1604,10 @@ const clickCommand = define({
1564
1604
  x: a.x,
1565
1605
  y: a.y
1566
1606
  };
1567
- await sleep$1(60);
1607
+ await sleep$2(60);
1568
1608
  }
1569
1609
  if (!point) {
1570
- consola.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
1610
+ consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
1571
1611
  process.exit(1);
1572
1612
  }
1573
1613
  const { x, y } = point;
@@ -1579,7 +1619,7 @@ const clickCommand = define({
1579
1619
  buttons: 0,
1580
1620
  pointerType: "mouse"
1581
1621
  });
1582
- await sleep$1(20);
1622
+ await sleep$2(20);
1583
1623
  await s.send("Input.dispatchMouseEvent", {
1584
1624
  type: "mousePressed",
1585
1625
  x,
@@ -1601,15 +1641,15 @@ const clickCommand = define({
1601
1641
  });
1602
1642
  return point.tag;
1603
1643
  });
1604
- consola.success(`clicked ${ref} <${trustedTag}> (trusted)`);
1644
+ consola$1.success(`clicked ${ref} <${trustedTag}> (trusted)`);
1605
1645
  return;
1606
1646
  }
1607
1647
  const r = await evaluate(targetId, clickExpr(ref));
1608
1648
  if (r.err) {
1609
- consola.error(r.err);
1649
+ consola$1.error(r.err);
1610
1650
  process.exit(1);
1611
1651
  }
1612
- consola.success(`clicked ${ref} <${r.tag}>`);
1652
+ consola$1.success(`clicked ${ref} <${r.tag}>`);
1613
1653
  }
1614
1654
  });
1615
1655
  //#endregion
@@ -1644,11 +1684,11 @@ const fillCommand = define({
1644
1684
  const ref = ctx.positionals[1];
1645
1685
  const value = ctx.positionals[2];
1646
1686
  if (!ref || !isValidRef(ref)) {
1647
- consola.error("A ref like \"e3\" is required (run `browser-automation snapshot` first)");
1687
+ consola$1.error("A ref like \"e3\" is required (run `browser-automation snapshot` first)");
1648
1688
  process.exit(1);
1649
1689
  }
1650
1690
  if (value === void 0) {
1651
- consola.error("A value is required");
1691
+ consola$1.error("A value is required");
1652
1692
  process.exit(1);
1653
1693
  }
1654
1694
  const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
@@ -1657,7 +1697,7 @@ const fillCommand = define({
1657
1697
  if (native) {
1658
1698
  const focus = await evaluate(targetId, focusAndSelectExpr(ref));
1659
1699
  if (focus.err) {
1660
- consola.error(focus.err);
1700
+ consola$1.error(focus.err);
1661
1701
  process.exit(1);
1662
1702
  }
1663
1703
  await withPage(targetId, async (s) => {
@@ -1680,23 +1720,23 @@ const fillCommand = define({
1680
1720
  } else {
1681
1721
  const r = await evaluate(targetId, fillExpr(ref, value, submit));
1682
1722
  if (r.err) {
1683
- consola.error(r.err);
1723
+ consola$1.error(r.err);
1684
1724
  process.exit(1);
1685
1725
  }
1686
1726
  }
1687
1727
  if (ctx.values.verify) {
1688
1728
  const v = await evaluate(targetId, readValueAndTrackerExpr(ref));
1689
- if (v.err) consola.warn(`verify failed to re-read field: ${v.err}`);
1729
+ if (v.err) consola$1.warn(`verify failed to re-read field: ${v.err}`);
1690
1730
  else {
1691
1731
  const domMatches = v.value === value;
1692
1732
  const trackerKnown = v.trackerValue !== null && v.trackerValue !== void 0;
1693
1733
  const trackerMatches = !trackerKnown || v.trackerValue === value;
1694
- if (!domMatches) consola.warn(`verify: DOM value is "${v.value}" but you requested "${value}" — wrong element selected, or the page rewrote it.`);
1695
- else if (!trackerMatches) consola.warn(`verify: DOM shows "${value}" but React's _valueTracker still holds "${v.trackerValue}". The form library will likely submit the stale value. Try --native, or capture the form's PUT endpoint and call it directly (see SKILL.md "Controlled-form state stickiness").`);
1696
- else if (v.hasReactFiber && !trackerKnown && !native) consola.info(`verify: field has a React fiber but no _valueTracker — if the next submit serializes the old value, try --native.`);
1734
+ if (!domMatches) consola$1.warn(`verify: DOM value is "${v.value}" but you requested "${value}" — wrong element selected, or the page rewrote it.`);
1735
+ else if (!trackerMatches) consola$1.warn(`verify: DOM shows "${value}" but React's _valueTracker still holds "${v.trackerValue}". The form library will likely submit the stale value. Try --native, or capture the form's PUT endpoint and call it directly (see SKILL.md "Controlled-form state stickiness").`);
1736
+ else if (v.hasReactFiber && !trackerKnown && !native) consola$1.info(`verify: field has a React fiber but no _valueTracker — if the next submit serializes the old value, try --native.`);
1697
1737
  }
1698
1738
  }
1699
- consola.success(`filled ${ref} = "${value}"${native ? " [native]" : ""}${submit ? " + submitted" : ""}`);
1739
+ consola$1.success(`filled ${ref} = "${value}"${native ? " [native]" : ""}${submit ? " + submitted" : ""}`);
1700
1740
  }
1701
1741
  });
1702
1742
  //#endregion
@@ -1712,6 +1752,89 @@ const readCommand = define({
1712
1752
  }
1713
1753
  });
1714
1754
  //#endregion
1755
+ //#region src/commands/focus.ts
1756
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
1757
+ /**
1758
+ * Make a tab believe it is the visible one.
1759
+ *
1760
+ * # Why this exists
1761
+ *
1762
+ * A backgrounded tab is not merely unwatched — it reports itself hidden, and
1763
+ * pages act on that. Measured 2026-09-14 on an ordinary tab this CLI had opened:
1764
+ *
1765
+ * {"visibility":"hidden","hasFocus":false,"hidden":true}
1766
+ *
1767
+ * Anything gated on `document.visibilityState` behaves differently there:
1768
+ * deferred rendering, paused polling and animation, charts that never draw,
1769
+ * carousels and videos that never start. `core/renderer-wake.ts` measures the
1770
+ * same deprioritisation one layer down — a background target's renderer answers
1771
+ * in a median 367ms against 19ms once activated, with a tail past 12s.
1772
+ *
1773
+ * Until now nothing exposed this. `click --trusted` and `drop` both force it as
1774
+ * a side effect of needing trusted input to land, so the capability was in the
1775
+ * codebase and reachable only by clicking something.
1776
+ *
1777
+ * # The two ways, and why the quiet one is the default
1778
+ *
1779
+ * `Emulation.setFocusEmulationEnabled` makes the renderer treat itself as
1780
+ * focused and visible whatever the real window is doing — no window moves, and
1781
+ * the operator's frontmost app is undisturbed. That is what this does by
1782
+ * default, and it is how Playwright drives backgrounded pages.
1783
+ *
1784
+ * `--raise` additionally calls `Target.activateTarget`, which genuinely brings
1785
+ * the tab to the front and **takes the operator's screen** — measured in
1786
+ * renderer-wake.ts: every route to a real activation moved the frontmost app
1787
+ * from the terminal to Chrome, and there is no quiet variant. Use it when a
1788
+ * person needs to SEE the tab, not to make a page render.
1789
+ *
1790
+ * # It reports the outcome, not the acceptance
1791
+ *
1792
+ * All three CDP commands are best-effort — an older Chrome may not expose one —
1793
+ * so "sent" says nothing. This reads `document.hasFocus()` and
1794
+ * `visibilityState` back afterwards and prints what it actually achieved,
1795
+ * naming what it could not confirm rather than printing a tick over it.
1796
+ */
1797
+ const focusCommand = define({
1798
+ name: "focus",
1799
+ description: "Make a tab report itself focused + visible, so pages that defer work while hidden (rendering, polling, charts, video) behave as if watched. Quiet by default — no window moves and the operator keeps their frontmost app. Add --raise to genuinely bring the tab to the front, which DOES take the screen.",
1800
+ args: {
1801
+ ...targetArgs,
1802
+ raise: {
1803
+ type: "boolean",
1804
+ short: "r",
1805
+ description: "Also bring the tab to the front for real (Target.activateTarget). This takes the operator's screen — Chrome comes forward over whatever they are using. Only for when a person needs to see the tab."
1806
+ }
1807
+ },
1808
+ async run(ctx) {
1809
+ const raise = ctx.values.raise;
1810
+ const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
1811
+ if (raise) await activateTab(targetId);
1812
+ const state = await withPage(targetId, async (s) => {
1813
+ await forceForeground(s);
1814
+ const deadline = Date.now() + 2e3;
1815
+ let last = {
1816
+ focused: false,
1817
+ visibility: "unknown"
1818
+ };
1819
+ while (Date.now() < deadline) {
1820
+ last = (await s.send("Runtime.evaluate", {
1821
+ expression: "({focused:document.hasFocus(),visibility:document.visibilityState})",
1822
+ returnByValue: true
1823
+ })).result?.value ?? last;
1824
+ if (last.focused && last.visibility === "visible") break;
1825
+ await sleep$1(50);
1826
+ }
1827
+ return last;
1828
+ });
1829
+ const how = raise ? "raised to the front" : "no window focus taken";
1830
+ if (state.focused && state.visibility === "visible") {
1831
+ consola.success(`[${targetId.slice(0, 12)}…] focused + visible (${how})`);
1832
+ return;
1833
+ }
1834
+ consola.warn(`[${targetId.slice(0, 12)}…] hasFocus=${state.focused} visibilityState=${state.visibility} (${how}). The page may still defer work it gates on focus. ` + (raise ? "" : "If the page needs a genuinely front tab, re-run with --raise."));
1835
+ }
1836
+ });
1837
+ //#endregion
1715
1838
  //#region src/commands/eval.ts
1716
1839
  const evalCommand = define({
1717
1840
  name: "eval",
@@ -1726,7 +1849,7 @@ const evalCommand = define({
1726
1849
  async run(ctx) {
1727
1850
  const expr = ctx.positionals[1];
1728
1851
  if (!expr) {
1729
- consola.error("A JS expression is required");
1852
+ consola$1.error("A JS expression is required");
1730
1853
  process.exit(1);
1731
1854
  }
1732
1855
  const v = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), expr);
@@ -1819,15 +1942,15 @@ const downloadCommand = define({
1819
1942
  const click = ctx.values.click;
1820
1943
  const url = ctx.values.url;
1821
1944
  if (!click && !url) {
1822
- consola.error("Provide --click <ref> or --url <url> to trigger the download");
1945
+ consola$1.error("Provide --click <ref> or --url <url> to trigger the download");
1823
1946
  process.exit(1);
1824
1947
  }
1825
1948
  if (click && !isValidRef(click)) {
1826
- consola.error(`--click expects a ref like e42 (run snapshot first)`);
1949
+ consola$1.error(`--click expects a ref like e42 (run snapshot first)`);
1827
1950
  process.exit(1);
1828
1951
  }
1829
1952
  const r = await captureDownload(await resolveExistingTargetId(targetOpts(ctx.values)), ctx.values.dir || DEFAULT_DIR$1, click ? clickTriggerExpr(click) : urlTriggerExpr(url), ctx.values.timeout ?? 3e4);
1830
- consola.success(`Downloaded ${r.filename} (${r.bytes} bytes)`);
1953
+ consola$1.success(`Downloaded ${r.filename} (${r.bytes} bytes)`);
1831
1954
  process.stdout.write(r.path + "\n");
1832
1955
  }
1833
1956
  });
@@ -1967,7 +2090,7 @@ function absFiles$2(paths) {
1967
2090
  return paths.map((p) => {
1968
2091
  const abs = resolve(p);
1969
2092
  if (!existsSync(abs) || !statSync(abs).isFile()) {
1970
- consola.error(`no such file: ${abs}`);
2093
+ consola$1.error(`no such file: ${abs}`);
1971
2094
  process.exit(1);
1972
2095
  }
1973
2096
  return abs;
@@ -1991,16 +2114,16 @@ const setfilesCommand = define({
1991
2114
  const ref = ctx.positionals[1];
1992
2115
  const paths = ctx.positionals.slice(2);
1993
2116
  if (!ref || !isValidRef(ref)) {
1994
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
2117
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1995
2118
  process.exit(1);
1996
2119
  }
1997
2120
  if (paths.length === 0) {
1998
- consola.error("At least one file path is required");
2121
+ consola$1.error("At least one file path is required");
1999
2122
  process.exit(1);
2000
2123
  }
2001
2124
  const files = absFiles$2(paths);
2002
2125
  const r = await setFilesByRef(await resolveExistingTargetId(targetOpts(ctx.values)), ref, files);
2003
- consola.success(`set ${r.files.length} file(s) on ${ref} <${r.tag} type=${r.type}>:`);
2126
+ consola$1.success(`set ${r.files.length} file(s) on ${ref} <${r.tag} type=${r.type}>:`);
2004
2127
  for (const f of r.files) process.stdout.write(f + "\n");
2005
2128
  }
2006
2129
  });
@@ -2011,7 +2134,7 @@ function absFiles$1(paths) {
2011
2134
  return paths.map((p) => {
2012
2135
  const abs = resolve(p);
2013
2136
  if (!existsSync(abs) || !statSync(abs).isFile()) {
2014
- consola.error(`no such file: ${abs}`);
2137
+ consola$1.error(`no such file: ${abs}`);
2015
2138
  process.exit(1);
2016
2139
  }
2017
2140
  return abs;
@@ -2039,28 +2162,28 @@ const uploadCommand = define({
2039
2162
  const click = ctx.values.click;
2040
2163
  const paths = ctx.positionals.slice(1);
2041
2164
  if (!click) {
2042
- consola.error("--click <ref> is required (the button that opens the file chooser)");
2165
+ consola$1.error("--click <ref> is required (the button that opens the file chooser)");
2043
2166
  process.exit(1);
2044
2167
  }
2045
2168
  if (!isValidRef(click)) {
2046
- consola.error("--click expects a ref like e42 (run `browser-automation snapshot` first)");
2169
+ consola$1.error("--click expects a ref like e42 (run `browser-automation snapshot` first)");
2047
2170
  process.exit(1);
2048
2171
  }
2049
2172
  if (paths.length === 0) {
2050
- consola.error("At least one file path is required");
2173
+ consola$1.error("At least one file path is required");
2051
2174
  process.exit(1);
2052
2175
  }
2053
2176
  const files = absFiles$1(paths);
2054
2177
  const r = await uploadViaChooser(await resolveExistingTargetId(targetOpts(ctx.values)), click, files, ctx.values.timeout ?? 15e3);
2055
2178
  if (r.delivered === 0) {
2056
- consola.error(`the file chooser opened (backendNodeId ${r.backendNodeId}) but the file never reached the page's change handler — the page likely replaced/destroyed the transient input before it could be set. Re-snapshot and confirm --click points at the real trigger, or try again.`);
2179
+ consola$1.error(`the file chooser opened (backendNodeId ${r.backendNodeId}) but the file never reached the page's change handler — the page likely replaced/destroyed the transient input before it could be set. Re-snapshot and confirm --click points at the real trigger, or try again.`);
2057
2180
  process.exit(1);
2058
2181
  }
2059
2182
  const note = r.reconnected ? " (input was detached — re-attached and re-dispatched input/change so the page's handler fired)" : "";
2060
- consola.success(`delivered ${r.files.length} file(s) to the page's file handler via chooser (backendNodeId ${r.backendNodeId})${note}:`);
2183
+ consola$1.success(`delivered ${r.files.length} file(s) to the page's file handler via chooser (backendNodeId ${r.backendNodeId})${note}:`);
2061
2184
  for (const f of r.files) process.stdout.write(f + "\n");
2062
- if (r.count === 0) consola.info("The app consumed the file and reset the input (normal). This confirms delivery, not staging — re-snapshot or screenshot to verify the attachment chip/preview actually appeared before submitting.");
2063
- else consola.info("Re-snapshot to confirm the attachment chip/preview appeared before submitting — the DOM changed.");
2185
+ if (r.count === 0) consola$1.info("The app consumed the file and reset the input (normal). This confirms delivery, not staging — re-snapshot or screenshot to verify the attachment chip/preview actually appeared before submitting.");
2186
+ else consola$1.info("Re-snapshot to confirm the attachment chip/preview appeared before submitting — the DOM changed.");
2064
2187
  }
2065
2188
  });
2066
2189
  //#endregion
@@ -2071,7 +2194,7 @@ function absFiles(paths) {
2071
2194
  return paths.map((p) => {
2072
2195
  const abs = resolve(p);
2073
2196
  if (!existsSync(abs) || !statSync(abs).isFile()) {
2074
- consola.error(`no such file: ${abs}`);
2197
+ consola$1.error(`no such file: ${abs}`);
2075
2198
  process.exit(1);
2076
2199
  }
2077
2200
  return abs;
@@ -2126,11 +2249,11 @@ const dropCommand = define({
2126
2249
  const ref = ctx.positionals[1];
2127
2250
  const paths = ctx.positionals.slice(2);
2128
2251
  if (!ref || !isValidRef(ref)) {
2129
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
2252
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
2130
2253
  process.exit(1);
2131
2254
  }
2132
2255
  if (paths.length === 0) {
2133
- consola.error("At least one file path is required");
2256
+ consola$1.error("At least one file path is required");
2134
2257
  process.exit(1);
2135
2258
  }
2136
2259
  const files = absFiles(paths);
@@ -2142,10 +2265,10 @@ const dropCommand = define({
2142
2265
  b64: readFileSync(p).toString("base64")
2143
2266
  }))));
2144
2267
  if (r.err) {
2145
- consola.error(r.err);
2268
+ consola$1.error(r.err);
2146
2269
  process.exit(1);
2147
2270
  }
2148
- consola.success(`dropped ${r.count} file(s) on ${ref} <${r.tag}> (synthetic — re-snapshot/screenshot to confirm the zone accepted them):`);
2271
+ consola$1.success(`dropped ${r.count} file(s) on ${ref} <${r.tag}> (synthetic — re-snapshot/screenshot to confirm the zone accepted them):`);
2149
2272
  for (const f of files) process.stdout.write(f + "\n");
2150
2273
  return;
2151
2274
  }
@@ -2176,7 +2299,7 @@ const dropCommand = define({
2176
2299
  while (Date.now() < actDeadline) {
2177
2300
  const a = await evalIn(actionabilityExpr(ref));
2178
2301
  if (a?.err) {
2179
- consola.error(a.err);
2302
+ consola$1.error(a.err);
2180
2303
  process.exit(1);
2181
2304
  }
2182
2305
  const stable = prev !== null && Math.abs(prev.x - a.x) < .5 && Math.abs(prev.y - a.y) < .5;
@@ -2196,7 +2319,7 @@ const dropCommand = define({
2196
2319
  await sleep(60);
2197
2320
  }
2198
2321
  if (!point) {
2199
- consola.error(`<${ref}> not actionable for a drop: ${lastReason}`);
2322
+ consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
2200
2323
  process.exit(1);
2201
2324
  }
2202
2325
  const { x, y } = point;
@@ -2226,9 +2349,9 @@ const dropCommand = define({
2226
2349
  });
2227
2350
  return point.tag;
2228
2351
  });
2229
- consola.success(`dropped ${files.length} file(s) on ${ref} <${tag}> (trusted):`);
2352
+ consola$1.success(`dropped ${files.length} file(s) on ${ref} <${tag}> (trusted):`);
2230
2353
  for (const f of files) process.stdout.write(f + "\n");
2231
- consola.info("Re-snapshot or screenshot to confirm the zone accepted the drop — the DOM changed.");
2354
+ consola$1.info("Re-snapshot or screenshot to confirm the zone accepted the drop — the DOM changed.");
2232
2355
  }
2233
2356
  });
2234
2357
  //#endregion
@@ -2341,7 +2464,7 @@ const networkCommand = define({
2341
2464
  async run(ctx) {
2342
2465
  const click = ctx.values.click;
2343
2466
  if (click && !isValidRef(click)) {
2344
- consola.error("--click expects a ref like e42");
2467
+ consola$1.error("--click expects a ref like e42");
2345
2468
  process.exit(1);
2346
2469
  }
2347
2470
  const entries = await captureNetwork(await resolveExistingTargetId(targetOpts(ctx.values)), {
@@ -2357,14 +2480,14 @@ const networkCommand = define({
2357
2480
  process.stdout.write(JSON.stringify(entries, null, 2) + "\n");
2358
2481
  return;
2359
2482
  }
2360
- consola.log(`# ${entries.length} requests`);
2483
+ consola$1.log(`# ${entries.length} requests`);
2361
2484
  for (const e of entries) {
2362
- consola.log(`${(e.method ?? "").padEnd(5)} ${String(e.status ?? "—").padEnd(4)} ${(e.type ?? "").padEnd(9)} ${e.url.slice(0, 100)}`);
2485
+ consola$1.log(`${(e.method ?? "").padEnd(5)} ${String(e.status ?? "—").padEnd(4)} ${(e.type ?? "").padEnd(9)} ${e.url.slice(0, 100)}`);
2363
2486
  if (ctx.values.headers) {
2364
- if (e.postData) consola.log(` ↑ body: ${e.postData.slice(0, 200)}`);
2365
- for (const [k, v] of Object.entries(e.requestHeaders ?? {})) if (/^(authorization|cookie|x-|content-type)/i.test(k)) consola.log(` ↑ ${k}: ${String(v).slice(0, 120)}`);
2487
+ if (e.postData) consola$1.log(` ↑ body: ${e.postData.slice(0, 200)}`);
2488
+ for (const [k, v] of Object.entries(e.requestHeaders ?? {})) if (/^(authorization|cookie|x-|content-type)/i.test(k)) consola$1.log(` ↑ ${k}: ${String(v).slice(0, 120)}`);
2366
2489
  }
2367
- if (ctx.values.body && e.body) consola.log(` ↓ ${e.body.replace(/\s+/g, " ").slice(0, 300)}`);
2490
+ if (ctx.values.body && e.body) consola$1.log(` ↓ ${e.body.replace(/\s+/g, " ").slice(0, 300)}`);
2368
2491
  }
2369
2492
  }
2370
2493
  });
@@ -2395,7 +2518,7 @@ const screenshotCommand = define({
2395
2518
  out = join(DEFAULT_DIR, `${((await listPageTargets()).find((p) => p.id === targetId)?.title || "page").replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").slice(0, 40) || "page"}.png`);
2396
2519
  }
2397
2520
  writeFileSync(out, png);
2398
- consola.success(`Saved screenshot (${png.length} bytes)`);
2521
+ consola$1.success(`Saved screenshot (${png.length} bytes)`);
2399
2522
  process.stdout.write(out + "\n");
2400
2523
  }
2401
2524
  });
@@ -2435,23 +2558,23 @@ const listCommand = define({
2435
2558
  const stale = sessions.filter((s) => !liveIds.has(s.targetId));
2436
2559
  const shown = ctx.values.all ? sessions : live;
2437
2560
  if (shown.length) {
2438
- consola.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
2439
- for (const s of shown) consola.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2440
- } else if (sessions.length) consola.log(`# sessions (0 live)`);
2441
- if (stale.length && !ctx.values.all) consola.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
2442
- if (sessions.length) consola.log("");
2443
- consola.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
2561
+ consola$1.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
2562
+ for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2563
+ } else if (sessions.length) consola$1.log(`# sessions (0 live)`);
2564
+ 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`);
2565
+ if (sessions.length) consola$1.log("");
2566
+ consola$1.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
2444
2567
  for (const t of targets) {
2445
2568
  const owner = sessions.find((s) => s.targetId === t.id);
2446
2569
  const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
2447
- consola.log(` ${t.id.slice(0, 12)} ${owner ? `(${owner.name}) ` : ""}${title.padEnd(28)} ${(t.url ?? "").slice(0, 70)}`);
2570
+ consola$1.log(` ${t.id.slice(0, 12)} ${owner ? `(${owner.name}) ` : ""}${title.padEnd(28)} ${(t.url ?? "").slice(0, 70)}`);
2448
2571
  }
2449
2572
  if (ctx.values.frames) {
2450
- consola.log("");
2451
- consola.log(`# cross-origin iframes (${frames.length}) — address with -F <substr> or -t <id>`);
2573
+ consola$1.log("");
2574
+ consola$1.log(`# cross-origin iframes (${frames.length}) — address with -F <substr> or -t <id>`);
2452
2575
  for (const f of frames) {
2453
2576
  const title = (f.title ?? "").replace(/\s+/g, " ").slice(0, 28);
2454
- consola.log(` ${f.id.slice(0, 12)} ${title.padEnd(28)} ${(f.url ?? "").slice(0, 70)}`);
2577
+ consola$1.log(` ${f.id.slice(0, 12)} ${title.padEnd(28)} ${(f.url ?? "").slice(0, 70)}`);
2455
2578
  }
2456
2579
  }
2457
2580
  }
@@ -2474,12 +2597,12 @@ const closeCommand = define({
2474
2597
  try {
2475
2598
  targetId = await resolveExistingTargetId(opts);
2476
2599
  } catch (e) {
2477
- consola.warn(e instanceof Error ? e.message : String(e));
2600
+ consola$1.warn(e instanceof Error ? e.message : String(e));
2478
2601
  return;
2479
2602
  }
2480
2603
  if (ctx.values.tab) {
2481
2604
  const ok = await closeTab(targetId).catch(() => false);
2482
- consola.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
2605
+ consola$1.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
2483
2606
  }
2484
2607
  const forgotten = [];
2485
2608
  for (const s of listSessions()) if (s.targetId === targetId) {
@@ -2493,8 +2616,8 @@ const closeCommand = define({
2493
2616
  forgotten.push(name);
2494
2617
  }
2495
2618
  }
2496
- if (forgotten.length) consola.success(`Forgot session(s): ${forgotten.join(", ")}.`);
2497
- else if (!ctx.values.tab) consola.info("No session bound to that tab and --tab not given — nothing to do.");
2619
+ if (forgotten.length) consola$1.success(`Forgot session(s): ${forgotten.join(", ")}.`);
2620
+ else if (!ctx.values.tab) consola$1.info("No session bound to that tab and --tab not given — nothing to do.");
2498
2621
  }
2499
2622
  });
2500
2623
  //#endregion
@@ -2508,7 +2631,7 @@ const bindCommand = define({
2508
2631
  const match = ctx.values.match;
2509
2632
  const target = ctx.values.target;
2510
2633
  if (!match && !target) {
2511
- consola.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
2634
+ consola$1.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
2512
2635
  process.exit(1);
2513
2636
  }
2514
2637
  let targetId;
@@ -2527,7 +2650,7 @@ const bindCommand = define({
2527
2650
  url,
2528
2651
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
2529
2652
  });
2530
- consola.success(`Bound session "${name}" → ${url ?? targetId}`);
2653
+ consola$1.success(`Bound session "${name}" → ${url ?? targetId}`);
2531
2654
  }
2532
2655
  });
2533
2656
  //#endregion
@@ -2539,6 +2662,123 @@ function launchScriptPath() {
2539
2662
  return join(packageRoot(), "scripts", "launch-chrome.sh");
2540
2663
  }
2541
2664
  //#endregion
2665
+ //#region src/core/profile.ts
2666
+ /** The default, under ~, reachable by every host. */
2667
+ function homeProfileDir() {
2668
+ return join(homedir(), ".browser-automation", "chrome-profile");
2669
+ }
2670
+ /** The old default, inside Google Chrome's own app-data folder. */
2671
+ function legacyProfileDir() {
2672
+ return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
2673
+ }
2674
+ /**
2675
+ * Does a path exist, as far as this process can tell?
2676
+ *
2677
+ * `unreadable` is its own answer and callers must not fold it into `absent`:
2678
+ * it is what a host denied Chrome's container sees for a profile that is very
2679
+ * much there.
2680
+ */
2681
+ function presence(p) {
2682
+ try {
2683
+ lstatSync(p);
2684
+ return "present";
2685
+ } catch (e) {
2686
+ return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
2687
+ }
2688
+ }
2689
+ /**
2690
+ * Which profile to use, WITHOUT changing anything on disk.
2691
+ *
2692
+ * The home folder once it exists; otherwise the legacy folder whenever it
2693
+ * might exist (present or unreadable); otherwise the home folder, for Chrome
2694
+ * to create on first launch.
2695
+ */
2696
+ function resolveProfile() {
2697
+ const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
2698
+ if (explicit) return {
2699
+ dir: explicit,
2700
+ source: "env"
2701
+ };
2702
+ const home = homeProfileDir();
2703
+ if (presence(home) === "present") return {
2704
+ dir: home,
2705
+ source: "home"
2706
+ };
2707
+ if (presence(legacyProfileDir()) !== "absent") return {
2708
+ dir: legacyProfileDir(),
2709
+ source: "legacy"
2710
+ };
2711
+ return {
2712
+ dir: home,
2713
+ source: "home"
2714
+ };
2715
+ }
2716
+ /** Is any Chrome of ours running with this --user-data-dir? */
2717
+ function inUse(dir) {
2718
+ try {
2719
+ execFileSync("pgrep", [
2720
+ "-u",
2721
+ String(process.getuid?.() ?? -1),
2722
+ "-f",
2723
+ "--",
2724
+ `--user-data-dir=${dir}`
2725
+ ], { stdio: "ignore" });
2726
+ return true;
2727
+ } catch {
2728
+ return false;
2729
+ }
2730
+ }
2731
+ /** Move the legacy profile into the home folder, if that is both needed and safe. */
2732
+ function migrateProfile() {
2733
+ const choice = resolveProfile();
2734
+ if (choice.source === "env") return {
2735
+ outcome: "explicit",
2736
+ dir: choice.dir
2737
+ };
2738
+ if (choice.source === "home") return {
2739
+ outcome: presence(choice.dir) === "present" ? "current" : "fresh",
2740
+ dir: choice.dir
2741
+ };
2742
+ const legacy = legacyProfileDir();
2743
+ const home = homeProfileDir();
2744
+ if (presence(legacy) === "unreadable") return {
2745
+ outcome: "refused",
2746
+ dir: legacy,
2747
+ 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.`
2748
+ };
2749
+ if (inUse(legacy)) return {
2750
+ outcome: "in-use",
2751
+ dir: legacy,
2752
+ 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\`.`
2753
+ };
2754
+ try {
2755
+ mkdirSync(dirname(home), { recursive: true });
2756
+ renameSync(legacy, home);
2757
+ } catch (e) {
2758
+ const code = e?.code;
2759
+ if (code === "EPERM" || code === "EACCES") return {
2760
+ outcome: "refused",
2761
+ dir: legacy,
2762
+ detail: `could not move ${legacy} (${code}): this process may not write Chrome's folder. On macOS that is the app-data grant for the app this is running under. Nothing was changed; the old profile keeps working. Run \`browser-automation profile --migrate\` once from a terminal that can reach it.`
2763
+ };
2764
+ return {
2765
+ outcome: "failed",
2766
+ dir: legacy,
2767
+ detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
2768
+ };
2769
+ }
2770
+ for (const f of [
2771
+ "SingletonLock",
2772
+ "SingletonSocket",
2773
+ "SingletonCookie"
2774
+ ]) rmSync(join(home, f), { force: true });
2775
+ return {
2776
+ outcome: "moved",
2777
+ dir: home,
2778
+ detail: `moved ${legacy} → ${home}`
2779
+ };
2780
+ }
2781
+ //#endregion
2542
2782
  //#region src/commands/launch.ts
2543
2783
  const launchCommand = define({
2544
2784
  name: "launch",
@@ -2556,16 +2796,33 @@ const launchCommand = define({
2556
2796
  async run(ctx) {
2557
2797
  const script = launchScriptPath();
2558
2798
  if (!existsSync(script)) {
2559
- consola.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2799
+ consola$1.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2560
2800
  process.exit(1);
2561
2801
  }
2562
- const r = spawnSync("bash", [script, ...[
2563
- "--port",
2564
- String(cdpPort()),
2565
- ...ctx.values.status ? ["--status"] : [],
2566
- ...ctx.values.restart ? ["--restart"] : []
2567
- ]], { stdio: "inherit" });
2568
- if (r.status !== 0 || ctx.values.status) process.exit(r.status ?? 1);
2802
+ const port = ["--port", String(cdpPort())];
2803
+ const bash = (extra) => spawnSync("bash", [
2804
+ script,
2805
+ ...port,
2806
+ ...extra
2807
+ ], { stdio: "inherit" });
2808
+ if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
2809
+ if (ctx.values.restart) {
2810
+ const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
2811
+ if (tabs !== null) consola$1.info(`Restarting Chrome on :${cdpPort()} — closing ${tabs} open tab(s).`);
2812
+ await closeBrowser().catch(() => {});
2813
+ const stop = bash([
2814
+ "--stop",
2815
+ "--profile",
2816
+ resolveProfile().dir
2817
+ ]);
2818
+ if (stop.status !== 0) process.exit(stop.status ?? 1);
2819
+ }
2820
+ const m = migrateProfile();
2821
+ if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
2822
+ else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
2823
+ else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
2824
+ const r = bash(["--profile", m.dir]);
2825
+ if (r.status !== 0) process.exit(r.status ?? 1);
2569
2826
  const health = await probeRenderer().catch((e) => ({
2570
2827
  ok: false,
2571
2828
  ms: 0,
@@ -2577,18 +2834,17 @@ const launchCommand = define({
2577
2834
  }));
2578
2835
  if (health.ok) {
2579
2836
  const woke = health.attempts.some((a) => a.woke);
2580
- consola.success(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms — this Chrome works.` + (woke ? " (It had to be activated to get there — this browser is slow to give background tabs a renderer.)" : ""));
2837
+ consola$1.success(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms — this Chrome works.` + (woke ? " (It had to be activated to get there — this browser is slow to give background tabs a renderer.)" : ""));
2581
2838
  return;
2582
2839
  }
2583
- consola.error(health.verdict === "wedged" ? "Chrome is up, but it can never make a renderer again — this browser is unusable.\n" : "Chrome is up, but a new tab did not get a working renderer in time.\n");
2584
- for (const line of explainRendererFailure(health).split("\n")) consola.log(line);
2585
- consola.log(`\nChrome's own log: ${chromeLogPath()}`);
2840
+ consola$1.error(health.verdict === "wedged" ? "Chrome is up, but it can never make a renderer again — this browser is unusable.\n" : "Chrome is up, but a new tab did not get a working renderer in time.\n");
2841
+ for (const line of explainRendererFailure(health).split("\n")) consola$1.log(line);
2842
+ consola$1.log(`\nChrome's own log: ${chromeLogPath()}`);
2586
2843
  process.exit(1);
2587
2844
  }
2588
2845
  });
2589
2846
  //#endregion
2590
2847
  //#region src/commands/doctor.ts
2591
- const PROFILE = process.env.BROWSER_AUTOMATION_PROFILE || `${homedir()}/Library/Application Support/Google/Chrome/browser-automation`;
2592
2848
  /**
2593
2849
  * Does a Chrome THIS user started serve our CDP port?
2594
2850
  *
@@ -2619,12 +2875,17 @@ const doctorCommand = define({
2619
2875
  description: "Diagnose the setup: Node, this user's Chrome, targets, sessions",
2620
2876
  args: {},
2621
2877
  async run() {
2622
- const ok = (m) => consola.log(` ✓ ${m}`);
2623
- const bad = (m) => consola.log(` ✗ ${m}`);
2878
+ const ok = (m) => consola$1.log(` ✓ ${m}`);
2879
+ const bad = (m) => consola$1.log(` ✗ ${m}`);
2624
2880
  if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
2625
2881
  else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
2626
- consola.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
2627
- consola.log(` • Profile: ${PROFILE}`);
2882
+ consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
2883
+ const profile = resolveProfile();
2884
+ consola$1.log(` • Profile: ${profile.dir}`);
2885
+ if (profile.source === "legacy") {
2886
+ consola$1.log(` ⚠ still inside Chrome's own folder, which an app-hosted session may be refused.`);
2887
+ consola$1.log(` Move it (logins included): browser-automation profile --migrate`);
2888
+ }
2628
2889
  let version;
2629
2890
  try {
2630
2891
  version = await (await fetch(`${cdpHost()}/json/version`)).json();
@@ -2643,7 +2904,7 @@ const doctorCommand = define({
2643
2904
  for (const t of targets) byType[t.type] = (byType[t.type] ?? 0) + 1;
2644
2905
  const summary = Object.entries(byType).map(([k, v]) => `${v} ${k}`).join(", ");
2645
2906
  ok(`${targets.length} targets (${summary})`);
2646
- consola.log(` (per-target CDP — target count never wedges this CLI)`);
2907
+ consola$1.log(` (per-target CDP — target count never wedges this CLI)`);
2647
2908
  } catch {
2648
2909
  bad("Could not enumerate targets");
2649
2910
  }
@@ -2660,23 +2921,23 @@ const doctorCommand = define({
2660
2921
  const woke = health.attempts.some((a) => a.woke);
2661
2922
  ok(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms`);
2662
2923
  if (woke) {
2663
- consola.log(` ⚠ it only answered after being activated — this Chrome is slow to give`);
2664
- consola.log(` BACKGROUND tabs a renderer (measured: median 367ms, tail past 30s).`);
2665
- consola.log(` Commands will work; new tabs may briefly raise the Chrome window.`);
2924
+ consola$1.log(` ⚠ it only answered after being activated — this Chrome is slow to give`);
2925
+ consola$1.log(` BACKGROUND tabs a renderer (measured: median 367ms, tail past 30s).`);
2926
+ consola$1.log(` Commands will work; new tabs may briefly raise the Chrome window.`);
2666
2927
  }
2667
2928
  const ev = gatherEvidence();
2668
2929
  if (ev.rendezvous === false) {
2669
- consola.log(` ⚠ but the Mach rendezvous service for pid ${ev.pid} is NOT registered —`);
2670
- consola.log(` new renderers are expected to start failing. Restart Chrome soon:`);
2671
- consola.log(` browser-automation launch --restart`);
2930
+ consola$1.log(` ⚠ but the Mach rendezvous service for pid ${ev.pid} is NOT registered —`);
2931
+ consola$1.log(` new renderers are expected to start failing. Restart Chrome soon:`);
2932
+ consola$1.log(` browser-automation launch --restart`);
2672
2933
  }
2673
2934
  } else {
2674
2935
  bad(`Renderer capacity: FAILED (${health.verdict})`);
2675
- for (const line of explainRendererFailure(health).split("\n")) consola.log(` ${line}`);
2676
- consola.log(` Chrome's own log: ${chromeLogPath()}`);
2936
+ for (const line of explainRendererFailure(health).split("\n")) consola$1.log(` ${line}`);
2937
+ consola$1.log(` Chrome's own log: ${chromeLogPath()}`);
2677
2938
  }
2678
2939
  const stats = recentProbeStats();
2679
- if (stats) consola.log(` • last ${stats.n} renderer probe(s): ${stats.failures} failed` + (stats.median >= 0 ? `, median ${stats.median}ms, slowest success ${stats.worst}ms` : ""));
2940
+ if (stats) consola$1.log(` • last ${stats.n} renderer probe(s): ${stats.failures} failed` + (stats.median >= 0 ? `, median ${stats.median}ms, slowest success ${stats.worst}ms` : ""));
2680
2941
  const sessions = listSessions();
2681
2942
  let live = 0;
2682
2943
  try {
@@ -2684,13 +2945,13 @@ const doctorCommand = define({
2684
2945
  live = sessions.filter((s) => liveIds.has(s.targetId)).length;
2685
2946
  } catch {}
2686
2947
  const stale = sessions.length - live;
2687
- consola.log(` • ${sessions.length} known session(s): ${live} live, ${stale} stale`);
2948
+ consola$1.log(` • ${sessions.length} known session(s): ${live} live, ${stale} stale`);
2688
2949
  if (sessions.length) {
2689
2950
  const names = sessions.map((s) => s.name);
2690
2951
  const shown = names.slice(0, 12).join(", ");
2691
- consola.log(` ${shown}${names.length > 12 ? `, … (+${names.length - 12} more — \`browser-automation list\`)` : ""}`);
2952
+ consola$1.log(` ${shown}${names.length > 12 ? `, … (+${names.length - 12} more — \`browser-automation list\`)` : ""}`);
2692
2953
  }
2693
- if (stale > 20) consola.log(` ${stale} stale bookmarks point at tabs that no longer exist — \`browser-automation gc --dry\` to review.`);
2954
+ if (stale > 20) consola$1.log(` ${stale} stale bookmarks point at tabs that no longer exist — \`browser-automation gc --dry\` to review.`);
2694
2955
  }
2695
2956
  });
2696
2957
  //#endregion
@@ -2748,10 +3009,10 @@ const gcCommand = define({
2748
3009
  const stale = sessions.filter((s) => !liveIds.has(s.targetId));
2749
3010
  for (const s of stale) {
2750
3011
  if (!dry) deleteSession(s.name);
2751
- consola.log(` session ${act} ${s.name} (tab gone: ${s.targetId.slice(0, 12)}…)`);
3012
+ consola$1.log(` session ${act} ${s.name} (tab gone: ${s.targetId.slice(0, 12)}…)`);
2752
3013
  }
2753
3014
  if (ctx.values.sessions) {
2754
- consola.success(`${stale.length} stale session bookmark(s) ${act}. No tabs touched.`);
3015
+ consola$1.success(`${stale.length} stale session bookmark(s) ${act}. No tabs touched.`);
2755
3016
  return;
2756
3017
  }
2757
3018
  const claimed = new Map(sessions.filter((s) => liveIds.has(s.targetId)).map((s) => [s.targetId, s.name]));
@@ -2763,17 +3024,17 @@ const gcCommand = define({
2763
3024
  for (const { t, dead: why } of dead) {
2764
3025
  const owner = claimed.get(t.id);
2765
3026
  if (!dry) await closeTab(t.id).catch(() => {});
2766
- consola.log(` dead tab ${actTab} ${t.id.slice(0, 12)}… ${owner ? `(${owner}) ` : ""}${(t.url ?? "").slice(0, 60) || "(no url)"} — ${why}`);
3027
+ consola$1.log(` dead tab ${actTab} ${t.id.slice(0, 12)}… ${owner ? `(${owner}) ` : ""}${(t.url ?? "").slice(0, 60) || "(no url)"} — ${why}`);
2767
3028
  }
2768
3029
  const orphans = probes.filter((p) => !p.dead && !claimed.has(p.t.id));
2769
3030
  if (ctx.values.orphans) for (const { t } of orphans) {
2770
3031
  if (!dry) await closeTab(t.id).catch(() => {});
2771
- consola.log(` orphan ${actTab} ${t.id.slice(0, 12)}… ${(t.title ?? "").slice(0, 28).padEnd(28)} ${(t.url ?? "").slice(0, 50)}`);
3032
+ consola$1.log(` orphan ${actTab} ${t.id.slice(0, 12)}… ${(t.title ?? "").slice(0, 28).padEnd(28)} ${(t.url ?? "").slice(0, 50)}`);
2772
3033
  }
2773
- consola.log("");
2774
- consola.success(`${stale.length} stale bookmark(s) and ${dead.length} dead tab(s) ${dry ? "would be removed" : "removed"}` + (ctx.values.orphans ? `, ${orphans.length} orphan tab(s) ${actTab}` : "") + ".");
2775
- if (!ctx.values.orphans && orphans.length) consola.log(` ${orphans.length} live tab(s) no session claims were left alone — \`gc --orphans --dry\` to review them.`);
2776
- if (dead.length && dead.length === pages.length && pages.length > 0) consola.warn("Every open tab was dead. That is the shape of a Chrome that can no longer launch renderers, which closing tabs does not fix — run `browser-automation doctor` for the diagnosis.");
3034
+ consola$1.log("");
3035
+ consola$1.success(`${stale.length} stale bookmark(s) and ${dead.length} dead tab(s) ${dry ? "would be removed" : "removed"}` + (ctx.values.orphans ? `, ${orphans.length} orphan tab(s) ${actTab}` : "") + ".");
3036
+ if (!ctx.values.orphans && orphans.length) consola$1.log(` ${orphans.length} live tab(s) no session claims were left alone — \`gc --orphans --dry\` to review them.`);
3037
+ if (dead.length && dead.length === pages.length && pages.length > 0) consola$1.warn("Every open tab was dead. That is the shape of a Chrome that can no longer launch renderers, which closing tabs does not fix — run `browser-automation doctor` for the diagnosis.");
2777
3038
  }
2778
3039
  });
2779
3040
  //#endregion
@@ -2787,6 +3048,40 @@ const portCommand = define({
2787
3048
  }
2788
3049
  });
2789
3050
  //#endregion
3051
+ //#region src/commands/profile.ts
3052
+ const profileCommand = define({
3053
+ name: "profile",
3054
+ description: "Print the Chrome profile directory this user's automation browser uses (one path, for scripts). --migrate moves a profile from the old location inside Chrome's own folder to ~/.browser-automation/chrome-profile, keeping every login.",
3055
+ args: { migrate: {
3056
+ type: "boolean",
3057
+ description: "Move the profile out of ~/Library/Application Support/Google/Chrome/ into ~/.browser-automation/chrome-profile. Refuses — and changes nothing — if a Chrome has it open or this process may not move it."
3058
+ } },
3059
+ async run(ctx) {
3060
+ if (!ctx.values.migrate) {
3061
+ process.stdout.write(`${resolveProfile().dir}\n`);
3062
+ return;
3063
+ }
3064
+ const m = migrateProfile();
3065
+ switch (m.outcome) {
3066
+ case "moved":
3067
+ consola$1.success(`Profile ${m.detail}. Logins travel with it.`);
3068
+ return;
3069
+ case "current":
3070
+ consola$1.info(`Profile already at ${m.dir}.`);
3071
+ return;
3072
+ case "fresh":
3073
+ consola$1.info(`No existing profile. Chrome will create ${m.dir} on first launch.`);
3074
+ return;
3075
+ case "explicit":
3076
+ consola$1.info(`BROWSER_AUTOMATION_PROFILE is set (${m.dir}); leaving it where you put it.`);
3077
+ return;
3078
+ default:
3079
+ consola$1.warn(`Profile not moved — ${m.detail}`);
3080
+ process.exitCode = 1;
3081
+ }
3082
+ }
3083
+ });
3084
+ //#endregion
2790
3085
  //#region src/commands/index.ts
2791
3086
  const defaultCommand = define({
2792
3087
  name: "browser-automation",
@@ -2804,6 +3099,7 @@ const subCommands = new Map([
2804
3099
  ["click", clickCommand],
2805
3100
  ["fill", fillCommand],
2806
3101
  ["read", readCommand],
3102
+ ["focus", focusCommand],
2807
3103
  ["eval", evalCommand],
2808
3104
  ["download", downloadCommand],
2809
3105
  ["setfiles", setfilesCommand],
@@ -2820,7 +3116,8 @@ const subCommands = new Map([
2820
3116
  ["doctor", doctorCommand],
2821
3117
  ["gc", gcCommand],
2822
3118
  ["prune", gcCommand],
2823
- ["port", portCommand]
3119
+ ["port", portCommand],
3120
+ ["profile", profileCommand]
2824
3121
  ]);
2825
3122
  function withRealPositionals(cmd, real) {
2826
3123
  return {