@generativereality/browser-automation 0.4.17 → 0.4.18

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "browser-automation",
3
3
  "description": "Daemonless, per-tab-isolated browser automation for Claude Code via the `browser-automation` CLI. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.",
4
- "version": "0.4.17",
4
+ "version": "0.4.18",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
package/README.md CHANGED
@@ -170,7 +170,8 @@ same one-action-per-snapshot rule as Playwright refs.
170
170
  button inside the zone works even when the zone div itself isn't
171
171
  snapshot-interactive. After dropping, confirm with `read`/`screenshot` and pull
172
172
  the result (often a `download --url` endpoint).
173
- - `launch` resolves Chrome on macOS/Linux; elsewhere start Chrome manually with
173
+ - `launch` works on macOS, Linux and Windows (on Windows it needs only Node; set
174
+ `BROWSER_AUTOMATION_CHROME` if `chrome.exe` is somewhere unusual). Anywhere else, start Chrome with
174
175
  `--remote-debugging-port=<your port> --user-data-dir="<profile>"` — `browser-automation doctor` prints the port.
175
176
 
176
177
  ## Environment
package/dist/index.js CHANGED
@@ -2,14 +2,14 @@
2
2
  import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
4
4
  import consola, { consola as consola$1 } from "consola";
5
- import { homedir } from "node:os";
5
+ import { homedir, tmpdir } from "node:os";
6
6
  import { basename, dirname, extname, join, resolve } from "node:path";
7
- import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
- import { execFileSync, spawnSync } from "node:child_process";
7
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { execFileSync, spawn, 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.17";
12
+ var version = "0.4.18";
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,
@@ -957,7 +957,7 @@ function gatherEvidence() {
957
957
  }
958
958
  /** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
959
959
  function chromeLogPath() {
960
- const tmp = process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
960
+ const tmp = process.platform === "win32" ? tmpdir() : process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
961
961
  return process.env.BROWSER_AUTOMATION_LOG || `${tmp}/chrome-${targetPort()}.log`;
962
962
  }
963
963
  function probeLogPath() {
@@ -1689,7 +1689,7 @@ const snapshotCommand = define({
1689
1689
  });
1690
1690
  //#endregion
1691
1691
  //#region src/commands/click.ts
1692
- const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
1692
+ const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
1693
1693
  const clickCommand = define({
1694
1694
  name: "click",
1695
1695
  description: "Click an element by ref (from the latest snapshot)",
@@ -1730,7 +1730,7 @@ const clickCommand = define({
1730
1730
  while (Date.now() < focusDeadline) {
1731
1731
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
1732
1732
  if (f && f.f && f.v === "visible") break;
1733
- await sleep$2(50);
1733
+ await sleep$3(50);
1734
1734
  }
1735
1735
  let prev = null;
1736
1736
  let point = null;
@@ -1756,7 +1756,7 @@ const clickCommand = define({
1756
1756
  x: a.x,
1757
1757
  y: a.y
1758
1758
  };
1759
- await sleep$2(60);
1759
+ await sleep$3(60);
1760
1760
  }
1761
1761
  if (!point) {
1762
1762
  consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
@@ -1771,7 +1771,7 @@ const clickCommand = define({
1771
1771
  buttons: 0,
1772
1772
  pointerType: "mouse"
1773
1773
  });
1774
- await sleep$2(20);
1774
+ await sleep$3(20);
1775
1775
  await s.send("Input.dispatchMouseEvent", {
1776
1776
  type: "mousePressed",
1777
1777
  x,
@@ -1905,7 +1905,7 @@ const readCommand = define({
1905
1905
  });
1906
1906
  //#endregion
1907
1907
  //#region src/commands/focus.ts
1908
- const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
1908
+ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
1909
1909
  /**
1910
1910
  * Make a tab believe it is the visible one.
1911
1911
  *
@@ -1974,7 +1974,7 @@ const focusCommand = define({
1974
1974
  returnByValue: true
1975
1975
  })).result?.value ?? last;
1976
1976
  if (last.focused && last.visibility === "visible") break;
1977
- await sleep$1(50);
1977
+ await sleep$2(50);
1978
1978
  }
1979
1979
  return last;
1980
1980
  });
@@ -2340,7 +2340,7 @@ const uploadCommand = define({
2340
2340
  });
2341
2341
  //#endregion
2342
2342
  //#region src/commands/drop.ts
2343
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2343
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
2344
2344
  /** Resolve each path to absolute and verify it's an existing file. */
2345
2345
  function absFiles(paths) {
2346
2346
  return paths.map((p) => {
@@ -2442,7 +2442,7 @@ const dropCommand = define({
2442
2442
  while (Date.now() < focusDeadline) {
2443
2443
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
2444
2444
  if (f && f.f && f.v === "visible") break;
2445
- await sleep(50);
2445
+ await sleep$1(50);
2446
2446
  }
2447
2447
  let prev = null;
2448
2448
  let point = null;
@@ -2468,7 +2468,7 @@ const dropCommand = define({
2468
2468
  x: a.x,
2469
2469
  y: a.y
2470
2470
  };
2471
- await sleep(60);
2471
+ await sleep$1(60);
2472
2472
  }
2473
2473
  if (!point) {
2474
2474
  consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
@@ -2492,7 +2492,7 @@ const dropCommand = define({
2492
2492
  y,
2493
2493
  data
2494
2494
  });
2495
- await sleep(20);
2495
+ await sleep$1(20);
2496
2496
  await s.send("Input.dispatchDragEvent", {
2497
2497
  type: "drop",
2498
2498
  x,
@@ -2931,6 +2931,140 @@ function migrateProfile() {
2931
2931
  };
2932
2932
  }
2933
2933
  //#endregion
2934
+ //#region src/core/launch-windows.ts
2935
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2936
+ /** chrome.exe: an explicit override, then the per-machine and per-user installs. */
2937
+ function windowsChromeExe() {
2938
+ const explicit = process.env.BROWSER_AUTOMATION_CHROME || process.env.CHROME;
2939
+ if (explicit) return existsSync(explicit) ? explicit : null;
2940
+ return [
2941
+ process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
2942
+ process.env["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
2943
+ process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe")
2944
+ ].filter(Boolean).find((p) => existsSync(p)) ?? null;
2945
+ }
2946
+ /** Is anything answering CDP on this port? (The script's `is_up`.) */
2947
+ async function cdpUp(port) {
2948
+ try {
2949
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2e3) })).ok;
2950
+ } catch {
2951
+ return false;
2952
+ }
2953
+ }
2954
+ /**
2955
+ * pid of OUR automation Chrome's browser process on this port, or 0.
2956
+ *
2957
+ * PowerShell for the command lines: Node cannot read another process's command
2958
+ * line on Windows, and `wmic` is gone from Windows 11 25H2.
2959
+ */
2960
+ function ourChromePid(port) {
2961
+ const script = [
2962
+ "$ProgressPreference = 'SilentlyContinue'",
2963
+ `$re = '--remote-debugging-port=${port}(\\s|"|$)'`,
2964
+ "$sid = [System.Diagnostics.Process]::GetCurrentProcess().SessionId",
2965
+ "$b = Get-CimInstance Win32_Process -Filter \"Name = 'chrome.exe'\" |",
2966
+ " Where-Object { $_.SessionId -eq $sid -and $_.CommandLine -and $_.CommandLine -match $re -and $_.CommandLine -notmatch '--type=' } |",
2967
+ " Select-Object -First 1 -ExpandProperty ProcessId",
2968
+ "Write-Output ('BA-PID ' + [int]$b)"
2969
+ ].join("\n");
2970
+ try {
2971
+ const out = execFileSync("powershell.exe", [
2972
+ "-NoProfile",
2973
+ "-NonInteractive",
2974
+ "-ExecutionPolicy",
2975
+ "Bypass",
2976
+ "-EncodedCommand",
2977
+ Buffer.from(script, "utf16le").toString("base64")
2978
+ ], {
2979
+ encoding: "utf8",
2980
+ stdio: [
2981
+ "ignore",
2982
+ "pipe",
2983
+ "ignore"
2984
+ ],
2985
+ timeout: 2e4,
2986
+ windowsHide: true
2987
+ });
2988
+ return Number(/^BA-PID (\d+)\s*$/m.exec(out)?.[1] ?? 0);
2989
+ } catch {
2990
+ return 0;
2991
+ }
2992
+ }
2993
+ function alive(pid) {
2994
+ try {
2995
+ process.kill(pid, 0);
2996
+ return true;
2997
+ } catch {
2998
+ return false;
2999
+ }
3000
+ }
3001
+ /**
3002
+ * Quit OUR Chrome on this port and wait until it has really exited.
3003
+ *
3004
+ * CDP Browser.close first — Chrome's own quit, which flushes the profile that
3005
+ * holds the logins. On Windows the process does exit after it (unlike macOS,
3006
+ * where it lingers windowless). taskkill /F only if it will not go.
3007
+ */
3008
+ async function stopOurChrome(port, say) {
3009
+ const pid = ourChromePid(port);
3010
+ if (!pid) return await cdpUp(port) ? "not-ours" : "none";
3011
+ await closeBrowser().catch(() => {});
3012
+ for (let i = 0; i < 40 && alive(pid); i++) await sleep(250);
3013
+ if (alive(pid)) {
3014
+ say(`Chrome (pid ${pid}) did not exit within 10s of being asked to quit; ending it.`);
3015
+ try {
3016
+ execFileSync("taskkill", [
3017
+ "/PID",
3018
+ String(pid),
3019
+ "/T",
3020
+ "/F"
3021
+ ], { stdio: "ignore" });
3022
+ } catch {}
3023
+ for (let i = 0; i < 20 && alive(pid); i++) await sleep(250);
3024
+ }
3025
+ if (alive(pid)) throw new Error(`Chrome on :${port} (pid ${pid}) would not exit. Not relaunching on top of it.`);
3026
+ for (let i = 0; i < 20 && await cdpUp(port); i++) await sleep(250);
3027
+ return "stopped";
3028
+ }
3029
+ /** Start the automation Chrome unless ours is already serving the port. */
3030
+ async function startChrome(port, profile, log) {
3031
+ if (await cdpUp(port)) return ourChromePid(port) ? { outcome: "already-running" } : { outcome: "not-ours" };
3032
+ const exe = windowsChromeExe();
3033
+ if (!exe) return { outcome: "no-chrome" };
3034
+ mkdirSync(profile, { recursive: true });
3035
+ mkdirSync(dirname(log), { recursive: true });
3036
+ try {
3037
+ if (statSync(log).size > 0) renameSync(log, `${log}.prev`);
3038
+ } catch {}
3039
+ const fd = openSync(log, "a");
3040
+ spawn(exe, [
3041
+ `--remote-debugging-port=${port}`,
3042
+ `--user-data-dir=${profile}`,
3043
+ "--no-first-run",
3044
+ "--no-default-browser-check",
3045
+ "about:blank"
3046
+ ], {
3047
+ detached: true,
3048
+ stdio: [
3049
+ "ignore",
3050
+ fd,
3051
+ fd
3052
+ ]
3053
+ }).unref();
3054
+ const started = Date.now();
3055
+ for (let i = 0; i < 240; i++) {
3056
+ if (await cdpUp(port)) return {
3057
+ outcome: "launched",
3058
+ seconds: Math.round((Date.now() - started) / 1e3)
3059
+ };
3060
+ await sleep(250);
3061
+ }
3062
+ return {
3063
+ outcome: "timeout",
3064
+ log
3065
+ };
3066
+ }
3067
+ //#endregion
2934
3068
  //#region src/commands/launch.ts
2935
3069
  const launchCommand = define({
2936
3070
  name: "launch",
@@ -2946,35 +3080,40 @@ const launchCommand = define({
2946
3080
  }
2947
3081
  },
2948
3082
  async run(ctx) {
2949
- const script = launchScriptPath();
2950
- if (!existsSync(script)) {
2951
- consola$1.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2952
- process.exit(1);
2953
- }
2954
- const port = ["--port", String(cdpPort())];
2955
- const bash = (extra) => spawnSync("bash", [
2956
- script,
2957
- ...port,
2958
- ...extra
2959
- ], { stdio: "inherit" });
2960
- if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
2961
- if (ctx.values.restart) {
2962
- const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
2963
- if (tabs !== null) consola$1.info(`Restarting Chrome on :${cdpPort()} — closing ${tabs} open tab(s).`);
2964
- await closeBrowser().catch(() => {});
2965
- const stop = bash([
2966
- "--stop",
2967
- "--profile",
2968
- resolveProfile().dir
2969
- ]);
2970
- if (stop.status !== 0) process.exit(stop.status ?? 1);
3083
+ if (process.platform === "win32") {
3084
+ if (!await launchWindows(ctx.values.status === true, ctx.values.restart === true)) process.exit(1);
3085
+ if (ctx.values.status) return;
3086
+ } else {
3087
+ const script = launchScriptPath();
3088
+ if (!existsSync(script)) {
3089
+ consola$1.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
3090
+ process.exit(1);
3091
+ }
3092
+ const port = ["--port", String(cdpPort())];
3093
+ const bash = (extra) => spawnSync("bash", [
3094
+ script,
3095
+ ...port,
3096
+ ...extra
3097
+ ], { stdio: "inherit" });
3098
+ if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
3099
+ if (ctx.values.restart) {
3100
+ const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
3101
+ if (tabs !== null) consola$1.info(`Restarting Chrome on :${cdpPort()} — closing ${tabs} open tab(s).`);
3102
+ await closeBrowser().catch(() => {});
3103
+ const stop = bash([
3104
+ "--stop",
3105
+ "--profile",
3106
+ resolveProfile().dir
3107
+ ]);
3108
+ if (stop.status !== 0) process.exit(stop.status ?? 1);
3109
+ }
3110
+ const m = migrateProfile();
3111
+ if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
3112
+ else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
3113
+ else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
3114
+ const r = bash(["--profile", m.dir]);
3115
+ if (r.status !== 0) process.exit(r.status ?? 1);
2971
3116
  }
2972
- const m = migrateProfile();
2973
- if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
2974
- else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
2975
- else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
2976
- const r = bash(["--profile", m.dir]);
2977
- if (r.status !== 0) process.exit(r.status ?? 1);
2978
3117
  const health = await probeRenderer().catch((e) => ({
2979
3118
  ok: false,
2980
3119
  ms: 0,
@@ -2995,6 +3134,56 @@ const launchCommand = define({
2995
3134
  process.exit(1);
2996
3135
  }
2997
3136
  });
3137
+ /**
3138
+ * Windows: the launch script's contract in TypeScript. Prints the same lines
3139
+ * the script prints, so an agent reading either learns the same thing.
3140
+ * Returns false on a failure that must stop `launch` before the health check.
3141
+ */
3142
+ async function launchWindows(statusOnly, restart) {
3143
+ const port = cdpPort();
3144
+ if (statusOnly) {
3145
+ const up = await cdpUp(port);
3146
+ consola$1.log(up ? `Chrome CDP on :${port} is up` : `Chrome CDP on :${port} is NOT running`);
3147
+ return up;
3148
+ }
3149
+ if (restart) {
3150
+ const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
3151
+ if (tabs !== null) consola$1.info(`Restarting Chrome on :${port} — closing ${tabs} open tab(s).`);
3152
+ try {
3153
+ if (await stopOurChrome(port, (s) => consola$1.warn(s)) === "not-ours") {
3154
+ consola$1.error(`Refusing to restart a Chrome this account did not start (something else serves :${port}).`);
3155
+ return false;
3156
+ }
3157
+ } catch (e) {
3158
+ consola$1.error(String(e?.message ?? e));
3159
+ return false;
3160
+ }
3161
+ }
3162
+ const m = migrateProfile();
3163
+ if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
3164
+ else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
3165
+ const r = await startChrome(port, m.dir, chromeLogPath());
3166
+ switch (r.outcome) {
3167
+ case "already-running":
3168
+ consola$1.log(`Already running on :${port} — the port is held.`);
3169
+ consola$1.log("Drive it with: browser-automation goto -s <session> <url>");
3170
+ consola$1.log("(Port held is not health. Check it works: browser-automation doctor)");
3171
+ return true;
3172
+ case "launched":
3173
+ consola$1.log(`Chrome launched on :${port} in ${r.seconds}s (profile: ${m.dir}, log: ${chromeLogPath()})`);
3174
+ consola$1.log("Drive it with: browser-automation goto -s <session> <url>");
3175
+ return true;
3176
+ case "not-ours":
3177
+ consola$1.error(`Something on this computer is already serving CDP on port ${port}, and it is not a Chrome this account started. Driving it would act in ANOTHER user's browser — quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port for this one.`);
3178
+ return false;
3179
+ case "no-chrome":
3180
+ consola$1.error("Chrome not found (looked in Program Files, Program Files (x86) and %LOCALAPPDATA%). Install it — winget install --id Google.Chrome -e — or set BROWSER_AUTOMATION_CHROME to chrome.exe.");
3181
+ return false;
3182
+ case "timeout":
3183
+ consola$1.error(`Chrome did not serve CDP on :${port} within 60s. Chrome's log: ${r.log}`);
3184
+ return false;
3185
+ }
3186
+ }
2998
3187
  //#endregion
2999
3188
  //#region src/commands/doctor.ts
3000
3189
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@generativereality/browser-automation",
3
- "version": "0.4.17",
3
+ "version": "0.4.18",
4
4
  "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.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -286,9 +286,15 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
286
286
  - **Page still loading.** `goto` waits for the load event, but SPAs render after.
287
287
  If a `read`/`snapshot` looks empty, re-run after a moment, or snapshot again
288
288
  once a known element should be present.
289
- - **`launch` is macOS/Linux only** (resolves the Chrome binary per-OS). On other
290
- setups, start Chrome manually with `--remote-debugging-port=<doctor's port>
291
- --user-data-dir="<profile>"`.
289
+ - **`launch` works on macOS, Linux and Windows.** On Windows it needs only Node
290
+ (no Git Bash): it finds `chrome.exe` in Program Files or `%LOCALAPPDATA%`
291
+ (override with `BROWSER_AUTOMATION_CHROME`), uses the same profile
292
+ (`%USERPROFILE%\.browser-automation\chrome-profile`) and the same rules —
293
+ idempotent, refuses a port held by a Chrome this account did not start, and
294
+ `--restart` quits Chrome cleanly so the logins survive. ⛔ So do not start
295
+ Chrome by hand on Windows any more; that was the workaround for CLIs older than
296
+ 0.4.18, which refused with `unsupported OS MINGW64_NT`. A cold start brings
297
+ Chrome to the front once, on every platform.
292
298
 
293
299
  ## Network insights — find the API behind a page
294
300