@rezkam/browser-tools 1.0.0 → 1.0.1

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/README.md CHANGED
@@ -69,7 +69,7 @@ import { connectBrowser, activePage, withBrowser } from '@rezkam/browser-tools';
69
69
 
70
70
  ## Behavior notes
71
71
 
72
- - Headless (`--headless`) runs full Chrome (`--headless=new`), not the legacy no-extensions engine, so profile, cookies, and extensions load the same as a windowed launch.
72
+ - Headless (`--headless`) runs full Chrome (`--headless=new`), not the legacy no-extensions engine, so profile, cookies, and extensions load the same as a windowed launch. On macOS it opts out of Dock recents, so background automation does not add another Chrome icon.
73
73
  - Profile Sync excludes the Google identity from a copied profile by default, so a clone cannot log your main Chrome out of Google; pass `--include-google` only for Google-backed workflows.
74
74
  - Every managed browser is owned by a token printed at `start`; `stop` refuses to kill a browser it does not own, another agent's browser, or your main Chrome.
75
75
  - GIF recording requires an explicit action-specific output name. `start` captures pre-action frames before returning, and `stop` captures post-action frames before finalizing the GIF.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rezkam/browser-tools",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Sandboxed, owner-token-protected Chrome automation for AI agents: control pages, record and review GIFs, capture HAR and raw CDP events, send CDP calls, and manage Chrome profiles.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -14,6 +14,7 @@ import {
14
14
  } from 'node:fs';
15
15
  import { homedir, tmpdir } from 'node:os';
16
16
  import { delimiter, dirname, join, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
17
18
  import puppeteer from 'puppeteer-core';
18
19
 
19
20
  export const DEFAULT_PORT = 9222;
@@ -951,7 +952,19 @@ export function headlessUserAgent(chromeBin = browserToolsChromeBin()) {
951
952
 
952
953
  export function managedBrowserForUserDataDir(userDataDir) {
953
954
  const result = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf-8' });
954
- if (result.error || result.status !== 0) return null;
955
+ if (result.error) {
956
+ const error = new Error(
957
+ `Cannot read the managed Chrome process inventory: ps failed to start (${result.error.code || 'unknown error'}). Refusing to treat a profile clone as unused.`,
958
+ );
959
+ error.cause = result.error;
960
+ throw error;
961
+ }
962
+ if (result.status !== 0) {
963
+ const outcome = result.signal ? `signal ${result.signal}` : `status ${result.status ?? 'unknown'}`;
964
+ throw new Error(
965
+ `Cannot read the managed Chrome process inventory: ps exited with ${outcome}. Refusing to treat a profile clone as unused.`,
966
+ );
967
+ }
955
968
 
956
969
  for (const line of result.stdout.split('\n')) {
957
970
  const trimmed = line.trim();
@@ -1438,6 +1451,42 @@ function assertChromeBinaryLaunchable(chromeBin) {
1438
1451
  throw new Error(`${problem}: ${chromeBin}. Set BROWSER_TOOLS_CHROME_BIN or browser.chromeBin in Browser Tools config.`);
1439
1452
  }
1440
1453
 
1454
+ function chromeAppBundleForExecutable(chromeBin) {
1455
+ const marker = '.app/Contents/MacOS/';
1456
+ const markerIndex = chromeBin.lastIndexOf(marker);
1457
+ if (markerIndex < 0) return null;
1458
+ return chromeBin.slice(0, markerIndex + '.app'.length);
1459
+ }
1460
+
1461
+ function launchHeadlessChromeApp({ chromeBin, args }) {
1462
+ if (process.platform !== 'darwin') return null;
1463
+ const appBundle = chromeAppBundleForExecutable(chromeBin);
1464
+ if (!appBundle) return null;
1465
+
1466
+ // The standard `open` command always makes a launched app eligible for Dock recents. Use the
1467
+ // native workspace option that opts out before Chrome registers, while retaining a new hidden
1468
+ // application instance for the isolated profile.
1469
+ const launcher = fileURLToPath(new URL('./mac-headless-launch.jxa', import.meta.url));
1470
+ const launched = spawnSync('osascript', ['-l', 'JavaScript', launcher, appBundle, ...args], {
1471
+ encoding: 'utf-8',
1472
+ });
1473
+ if (launched.error) {
1474
+ const error = new Error(`Chrome failed to launch through macOS NSWorkspace: ${launched.error.message}`);
1475
+ error.cause = launched.error;
1476
+ throw error;
1477
+ }
1478
+ if (launched.status !== 0) {
1479
+ const detail = launched.stderr.trim() || launched.stdout.trim() || `status ${launched.status}`;
1480
+ throw new Error(`Chrome failed to launch through macOS NSWorkspace: ${detail}`);
1481
+ }
1482
+
1483
+ const pid = Number.parseInt(launched.stdout.trim(), 10);
1484
+ if (!Number.isInteger(pid) || pid < 1) {
1485
+ throw new Error('Chrome launched through macOS NSWorkspace, but no process PID was returned');
1486
+ }
1487
+ return { pid };
1488
+ }
1489
+
1441
1490
  export function launchChrome({ port = DEFAULT_PORT, profileName = null, userDataDir = null, ownerToken = null, ownerId = null, headless = false, includeGoogle = false } = {}) {
1442
1491
  ensureCacheDir();
1443
1492
  const normalizedPort = normalizePort(port);
@@ -1450,15 +1499,19 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1450
1499
  assertChromeBinaryLaunchable(chromeBin);
1451
1500
  const pidFile = pidFileForPort(normalizedPort);
1452
1501
  const stateFile = stateFileForPort(normalizedPort);
1453
- const proc = spawn(chromeBin, args, {
1454
- detached: true,
1455
- stdio: 'ignore',
1456
- });
1457
- proc.once('error', (error) => {
1458
- rmSync(pidFile, { force: true });
1459
- rmSync(stateFile, { force: true });
1460
- console.error(`[browser-control] Chrome spawn failed: ${error.message}`);
1461
- });
1502
+ let proc = headless ? launchHeadlessChromeApp({ chromeBin, args }) : null;
1503
+ if (!proc) {
1504
+ proc = spawn(chromeBin, args, {
1505
+ detached: true,
1506
+ stdio: 'ignore',
1507
+ });
1508
+ proc.once('error', (error) => {
1509
+ rmSync(pidFile, { force: true });
1510
+ rmSync(stateFile, { force: true });
1511
+ console.error(`[browser-control] Chrome spawn failed: ${error.message}`);
1512
+ });
1513
+ proc.unref();
1514
+ }
1462
1515
  if (!Number.isInteger(proc.pid)) {
1463
1516
  throw new Error(`Chrome failed to start: no child process PID for ${chromeBin}`);
1464
1517
  }
@@ -1478,7 +1531,6 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1478
1531
  args,
1479
1532
  startedAt: new Date().toISOString(),
1480
1533
  }, null, 2));
1481
- proc.unref();
1482
1534
  return proc;
1483
1535
  }
1484
1536
 
@@ -1885,8 +1937,10 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1885
1937
  const killSafety = verifyManagedChromeProcess({ pid, port: normalizedPort, state });
1886
1938
  if (killSafety.ok) {
1887
1939
  process.kill(pid, 'SIGKILL');
1888
- waitForProcessExit(pid, 1000);
1889
- status = 'killed';
1940
+ status = forcedKillStatus(waitForProcessExit(pid, 1000));
1941
+ if (status === 'failed') {
1942
+ error = new Error('Managed Chrome remained alive after SIGKILL');
1943
+ }
1890
1944
  } else {
1891
1945
  status = 'failed';
1892
1946
  error = new Error(`Refusing SIGKILL after failed safety recheck: ${killSafety.reason}`);
@@ -1900,6 +1954,13 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1900
1954
  }
1901
1955
  }
1902
1956
 
1957
+ // A failed stop means the browser may still own its process and clone. Keep every lifecycle handle
1958
+ // so the owner can retry and the process inventory can still classify it. Removing them here turns
1959
+ // a shutdown failure into the same invisible orphan this cleanup path exists to prevent.
1960
+ if (status === 'failed') {
1961
+ return { status, port: normalizedPort, pid, cleaned: false, error, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1962
+ }
1963
+
1903
1964
  rmSync(paths.pidFile, { force: true });
1904
1965
  rmSync(paths.stateFile, { force: true });
1905
1966
  let cleaned = false;
@@ -2010,10 +2071,19 @@ function processStartIdentity(pid) {
2010
2071
  return createHash('sha256').update(identity, 'utf8').digest('hex');
2011
2072
  }
2012
2073
 
2074
+ function processIsZombie(pid) {
2075
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'state='], { encoding: 'utf-8' });
2076
+ if (result.error || result.status !== 0) return false;
2077
+ return result.stdout.trim().startsWith('Z');
2078
+ }
2079
+
2013
2080
  function processExists(pid) {
2014
2081
  try {
2015
2082
  process.kill(pid, 0);
2016
- return true;
2083
+ // A directly spawned child stays in the process table as a zombie until Node's event loop can
2084
+ // reap it. Signals cannot affect it, so treating it as alive causes synchronous shutdown to
2085
+ // report failure and retain lifecycle data for a browser that has already exited.
2086
+ return !processIsZombie(pid);
2017
2087
  } catch (e) {
2018
2088
  return e.code !== 'ESRCH';
2019
2089
  }
@@ -0,0 +1,27 @@
1
+ ObjC.import('AppKit');
2
+
3
+ function run(argv) {
4
+ const applicationURL = $.NSURL.fileURLWithPath($(argv[0]));
5
+ const options = Number($.NSWorkspaceLaunchWithoutAddingToRecents)
6
+ | Number($.NSWorkspaceLaunchWithoutActivation)
7
+ | Number($.NSWorkspaceLaunchNewInstance)
8
+ | Number($.NSWorkspaceLaunchAndHide);
9
+ const configuration = $.NSMutableDictionary.dictionary;
10
+ configuration.setObjectForKey($(argv.slice(1)), $.NSWorkspaceLaunchConfigurationArguments);
11
+ configuration.setObjectForKey(
12
+ $.NSProcessInfo.processInfo.environment,
13
+ $.NSWorkspaceLaunchConfigurationEnvironment,
14
+ );
15
+ const error = Ref();
16
+ const launched = $.NSWorkspace.sharedWorkspace.launchApplicationAtURLOptionsConfigurationError(
17
+ applicationURL,
18
+ options,
19
+ configuration,
20
+ error,
21
+ );
22
+ if (!launched || launched.isNil()) {
23
+ const detail = error[0] ? error[0].localizedDescription.js : 'unknown error';
24
+ throw new Error(`NSWorkspace launch failed: ${detail}`);
25
+ }
26
+ return Number(launched.processIdentifier);
27
+ }
package/scripts/stop.mjs CHANGED
@@ -121,6 +121,7 @@ if (result.status === 'would-stop') {
121
121
  process.exit(1);
122
122
  } else {
123
123
  console.error(`✗ Failed to stop Chrome: ${result.error?.message || 'unknown error'}`);
124
+ process.exit(1);
124
125
  }
125
126
 
126
127
  if (result.cleaned) console.log('✓ Cleaned up cached profile copy');