@rezkam/browser-tools 0.3.0 → 1.0.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rezkam/browser-tools",
3
- "version": "0.3.0",
3
+ "version": "1.0.0",
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",
@@ -13,7 +13,7 @@ import {
13
13
  writeFileSync,
14
14
  } from 'node:fs';
15
15
  import { homedir, tmpdir } from 'node:os';
16
- import { delimiter, dirname, join } from 'node:path';
16
+ import { delimiter, dirname, join, resolve } from 'node:path';
17
17
  import puppeteer from 'puppeteer-core';
18
18
 
19
19
  export const DEFAULT_PORT = 9222;
@@ -35,9 +35,21 @@ export const FRESH_PROFILE_DIR = join(CACHE_DIR, 'chrome-fresh');
35
35
  export const PROFILE_SYNC_STATE_FILE = join(CACHE_DIR, 'chrome-profile-sync.json');
36
36
  export const OWNER_TOKEN_ENV = 'BROWSER_TOOLS_OWNER_TOKEN';
37
37
  export const OWNER_ID_ENV = 'BROWSER_TOOLS_OWNER_ID';
38
+ // Owner stamped on a launch started straight from the command line, so no browser is ever unowned.
39
+ export const CLI_OWNER_ID = 'cli';
38
40
  export const OWNER_TOKEN_HASH_ALGORITHM = 'sha256';
39
41
  export const PORT_LOCK_STALE_MS = 30000;
40
42
 
43
+ // Concurrency guardrails. A managed Chrome costs roughly 800 MB across a browser process and its
44
+ // helpers, so an unbounded fan-out of `start` calls exhausts memory long before it exhausts ports.
45
+ // The cap is deliberately small: agents should reuse or stop a browser, not accumulate them.
46
+ export const DEFAULT_MAX_MANAGED_BROWSERS = 5;
47
+ export const MAX_BROWSERS_ENV = 'BROWSER_TOOLS_MAX_BROWSERS';
48
+ // A managed browser older than this is almost certainly a leftover from a finished agent session.
49
+ export const STALE_BROWSER_AGE_MS = 2 * 60 * 60 * 1000;
50
+ export const PENDING_BROWSER_STATE_MAX_AGE_MS = 5000;
51
+ export const REAP_HINT = 'Run scripts/stop.mjs --reap to sweep managed browsers that no lifecycle file accounts for.';
52
+
41
53
  export function agentConfigRoot() {
42
54
  return process.env.AGENT_CONFIG_DIR || join(homedir(), '.agents');
43
55
  }
@@ -76,6 +88,7 @@ export function browserToolsRuntimeConfig({ configDir = browserToolsConfigDir()
76
88
  chromeSourceDir: expandHomePath(process.env.BROWSER_TOOLS_CHROME_SOURCE_DIR || config.directories?.chromeSourceDir || config.sourceDir || DEFAULT_CHROME_SRC),
77
89
  cacheDir: expandHomePath(process.env.BROWSER_TOOLS_CACHE_DIR || config.directories?.cacheDir || DEFAULT_CACHE_DIR),
78
90
  artifactDir: expandHomePath(process.env.BROWSER_TOOLS_ARTIFACT_DIR || config.directories?.artifactDir || DEFAULT_ARTIFACT_DIR),
91
+ maxBrowsers: config.browser?.maxBrowsers ?? config.maxBrowsers ?? null,
79
92
  };
80
93
  }
81
94
 
@@ -257,7 +270,9 @@ function buildOwnerState({ ownerToken, ownerId = null }) {
257
270
  };
258
271
  }
259
272
 
260
- export function managedBrowserOwnershipSafety({ state, ownerToken }) {
273
+ // allowUnowned is for stopping only. Adoption and connection must never opt in, or an unowned
274
+ // browser could be hijacked by any caller instead of merely being cleaned up.
275
+ export function managedBrowserOwnershipSafety({ state, ownerToken, allowUnowned = false }) {
261
276
  if (!state || state.managedBy !== 'browser-tools') {
262
277
  return { ok: false, reason: 'missing-managed-state' };
263
278
  }
@@ -266,6 +281,11 @@ export function managedBrowserOwnershipSafety({ state, ownerToken }) {
266
281
  }
267
282
  const token = normalizeOwnerValue(ownerToken);
268
283
  if (!token) {
284
+ // Nothing owns this browser, so no surviving caller holds a token that could ever stop it.
285
+ // Refusing here is what makes a leaked browser permanent, so allow the reclaim and report it.
286
+ if (allowUnowned && !normalizeOwnerValue(state.ownerId)) {
287
+ return { ok: true, ownerId: null, reclaimedUnowned: true };
288
+ }
269
289
  return { ok: false, reason: 'missing-owner-token', ownerId: state.ownerId || null };
270
290
  }
271
291
  if (ownerTokenHash(token) !== state.ownerTokenHash) {
@@ -286,6 +306,55 @@ export function portLockDirForPort(port) {
286
306
  return join(browserToolsCacheDir(), `chrome-${normalizePort(port)}.lock`);
287
307
  }
288
308
 
309
+ function lockDirectoryIsActive(lockDir, { staleMs = PORT_LOCK_STALE_MS } = {}) {
310
+ if (!existsSync(lockDir)) return false;
311
+
312
+ let lockState = null;
313
+ try {
314
+ lockState = safeReadJson(join(lockDir, 'lock.json'));
315
+ } catch {
316
+ lockState = null;
317
+ }
318
+ const ownerPid = Number(lockState?.pid);
319
+ let staleByAge;
320
+ try {
321
+ staleByAge = Date.now() - statSync(lockDir).mtimeMs > staleMs;
322
+ } catch {
323
+ staleByAge = true;
324
+ }
325
+
326
+ let stale = staleByAge;
327
+ if (Number.isInteger(ownerPid) && ownerPid > 0) {
328
+ const recordedIdentity = typeof lockState?.processStartIdentity === 'string'
329
+ ? lockState.processStartIdentity
330
+ : null;
331
+ const currentIdentity = recordedIdentity ? processStartIdentity(ownerPid) : null;
332
+ if (recordedIdentity && currentIdentity === recordedIdentity) {
333
+ return true;
334
+ }
335
+ stale = !processExists(ownerPid) || staleByAge;
336
+ }
337
+ if (!stale) return true;
338
+ rmSync(lockDir, { recursive: true, force: true });
339
+ return false;
340
+ }
341
+
342
+ function releaseOwnedLockDirectory(lockDir, lockId) {
343
+ let lockState;
344
+ try {
345
+ lockState = safeReadJson(join(lockDir, 'lock.json'));
346
+ } catch {
347
+ return false;
348
+ }
349
+ if (!lockState || lockState.lockId !== lockId) return false;
350
+ rmSync(lockDir, { recursive: true, force: true });
351
+ return true;
352
+ }
353
+
354
+ export function portLockIsActive(port = DEFAULT_PORT, options = {}) {
355
+ return lockDirectoryIsActive(portLockDirForPort(port), options);
356
+ }
357
+
289
358
  export function chromePaths(port = DEFAULT_PORT) {
290
359
  const runtime = browserToolsRuntimeConfig();
291
360
  return {
@@ -387,12 +456,16 @@ export function acquirePortLock(port = DEFAULT_PORT, { ownerId = null, staleMs =
387
456
  const normalizedPort = normalizePort(port);
388
457
  ensureCacheDir();
389
458
  const lockDir = portLockDirForPort(normalizedPort);
459
+ const lockId = randomUUID();
460
+ const ownerProcessStartIdentity = processStartIdentity(process.pid);
390
461
 
391
462
  for (let attempt = 0; attempt < 2; attempt += 1) {
392
463
  try {
393
464
  mkdirSync(lockDir, { mode: 0o700 });
394
465
  writePrivateFile(join(lockDir, 'lock.json'), JSON.stringify({
466
+ lockId,
395
467
  pid: process.pid,
468
+ processStartIdentity: ownerProcessStartIdentity,
396
469
  port: normalizedPort,
397
470
  ownerId: normalizeOwnerValue(ownerId),
398
471
  createdAt: new Date().toISOString(),
@@ -401,30 +474,14 @@ export function acquirePortLock(port = DEFAULT_PORT, { ownerId = null, staleMs =
401
474
  port: normalizedPort,
402
475
  lockDir,
403
476
  release() {
404
- rmSync(lockDir, { recursive: true, force: true });
477
+ releaseOwnedLockDirectory(lockDir, lockId);
405
478
  },
406
479
  };
407
480
  } catch (e) {
408
481
  if (e.code !== 'EEXIST') throw e;
409
- // A start that crashed mid-write can leave a partial or corrupt lock.json. Treat an unreadable
410
- // lock as having no metadata rather than throwing, so the age-based staleness check below can
411
- // still recover the port (and a fresh, possibly mid-write lock is left alone until it ages out).
412
- let lockState = null;
413
- try {
414
- lockState = safeReadJson(join(lockDir, 'lock.json'));
415
- } catch {
416
- lockState = null;
417
- }
418
- let stale = false;
419
- if (lockState?.pid && !processExists(Number(lockState.pid))) stale = true;
420
- try {
421
- const ageMs = Date.now() - statSync(lockDir).mtimeMs;
422
- if (ageMs > staleMs) stale = true;
423
- } catch {
424
- stale = true;
425
- }
426
- if (!stale) return null;
427
- rmSync(lockDir, { recursive: true, force: true });
482
+ // A start that crashed mid-write can leave a partial or corrupt lock.json. Fresh partial locks
483
+ // remain active until they age out, while stale locks are reclaimed by the shared lock check.
484
+ if (portLockIsActive(normalizedPort, { staleMs })) return null;
428
485
  }
429
486
  }
430
487
 
@@ -527,6 +584,14 @@ export function buildBrowserToolsConfig({ sourceDir = browserToolsChromeSourceDi
527
584
  },
528
585
  browser: {
529
586
  chromeBin: existingBrowser.chromeBin || browserToolsChromeBin(),
587
+ // Only carry an explicitly configured cap. Writing a default here would freeze the value and
588
+ // silently override a later change to the built-in limit.
589
+ // browserToolsRuntimeConfig also honours a legacy top-level maxBrowsers, so carry that form
590
+ // through too. Nested wins when both exist, matching how the value is read.
591
+ ...(() => {
592
+ const cap = existingBrowser.maxBrowsers ?? existing?.maxBrowsers;
593
+ return cap === undefined || cap === null ? {} : { maxBrowsers: cap };
594
+ })(),
530
595
  },
531
596
  profiles: Object.fromEntries(profiles.map((profile) => [profile.folder, profile])),
532
597
  aliases: buildAliases(profiles),
@@ -887,7 +952,6 @@ export function headlessUserAgent(chromeBin = browserToolsChromeBin()) {
887
952
  export function managedBrowserForUserDataDir(userDataDir) {
888
953
  const result = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf-8' });
889
954
  if (result.error || result.status !== 0) return null;
890
- const chromeBin = browserToolsChromeBin();
891
955
 
892
956
  for (const line of result.stdout.split('\n')) {
893
957
  const trimmed = line.trim();
@@ -896,14 +960,456 @@ export function managedBrowserForUserDataDir(userDataDir) {
896
960
  if (!match) continue;
897
961
  const pid = Number.parseInt(match[1], 10);
898
962
  const command = match[2];
899
- if (!command.includes(chromeBin)) continue;
900
- if (!command.includes(`--user-data-dir=${userDataDir}`)) continue;
901
- if (!command.includes('--pi-browser-tools-managed=')) continue;
902
- const portMatch = command.match(/--remote-debugging-port=(\d+)/);
903
- if (!portMatch) continue;
904
- return { pid, port: normalizePort(portMatch[1]), command };
963
+ const managed = managedChromeProcessFromCommand({ pid, command });
964
+ if (!managed || managed.userDataDir !== userDataDir) continue;
965
+ return managed;
966
+ }
967
+
968
+ return null;
969
+ }
970
+
971
+ // Convert a ps etime field ("MM:SS", "HH:MM:SS", or "DD-HH:MM:SS") to milliseconds.
972
+ export function parseProcessAgeMs(etime) {
973
+ const raw = String(etime ?? '').trim();
974
+ const match = raw.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
975
+ if (!match) return null;
976
+ const [, days, hours, minutes, seconds] = match;
977
+ const total = ((Number(days || 0) * 24 + Number(hours || 0)) * 60 + Number(minutes)) * 60 + Number(seconds);
978
+ return total * 1000;
979
+ }
980
+
981
+ // Parse `ps -axo pid=,etime=,command=` output into the managed *browser* processes only.
982
+ //
983
+ // Pure so the filtering rules stay testable without spawning Chrome. Two exclusions matter:
984
+ // renderer/GPU/utility helpers inherit --user-data-dir and the managed token from their parent, so
985
+ // counting them would inflate the browser count roughly tenfold; and a user-data-dir outside our
986
+ // cache dir is somebody else's Chrome, which we must never count or kill.
987
+ // Extract --user-data-dir from a Chrome command line. Chrome does not quote this argument, and the
988
+ // path is user-configurable, so it can legitimately contain spaces ("/Volumes/My Drive/..."). Read
989
+ // to the next " --" rather than to the next space: a \S+ capture truncates the path, the cache-dir
990
+ // test then fails, and the browser silently disappears from the inventory.
991
+ // Strip trailing separators so a configured cache dir of "/tmp/cache/" builds the same prefix that
992
+ // join() produces when launching. Without this the prefix test becomes "/tmp/cache//chrome-", every
993
+ // managed browser disappears from the inventory, and the cap silently stops applying.
994
+ export function normalizeCacheDirPath(cacheDir) {
995
+ const value = String(cacheDir ?? '');
996
+ return value ? resolve(value) : value;
997
+ }
998
+
999
+ // Does this user-data-dir sit inside the cache dir as one of our clone directories? Compared on path
1000
+ // segments rather than raw text so a sibling like "/opt/cache-other" can never match "/opt/cache".
1001
+ export function isManagedCloneDir(userDataDir, cacheDir = browserToolsCacheDir()) {
1002
+ if (!userDataDir) return false;
1003
+ const root = normalizeCacheDirPath(cacheDir);
1004
+ const candidate = resolve(userDataDir);
1005
+ if (!candidate.startsWith(`${root}/`)) return false;
1006
+ const rest = candidate.slice(root.length + 1);
1007
+ return /^chrome-(?:data|fresh)-/.test(rest);
1008
+ }
1009
+
1010
+ export function parseUserDataDirArg(command) {
1011
+ const match = String(command ?? '').match(/--user-data-dir=(.+?)(?=\s--|$)/);
1012
+ return match ? match[1].trim() : null;
1013
+ }
1014
+
1015
+ // Decide whether one ps line is a managed browser, and describe it. Shared by the inventory scan and
1016
+ // by the pre-signal recheck in the reaper, so both apply exactly the same definition.
1017
+ export function managedChromeProcessFromCommand({ pid, etime = null, command, cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() }) {
1018
+ if (!command) return null;
1019
+ if (/--type=/.test(command)) return null;
1020
+ if (!command.includes('--pi-browser-tools-managed=')) return null;
1021
+ const portMatch = command.match(/--remote-debugging-port=(\d+)/);
1022
+ if (!portMatch) return null;
1023
+ const userDataDir = parseUserDataDirArg(command);
1024
+ if (!isManagedCloneDir(userDataDir, cacheDir)) return null;
1025
+ const tokenMatch = command.match(/--pi-browser-tools-managed=(\S+)/);
1026
+ return {
1027
+ pid: Number.parseInt(String(pid), 10),
1028
+ port: normalizePort(portMatch[1]),
1029
+ ageMs: parseProcessAgeMs(etime),
1030
+ userDataDir,
1031
+ // Per-launch UUID. Two different browsers never share one, so it pins process identity across
1032
+ // a PID that may have been recycled between the scan and the signal.
1033
+ managedToken: tokenMatch ? tokenMatch[1] : null,
1034
+ command,
1035
+ };
1036
+ }
1037
+
1038
+ export function parseManagedChromeProcesses(psOutput, { cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() } = {}) {
1039
+ const found = [];
1040
+ for (const line of String(psOutput ?? '').split('\n')) {
1041
+ const match = line.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);
1042
+ if (!match) continue;
1043
+ const [, pidText, etime, command] = match;
1044
+ const entry = managedChromeProcessFromCommand({ pid: pidText, etime, command, cacheDir, chromeBin });
1045
+ if (entry) found.push(entry);
1046
+ }
1047
+ return found;
1048
+ }
1049
+
1050
+ // Is this PID, right now, still one of our managed browsers? Used immediately before sending a
1051
+ // signal so a recycled PID cannot be hit.
1052
+ // Is `current` the same browser the scan saw? A PID alone is not identity: it can be recycled by a
1053
+ // different managed Chrome, and signalling on PID-only would then kill a healthy browser.
1054
+ export function managedBrowserIdentityMatches(expected, current) {
1055
+ if (!expected || !current) return false;
1056
+ if (Number(expected.pid) !== Number(current.pid)) return false;
1057
+ if (Number(expected.port) !== Number(current.port)) return false;
1058
+ if (expected.userDataDir !== current.userDataDir) return false;
1059
+ // The per-launch token is the strongest signal: a reused PID running a fresh Chrome has a new one.
1060
+ if (expected.managedToken && current.managedToken && expected.managedToken !== current.managedToken) return false;
1061
+ return true;
1062
+ }
1063
+
1064
+ export function verifyManagedChromePid(pid, { cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() } = {}) {
1065
+ const command = commandForPid(pid);
1066
+ if (!command) return null;
1067
+ return managedChromeProcessFromCommand({ pid, command, cacheDir, chromeBin });
1068
+ }
1069
+
1070
+ // The live inventory of managed browsers. This reads the process table rather than the lifecycle
1071
+ // files on purpose: the files can be deleted while a browser keeps running, which is precisely how
1072
+ // a previous leak became invisible to `stop`. Processes cannot lie about existing.
1073
+ export function listManagedChromeProcesses() {
1074
+ const result = spawnSync('ps', ['-axo', 'pid=,etime=,command='], { encoding: 'utf-8' });
1075
+ if (result.error) {
1076
+ const error = new Error(
1077
+ `Cannot read the managed Chrome process inventory: ps failed to start (${result.error.code || 'unknown error'}). Refusing to launch without enforcing the browser cap.`,
1078
+ );
1079
+ error.cause = result.error;
1080
+ throw error;
1081
+ }
1082
+ if (result.status !== 0) {
1083
+ const outcome = result.signal ? `signal ${result.signal}` : `status ${result.status ?? 'unknown'}`;
1084
+ throw new Error(
1085
+ `Cannot read the managed Chrome process inventory: ps exited with ${outcome}. Refusing to launch without enforcing the browser cap.`,
1086
+ );
1087
+ }
1088
+ return parseManagedChromeProcesses(result.stdout);
1089
+ }
1090
+
1091
+ export function maxManagedBrowsers(options = {}) {
1092
+ const raw = process.env[MAX_BROWSERS_ENV] ?? browserToolsRuntimeConfig(options).maxBrowsers;
1093
+ const parsed = Number.parseInt(String(raw ?? ''), 10);
1094
+ if (!Number.isInteger(parsed) || parsed < 1) return DEFAULT_MAX_MANAGED_BROWSERS;
1095
+ return parsed;
1096
+ }
1097
+
1098
+ export function launchLockDir() {
1099
+ return join(browserToolsCacheDir(), 'launch.lock');
1100
+ }
1101
+
1102
+ // A single cache-wide lock, distinct from the per-port locks. Per-port locks cannot bound total
1103
+ // concurrency: two starts racing for different ports never contend, so both can pass a 4-of-5 check
1104
+ // and both launch. Slot reservation has to serialise on one lock.
1105
+ export function acquireLaunchLock({ staleMs = PORT_LOCK_STALE_MS, waitMs = 30000, pollMs = 50 } = {}) {
1106
+ ensureCacheDir();
1107
+ const lockDir = launchLockDir();
1108
+ const deadline = Date.now() + Math.max(0, waitMs);
1109
+ const lockId = randomUUID();
1110
+ const ownerProcessStartIdentity = processStartIdentity(process.pid);
1111
+
1112
+ while (true) {
1113
+ try {
1114
+ mkdirSync(lockDir, { mode: 0o700 });
1115
+ writePrivateFile(join(lockDir, 'lock.json'), JSON.stringify({
1116
+ lockId,
1117
+ pid: process.pid,
1118
+ processStartIdentity: ownerProcessStartIdentity,
1119
+ createdAt: new Date().toISOString(),
1120
+ }, null, 2));
1121
+ return { lockDir, release() { releaseOwnedLockDirectory(lockDir, lockId); } };
1122
+ } catch (e) {
1123
+ if (e.code !== 'EEXIST') throw e;
1124
+ if (!lockDirectoryIsActive(lockDir, { staleMs })) continue;
1125
+ if (Date.now() >= deadline) return null;
1126
+ sleepSync(pollMs);
1127
+ }
1128
+ }
1129
+ }
1130
+
1131
+ // Ports that currently hold a slot. A running process holds one, and so does a browser whose state
1132
+ // file exists with a live PID: launchChrome writes that file synchronously at spawn, but the process
1133
+ // takes a moment to appear in ps, and a concurrent start must not read the gap as a free slot.
1134
+ export function occupiedManagedSlotPorts({ processes = listManagedChromeProcesses() } = {}) {
1135
+ const ports = new Set(processes.map((entry) => entry.port));
1136
+ let entries = [];
1137
+ try {
1138
+ entries = readdirSync(browserToolsCacheDir(), { withFileTypes: true });
1139
+ } catch {
1140
+ return ports;
1141
+ }
1142
+ for (const entry of entries) {
1143
+ const match = entry.name.match(/^chrome-(\d+)\.json$/);
1144
+ if (!match || !entry.isFile()) continue;
1145
+ const port = Number.parseInt(match[1], 10);
1146
+ if (ports.has(port)) continue;
1147
+ const state = readManagedState(stateFileForPort(port));
1148
+ if (!state || state.managedBy !== 'browser-tools') continue;
1149
+ const pid = Number(state.pid);
1150
+ if (!Number.isInteger(pid) || readManagedPid(pidFileForPort(port)) !== pid || !processExists(pid)) continue;
1151
+ if (verifyManagedChromeProcess({ pid, port, state }).ok) {
1152
+ ports.add(port);
1153
+ continue;
1154
+ }
1155
+ const startedAtMs = Date.parse(state.startedAt);
1156
+ const stateAgeMs = Date.now() - startedAtMs;
1157
+ const isPendingProcessScan =
1158
+ Number.isFinite(startedAtMs) &&
1159
+ stateAgeMs >= 0 &&
1160
+ stateAgeMs <= PENDING_BROWSER_STATE_MAX_AGE_MS &&
1161
+ managedChromeLifecycleStateSafety({ pid, port, state }).ok;
1162
+ if (isPendingProcessScan) ports.add(port);
1163
+ }
1164
+ return ports;
1165
+ }
1166
+
1167
+ function managedBrowserCandidatesForOccupiedSlots(processes, occupiedPorts) {
1168
+ const candidates = [...processes];
1169
+ const visiblePorts = new Set(processes.map((entry) => entry.port));
1170
+ for (const port of occupiedPorts) {
1171
+ if (visiblePorts.has(port)) continue;
1172
+ const state = readManagedState(stateFileForPort(port));
1173
+ if (!state) continue;
1174
+ candidates.push({
1175
+ pid: Number(state.pid),
1176
+ port,
1177
+ ageMs: null,
1178
+ userDataDir: state.userDataDir,
1179
+ managedToken: state.managedToken,
1180
+ });
1181
+ }
1182
+ return candidates;
1183
+ }
1184
+
1185
+ export function managedBrowserCapacity({ processes = listManagedChromeProcesses(), max = maxManagedBrowsers() } = {}) {
1186
+ const count = processes.length;
1187
+ return {
1188
+ count,
1189
+ max,
1190
+ remaining: Math.max(0, max - count),
1191
+ atCap: count >= max,
1192
+ // Warn on the last free slot so the cap is never a surprise.
1193
+ approaching: count > 0 && count === max - 1,
1194
+ processes,
1195
+ };
1196
+ }
1197
+
1198
+ export function staleManagedBrowsers(processes = listManagedChromeProcesses(), { maxAgeMs = STALE_BROWSER_AGE_MS } = {}) {
1199
+ return processes.filter((entry) => Number.isFinite(entry.ageMs) && entry.ageMs >= maxAgeMs);
1200
+ }
1201
+
1202
+ function readManagedPid(pidFile) {
1203
+ try {
1204
+ const pid = Number.parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
1205
+ return Number.isInteger(pid) ? pid : null;
1206
+ } catch {
1207
+ return null;
1208
+ }
1209
+ }
1210
+
1211
+ // A managed browser whose lifecycle files no longer describe it. `stop --port N` cannot reach these,
1212
+ // so they would otherwise accumulate forever.
1213
+ export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()) {
1214
+ return processes.filter((entry) => {
1215
+ // A concurrent start holds the port lock from before the spawn until the readiness probe passes,
1216
+ // so there is a window where its browser is live but not yet written to a state file. Never reap
1217
+ // inside that window or we would kill a healthy browser out from under another agent.
1218
+ if (portLockIsActive(entry.port)) return false;
1219
+ const state = readManagedState(stateFileForPort(entry.port));
1220
+ if (!state || state.managedBy !== 'browser-tools') return true;
1221
+ if (Number(state.pid) !== Number(entry.pid)) return true;
1222
+ // Both lifecycle files must be present and agree. stopChrome refuses to manage a half-written
1223
+ // pair, so sparing one here would leave the browser unreachable by stop *and* by reap.
1224
+ const pidFile = pidFileForPort(entry.port);
1225
+ const recordedPid = readManagedPid(pidFile);
1226
+ if (recordedPid !== Number(entry.pid)) return true;
1227
+ // A PID match alone is not tracking. Apply the same lifecycle-state validation as stopChrome,
1228
+ // then compare the recorded identity with the process inventory.
1229
+ if (!managedChromeLifecycleStateSafety({ pid: entry.pid, port: entry.port, state }).ok) return true;
1230
+ if (state.userDataDir !== entry.userDataDir) return true;
1231
+ if (state.managedToken !== entry.managedToken) return true;
1232
+ // An unowned browser is tracked but unreachable: its owner token lives only in the caller that
1233
+ // started it, so once that process exits nothing can adopt or stop it. Reclaim it as garbage.
1234
+ if (!normalizeOwnerValue(state.ownerId)) return true;
1235
+ return false;
1236
+ });
1237
+ }
1238
+
1239
+ export function forcedKillStatus(exited) {
1240
+ return exited ? 'killed' : 'failed';
1241
+ }
1242
+
1243
+ // Kill managed browsers that no lifecycle file accounts for, then drop their leftover clone dirs.
1244
+ // Safe by construction: every target came from parseManagedChromeProcesses, so it carries our
1245
+ // managed token and a user-data-dir inside our cache dir.
1246
+ export function reapOrphanedChromes({ dryRun = false, processes = listManagedChromeProcesses() } = {}) {
1247
+ const orphans = orphanedManagedBrowsers(processes);
1248
+ const reaped = [];
1249
+ for (const orphan of orphans) {
1250
+ if (dryRun) {
1251
+ reaped.push({ ...orphan, status: 'would-reap' });
1252
+ continue;
1253
+ }
1254
+ // Recheck before every signal. The PID came from a scan taken moments ago; if that process has
1255
+ // since exited and the PID been recycled, an unguarded kill lands on something unrelated.
1256
+ // stopChrome already does this between SIGTERM and SIGKILL, and this path runs automatically on
1257
+ // every start, so it must be at least as careful.
1258
+ if (!managedBrowserIdentityMatches(orphan, verifyManagedChromePid(orphan.pid))) {
1259
+ reaped.push({ ...orphan, status: processExists(orphan.pid) ? 'skipped-not-managed' : 'already-gone' });
1260
+ continue;
1261
+ }
1262
+ let status = 'reaped';
1263
+ try {
1264
+ process.kill(orphan.pid, 'SIGTERM');
1265
+ if (!waitForProcessExit(orphan.pid, 2000)) {
1266
+ if (!managedBrowserIdentityMatches(orphan, verifyManagedChromePid(orphan.pid))) {
1267
+ reaped.push({ ...orphan, status: 'skipped-not-managed' });
1268
+ continue;
1269
+ }
1270
+ process.kill(orphan.pid, 'SIGKILL');
1271
+ status = forcedKillStatus(waitForProcessExit(orphan.pid, 1000));
1272
+ }
1273
+ } catch (e) {
1274
+ status = e.code === 'ESRCH' ? 'already-gone' : 'failed';
1275
+ }
1276
+ reaped.push({ ...orphan, status });
1277
+ }
1278
+ return { reaped, dryRun };
1279
+ }
1280
+
1281
+ function describePorts(processes, limit = 8) {
1282
+ const ports = processes.map((entry) => `:${entry.port}`);
1283
+ if (ports.length <= limit) return ports.join(', ');
1284
+ return `${ports.slice(0, limit).join(', ')} and ${ports.length - limit} more`;
1285
+ }
1286
+
1287
+ // Hard stop before a new launch. Refusing is better than allocating yet another port: an unbounded
1288
+ // fan-out of starts is exactly what filled memory and swap on a previous run.
1289
+ export function formatBrowserAge(ageMs) {
1290
+ if (!Number.isFinite(ageMs)) return 'unknown age';
1291
+ const hours = ageMs / 3600000;
1292
+ if (hours < 1) return `${Math.max(1, Math.round(ageMs / 60000))}m`;
1293
+ return `${hours.toFixed(1)}h`;
1294
+ }
1295
+
1296
+ // One inventory line per occupied slot. The age and the leftover marker are the whole point: they
1297
+ // turn "you are at the limit" into "these four are junk from finished sessions, clear them".
1298
+ function describeBrowserInventory(processes, { limit = 10, staleMaxAgeMs = STALE_BROWSER_AGE_MS } = {}) {
1299
+ const lines = processes.slice(0, limit).map((entry) => {
1300
+ const stale = Number.isFinite(entry.ageMs) && entry.ageMs >= staleMaxAgeMs;
1301
+ const pid = Number.isInteger(Number(entry.pid)) ? `PID ${entry.pid}` : 'PID unknown';
1302
+ return ` :${entry.port} ${pid} up ${formatBrowserAge(entry.ageMs)}${stale ? ' <- idle over 2h, likely a leftover' : ''}`;
1303
+ });
1304
+ if (processes.length > limit) lines.push(` ... and ${processes.length - limit} more`);
1305
+ return lines.join('\n');
1306
+ }
1307
+
1308
+ export function assertManagedBrowserCapacity({ processes = listManagedChromeProcesses(), max = maxManagedBrowsers() } = {}) {
1309
+ const capacity = managedBrowserCapacity({ processes, max });
1310
+ if (!capacity.atCap) return capacity;
1311
+ const stale = staleManagedBrowsers(processes);
1312
+ const staleLine = stale.length
1313
+ ? `\n ${stale.length} of these ${stale.length === 1 ? 'has' : 'have'} been running over 2h and ${stale.length === 1 ? 'is' : 'are'} probably left over from a finished session.\n`
1314
+ : '';
1315
+ throw new Error(
1316
+ `Refusing to start another managed Chrome: ${capacity.count} of ${max} browser slots are in use.\n\n` +
1317
+ ` This is a deliberate limit, not a browser failure. Each managed Chrome costs roughly\n` +
1318
+ ` 800 MB across its process tree, so starts that are never stopped will exhaust memory\n` +
1319
+ ` and swap. The limit stops a runaway fan-out from taking the machine down.\n\n` +
1320
+ ` Currently running (${capacity.count} of ${max}):\n` +
1321
+ `${describeBrowserInventory(processes)}\n` +
1322
+ staleLine +
1323
+ `\n To continue, do one of these:\n` +
1324
+ ` scripts/stop.mjs --status see this list again at any time\n` +
1325
+ ` scripts/stop.mjs --reap --dry-run preview browsers no lifecycle file tracks\n` +
1326
+ ` scripts/stop.mjs --prune reap those, then drop their unused clones\n` +
1327
+ ` scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}" stop one you own\n\n` +
1328
+ ` Best fix if these are yours: export ${OWNER_TOKEN_ENV} from the first start, and later\n` +
1329
+ ` starts reuse that browser instead of needing a new slot at all.\n\n` +
1330
+ ` If you genuinely need more at once: ${MAX_BROWSERS_ENV}=<n>`,
1331
+ );
1332
+ }
1333
+
1334
+ // Non-fatal notices printed before a launch: one for the last free slot, one for browsers old enough
1335
+ // to be leftovers from a finished session.
1336
+ export function managedBrowserStartupWarnings({
1337
+ processes = listManagedChromeProcesses(),
1338
+ max = maxManagedBrowsers(),
1339
+ staleMaxAgeMs = STALE_BROWSER_AGE_MS,
1340
+ } = {}) {
1341
+ const warnings = [];
1342
+ const capacity = managedBrowserCapacity({ processes, max });
1343
+ if (capacity.approaching) {
1344
+ warnings.push(
1345
+ `${capacity.count} of ${max} managed Chrome browsers are running (${describePorts(processes)}); ` +
1346
+ `${capacity.remaining} slot left before starts are refused. Stop what you no longer need.`,
1347
+ );
905
1348
  }
1349
+ const stale = staleManagedBrowsers(processes, { maxAgeMs: staleMaxAgeMs });
1350
+ if (stale.length) {
1351
+ const hours = Math.floor(staleMaxAgeMs / (60 * 60 * 1000));
1352
+ warnings.push(
1353
+ `${stale.length} managed browser${stale.length === 1 ? '' : 's'} ${stale.length === 1 ? 'has' : 'have'} been running over ${hours}h ` +
1354
+ `(${describePorts(stale)}), likely left over from a finished session. ` +
1355
+ `Stop a tracked browser with scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}". ` +
1356
+ `Use scripts/stop.mjs --reap --dry-run and scripts/stop.mjs --prune only for untracked browsers.`,
1357
+ );
1358
+ }
1359
+ return warnings;
1360
+ }
906
1361
 
1362
+ // The one gate deciding whether an already-running managed browser may be adopted. Both the explicit
1363
+ // --port path and the auto-allocated path go through this: they used to diverge, and the
1364
+ // auto-allocated path skipped reuse entirely, so every bare `start` spawned another browser.
1365
+ export function managedBrowserReuseDecision({
1366
+ safety,
1367
+ state,
1368
+ ownerToken,
1369
+ includeGoogle = false,
1370
+ profileName = null,
1371
+ headless = false,
1372
+ forceProfileSync = false,
1373
+ }) {
1374
+ if (!safety?.ok) return { ok: false, reason: safety?.reason || 'missing-managed-state' };
1375
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1376
+ if (!ownership.ok) return { ok: false, reason: ownership.reason, ownerId: ownership.ownerId };
1377
+ const fail = (reason) => ({ ok: false, reason, ownerId: ownership.ownerId });
1378
+ // Never adopt across Google modes: a stripped start must not inherit a Google-included browser
1379
+ // (logout risk for the source profile), and a Google workflow must not inherit a stripped one.
1380
+ if (Boolean(state?.includeGoogle) !== Boolean(includeGoogle)) return fail('google-mode-mismatch');
1381
+ // --sync means "I want freshly copied credentials", so handing back a running browser built from
1382
+ // an older copy would silently defeat the request.
1383
+ if (forceProfileSync) return fail('sync-requested');
1384
+ // Adopting a browser built from a different profile (or a fresh, signed-out clone) would run the
1385
+ // caller's automation against the wrong account.
1386
+ if ((state?.profileName || null) !== (profileName || null)) return fail('profile-mismatch');
1387
+ // Headless is fixed at launch, so a windowed request cannot be served by a headless browser.
1388
+ if (Boolean(state?.headless) !== Boolean(headless)) return fail('headless-mismatch');
1389
+ return { ok: true, ownerId: ownership.ownerId, state };
1390
+ }
1391
+
1392
+ // Find a live managed browser the caller can prove it owns, on any port. An auto-allocated start
1393
+ // begins at DEFAULT_PORT, so without this a session whose browser landed on :9301 would look at
1394
+ // :9222, find nothing, and launch a second browser on every subsequent start.
1395
+ export function findReusableManagedBrowser({
1396
+ ownerToken,
1397
+ includeGoogle = false,
1398
+ profileName = null,
1399
+ headless = false,
1400
+ forceProfileSync = false,
1401
+ processes = listManagedChromeProcesses(),
1402
+ } = {}) {
1403
+ if (!normalizeOwnerValue(ownerToken)) return null;
1404
+ if (forceProfileSync) return null;
1405
+ for (const entry of processes) {
1406
+ const state = readManagedState(stateFileForPort(entry.port));
1407
+ if (!state || Number(state.pid) !== Number(entry.pid)) continue;
1408
+ const decision = managedBrowserReuseDecision({
1409
+ safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync,
1410
+ });
1411
+ if (decision.ok) return { ...entry, state };
1412
+ }
907
1413
  return null;
908
1414
  }
909
1415
 
@@ -967,6 +1473,8 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
967
1473
  includeGoogle: Boolean(includeGoogle),
968
1474
  managedToken,
969
1475
  ...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
1476
+ // Who launched this browser, so a leaked one is attributable instead of anonymous.
1477
+ launchedByPid: process.pid,
970
1478
  args,
971
1479
  startedAt: new Date().toISOString(),
972
1480
  }, null, 2));
@@ -1008,9 +1516,54 @@ export async function startChrome({
1008
1516
  const providedOwnerToken = normalizeOwnerValue(ownerToken);
1009
1517
  const effectiveOwnerToken = providedOwnerToken || generateOwnerToken();
1010
1518
  const normalizedOwnerId = normalizeOwnerValue(ownerId);
1519
+ if (!normalizedOwnerId) {
1520
+ throw new Error([
1521
+ 'Refusing to start managed Chrome without an owner id.',
1522
+ 'An unowned browser cannot be adopted or stopped by anything: its owner token exists only in the',
1523
+ 'caller that started it, so once that process exits the browser leaks with no way to reclaim it.',
1524
+ 'Pass ownerId with a stable name for the task that owns this browser, for example ownerId: "ai-chat".',
1525
+ 'From the command line, start.mjs stamps the owner for you; pass --owner-id to override it.',
1526
+ ].join(' '));
1527
+ }
1011
1528
  const { requestedProfileName, resolvedProfileName } = resolveStartProfileName({ profileName, taskName, defaultProfileName });
1012
1529
  ensureCacheDir();
1013
1530
 
1531
+ // Clean up before counting, so the cap reflects browsers that are actually reachable. Orphans are
1532
+ // browsers no lifecycle file tracks: nothing can address or stop them, so they are pure garbage.
1533
+ const reaped = reapOrphanedChromes();
1534
+ if (reaped.reaped.length) {
1535
+ console.error(`⟳ Reaped ${reaped.reaped.length} untracked managed browser${reaped.reaped.length === 1 ? '' : 's'} (${describePorts(reaped.reaped)})`);
1536
+ try {
1537
+ pruneChromeClones({ keepPorts: [normalizedPort] });
1538
+ } catch {
1539
+ // Best-effort disk cleanup must never block a launch.
1540
+ }
1541
+ }
1542
+
1543
+ const liveBrowsers = listManagedChromeProcesses();
1544
+ for (const warning of managedBrowserStartupWarnings({ processes: liveBrowsers })) {
1545
+ console.error(`⚠ ${warning}`);
1546
+ }
1547
+ // Prefer returning a browser the caller already owns over adding another. For an auto-allocated
1548
+ // start that means searching every port, since the caller's browser may not be on DEFAULT_PORT.
1549
+ // This is the single biggest source of the leak: every bare start used to mean one more Chrome.
1550
+ let reusable = null;
1551
+ if (providedOwnerToken) {
1552
+ const candidates = autoAllocatePort ? liveBrowsers : liveBrowsers.filter((entry) => entry.port === normalizedPort);
1553
+ const found = findReusableManagedBrowser({
1554
+ ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
1555
+ profileName: resolvedProfileName, headless, forceProfileSync,
1556
+ });
1557
+ if (found && await browserWSEndpoint(found.port)) {
1558
+ reusable = found;
1559
+ normalizedPort = found.port;
1560
+ }
1561
+ }
1562
+
1563
+ // Only a genuine reuse is exempt from the cap. A browser merely occupying the port we would start
1564
+ // from is not reusable, so it must not buy a free pass past the limit.
1565
+ if (!reusable) assertManagedBrowserCapacity({ processes: liveBrowsers });
1566
+
1014
1567
  while (true) {
1015
1568
  const portLock = acquirePortLock(normalizedPort, { ownerId: normalizedOwnerId });
1016
1569
  if (!portLock) {
@@ -1024,36 +1577,58 @@ export async function startChrome({
1024
1577
 
1025
1578
  if (await browserWSEndpoint(normalizedPort)) {
1026
1579
  const safety = managedBrowserSafetyForPort(normalizedPort);
1580
+ const state = readManagedStateForPort(normalizedPort);
1581
+ const reuse = managedBrowserReuseDecision({
1582
+ safety, state, ownerToken: providedOwnerToken, includeGoogle,
1583
+ profileName: resolvedProfileName, headless, forceProfileSync,
1584
+ });
1585
+ // Reuse first, on both paths. An auto-allocated start used to skip this entirely and walk to
1586
+ // the next free port, so a session that called start twice got two browsers instead of one.
1587
+ if (reuse.ok) {
1588
+ return {
1589
+ status: 'reused',
1590
+ port: normalizedPort,
1591
+ headless: Boolean(state?.headless),
1592
+ includeGoogle: Boolean(state?.includeGoogle),
1593
+ ownerToken: effectiveOwnerToken,
1594
+ ownerId: reuse.ownerId,
1595
+ ownerTokenGenerated: false,
1596
+ };
1597
+ }
1027
1598
  if (!autoAllocatePort) {
1028
1599
  if (!safety.ok) {
1029
1600
  throw new Error(
1030
1601
  `Chrome DevTools is already listening on :${normalizedPort}, but it is not a Browser Tools managed browser (${safety.reason}). Use a different --port or stop that browser manually.`,
1031
1602
  );
1032
1603
  }
1033
- const state = readManagedStateForPort(normalizedPort);
1034
- const ownership = managedBrowserOwnershipSafety({ state, ownerToken: providedOwnerToken });
1035
- if (!ownership.ok) {
1604
+ if (reuse.reason === 'google-mode-mismatch') {
1036
1605
  throw new Error(
1037
- `Chrome DevTools on :${normalizedPort} is owned by another Browser Tools agent (${ownership.reason}). Use a different --port or provide the correct --owner-token.`,
1606
+ `Chrome on :${normalizedPort} is running with Google ${state?.includeGoogle ? 'included' : 'excluded'}, but this start requested Google ${includeGoogle ? 'included' : 'excluded'}. Stop it with scripts/stop.mjs --clean and start again.`,
1038
1607
  );
1039
1608
  }
1040
- // Never reuse across a different Google mode: a default (stripped) start must not adopt a
1041
- // Google-included browser (logout risk), and a Google workflow must not adopt a stripped one.
1042
- if (Boolean(state?.includeGoogle) !== includeGoogle) {
1609
+ // A configuration mismatch is not an ownership problem: the caller owns this browser, it
1610
+ // was just built differently. Say so, rather than sending them to look for a token.
1611
+ if (reuse.reason === 'profile-mismatch') {
1043
1612
  throw new Error(
1044
- `Chrome on :${normalizedPort} is running with Google ${state?.includeGoogle ? 'included' : 'excluded'}, but this start requested Google ${includeGoogle ? 'included' : 'excluded'}. Stop it with scripts/stop.mjs --clean and start again.`,
1613
+ `Chrome on :${normalizedPort} was started with profile ${state?.profileName ? `"${state.profileName}"` : '(fresh, no profile)'}, but this start requested ${resolvedProfileName ? `"${resolvedProfileName}"` : '(fresh, no profile)'}. Reusing it would run against the wrong account. Stop it with scripts/stop.mjs --clean and start again, or pick a different --port.`,
1045
1614
  );
1046
1615
  }
1047
- return {
1048
- status: 'reused',
1049
- port: normalizedPort,
1050
- headless: Boolean(state?.headless),
1051
- includeGoogle: Boolean(state?.includeGoogle),
1052
- ownerToken: effectiveOwnerToken,
1053
- ownerId: ownership.ownerId,
1054
- ownerTokenGenerated: false,
1055
- };
1616
+ if (reuse.reason === 'headless-mismatch') {
1617
+ throw new Error(
1618
+ `Chrome on :${normalizedPort} is running ${state?.headless ? 'headless' : 'windowed'}, but this start requested ${headless ? 'headless' : 'windowed'}. Headless is fixed at launch: stop it with scripts/stop.mjs --clean and start again.`,
1619
+ );
1620
+ }
1621
+ if (reuse.reason === 'sync-requested') {
1622
+ throw new Error(
1623
+ `Chrome on :${normalizedPort} is already running, and --sync asks for a freshly copied profile. Stop it with scripts/stop.mjs --clean and start again with --sync.`,
1624
+ );
1625
+ }
1626
+ throw new Error(
1627
+ `Chrome DevTools on :${normalizedPort} is owned by another Browser Tools agent (${reuse.reason}). Use a different --port or provide the correct --owner-token.`,
1628
+ );
1056
1629
  }
1630
+ // Cannot adopt it, so this really will be a new browser: it must fit under the cap.
1631
+ assertManagedBrowserCapacity();
1057
1632
  normalizedPort = await findAvailablePort(normalizedPort + 1);
1058
1633
  continue;
1059
1634
  }
@@ -1108,15 +1683,83 @@ export async function startChrome({
1108
1683
  }
1109
1684
  }
1110
1685
  }
1111
- const proc = launchChrome({
1112
- port: normalizedPort,
1113
- profileName: resolvedProfileName,
1114
- userDataDir,
1115
- ownerToken: effectiveOwnerToken,
1116
- ownerId: normalizedOwnerId,
1117
- headless,
1118
- includeGoogle,
1119
- });
1686
+ // Reserve the slot and spawn under one cache-wide lock. The earlier check is only advisory:
1687
+ // it runs before profile sync, which can take seconds, so on its own it lets two concurrent
1688
+ // starts both observe 4 of 5 and both launch. This recount is the binding one, and it holds
1689
+ // until launchChrome has written the state file that makes the new browser visible to others.
1690
+ const launchLock = acquireLaunchLock();
1691
+ if (!launchLock) {
1692
+ throw new Error(
1693
+ 'Timed out waiting for the Browser Tools launch lock. Another start is reserving a browser slot; retry shortly.',
1694
+ );
1695
+ }
1696
+ let proc;
1697
+ let serializedReuse = null;
1698
+ try {
1699
+ const live = listManagedChromeProcesses();
1700
+ const occupied = occupiedManagedSlotPorts({ processes: live });
1701
+ if (autoAllocatePort && providedOwnerToken) {
1702
+ serializedReuse = findReusableManagedBrowser({
1703
+ ownerToken: providedOwnerToken,
1704
+ includeGoogle,
1705
+ profileName: resolvedProfileName,
1706
+ headless,
1707
+ forceProfileSync,
1708
+ processes: managedBrowserCandidatesForOccupiedSlots(live, occupied),
1709
+ });
1710
+ }
1711
+ if (!serializedReuse) {
1712
+ occupied.delete(normalizedPort);
1713
+ assertManagedBrowserCapacity({
1714
+ processes: [...occupied].map((p) =>
1715
+ live.find((entry) => entry.port === p)
1716
+ || { pid: readManagedState(stateFileForPort(p))?.pid ?? null, port: p, ageMs: null }),
1717
+ });
1718
+ proc = launchChrome({
1719
+ port: normalizedPort,
1720
+ profileName: resolvedProfileName,
1721
+ userDataDir,
1722
+ ownerToken: effectiveOwnerToken,
1723
+ ownerId: normalizedOwnerId,
1724
+ headless,
1725
+ includeGoogle,
1726
+ });
1727
+ }
1728
+ } finally {
1729
+ launchLock.release();
1730
+ }
1731
+ if (serializedReuse) {
1732
+ const ready = await waitForChromeReady(serializedReuse.port, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1733
+ if (!ready) {
1734
+ throw new Error(
1735
+ `Matching managed Chrome on :${serializedReuse.port} did not become ready after a concurrent start.`,
1736
+ );
1737
+ }
1738
+ const state = readManagedStateForPort(serializedReuse.port);
1739
+ const reuse = managedBrowserReuseDecision({
1740
+ safety: managedBrowserSafetyForPort(serializedReuse.port),
1741
+ state,
1742
+ ownerToken: providedOwnerToken,
1743
+ includeGoogle,
1744
+ profileName: resolvedProfileName,
1745
+ headless,
1746
+ forceProfileSync,
1747
+ });
1748
+ if (!reuse.ok) {
1749
+ throw new Error(
1750
+ `Matching managed Chrome on :${serializedReuse.port} changed while a concurrent start was completing (${reuse.reason}).`,
1751
+ );
1752
+ }
1753
+ return {
1754
+ status: 'reused',
1755
+ port: serializedReuse.port,
1756
+ headless: Boolean(state?.headless),
1757
+ includeGoogle: Boolean(state?.includeGoogle),
1758
+ ownerToken: effectiveOwnerToken,
1759
+ ownerId: reuse.ownerId,
1760
+ ownerTokenGenerated: false,
1761
+ };
1762
+ }
1120
1763
  const ready = await waitForChromeReady(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1121
1764
  if (!ready) {
1122
1765
  stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
@@ -1156,6 +1799,20 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1156
1799
  return { status: 'missing', port: normalizedPort, cleaned: false };
1157
1800
  }
1158
1801
  if (!hasPidFile || !hasStateFile) {
1802
+ // A surviving pid file for a live process is the only handle we have on that browser. Deleting
1803
+ // it strands the process where neither stop nor a future start can see it, so keep it and let
1804
+ // the reaper deal with the process itself.
1805
+ const strandedPid = hasPidFile ? Number.parseInt(readFileSync(paths.pidFile, 'utf-8').trim(), 10) : NaN;
1806
+ if (Number.isInteger(strandedPid) && processExists(strandedPid)) {
1807
+ return {
1808
+ status: 'not-managed',
1809
+ port: normalizedPort,
1810
+ pid: strandedPid,
1811
+ cleaned: false,
1812
+ reason: 'incomplete-managed-state',
1813
+ hint: REAP_HINT,
1814
+ };
1815
+ }
1159
1816
  rmSync(paths.pidFile, { force: true });
1160
1817
  rmSync(paths.stateFile, { force: true });
1161
1818
  return { status: 'not-managed', port: normalizedPort, cleaned: false, reason: 'incomplete-managed-state' };
@@ -1176,7 +1833,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1176
1833
  return { status: 'already-gone', port: normalizedPort, pid, cleaned };
1177
1834
  }
1178
1835
 
1179
- const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1836
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken, allowUnowned: true });
1180
1837
  if (!ownership.ok) {
1181
1838
  return {
1182
1839
  status: 'not-owned',
@@ -1190,6 +1847,19 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1190
1847
  }
1191
1848
 
1192
1849
  if (!safety.ok) {
1850
+ // The process failed a safety check but is still running. Forgetting its lifecycle files here is
1851
+ // what previously turned mismatched browsers into permanent orphans, so keep them.
1852
+ if (processExists(pid)) {
1853
+ return {
1854
+ status: 'not-managed',
1855
+ port: normalizedPort,
1856
+ pid,
1857
+ cleaned: false,
1858
+ reason: safety.reason,
1859
+ command: safety.command,
1860
+ hint: REAP_HINT,
1861
+ };
1862
+ }
1193
1863
  rmSync(paths.pidFile, { force: true });
1194
1864
  rmSync(paths.stateFile, { force: true });
1195
1865
  return {
@@ -1203,7 +1873,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1203
1873
  }
1204
1874
 
1205
1875
  if (dryRun) {
1206
- return { status: 'would-stop', port: normalizedPort, pid, cleaned: false, command: safety.command, ownerId: ownership.ownerId };
1876
+ return { status: 'would-stop', port: normalizedPort, pid, cleaned: false, command: safety.command, ownerId: ownership.ownerId, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1207
1877
  }
1208
1878
 
1209
1879
  let status = 'stopped';
@@ -1239,14 +1909,23 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1239
1909
  cleaned = true;
1240
1910
  }
1241
1911
 
1242
- return { status, port: normalizedPort, pid, cleaned, error };
1912
+ return { status, port: normalizedPort, pid, cleaned, error, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1243
1913
  }
1244
1914
 
1245
1915
  // Sweep cached profile clones that are not currently in use by a running managed Chrome.
1246
1916
  // Removes the clone data dir plus its per-port sync-state and lifecycle files. A clone whose
1247
1917
  // user-data-dir is still owned by a live managed Chrome is kept. Never touches non-clone cache
1248
1918
  // entries (for example ai-chat data), because every path comes from the per-port helpers.
1249
- export function pruneChromeClones({ dryRun = false, keepPorts = [] } = {}) {
1919
+ export function reapExitCode(reaped = []) {
1920
+ return reaped.some((entry) => entry?.status === 'failed') ? 1 : 0;
1921
+ }
1922
+
1923
+ export function pruneChromeClones({ dryRun = false, keepPorts = [], assumeStoppedPorts = [] } = {}) {
1924
+ // Ports a preceding reap has freed, or would free in a dry run. Without this a `--prune --dry-run`
1925
+ // reports those clones as still in use and hides the removals the real command performs.
1926
+ const assumeStopped = new Set(
1927
+ (dryRun ? assumeStoppedPorts : []).map((value) => Number.parseInt(value, 10)),
1928
+ );
1250
1929
  const cacheDir = browserToolsCacheDir();
1251
1930
  const keep = new Set(keepPorts.map((value) => Number.parseInt(value, 10)));
1252
1931
  const removed = [];
@@ -1283,8 +1962,8 @@ export function pruneChromeClones({ dryRun = false, keepPorts = [] } = {}) {
1283
1962
  const freshDir = freshProfileDirForPort(port);
1284
1963
  // Both a stale profiled clone and a live fresh clone can share a port, so check each candidate
1285
1964
  // dir for a live owner. Removing either dir while one is in use would corrupt a running browser.
1286
- const runningData = existsSync(dataDir) ? managedBrowserForUserDataDir(dataDir) : null;
1287
- const runningFresh = existsSync(freshDir) ? managedBrowserForUserDataDir(freshDir) : null;
1965
+ const runningData = !assumeStopped.has(port) && existsSync(dataDir) ? managedBrowserForUserDataDir(dataDir) : null;
1966
+ const runningFresh = !assumeStopped.has(port) && existsSync(freshDir) ? managedBrowserForUserDataDir(freshDir) : null;
1288
1967
  const running = runningData || runningFresh;
1289
1968
  if (running) {
1290
1969
  kept.push({ port, reason: 'running', pid: running.pid, dir: runningData ? dataDir : freshDir });
@@ -1317,6 +1996,20 @@ function commandForPid(pid) {
1317
1996
  return command || null;
1318
1997
  }
1319
1998
 
1999
+ function processStartIdentity(pid) {
2000
+ const normalizedPid = Number(pid);
2001
+ if (!Number.isInteger(normalizedPid) || normalizedPid < 1) return null;
2002
+ const result = spawnSync(
2003
+ 'ps',
2004
+ ['-p', String(normalizedPid), '-o', 'lstart=', '-o', 'command='],
2005
+ { encoding: 'utf-8' },
2006
+ );
2007
+ if (result.error || result.status !== 0) return null;
2008
+ const identity = result.stdout.trim();
2009
+ if (!identity) return null;
2010
+ return createHash('sha256').update(identity, 'utf8').digest('hex');
2011
+ }
2012
+
1320
2013
  function processExists(pid) {
1321
2014
  try {
1322
2015
  process.kill(pid, 0);
@@ -1347,42 +2040,49 @@ function verifyManagedChromeProcess({ pid, port, state }) {
1347
2040
 
1348
2041
  export function isBrowserToolsUserDataDir(userDataDir) {
1349
2042
  if (!userDataDir || typeof userDataDir !== 'string') return false;
1350
- const cacheDir = browserToolsCacheDir();
1351
2043
  return userDataDir === PROFILE_DST ||
1352
2044
  userDataDir === FRESH_PROFILE_DIR ||
1353
2045
  userDataDir === profileDataDirForPort(DEFAULT_PORT) ||
1354
2046
  userDataDir === freshProfileDirForPort(DEFAULT_PORT) ||
1355
- userDataDir.startsWith(`${cacheDir}/chrome-data-`) ||
1356
- userDataDir.startsWith(`${cacheDir}/chrome-fresh-`);
2047
+ isManagedCloneDir(userDataDir);
1357
2048
  }
1358
2049
 
1359
- export function managedChromeCommandSafety({ pid, port, state, command }) {
2050
+ export function managedChromeLifecycleStateSafety({ pid, port, state }) {
1360
2051
  if (!state || state.managedBy !== 'browser-tools') {
1361
- return { ok: false, reason: 'missing-managed-state', command };
2052
+ return { ok: false, reason: 'missing-managed-state' };
1362
2053
  }
1363
2054
  if (Number(state.pid) !== Number(pid) || Number(state.port) !== Number(port)) {
1364
- return { ok: false, reason: 'state-mismatch', command };
2055
+ return { ok: false, reason: 'state-mismatch' };
1365
2056
  }
1366
2057
  if (!state.managedToken) {
1367
- return { ok: false, reason: 'missing-managed-token', command };
2058
+ return { ok: false, reason: 'missing-managed-token' };
1368
2059
  }
1369
2060
  if (!isBrowserToolsUserDataDir(state.userDataDir)) {
1370
- return { ok: false, reason: 'state-user-data-dir-mismatch', command };
2061
+ return { ok: false, reason: 'state-user-data-dir-mismatch' };
1371
2062
  }
1372
2063
 
1373
2064
  const expectedDebugPort = `--remote-debugging-port=${port}`;
1374
2065
  const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
1375
2066
  const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
1376
2067
  const expectedArgs = Array.isArray(state.args) ? state.args : [];
1377
- const isChrome = command.includes('Google Chrome') || command.includes(browserToolsChromeBin()) || command.includes(CHROME_BIN);
2068
+ if (!expectedArgs.includes(expectedDebugPort)) return { ok: false, reason: 'state-debug-port-missing' };
2069
+ if (!expectedArgs.includes(expectedUserDataDir)) return { ok: false, reason: 'state-user-data-dir-missing' };
2070
+ if (!expectedArgs.includes(expectedToken)) return { ok: false, reason: 'state-managed-token-missing' };
2071
+
2072
+ return { ok: true };
2073
+ }
2074
+
2075
+ export function managedChromeCommandSafety({ pid, port, state, command }) {
2076
+ const stateSafety = managedChromeLifecycleStateSafety({ pid, port, state });
2077
+ if (!stateSafety.ok) return { ...stateSafety, command };
2078
+
2079
+ const expectedDebugPort = `--remote-debugging-port=${port}`;
2080
+ const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
2081
+ const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
1378
2082
 
1379
- if (!isChrome) return { ok: false, reason: 'not-chrome-process', command };
1380
2083
  if (!command.includes(expectedDebugPort)) return { ok: false, reason: 'debug-port-mismatch', command };
1381
2084
  if (!command.includes(expectedUserDataDir)) return { ok: false, reason: 'user-data-dir-mismatch', command };
1382
2085
  if (!command.includes(expectedToken)) return { ok: false, reason: 'managed-token-mismatch', command };
1383
- if (!expectedArgs.includes(expectedDebugPort)) return { ok: false, reason: 'state-debug-port-missing', command };
1384
- if (!expectedArgs.includes(expectedUserDataDir)) return { ok: false, reason: 'state-user-data-dir-missing', command };
1385
- if (!expectedArgs.includes(expectedToken)) return { ok: false, reason: 'state-managed-token-missing', command };
1386
2086
 
1387
2087
  return { ok: true, command };
1388
2088
  }
package/scripts/start.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  * BROWSER_TOOLS_OWNER_TOKEN="<owner token>" scripts/start.mjs
14
14
  */
15
15
 
16
- import { hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
16
+ import { CLI_OWNER_ID, hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
17
17
 
18
18
  const args = process.argv.slice(2);
19
19
  const profileName = requiredOptionValue(args, '--profile', null);
@@ -24,7 +24,7 @@ const includeGoogle = hasFlag(args, '--include-google');
24
24
  const explicitPort = args.includes('--port');
25
25
  const port = parsePort(args);
26
26
  const ownerToken = parseOwnerToken(args);
27
- const ownerId = parseOwnerId(args);
27
+ const ownerId = parseOwnerId(args) || CLI_OWNER_ID;
28
28
 
29
29
  try {
30
30
  const result = await startChrome({ port, profileName, taskName, forceProfileSync, autoAllocatePort: !explicitPort, ownerToken, ownerId, headless, includeGoogle });
package/scripts/stop.mjs CHANGED
@@ -8,11 +8,24 @@
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 (remove all cached clones not in use)
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)
13
+ * scripts/stop.mjs --reap --dry-run (list them without killing anything)
14
+ * scripts/stop.mjs --status (show how many managed browsers are running)
12
15
  * scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
13
16
  */
14
17
 
15
- import { hasFlag, parseOwnerToken, parsePort, pruneChromeClones, stopChrome } from './browser-control.mjs';
18
+ import {
19
+ hasFlag,
20
+ managedBrowserCapacity,
21
+ managedBrowserStartupWarnings,
22
+ parseOwnerToken,
23
+ parsePort,
24
+ pruneChromeClones,
25
+ reapExitCode,
26
+ reapOrphanedChromes,
27
+ stopChrome,
28
+ } from './browser-control.mjs';
16
29
 
17
30
  const args = process.argv.slice(2);
18
31
  const port = parsePort(args);
@@ -20,8 +33,48 @@ const clean = hasFlag(args, '--clean');
20
33
  const dryRun = hasFlag(args, '--dry-run');
21
34
  const ownerToken = parseOwnerToken(args);
22
35
 
36
+ function reportReaped(reaped, wasDryRun) {
37
+ if (!reaped.length) {
38
+ console.log('No untracked managed browsers found.');
39
+ return;
40
+ }
41
+ for (const entry of reaped) {
42
+ const verb = wasDryRun ? 'Would reap' : entry.status === 'failed' ? '✗ Failed to reap' : '✓ Reaped';
43
+ console.log(`${verb} :${entry.port} (PID ${entry.pid})`);
44
+ }
45
+ }
46
+
47
+ if (hasFlag(args, '--status')) {
48
+ const capacity = managedBrowserCapacity();
49
+ console.log(`${capacity.count} of ${capacity.max} managed Chrome browsers running, ${capacity.remaining} slot(s) free`);
50
+ for (const entry of capacity.processes) {
51
+ const hours = Number.isFinite(entry.ageMs) ? (entry.ageMs / 3600000).toFixed(1) : '?';
52
+ console.log(` :${entry.port} PID ${entry.pid} up ${hours}h`);
53
+ }
54
+ for (const warning of managedBrowserStartupWarnings({ processes: capacity.processes, max: capacity.max })) {
55
+ console.log(`⚠ ${warning}`);
56
+ }
57
+ process.exit(0);
58
+ }
59
+
60
+ if (hasFlag(args, '--reap')) {
61
+ const result = reapOrphanedChromes({ dryRun });
62
+ reportReaped(result.reaped, dryRun);
63
+ // A caller reaping to free a slot must be able to tell that a browser survived.
64
+ process.exit(reapExitCode(result.reaped));
65
+ }
66
+
23
67
  if (hasFlag(args, '--prune')) {
24
- const prune = pruneChromeClones({ dryRun });
68
+ // Reap first: a clone dir held open by an untracked browser is otherwise unreclaimable, which is
69
+ // how 2.4 GB of clones survived every prune during the leak.
70
+ const reaped = reapOrphanedChromes({ dryRun });
71
+ reportReaped(reaped.reaped, dryRun);
72
+ // A real prune reclaims the clones of the browsers just reaped. Tell the dry run to assume the
73
+ // same, otherwise the preview reports those clones as in use and understates what will be removed.
74
+ const freedPorts = reaped.reaped
75
+ .filter((entry) => entry.status === 'would-reap' || entry.status === 'reaped' || entry.status === 'killed' || entry.status === 'already-gone')
76
+ .map((entry) => entry.port);
77
+ const prune = pruneChromeClones({ dryRun, assumeStoppedPorts: dryRun ? freedPorts : [] });
25
78
  if (!prune.removed.length && !prune.kept.length) {
26
79
  console.log('No cached Chrome clones found.');
27
80
  }
@@ -32,7 +85,7 @@ if (hasFlag(args, '--prune')) {
32
85
  const count = entry.paths.length;
33
86
  console.log(`${dryRun ? '• Would remove' : '✓ Removed'} clone for :${entry.port} (${count} item${count === 1 ? '' : 's'})`);
34
87
  }
35
- process.exit(0);
88
+ process.exit(reapExitCode(reaped.reaped));
36
89
  }
37
90
 
38
91
  const result = stopChrome({ port, clean, dryRun, ownerToken });
@@ -45,7 +98,8 @@ if (result.status === 'missing') {
45
98
  if (result.status === 'would-stop') {
46
99
  console.log(`✓ Dry run: would stop managed Chrome (PID ${result.pid}) on :${port}`);
47
100
  } else if (result.status === 'stopped') {
48
- console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}`);
101
+ const reclaimed = result.reclaimedUnowned ? ' (reclaimed: nothing owned it)' : '';
102
+ console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}${reclaimed}`);
49
103
  } else if (result.status === 'killed') {
50
104
  console.log(`✓ Killed managed Chrome (PID ${result.pid}) on :${port} after SIGTERM did not exit`);
51
105
  } else if (result.status === 'already-gone') {
@@ -54,6 +108,7 @@ if (result.status === 'would-stop') {
54
108
  const target = result.pid ? `PID ${result.pid}` : `port ${port}`;
55
109
  console.error(`✗ Refusing to stop ${target}: ${result.reason}`);
56
110
  console.error(' Safety rule: stop.mjs only kills Chrome processes launched by start.mjs.');
111
+ if (result.hint) console.error(` ${result.hint}`);
57
112
  process.exit(1);
58
113
  } else if (result.status === 'not-owned') {
59
114
  const owner = result.ownerId ? ` owned by ${result.ownerId}` : '';