@rezkam/browser-tools 1.0.3 → 1.0.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
+ ## 1.0.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 2ef608b: Automatically reclaim managed Chrome sessions that have run for two hours after their recorded launcher exits. Record immutable launcher process identity to detect PID reuse, keep live launchers protected regardless of age, and run the fail-safe reap before enforcing the browser limit.
8
+ - e453b80: Skip local ports occupied by non-CDP processes during automatic managed Chrome allocation, and verify that the process responding after launch is the managed Chrome that was started.
9
+
3
10
  ## 1.0.3
4
11
 
5
12
  ### Patch Changes
package/README.md CHANGED
@@ -1,96 +1,105 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
- Sandboxed, owner-token-protected Chrome automation for AI agents: launch a managed Chrome with a copied profile, navigate, evaluate page JavaScript, screenshot, and stop it safely, all without touching your main Chrome.
3
+ Managed Chrome automation with isolated profiles and owner-protected sessions. Browser Tools can drive pages, inspect the DOM, capture visual and network evidence, and extract page content without connecting to or stopping your main Chrome.
4
4
 
5
- This repository is the source of both the `browser-tools` skill and the `@rezkam/browser-tools` package. The skill drives this package's CLI, so there is one supported way to run Browser Tools whether you got here through the skill or through npm directly.
5
+ This repository provides both the `browser-tools` skill and the `@rezkam/browser-tools` npm package. The skill uses the same CLI that the package installs.
6
6
 
7
- ## Install
7
+ ## Features
8
+
9
+ - **Isolated browser sessions:** launch windowed or headless Chrome with a fresh profile or a copied Chrome profile, including existing site sessions and extensions.
10
+ - **Safe lifecycle management:** every managed browser has an owner token. Browser Tools verifies process identity before connecting or stopping, limits concurrent browsers, and automatically reclaims old sessions after their recorded launcher exits.
11
+ - **Page control and inspection:** navigate tabs, evaluate asynchronous JavaScript, take viewport or full-page screenshots, and interactively pick single or multiple DOM elements.
12
+ - **Page extraction:** collect article-like links and nearby timestamps, or extract readable article text from the active tab.
13
+ - **Visual evidence:** record an active-tab interaction as a GIF, then generate a sampled contact sheet and JSON metadata for review.
14
+ - **Network and protocol tooling:** capture filtered HAR 1.2 traffic, extract a chronological request recipe, record selected raw CDP events, and send guarded CDP calls to the active tab.
15
+ - **Local profile configuration:** discover Chrome profiles, create private aliases, and associate one or more profiles with a task.
8
16
 
9
- Two independent installs, pick what you need:
17
+ ## Install
10
18
 
11
- **The skill** (for an agent that should discover and use Browser Tools as a skill):
19
+ Install the skill when Browser Tools should be discoverable as an automation skill:
12
20
 
13
21
  ```bash
14
22
  npx skills add rezkam/browser-tools
15
23
  ```
16
24
 
17
- **The package/CLI** (what the skill depends on, and what any project can depend on directly):
25
+ Install the package for the global CLI and programmatic exports:
18
26
 
19
27
  ```bash
20
28
  npm install -g @rezkam/browser-tools
21
29
  ```
22
30
 
23
- This installs a global `browser-tools` command (via the package's `bin` entry) and, for programmatic use, exports the browser control module. If you would rather not install it globally, run any command through `npx @rezkam/browser-tools <subcommand>` instead.
31
+ Commands can also run without a global install:
32
+
33
+ ```bash
34
+ npx @rezkam/browser-tools <command>
35
+ ```
24
36
 
25
- GIF recording and review also require ffmpeg and its ffprobe tool:
37
+ Browser Tools requires macOS, Google Chrome, and Node.js 20 or newer. GIF recording and review additionally require `ffmpeg` and `ffprobe`:
26
38
 
27
39
  ```bash
28
40
  brew install ffmpeg
29
41
  ```
30
42
 
31
- ## CLI
32
-
33
- Each subcommand dispatches to the matching script unchanged; flags are the same as the underlying script.
43
+ ## Quick start
34
44
 
35
45
  ```bash
36
- browser-tools start --task <task> --headless # launch, prints an owner token on first start
46
+ browser-tools start --headless
37
47
  export BROWSER_TOOLS_OWNER_TOKEN="<owner token from start output>"
38
- browser-tools status --port <reported port> # report whether it's running
48
+
39
49
  browser-tools nav https://example.com --port <reported port>
40
50
  browser-tools eval 'document.title' --port <reported port>
41
51
  browser-tools screenshot --full --port <reported port>
42
- browser-tools record-gif start --output "$PWD/login_process.gif" --port <reported port>
43
- # Perform the multi-step interaction.
44
- browser-tools record-gif stop --port <reported port>
45
- browser-tools review-gif "$PWD/login_process.gif"
46
- browser-tools record-har start --output "$PWD/checkout_api_network.har" --preset api --port <reported port>
47
- # Perform the browser interaction, then stop and extract a non-executable recipe.
48
- browser-tools record-har stop --port <reported port>
49
- browser-tools extract-har "$PWD/checkout_api_network.har"
50
- browser-tools record-cdp start --output "$PWD/checkout_network_events.jsonl" --domain Network --event 'Network.*' --port <reported port>
51
- browser-tools record-cdp stop --port <reported port>
52
- browser-tools cdp call Runtime.evaluate --params '{"expression":"document.title"}' --port <reported port>
53
- browser-tools pick "Click the price" --port <reported port>
54
- browser-tools scrape-page --port <reported port>
55
- browser-tools extract-article --chars 6000 --port <reported port>
52
+
56
53
  browser-tools stop --clean --port <reported port>
57
- browser-tools config task-profile set <task> --profile "<alias>"
58
54
  ```
59
55
 
60
- Run `browser-tools --help` for the full command list.
56
+ Use `--profile "<profile or alias>"` when an existing login is needed, `--sync` to refresh the copied profile, or `--task <task>` to use configured task profiles.
61
57
 
62
- ## Programmatic use
58
+ ## CLI capabilities
63
59
 
64
- ```js
65
- import { connectBrowser, activePage, withBrowser } from '@rezkam/browser-tools';
66
- ```
60
+ | Area | Commands | What they do |
61
+ | --- | --- | --- |
62
+ | Browser lifecycle | `start`, `status`, `stop` | Launch, inspect, stop, clean, reap, and prune managed Chrome sessions |
63
+ | Profile configuration | `config` | Discover profiles, list active profiles, and manage task-to-profile mappings |
64
+ | Page control | `nav`, `eval`, `screenshot` | Navigate the active tab or a new background tab, run page JavaScript, and capture PNG screenshots |
65
+ | DOM inspection | `pick` | Select one or more visible elements and return tag, id, class, text, HTML, and parent information |
66
+ | Page extraction | `scrape-page`, `extract-article` | Extract article-like links with timestamps or readable article text from the active tab |
67
+ | Visual recording | `record-gif`, `review-gif` | Record an interaction with pre-roll and post-roll frames, then create a contact sheet and metadata report |
68
+ | HTTP capture | `record-har`, `extract-har` | Capture filtered active-tab traffic and derive a compact, non-executable request recipe |
69
+ | Chrome DevTools Protocol | `record-cdp`, `cdp` | Record selected raw protocol events or send one guarded direct method call |
67
70
 
68
- `@rezkam/browser-tools` and `@rezkam/browser-tools/browser-control.mjs` both resolve to the browser control module (launch, stop, profile sync, owner-token safety, CDP connect). `@rezkam/browser-tools/resource-helper.mjs` resolves to the shared generic-extractor lifecycle helper.
71
+ Run `browser-tools --help` for the command list. Commands with detailed option references, such as `record-har`, `record-cdp`, and `review-gif`, also support command-level `--help`.
69
72
 
70
- ## Behavior notes
73
+ ## Safety model
71
74
 
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
- - 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
- - 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
- - 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.
76
- - `review-gif` probes frame count, duration, frame rate, and dimensions, then creates a sampled contact sheet and JSON report under the GIF's owner-only `.gif-review/` directory.
77
- - `record-har` captures owner-protected filtered active-tab HTTP traffic as private HAR 1.2. `extract-har` derives a compact chronological recipe without executing requests. WebSocket handshakes and frames require `record-cdp`.
78
- - `record-cdp` writes selected raw protocol events as private JSONL. `cdp call` sends one owner-protected active-tab method while blocking known managed-lifecycle bypasses.
79
- - HAR, recipes, raw CDP events, and direct results preserve exact debugging evidence by default. Add `--redact` to filter sensitive-looking values. Capture files are owner-only `0600`, not encrypted.
80
- - Config, cache, and artifact directories default to `~/.agents/browser-tools/config.json`, `~/.cache/pi-browser-tools`, and `/tmp`, overridable via `BROWSER_TOOLS_CONFIG_DIR`, `BROWSER_TOOLS_CACHE_DIR`, `BROWSER_TOOLS_ARTIFACT_DIR`, `BROWSER_TOOLS_CHROME_SOURCE_DIR`, and `BROWSER_TOOLS_CHROME_BIN`.
81
- - Requires macOS Chrome and Node.js 20+. GIF recording and review require ffmpeg and ffprobe.
75
+ - Managed Chrome always uses a separate user data directory. Copied profiles are snapshots and never run against the live Chrome profile.
76
+ - Commands that connect to Chrome or stop an owned browser require the owner token printed by `start`. The token protects browser control, recordings, network capture, CDP access, and shutdown.
77
+ - Google identity data is removed from copied profiles by default to protect the source session. `--include-google` is an explicit opt-in for Google-backed workflows.
78
+ - Starting without an explicit port can reuse a browser already owned by the caller or allocate another available port. The default concurrent browser limit is five.
79
+ - A managed browser older than two hours becomes reclaimable after its recorded launcher exits. The next start reaps it before enforcing the concurrency limit, while browsers with live launchers remain protected regardless of age.
80
+ - HAR files, extracted recipes, raw CDP events, and GIF review artifacts are written as private local files. Network and protocol output preserves exact evidence by default, with `--redact` available when sensitive values are not needed.
81
+ - `extract-har` only describes captured requests. It does not execute or replay them. Known direct CDP methods that bypass managed-browser lifecycle controls are blocked.
82
82
 
83
- For the full behavior reference (profile sync internals, ownership rules, stop safety checks, gotchas), see the skill docs in this repository: [SKILL.md](https://github.com/rezkam/browser-tools/blob/main/SKILL.md) and [references/browser-control.md](https://github.com/rezkam/browser-tools/blob/main/references/browser-control.md).
83
+ Browser Tools stores local configuration under `~/.agents/browser-tools` and managed profiles under `~/.cache/pi-browser-tools`. Timestamped artifacts such as screenshots default to the system temporary directory, while derived outputs such as HAR recipes and GIF reviews stay beside their input files. The documented `BROWSER_TOOLS_*` environment variables override configurable locations.
84
84
 
85
- ## Testing
85
+ For detailed ownership rules, profile behavior, capture filters, and command options, see the repository's [SKILL.md](https://github.com/rezkam/browser-tools/blob/main/SKILL.md) and [Browser Control reference](https://github.com/rezkam/browser-tools/blob/main/references/browser-control.md).
86
86
 
87
- ```bash
88
- npm test # Fast unit and CLI contract tests
89
- npm run test:e2e # Real headless Chrome and ffmpeg GIF interaction test
90
- npm run validate # Both suites
87
+ ## Programmatic use
88
+
89
+ ```js
90
+ import { activePage, connectBrowser, startChrome, stopChrome, withBrowser } from '@rezkam/browser-tools';
91
+ import { runBrowserResource } from '@rezkam/browser-tools/resource-helper.mjs';
91
92
  ```
92
93
 
93
- The E2E tests use real Chrome, ffmpeg, and ffprobe against local isolated fixtures. GIF tests validate recording, private output, and contact-sheet review. Network tests validate raw filtered HAR capture, optional recipe redaction, raw wildcard CDP events, direct CDP calls, owner-token refusal, private file modes, hard event limits, and lifecycle-method blocking. They do not use a live account or external server.
94
+ The root package export and `@rezkam/browser-tools/browser-control.mjs` both expose the browser lifecycle and connection module. The resource helper export provides the shared lifecycle for generic extractors.
95
+
96
+ ## Development
97
+
98
+ ```bash
99
+ npm test # Unit and CLI contract tests
100
+ npm run test:e2e # Real Chrome and ffmpeg integration tests
101
+ npm run validate # Full validation suite
102
+ ```
94
103
 
95
104
  ## License
96
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rezkam/browser-tools",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
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",
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
+ import { createConnection } from 'node:net';
3
4
  import {
4
5
  accessSync,
5
6
  chmodSync,
@@ -19,6 +20,7 @@ import puppeteer from 'puppeteer-core';
19
20
 
20
21
  export const DEFAULT_PORT = 9222;
21
22
  export const CONNECT_PROBE_TIMEOUT_MS = 3000;
23
+ export const PORT_OCCUPANCY_PROBE_TIMEOUT_MS = 250;
22
24
  export const CHROME_READY_TIMEOUT_MS = 15000;
23
25
  export const CHROME_READY_PROBE_TIMEOUT_MS = 250;
24
26
  export const DEFAULT_CHROME_BIN = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
@@ -49,7 +51,7 @@ export const MAX_BROWSERS_ENV = 'BROWSER_TOOLS_MAX_BROWSERS';
49
51
  // A managed browser older than this is almost certainly a leftover from a finished agent session.
50
52
  export const STALE_BROWSER_AGE_MS = 2 * 60 * 60 * 1000;
51
53
  export const PENDING_BROWSER_STATE_MAX_AGE_MS = 5000;
52
- export const REAP_HINT = 'Run scripts/stop.mjs --reap to sweep managed browsers that no lifecycle file accounts for.';
54
+ export const REAP_HINT = 'Run scripts/stop.mjs --reap to sweep reclaimable managed browsers whose lifecycle tracking or launcher lease has expired.';
53
55
 
54
56
  export function agentConfigRoot() {
55
57
  return process.env.AGENT_CONFIG_DIR || join(homedir(), '.agents');
@@ -388,18 +390,73 @@ export async function browserWSEndpoint(port = DEFAULT_PORT, timeoutMs = CONNECT
388
390
  }
389
391
  }
390
392
 
391
- export async function waitForChromeReady(
393
+ /**
394
+ * Detect any local listener, not just a responsive CDP endpoint. A normal Chrome
395
+ * can occupy the preferred debugging port without exposing a usable
396
+ * /json/version response, and launching against that port otherwise fails only
397
+ * after the full readiness timeout. Unexpected probe errors are treated as
398
+ * occupied so an uncertain port is never handed to Chrome.
399
+ */
400
+ function tcpListenerOnHost(port, host, timeoutMs) {
401
+ return new Promise((resolvePromise) => {
402
+ const socket = createConnection({ host, port });
403
+ let settled = false;
404
+ const finish = (occupied) => {
405
+ if (settled) return;
406
+ settled = true;
407
+ socket.destroy();
408
+ resolvePromise(occupied);
409
+ };
410
+ socket.once('connect', () => finish(true));
411
+ socket.once('error', (error) => {
412
+ const code = error && typeof error === 'object' ? error.code : undefined;
413
+ finish(!['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EPROTONOSUPPORT', 'ENOTSUP'].includes(code));
414
+ });
415
+ socket.setTimeout(timeoutMs, () => finish(true));
416
+ });
417
+ }
418
+
419
+ export async function isPortOccupied(port = DEFAULT_PORT, timeoutMs = PORT_OCCUPANCY_PROBE_TIMEOUT_MS) {
420
+ const normalizedPort = normalizePort(port);
421
+ const [ipv4, ipv6] = await Promise.all([
422
+ tcpListenerOnHost(normalizedPort, '127.0.0.1', timeoutMs),
423
+ tcpListenerOnHost(normalizedPort, '::1', timeoutMs),
424
+ ]);
425
+ return ipv4 || ipv6;
426
+ }
427
+
428
+ export function devToolsActivePortMatches(userDataDir, endpoint) {
429
+ if (!userDataDir || !endpoint) return false;
430
+ try {
431
+ const url = new URL(endpoint);
432
+ const activePortFile = readFileSync(join(userDataDir, 'DevToolsActivePort'), 'utf8').trim().split(/\r?\n/);
433
+ const endpointPort = url.port || (url.protocol === 'ws:' ? '80' : url.protocol === 'wss:' ? '443' : '');
434
+ return activePortFile[0] === endpointPort && activePortFile[1] === url.pathname;
435
+ } catch {
436
+ return false;
437
+ }
438
+ }
439
+
440
+ export async function waitForChromeEndpoint(
392
441
  port = DEFAULT_PORT,
393
442
  { timeoutMs = CHROME_READY_TIMEOUT_MS, intervalMs = 250, probeTimeoutMs = CHROME_READY_PROBE_TIMEOUT_MS } = {},
394
443
  ) {
395
444
  const deadline = Date.now() + timeoutMs;
396
445
  while (Date.now() < deadline) {
397
446
  const remainingMs = Math.max(1, deadline - Date.now());
398
- if (await browserWSEndpoint(port, Math.min(probeTimeoutMs, remainingMs))) return true;
447
+ const endpoint = await browserWSEndpoint(port, Math.min(probeTimeoutMs, remainingMs));
448
+ if (endpoint) return endpoint;
399
449
  const sleepMs = Math.min(intervalMs, Math.max(0, deadline - Date.now()));
400
450
  if (sleepMs > 0) await sleep(sleepMs);
401
451
  }
402
- return false;
452
+ return null;
453
+ }
454
+
455
+ export async function waitForChromeReady(
456
+ port = DEFAULT_PORT,
457
+ options = {},
458
+ ) {
459
+ return Boolean(await waitForChromeEndpoint(port, options));
403
460
  }
404
461
 
405
462
  export function profileCopyReady(profileName, profileDataDir = profileDataDirForPort()) {
@@ -1212,6 +1269,21 @@ export function staleManagedBrowsers(processes = listManagedChromeProcesses(), {
1212
1269
  return processes.filter((entry) => Number.isFinite(entry.ageMs) && entry.ageMs >= maxAgeMs);
1213
1270
  }
1214
1271
 
1272
+ function managedBrowserLauncherIsActive(state) {
1273
+ const launcherPid = Number(state?.launchedByPid);
1274
+ if (!Number.isInteger(launcherPid) || launcherPid < 1) return false;
1275
+ const recordedIdentity = typeof state?.launchedByProcessStartIdentity === 'string'
1276
+ ? state.launchedByProcessStartIdentity
1277
+ : null;
1278
+ if (!recordedIdentity) return processExists(launcherPid);
1279
+
1280
+ const currentIdentity = processStartIdentity(launcherPid);
1281
+ if (currentIdentity) return currentIdentity === recordedIdentity;
1282
+ // A transient process-table read failure must fail closed. Only consider the launcher gone when
1283
+ // the independent process existence check agrees that the PID no longer exists.
1284
+ return processExists(launcherPid);
1285
+ }
1286
+
1215
1287
  function readManagedPid(pidFile) {
1216
1288
  try {
1217
1289
  const pid = Number.parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
@@ -1221,8 +1293,8 @@ function readManagedPid(pidFile) {
1221
1293
  }
1222
1294
  }
1223
1295
 
1224
- // A managed browser whose lifecycle files no longer describe it. `stop --port N` cannot reach these,
1225
- // so they would otherwise accumulate forever.
1296
+ // Managed browsers the reaper may safely reclaim. This includes browsers whose lifecycle files no
1297
+ // longer describe them, unowned browsers, and old browsers whose recorded launcher has exited.
1226
1298
  export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()) {
1227
1299
  return processes.filter((entry) => {
1228
1300
  // A concurrent start holds the port lock from before the spawn until the readiness probe passes,
@@ -1245,6 +1317,13 @@ export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()
1245
1317
  // An unowned browser is tracked but unreachable: its owner token lives only in the caller that
1246
1318
  // started it, so once that process exits nothing can adopt or stop it. Reclaim it as garbage.
1247
1319
  if (!normalizeOwnerValue(state.ownerId)) return true;
1320
+ // Ownership cannot make a leaked browser immortal. Once the browser is old enough to be stale
1321
+ // and the process that launched it is gone, no live owner process remains to close it.
1322
+ if (
1323
+ Number.isFinite(entry.ageMs) &&
1324
+ entry.ageMs >= STALE_BROWSER_AGE_MS &&
1325
+ !managedBrowserLauncherIsActive(state)
1326
+ ) return true;
1248
1327
  return false;
1249
1328
  });
1250
1329
  }
@@ -1253,9 +1332,9 @@ export function forcedKillStatus(exited) {
1253
1332
  return exited ? 'killed' : 'failed';
1254
1333
  }
1255
1334
 
1256
- // Kill managed browsers that no lifecycle file accounts for, then drop their leftover clone dirs.
1257
- // Safe by construction: every target came from parseManagedChromeProcesses, so it carries our
1258
- // managed token and a user-data-dir inside our cache dir.
1335
+ // Kill reclaimable managed browsers. Safe by construction: every target came from
1336
+ // parseManagedChromeProcesses, so it carries our managed token and a user-data-dir inside our cache
1337
+ // dir. Old tracked browsers are eligible only after their launcher exits and the grace period ends.
1259
1338
  export function reapOrphanedChromes({ dryRun = false, processes = listManagedChromeProcesses() } = {}) {
1260
1339
  const orphans = orphanedManagedBrowsers(processes);
1261
1340
  const reaped = [];
@@ -1312,7 +1391,7 @@ function describeBrowserInventory(processes, { limit = 10, staleMaxAgeMs = STALE
1312
1391
  const lines = processes.slice(0, limit).map((entry) => {
1313
1392
  const stale = Number.isFinite(entry.ageMs) && entry.ageMs >= staleMaxAgeMs;
1314
1393
  const pid = Number.isInteger(Number(entry.pid)) ? `PID ${entry.pid}` : 'PID unknown';
1315
- return ` :${entry.port} ${pid} up ${formatBrowserAge(entry.ageMs)}${stale ? ' <- idle over 2h, likely a leftover' : ''}`;
1394
+ return ` :${entry.port} ${pid} up ${formatBrowserAge(entry.ageMs)}${stale ? ' <- running over 2h, likely a leftover' : ''}`;
1316
1395
  });
1317
1396
  if (processes.length > limit) lines.push(` ... and ${processes.length - limit} more`);
1318
1397
  return lines.join('\n');
@@ -1335,7 +1414,7 @@ export function assertManagedBrowserCapacity({ processes = listManagedChromeProc
1335
1414
  staleLine +
1336
1415
  `\n To continue, do one of these:\n` +
1337
1416
  ` scripts/stop.mjs --status see this list again at any time\n` +
1338
- ` scripts/stop.mjs --reap --dry-run preview browsers no lifecycle file tracks\n` +
1417
+ ` scripts/stop.mjs --reap --dry-run preview reclaimable leaked browsers\n` +
1339
1418
  ` scripts/stop.mjs --prune reap those, then drop their unused clones\n` +
1340
1419
  ` scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}" stop one you own\n\n` +
1341
1420
  ` Best fix if these are yours: export ${OWNER_TOKEN_ENV} from the first start, and later\n` +
@@ -1366,7 +1445,8 @@ export function managedBrowserStartupWarnings({
1366
1445
  `${stale.length} managed browser${stale.length === 1 ? '' : 's'} ${stale.length === 1 ? 'has' : 'have'} been running over ${hours}h ` +
1367
1446
  `(${describePorts(stale)}), likely left over from a finished session. ` +
1368
1447
  `Stop a tracked browser with scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}". ` +
1369
- `Use scripts/stop.mjs --reap --dry-run and scripts/stop.mjs --prune only for untracked browsers.`,
1448
+ `Old sessions whose launcher has exited are reclaimed automatically by the next start. ` +
1449
+ `Use scripts/stop.mjs --reap --dry-run to preview all reclaimable sessions.`,
1370
1450
  );
1371
1451
  }
1372
1452
  return warnings;
@@ -1496,6 +1576,8 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1496
1576
  const chromeBin = browserToolsChromeBin();
1497
1577
  const userAgent = headless ? headlessUserAgent(chromeBin) : null;
1498
1578
  const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent });
1579
+ // A stale marker must not make a later launch appear to own a competing endpoint.
1580
+ rmSync(join(launchUserDataDir, 'DevToolsActivePort'), { force: true });
1499
1581
  assertChromeBinaryLaunchable(chromeBin);
1500
1582
  const pidFile = pidFileForPort(normalizedPort);
1501
1583
  const stateFile = stateFileForPort(normalizedPort);
@@ -1528,6 +1610,9 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1528
1610
  ...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
1529
1611
  // Who launched this browser, so a leaked one is attributable instead of anonymous.
1530
1612
  launchedByPid: process.pid,
1613
+ // The PID can be reused after the launcher exits. Record its start identity so a different
1614
+ // process inheriting the same number cannot keep an expired browser lease alive.
1615
+ launchedByProcessStartIdentity: processStartIdentity(process.pid),
1531
1616
  args,
1532
1617
  startedAt: new Date().toISOString(),
1533
1618
  }, null, 2));
@@ -1544,6 +1629,7 @@ export async function findAvailablePort(startPort = DEFAULT_PORT, { maxAttempts
1544
1629
  cleanupStaleManagedStateForPort(port);
1545
1630
  if (
1546
1631
  !(await browserWSEndpoint(port)) &&
1632
+ !(await isPortOccupied(port)) &&
1547
1633
  !existsSync(stateFileForPort(port)) &&
1548
1634
  !existsSync(pidFileForPort(port))
1549
1635
  ) return port;
@@ -1580,11 +1666,11 @@ export async function startChrome({
1580
1666
  const { requestedProfileName, resolvedProfileName } = resolveStartProfileName({ profileName, taskName, defaultProfileName });
1581
1667
  ensureCacheDir();
1582
1668
 
1583
- // Clean up before counting, so the cap reflects browsers that are actually reachable. Orphans are
1584
- // browsers no lifecycle file tracks: nothing can address or stop them, so they are pure garbage.
1669
+ // Clean up before counting, so the cap reflects browsers that are still actively owned. Untracked
1670
+ // browsers and old browsers whose launcher has exited are safe to reclaim before reserving a slot.
1585
1671
  const reaped = reapOrphanedChromes();
1586
1672
  if (reaped.reaped.length) {
1587
- console.error(`⟳ Reaped ${reaped.reaped.length} untracked managed browser${reaped.reaped.length === 1 ? '' : 's'} (${describePorts(reaped.reaped)})`);
1673
+ console.error(`⟳ Reaped ${reaped.reaped.length} reclaimable managed browser${reaped.reaped.length === 1 ? '' : 's'} (${describePorts(reaped.reaped)})`);
1588
1674
  try {
1589
1675
  pruneChromeClones({ keepPorts: [normalizedPort] });
1590
1676
  } catch {
@@ -1606,7 +1692,8 @@ export async function startChrome({
1606
1692
  ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
1607
1693
  profileName: resolvedProfileName, headless, forceProfileSync,
1608
1694
  });
1609
- if (found && await browserWSEndpoint(found.port)) {
1695
+ const foundEndpoint = found ? await browserWSEndpoint(found.port) : null;
1696
+ if (found && foundEndpoint) {
1610
1697
  reusable = found;
1611
1698
  normalizedPort = found.port;
1612
1699
  }
@@ -1627,7 +1714,21 @@ export async function startChrome({
1627
1714
  try {
1628
1715
  cleanupStaleManagedStateForPort(normalizedPort);
1629
1716
 
1630
- if (await browserWSEndpoint(normalizedPort)) {
1717
+ const endpoint = await browserWSEndpoint(normalizedPort);
1718
+ const occupied = !endpoint && await isPortOccupied(normalizedPort);
1719
+ if (endpoint || occupied) {
1720
+ // A non-CDP listener is never an adoption candidate, even if stale
1721
+ // managed state happens to match this port and owner token.
1722
+ if (occupied) {
1723
+ if (!autoAllocatePort) {
1724
+ throw new Error(
1725
+ `Port :${normalizedPort} is already in use, but it is not a Browser Tools managed browser. Use a different --port or stop that listener manually.`,
1726
+ );
1727
+ }
1728
+ assertManagedBrowserCapacity();
1729
+ normalizedPort = await findAvailablePort(normalizedPort + 1);
1730
+ continue;
1731
+ }
1631
1732
  const safety = managedBrowserSafetyForPort(normalizedPort);
1632
1733
  const state = readManagedStateForPort(normalizedPort);
1633
1734
  const reuse = managedBrowserReuseDecision({
@@ -1812,11 +1913,19 @@ export async function startChrome({
1812
1913
  ownerTokenGenerated: false,
1813
1914
  };
1814
1915
  }
1815
- const ready = await waitForChromeReady(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1816
- if (!ready) {
1916
+ const launchedEndpoint = await waitForChromeEndpoint(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1917
+ if (!launchedEndpoint) {
1817
1918
  stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
1818
1919
  throw new Error(`Failed to connect to Chrome after ${Math.round(CHROME_READY_TIMEOUT_MS / 1000)}s`);
1819
1920
  }
1921
+ const launchedState = readManagedStateForPort(normalizedPort);
1922
+ const launchedSafety = managedBrowserSafetyForPort(normalizedPort);
1923
+ if (!launchedSafety.ok || Number(launchedState?.pid) !== Number(proc?.pid) || !devToolsActivePortMatches(launchedState?.userDataDir, launchedEndpoint)) {
1924
+ stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
1925
+ throw new Error(
1926
+ `Chrome reported ready on :${normalizedPort}, but the responding process was not verified as the managed launch (${launchedSafety.reason || 'pid-mismatch'}).`,
1927
+ );
1928
+ }
1820
1929
  return {
1821
1930
  status: 'started',
1822
1931
  port: normalizedPort,
@@ -2067,12 +2176,20 @@ function processStartIdentity(pid) {
2067
2176
  if (!Number.isInteger(normalizedPid) || normalizedPid < 1) return null;
2068
2177
  const result = spawnSync(
2069
2178
  'ps',
2070
- ['-p', String(normalizedPid), '-o', 'lstart=', '-o', 'command='],
2071
- { encoding: 'utf-8' },
2179
+ ['-p', String(normalizedPid), '-o', 'lstart='],
2180
+ {
2181
+ encoding: 'utf-8',
2182
+ // BSD ps formats lstart through the caller's locale and timezone. Canonicalize both so two
2183
+ // processes observing the same live launcher hash the same immutable start metadata.
2184
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C', LC_TIME: 'C', TZ: 'UTC' },
2185
+ },
2072
2186
  );
2073
2187
  if (result.error || result.status !== 0) return null;
2074
- const identity = result.stdout.trim();
2075
- if (!identity) return null;
2188
+ const startedAt = result.stdout.trim();
2189
+ if (!startedAt) return null;
2190
+ // PID and kernel-reported start time stay fixed for the process lifetime. Command and argv do not:
2191
+ // process.title can rewrite them while the same live process continues owning the browser.
2192
+ const identity = `${normalizedPid}\n${startedAt}`;
2076
2193
  return createHash('sha256').update(identity, 'utf8').digest('hex');
2077
2194
  }
2078
2195
 
package/scripts/stop.mjs CHANGED
@@ -8,8 +8,8 @@
8
8
  * scripts/stop.mjs --port 9223
9
9
  * scripts/stop.mjs --clean
10
10
  * scripts/stop.mjs --dry-run
11
- * scripts/stop.mjs --prune (reap orphans, then remove all cached clones not in use)
12
- * scripts/stop.mjs --reap (kill managed browsers no lifecycle file tracks)
11
+ * scripts/stop.mjs --prune (reap leftovers, then remove all cached clones not in use)
12
+ * scripts/stop.mjs --reap (kill reclaimable managed browsers)
13
13
  * scripts/stop.mjs --reap --dry-run (list them without killing anything)
14
14
  * scripts/stop.mjs --status (show how many managed browsers are running)
15
15
  * scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
@@ -35,7 +35,7 @@ const ownerToken = parseOwnerToken(args);
35
35
 
36
36
  function reportReaped(reaped, wasDryRun) {
37
37
  if (!reaped.length) {
38
- console.log('No untracked managed browsers found.');
38
+ console.log('No reclaimable managed browsers found.');
39
39
  return;
40
40
  }
41
41
  for (const entry of reaped) {