@rezkam/browser-tools 0.3.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,8 @@ 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
+ import { fileURLToPath } from 'node:url';
17
18
  import puppeteer from 'puppeteer-core';
18
19
 
19
20
  export const DEFAULT_PORT = 9222;
@@ -35,9 +36,21 @@ export const FRESH_PROFILE_DIR = join(CACHE_DIR, 'chrome-fresh');
35
36
  export const PROFILE_SYNC_STATE_FILE = join(CACHE_DIR, 'chrome-profile-sync.json');
36
37
  export const OWNER_TOKEN_ENV = 'BROWSER_TOOLS_OWNER_TOKEN';
37
38
  export const OWNER_ID_ENV = 'BROWSER_TOOLS_OWNER_ID';
39
+ // Owner stamped on a launch started straight from the command line, so no browser is ever unowned.
40
+ export const CLI_OWNER_ID = 'cli';
38
41
  export const OWNER_TOKEN_HASH_ALGORITHM = 'sha256';
39
42
  export const PORT_LOCK_STALE_MS = 30000;
40
43
 
44
+ // Concurrency guardrails. A managed Chrome costs roughly 800 MB across a browser process and its
45
+ // helpers, so an unbounded fan-out of `start` calls exhausts memory long before it exhausts ports.
46
+ // The cap is deliberately small: agents should reuse or stop a browser, not accumulate them.
47
+ export const DEFAULT_MAX_MANAGED_BROWSERS = 5;
48
+ export const MAX_BROWSERS_ENV = 'BROWSER_TOOLS_MAX_BROWSERS';
49
+ // A managed browser older than this is almost certainly a leftover from a finished agent session.
50
+ export const STALE_BROWSER_AGE_MS = 2 * 60 * 60 * 1000;
51
+ 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.';
53
+
41
54
  export function agentConfigRoot() {
42
55
  return process.env.AGENT_CONFIG_DIR || join(homedir(), '.agents');
43
56
  }
@@ -76,6 +89,7 @@ export function browserToolsRuntimeConfig({ configDir = browserToolsConfigDir()
76
89
  chromeSourceDir: expandHomePath(process.env.BROWSER_TOOLS_CHROME_SOURCE_DIR || config.directories?.chromeSourceDir || config.sourceDir || DEFAULT_CHROME_SRC),
77
90
  cacheDir: expandHomePath(process.env.BROWSER_TOOLS_CACHE_DIR || config.directories?.cacheDir || DEFAULT_CACHE_DIR),
78
91
  artifactDir: expandHomePath(process.env.BROWSER_TOOLS_ARTIFACT_DIR || config.directories?.artifactDir || DEFAULT_ARTIFACT_DIR),
92
+ maxBrowsers: config.browser?.maxBrowsers ?? config.maxBrowsers ?? null,
79
93
  };
80
94
  }
81
95
 
@@ -257,7 +271,9 @@ function buildOwnerState({ ownerToken, ownerId = null }) {
257
271
  };
258
272
  }
259
273
 
260
- export function managedBrowserOwnershipSafety({ state, ownerToken }) {
274
+ // allowUnowned is for stopping only. Adoption and connection must never opt in, or an unowned
275
+ // browser could be hijacked by any caller instead of merely being cleaned up.
276
+ export function managedBrowserOwnershipSafety({ state, ownerToken, allowUnowned = false }) {
261
277
  if (!state || state.managedBy !== 'browser-tools') {
262
278
  return { ok: false, reason: 'missing-managed-state' };
263
279
  }
@@ -266,6 +282,11 @@ export function managedBrowserOwnershipSafety({ state, ownerToken }) {
266
282
  }
267
283
  const token = normalizeOwnerValue(ownerToken);
268
284
  if (!token) {
285
+ // Nothing owns this browser, so no surviving caller holds a token that could ever stop it.
286
+ // Refusing here is what makes a leaked browser permanent, so allow the reclaim and report it.
287
+ if (allowUnowned && !normalizeOwnerValue(state.ownerId)) {
288
+ return { ok: true, ownerId: null, reclaimedUnowned: true };
289
+ }
269
290
  return { ok: false, reason: 'missing-owner-token', ownerId: state.ownerId || null };
270
291
  }
271
292
  if (ownerTokenHash(token) !== state.ownerTokenHash) {
@@ -286,6 +307,55 @@ export function portLockDirForPort(port) {
286
307
  return join(browserToolsCacheDir(), `chrome-${normalizePort(port)}.lock`);
287
308
  }
288
309
 
310
+ function lockDirectoryIsActive(lockDir, { staleMs = PORT_LOCK_STALE_MS } = {}) {
311
+ if (!existsSync(lockDir)) return false;
312
+
313
+ let lockState = null;
314
+ try {
315
+ lockState = safeReadJson(join(lockDir, 'lock.json'));
316
+ } catch {
317
+ lockState = null;
318
+ }
319
+ const ownerPid = Number(lockState?.pid);
320
+ let staleByAge;
321
+ try {
322
+ staleByAge = Date.now() - statSync(lockDir).mtimeMs > staleMs;
323
+ } catch {
324
+ staleByAge = true;
325
+ }
326
+
327
+ let stale = staleByAge;
328
+ if (Number.isInteger(ownerPid) && ownerPid > 0) {
329
+ const recordedIdentity = typeof lockState?.processStartIdentity === 'string'
330
+ ? lockState.processStartIdentity
331
+ : null;
332
+ const currentIdentity = recordedIdentity ? processStartIdentity(ownerPid) : null;
333
+ if (recordedIdentity && currentIdentity === recordedIdentity) {
334
+ return true;
335
+ }
336
+ stale = !processExists(ownerPid) || staleByAge;
337
+ }
338
+ if (!stale) return true;
339
+ rmSync(lockDir, { recursive: true, force: true });
340
+ return false;
341
+ }
342
+
343
+ function releaseOwnedLockDirectory(lockDir, lockId) {
344
+ let lockState;
345
+ try {
346
+ lockState = safeReadJson(join(lockDir, 'lock.json'));
347
+ } catch {
348
+ return false;
349
+ }
350
+ if (!lockState || lockState.lockId !== lockId) return false;
351
+ rmSync(lockDir, { recursive: true, force: true });
352
+ return true;
353
+ }
354
+
355
+ export function portLockIsActive(port = DEFAULT_PORT, options = {}) {
356
+ return lockDirectoryIsActive(portLockDirForPort(port), options);
357
+ }
358
+
289
359
  export function chromePaths(port = DEFAULT_PORT) {
290
360
  const runtime = browserToolsRuntimeConfig();
291
361
  return {
@@ -387,12 +457,16 @@ export function acquirePortLock(port = DEFAULT_PORT, { ownerId = null, staleMs =
387
457
  const normalizedPort = normalizePort(port);
388
458
  ensureCacheDir();
389
459
  const lockDir = portLockDirForPort(normalizedPort);
460
+ const lockId = randomUUID();
461
+ const ownerProcessStartIdentity = processStartIdentity(process.pid);
390
462
 
391
463
  for (let attempt = 0; attempt < 2; attempt += 1) {
392
464
  try {
393
465
  mkdirSync(lockDir, { mode: 0o700 });
394
466
  writePrivateFile(join(lockDir, 'lock.json'), JSON.stringify({
467
+ lockId,
395
468
  pid: process.pid,
469
+ processStartIdentity: ownerProcessStartIdentity,
396
470
  port: normalizedPort,
397
471
  ownerId: normalizeOwnerValue(ownerId),
398
472
  createdAt: new Date().toISOString(),
@@ -401,30 +475,14 @@ export function acquirePortLock(port = DEFAULT_PORT, { ownerId = null, staleMs =
401
475
  port: normalizedPort,
402
476
  lockDir,
403
477
  release() {
404
- rmSync(lockDir, { recursive: true, force: true });
478
+ releaseOwnedLockDirectory(lockDir, lockId);
405
479
  },
406
480
  };
407
481
  } catch (e) {
408
482
  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 });
483
+ // A start that crashed mid-write can leave a partial or corrupt lock.json. Fresh partial locks
484
+ // remain active until they age out, while stale locks are reclaimed by the shared lock check.
485
+ if (portLockIsActive(normalizedPort, { staleMs })) return null;
428
486
  }
429
487
  }
430
488
 
@@ -527,6 +585,14 @@ export function buildBrowserToolsConfig({ sourceDir = browserToolsChromeSourceDi
527
585
  },
528
586
  browser: {
529
587
  chromeBin: existingBrowser.chromeBin || browserToolsChromeBin(),
588
+ // Only carry an explicitly configured cap. Writing a default here would freeze the value and
589
+ // silently override a later change to the built-in limit.
590
+ // browserToolsRuntimeConfig also honours a legacy top-level maxBrowsers, so carry that form
591
+ // through too. Nested wins when both exist, matching how the value is read.
592
+ ...(() => {
593
+ const cap = existingBrowser.maxBrowsers ?? existing?.maxBrowsers;
594
+ return cap === undefined || cap === null ? {} : { maxBrowsers: cap };
595
+ })(),
530
596
  },
531
597
  profiles: Object.fromEntries(profiles.map((profile) => [profile.folder, profile])),
532
598
  aliases: buildAliases(profiles),
@@ -886,8 +952,19 @@ export function headlessUserAgent(chromeBin = browserToolsChromeBin()) {
886
952
 
887
953
  export function managedBrowserForUserDataDir(userDataDir) {
888
954
  const result = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf-8' });
889
- if (result.error || result.status !== 0) return null;
890
- const chromeBin = browserToolsChromeBin();
955
+ if (result.error) {
956
+ const error = new Error(
957
+ `Cannot read the managed Chrome process inventory: ps failed to start (${result.error.code || 'unknown error'}). Refusing to treat a profile clone as unused.`,
958
+ );
959
+ error.cause = result.error;
960
+ throw error;
961
+ }
962
+ if (result.status !== 0) {
963
+ const outcome = result.signal ? `signal ${result.signal}` : `status ${result.status ?? 'unknown'}`;
964
+ throw new Error(
965
+ `Cannot read the managed Chrome process inventory: ps exited with ${outcome}. Refusing to treat a profile clone as unused.`,
966
+ );
967
+ }
891
968
 
892
969
  for (const line of result.stdout.split('\n')) {
893
970
  const trimmed = line.trim();
@@ -896,17 +973,459 @@ export function managedBrowserForUserDataDir(userDataDir) {
896
973
  if (!match) continue;
897
974
  const pid = Number.parseInt(match[1], 10);
898
975
  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 };
976
+ const managed = managedChromeProcessFromCommand({ pid, command });
977
+ if (!managed || managed.userDataDir !== userDataDir) continue;
978
+ return managed;
905
979
  }
906
980
 
907
981
  return null;
908
982
  }
909
983
 
984
+ // Convert a ps etime field ("MM:SS", "HH:MM:SS", or "DD-HH:MM:SS") to milliseconds.
985
+ export function parseProcessAgeMs(etime) {
986
+ const raw = String(etime ?? '').trim();
987
+ const match = raw.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
988
+ if (!match) return null;
989
+ const [, days, hours, minutes, seconds] = match;
990
+ const total = ((Number(days || 0) * 24 + Number(hours || 0)) * 60 + Number(minutes)) * 60 + Number(seconds);
991
+ return total * 1000;
992
+ }
993
+
994
+ // Parse `ps -axo pid=,etime=,command=` output into the managed *browser* processes only.
995
+ //
996
+ // Pure so the filtering rules stay testable without spawning Chrome. Two exclusions matter:
997
+ // renderer/GPU/utility helpers inherit --user-data-dir and the managed token from their parent, so
998
+ // counting them would inflate the browser count roughly tenfold; and a user-data-dir outside our
999
+ // cache dir is somebody else's Chrome, which we must never count or kill.
1000
+ // Extract --user-data-dir from a Chrome command line. Chrome does not quote this argument, and the
1001
+ // path is user-configurable, so it can legitimately contain spaces ("/Volumes/My Drive/..."). Read
1002
+ // to the next " --" rather than to the next space: a \S+ capture truncates the path, the cache-dir
1003
+ // test then fails, and the browser silently disappears from the inventory.
1004
+ // Strip trailing separators so a configured cache dir of "/tmp/cache/" builds the same prefix that
1005
+ // join() produces when launching. Without this the prefix test becomes "/tmp/cache//chrome-", every
1006
+ // managed browser disappears from the inventory, and the cap silently stops applying.
1007
+ export function normalizeCacheDirPath(cacheDir) {
1008
+ const value = String(cacheDir ?? '');
1009
+ return value ? resolve(value) : value;
1010
+ }
1011
+
1012
+ // Does this user-data-dir sit inside the cache dir as one of our clone directories? Compared on path
1013
+ // segments rather than raw text so a sibling like "/opt/cache-other" can never match "/opt/cache".
1014
+ export function isManagedCloneDir(userDataDir, cacheDir = browserToolsCacheDir()) {
1015
+ if (!userDataDir) return false;
1016
+ const root = normalizeCacheDirPath(cacheDir);
1017
+ const candidate = resolve(userDataDir);
1018
+ if (!candidate.startsWith(`${root}/`)) return false;
1019
+ const rest = candidate.slice(root.length + 1);
1020
+ return /^chrome-(?:data|fresh)-/.test(rest);
1021
+ }
1022
+
1023
+ export function parseUserDataDirArg(command) {
1024
+ const match = String(command ?? '').match(/--user-data-dir=(.+?)(?=\s--|$)/);
1025
+ return match ? match[1].trim() : null;
1026
+ }
1027
+
1028
+ // Decide whether one ps line is a managed browser, and describe it. Shared by the inventory scan and
1029
+ // by the pre-signal recheck in the reaper, so both apply exactly the same definition.
1030
+ export function managedChromeProcessFromCommand({ pid, etime = null, command, cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() }) {
1031
+ if (!command) return null;
1032
+ if (/--type=/.test(command)) return null;
1033
+ if (!command.includes('--pi-browser-tools-managed=')) return null;
1034
+ const portMatch = command.match(/--remote-debugging-port=(\d+)/);
1035
+ if (!portMatch) return null;
1036
+ const userDataDir = parseUserDataDirArg(command);
1037
+ if (!isManagedCloneDir(userDataDir, cacheDir)) return null;
1038
+ const tokenMatch = command.match(/--pi-browser-tools-managed=(\S+)/);
1039
+ return {
1040
+ pid: Number.parseInt(String(pid), 10),
1041
+ port: normalizePort(portMatch[1]),
1042
+ ageMs: parseProcessAgeMs(etime),
1043
+ userDataDir,
1044
+ // Per-launch UUID. Two different browsers never share one, so it pins process identity across
1045
+ // a PID that may have been recycled between the scan and the signal.
1046
+ managedToken: tokenMatch ? tokenMatch[1] : null,
1047
+ command,
1048
+ };
1049
+ }
1050
+
1051
+ export function parseManagedChromeProcesses(psOutput, { cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() } = {}) {
1052
+ const found = [];
1053
+ for (const line of String(psOutput ?? '').split('\n')) {
1054
+ const match = line.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);
1055
+ if (!match) continue;
1056
+ const [, pidText, etime, command] = match;
1057
+ const entry = managedChromeProcessFromCommand({ pid: pidText, etime, command, cacheDir, chromeBin });
1058
+ if (entry) found.push(entry);
1059
+ }
1060
+ return found;
1061
+ }
1062
+
1063
+ // Is this PID, right now, still one of our managed browsers? Used immediately before sending a
1064
+ // signal so a recycled PID cannot be hit.
1065
+ // Is `current` the same browser the scan saw? A PID alone is not identity: it can be recycled by a
1066
+ // different managed Chrome, and signalling on PID-only would then kill a healthy browser.
1067
+ export function managedBrowserIdentityMatches(expected, current) {
1068
+ if (!expected || !current) return false;
1069
+ if (Number(expected.pid) !== Number(current.pid)) return false;
1070
+ if (Number(expected.port) !== Number(current.port)) return false;
1071
+ if (expected.userDataDir !== current.userDataDir) return false;
1072
+ // The per-launch token is the strongest signal: a reused PID running a fresh Chrome has a new one.
1073
+ if (expected.managedToken && current.managedToken && expected.managedToken !== current.managedToken) return false;
1074
+ return true;
1075
+ }
1076
+
1077
+ export function verifyManagedChromePid(pid, { cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() } = {}) {
1078
+ const command = commandForPid(pid);
1079
+ if (!command) return null;
1080
+ return managedChromeProcessFromCommand({ pid, command, cacheDir, chromeBin });
1081
+ }
1082
+
1083
+ // The live inventory of managed browsers. This reads the process table rather than the lifecycle
1084
+ // files on purpose: the files can be deleted while a browser keeps running, which is precisely how
1085
+ // a previous leak became invisible to `stop`. Processes cannot lie about existing.
1086
+ export function listManagedChromeProcesses() {
1087
+ const result = spawnSync('ps', ['-axo', 'pid=,etime=,command='], { encoding: 'utf-8' });
1088
+ if (result.error) {
1089
+ const error = new Error(
1090
+ `Cannot read the managed Chrome process inventory: ps failed to start (${result.error.code || 'unknown error'}). Refusing to launch without enforcing the browser cap.`,
1091
+ );
1092
+ error.cause = result.error;
1093
+ throw error;
1094
+ }
1095
+ if (result.status !== 0) {
1096
+ const outcome = result.signal ? `signal ${result.signal}` : `status ${result.status ?? 'unknown'}`;
1097
+ throw new Error(
1098
+ `Cannot read the managed Chrome process inventory: ps exited with ${outcome}. Refusing to launch without enforcing the browser cap.`,
1099
+ );
1100
+ }
1101
+ return parseManagedChromeProcesses(result.stdout);
1102
+ }
1103
+
1104
+ export function maxManagedBrowsers(options = {}) {
1105
+ const raw = process.env[MAX_BROWSERS_ENV] ?? browserToolsRuntimeConfig(options).maxBrowsers;
1106
+ const parsed = Number.parseInt(String(raw ?? ''), 10);
1107
+ if (!Number.isInteger(parsed) || parsed < 1) return DEFAULT_MAX_MANAGED_BROWSERS;
1108
+ return parsed;
1109
+ }
1110
+
1111
+ export function launchLockDir() {
1112
+ return join(browserToolsCacheDir(), 'launch.lock');
1113
+ }
1114
+
1115
+ // A single cache-wide lock, distinct from the per-port locks. Per-port locks cannot bound total
1116
+ // concurrency: two starts racing for different ports never contend, so both can pass a 4-of-5 check
1117
+ // and both launch. Slot reservation has to serialise on one lock.
1118
+ export function acquireLaunchLock({ staleMs = PORT_LOCK_STALE_MS, waitMs = 30000, pollMs = 50 } = {}) {
1119
+ ensureCacheDir();
1120
+ const lockDir = launchLockDir();
1121
+ const deadline = Date.now() + Math.max(0, waitMs);
1122
+ const lockId = randomUUID();
1123
+ const ownerProcessStartIdentity = processStartIdentity(process.pid);
1124
+
1125
+ while (true) {
1126
+ try {
1127
+ mkdirSync(lockDir, { mode: 0o700 });
1128
+ writePrivateFile(join(lockDir, 'lock.json'), JSON.stringify({
1129
+ lockId,
1130
+ pid: process.pid,
1131
+ processStartIdentity: ownerProcessStartIdentity,
1132
+ createdAt: new Date().toISOString(),
1133
+ }, null, 2));
1134
+ return { lockDir, release() { releaseOwnedLockDirectory(lockDir, lockId); } };
1135
+ } catch (e) {
1136
+ if (e.code !== 'EEXIST') throw e;
1137
+ if (!lockDirectoryIsActive(lockDir, { staleMs })) continue;
1138
+ if (Date.now() >= deadline) return null;
1139
+ sleepSync(pollMs);
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+ // Ports that currently hold a slot. A running process holds one, and so does a browser whose state
1145
+ // file exists with a live PID: launchChrome writes that file synchronously at spawn, but the process
1146
+ // takes a moment to appear in ps, and a concurrent start must not read the gap as a free slot.
1147
+ export function occupiedManagedSlotPorts({ processes = listManagedChromeProcesses() } = {}) {
1148
+ const ports = new Set(processes.map((entry) => entry.port));
1149
+ let entries = [];
1150
+ try {
1151
+ entries = readdirSync(browserToolsCacheDir(), { withFileTypes: true });
1152
+ } catch {
1153
+ return ports;
1154
+ }
1155
+ for (const entry of entries) {
1156
+ const match = entry.name.match(/^chrome-(\d+)\.json$/);
1157
+ if (!match || !entry.isFile()) continue;
1158
+ const port = Number.parseInt(match[1], 10);
1159
+ if (ports.has(port)) continue;
1160
+ const state = readManagedState(stateFileForPort(port));
1161
+ if (!state || state.managedBy !== 'browser-tools') continue;
1162
+ const pid = Number(state.pid);
1163
+ if (!Number.isInteger(pid) || readManagedPid(pidFileForPort(port)) !== pid || !processExists(pid)) continue;
1164
+ if (verifyManagedChromeProcess({ pid, port, state }).ok) {
1165
+ ports.add(port);
1166
+ continue;
1167
+ }
1168
+ const startedAtMs = Date.parse(state.startedAt);
1169
+ const stateAgeMs = Date.now() - startedAtMs;
1170
+ const isPendingProcessScan =
1171
+ Number.isFinite(startedAtMs) &&
1172
+ stateAgeMs >= 0 &&
1173
+ stateAgeMs <= PENDING_BROWSER_STATE_MAX_AGE_MS &&
1174
+ managedChromeLifecycleStateSafety({ pid, port, state }).ok;
1175
+ if (isPendingProcessScan) ports.add(port);
1176
+ }
1177
+ return ports;
1178
+ }
1179
+
1180
+ function managedBrowserCandidatesForOccupiedSlots(processes, occupiedPorts) {
1181
+ const candidates = [...processes];
1182
+ const visiblePorts = new Set(processes.map((entry) => entry.port));
1183
+ for (const port of occupiedPorts) {
1184
+ if (visiblePorts.has(port)) continue;
1185
+ const state = readManagedState(stateFileForPort(port));
1186
+ if (!state) continue;
1187
+ candidates.push({
1188
+ pid: Number(state.pid),
1189
+ port,
1190
+ ageMs: null,
1191
+ userDataDir: state.userDataDir,
1192
+ managedToken: state.managedToken,
1193
+ });
1194
+ }
1195
+ return candidates;
1196
+ }
1197
+
1198
+ export function managedBrowserCapacity({ processes = listManagedChromeProcesses(), max = maxManagedBrowsers() } = {}) {
1199
+ const count = processes.length;
1200
+ return {
1201
+ count,
1202
+ max,
1203
+ remaining: Math.max(0, max - count),
1204
+ atCap: count >= max,
1205
+ // Warn on the last free slot so the cap is never a surprise.
1206
+ approaching: count > 0 && count === max - 1,
1207
+ processes,
1208
+ };
1209
+ }
1210
+
1211
+ export function staleManagedBrowsers(processes = listManagedChromeProcesses(), { maxAgeMs = STALE_BROWSER_AGE_MS } = {}) {
1212
+ return processes.filter((entry) => Number.isFinite(entry.ageMs) && entry.ageMs >= maxAgeMs);
1213
+ }
1214
+
1215
+ function readManagedPid(pidFile) {
1216
+ try {
1217
+ const pid = Number.parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
1218
+ return Number.isInteger(pid) ? pid : null;
1219
+ } catch {
1220
+ return null;
1221
+ }
1222
+ }
1223
+
1224
+ // A managed browser whose lifecycle files no longer describe it. `stop --port N` cannot reach these,
1225
+ // so they would otherwise accumulate forever.
1226
+ export function orphanedManagedBrowsers(processes = listManagedChromeProcesses()) {
1227
+ return processes.filter((entry) => {
1228
+ // A concurrent start holds the port lock from before the spawn until the readiness probe passes,
1229
+ // so there is a window where its browser is live but not yet written to a state file. Never reap
1230
+ // inside that window or we would kill a healthy browser out from under another agent.
1231
+ if (portLockIsActive(entry.port)) return false;
1232
+ const state = readManagedState(stateFileForPort(entry.port));
1233
+ if (!state || state.managedBy !== 'browser-tools') return true;
1234
+ if (Number(state.pid) !== Number(entry.pid)) return true;
1235
+ // Both lifecycle files must be present and agree. stopChrome refuses to manage a half-written
1236
+ // pair, so sparing one here would leave the browser unreachable by stop *and* by reap.
1237
+ const pidFile = pidFileForPort(entry.port);
1238
+ const recordedPid = readManagedPid(pidFile);
1239
+ if (recordedPid !== Number(entry.pid)) return true;
1240
+ // A PID match alone is not tracking. Apply the same lifecycle-state validation as stopChrome,
1241
+ // then compare the recorded identity with the process inventory.
1242
+ if (!managedChromeLifecycleStateSafety({ pid: entry.pid, port: entry.port, state }).ok) return true;
1243
+ if (state.userDataDir !== entry.userDataDir) return true;
1244
+ if (state.managedToken !== entry.managedToken) return true;
1245
+ // An unowned browser is tracked but unreachable: its owner token lives only in the caller that
1246
+ // started it, so once that process exits nothing can adopt or stop it. Reclaim it as garbage.
1247
+ if (!normalizeOwnerValue(state.ownerId)) return true;
1248
+ return false;
1249
+ });
1250
+ }
1251
+
1252
+ export function forcedKillStatus(exited) {
1253
+ return exited ? 'killed' : 'failed';
1254
+ }
1255
+
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.
1259
+ export function reapOrphanedChromes({ dryRun = false, processes = listManagedChromeProcesses() } = {}) {
1260
+ const orphans = orphanedManagedBrowsers(processes);
1261
+ const reaped = [];
1262
+ for (const orphan of orphans) {
1263
+ if (dryRun) {
1264
+ reaped.push({ ...orphan, status: 'would-reap' });
1265
+ continue;
1266
+ }
1267
+ // Recheck before every signal. The PID came from a scan taken moments ago; if that process has
1268
+ // since exited and the PID been recycled, an unguarded kill lands on something unrelated.
1269
+ // stopChrome already does this between SIGTERM and SIGKILL, and this path runs automatically on
1270
+ // every start, so it must be at least as careful.
1271
+ if (!managedBrowserIdentityMatches(orphan, verifyManagedChromePid(orphan.pid))) {
1272
+ reaped.push({ ...orphan, status: processExists(orphan.pid) ? 'skipped-not-managed' : 'already-gone' });
1273
+ continue;
1274
+ }
1275
+ let status = 'reaped';
1276
+ try {
1277
+ process.kill(orphan.pid, 'SIGTERM');
1278
+ if (!waitForProcessExit(orphan.pid, 2000)) {
1279
+ if (!managedBrowserIdentityMatches(orphan, verifyManagedChromePid(orphan.pid))) {
1280
+ reaped.push({ ...orphan, status: 'skipped-not-managed' });
1281
+ continue;
1282
+ }
1283
+ process.kill(orphan.pid, 'SIGKILL');
1284
+ status = forcedKillStatus(waitForProcessExit(orphan.pid, 1000));
1285
+ }
1286
+ } catch (e) {
1287
+ status = e.code === 'ESRCH' ? 'already-gone' : 'failed';
1288
+ }
1289
+ reaped.push({ ...orphan, status });
1290
+ }
1291
+ return { reaped, dryRun };
1292
+ }
1293
+
1294
+ function describePorts(processes, limit = 8) {
1295
+ const ports = processes.map((entry) => `:${entry.port}`);
1296
+ if (ports.length <= limit) return ports.join(', ');
1297
+ return `${ports.slice(0, limit).join(', ')} and ${ports.length - limit} more`;
1298
+ }
1299
+
1300
+ // Hard stop before a new launch. Refusing is better than allocating yet another port: an unbounded
1301
+ // fan-out of starts is exactly what filled memory and swap on a previous run.
1302
+ export function formatBrowserAge(ageMs) {
1303
+ if (!Number.isFinite(ageMs)) return 'unknown age';
1304
+ const hours = ageMs / 3600000;
1305
+ if (hours < 1) return `${Math.max(1, Math.round(ageMs / 60000))}m`;
1306
+ return `${hours.toFixed(1)}h`;
1307
+ }
1308
+
1309
+ // One inventory line per occupied slot. The age and the leftover marker are the whole point: they
1310
+ // turn "you are at the limit" into "these four are junk from finished sessions, clear them".
1311
+ function describeBrowserInventory(processes, { limit = 10, staleMaxAgeMs = STALE_BROWSER_AGE_MS } = {}) {
1312
+ const lines = processes.slice(0, limit).map((entry) => {
1313
+ const stale = Number.isFinite(entry.ageMs) && entry.ageMs >= staleMaxAgeMs;
1314
+ 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' : ''}`;
1316
+ });
1317
+ if (processes.length > limit) lines.push(` ... and ${processes.length - limit} more`);
1318
+ return lines.join('\n');
1319
+ }
1320
+
1321
+ export function assertManagedBrowserCapacity({ processes = listManagedChromeProcesses(), max = maxManagedBrowsers() } = {}) {
1322
+ const capacity = managedBrowserCapacity({ processes, max });
1323
+ if (!capacity.atCap) return capacity;
1324
+ const stale = staleManagedBrowsers(processes);
1325
+ const staleLine = stale.length
1326
+ ? `\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`
1327
+ : '';
1328
+ throw new Error(
1329
+ `Refusing to start another managed Chrome: ${capacity.count} of ${max} browser slots are in use.\n\n` +
1330
+ ` This is a deliberate limit, not a browser failure. Each managed Chrome costs roughly\n` +
1331
+ ` 800 MB across its process tree, so starts that are never stopped will exhaust memory\n` +
1332
+ ` and swap. The limit stops a runaway fan-out from taking the machine down.\n\n` +
1333
+ ` Currently running (${capacity.count} of ${max}):\n` +
1334
+ `${describeBrowserInventory(processes)}\n` +
1335
+ staleLine +
1336
+ `\n To continue, do one of these:\n` +
1337
+ ` 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` +
1339
+ ` scripts/stop.mjs --prune reap those, then drop their unused clones\n` +
1340
+ ` scripts/stop.mjs --port <n> --owner-token "$${OWNER_TOKEN_ENV}" stop one you own\n\n` +
1341
+ ` Best fix if these are yours: export ${OWNER_TOKEN_ENV} from the first start, and later\n` +
1342
+ ` starts reuse that browser instead of needing a new slot at all.\n\n` +
1343
+ ` If you genuinely need more at once: ${MAX_BROWSERS_ENV}=<n>`,
1344
+ );
1345
+ }
1346
+
1347
+ // Non-fatal notices printed before a launch: one for the last free slot, one for browsers old enough
1348
+ // to be leftovers from a finished session.
1349
+ export function managedBrowserStartupWarnings({
1350
+ processes = listManagedChromeProcesses(),
1351
+ max = maxManagedBrowsers(),
1352
+ staleMaxAgeMs = STALE_BROWSER_AGE_MS,
1353
+ } = {}) {
1354
+ const warnings = [];
1355
+ const capacity = managedBrowserCapacity({ processes, max });
1356
+ if (capacity.approaching) {
1357
+ warnings.push(
1358
+ `${capacity.count} of ${max} managed Chrome browsers are running (${describePorts(processes)}); ` +
1359
+ `${capacity.remaining} slot left before starts are refused. Stop what you no longer need.`,
1360
+ );
1361
+ }
1362
+ const stale = staleManagedBrowsers(processes, { maxAgeMs: staleMaxAgeMs });
1363
+ if (stale.length) {
1364
+ const hours = Math.floor(staleMaxAgeMs / (60 * 60 * 1000));
1365
+ warnings.push(
1366
+ `${stale.length} managed browser${stale.length === 1 ? '' : 's'} ${stale.length === 1 ? 'has' : 'have'} been running over ${hours}h ` +
1367
+ `(${describePorts(stale)}), likely left over from a finished session. ` +
1368
+ `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.`,
1370
+ );
1371
+ }
1372
+ return warnings;
1373
+ }
1374
+
1375
+ // The one gate deciding whether an already-running managed browser may be adopted. Both the explicit
1376
+ // --port path and the auto-allocated path go through this: they used to diverge, and the
1377
+ // auto-allocated path skipped reuse entirely, so every bare `start` spawned another browser.
1378
+ export function managedBrowserReuseDecision({
1379
+ safety,
1380
+ state,
1381
+ ownerToken,
1382
+ includeGoogle = false,
1383
+ profileName = null,
1384
+ headless = false,
1385
+ forceProfileSync = false,
1386
+ }) {
1387
+ if (!safety?.ok) return { ok: false, reason: safety?.reason || 'missing-managed-state' };
1388
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1389
+ if (!ownership.ok) return { ok: false, reason: ownership.reason, ownerId: ownership.ownerId };
1390
+ const fail = (reason) => ({ ok: false, reason, ownerId: ownership.ownerId });
1391
+ // Never adopt across Google modes: a stripped start must not inherit a Google-included browser
1392
+ // (logout risk for the source profile), and a Google workflow must not inherit a stripped one.
1393
+ if (Boolean(state?.includeGoogle) !== Boolean(includeGoogle)) return fail('google-mode-mismatch');
1394
+ // --sync means "I want freshly copied credentials", so handing back a running browser built from
1395
+ // an older copy would silently defeat the request.
1396
+ if (forceProfileSync) return fail('sync-requested');
1397
+ // Adopting a browser built from a different profile (or a fresh, signed-out clone) would run the
1398
+ // caller's automation against the wrong account.
1399
+ if ((state?.profileName || null) !== (profileName || null)) return fail('profile-mismatch');
1400
+ // Headless is fixed at launch, so a windowed request cannot be served by a headless browser.
1401
+ if (Boolean(state?.headless) !== Boolean(headless)) return fail('headless-mismatch');
1402
+ return { ok: true, ownerId: ownership.ownerId, state };
1403
+ }
1404
+
1405
+ // Find a live managed browser the caller can prove it owns, on any port. An auto-allocated start
1406
+ // begins at DEFAULT_PORT, so without this a session whose browser landed on :9301 would look at
1407
+ // :9222, find nothing, and launch a second browser on every subsequent start.
1408
+ export function findReusableManagedBrowser({
1409
+ ownerToken,
1410
+ includeGoogle = false,
1411
+ profileName = null,
1412
+ headless = false,
1413
+ forceProfileSync = false,
1414
+ processes = listManagedChromeProcesses(),
1415
+ } = {}) {
1416
+ if (!normalizeOwnerValue(ownerToken)) return null;
1417
+ if (forceProfileSync) return null;
1418
+ for (const entry of processes) {
1419
+ const state = readManagedState(stateFileForPort(entry.port));
1420
+ if (!state || Number(state.pid) !== Number(entry.pid)) continue;
1421
+ const decision = managedBrowserReuseDecision({
1422
+ safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync,
1423
+ });
1424
+ if (decision.ok) return { ...entry, state };
1425
+ }
1426
+ return null;
1427
+ }
1428
+
910
1429
  function chromeBinCandidates(chromeBin) {
911
1430
  if (String(chromeBin).includes('/')) return [chromeBin];
912
1431
  const pathDirs = (process.env.PATH || '').split(delimiter).filter(Boolean);
@@ -932,6 +1451,42 @@ function assertChromeBinaryLaunchable(chromeBin) {
932
1451
  throw new Error(`${problem}: ${chromeBin}. Set BROWSER_TOOLS_CHROME_BIN or browser.chromeBin in Browser Tools config.`);
933
1452
  }
934
1453
 
1454
+ function chromeAppBundleForExecutable(chromeBin) {
1455
+ const marker = '.app/Contents/MacOS/';
1456
+ const markerIndex = chromeBin.lastIndexOf(marker);
1457
+ if (markerIndex < 0) return null;
1458
+ return chromeBin.slice(0, markerIndex + '.app'.length);
1459
+ }
1460
+
1461
+ function launchHeadlessChromeApp({ chromeBin, args }) {
1462
+ if (process.platform !== 'darwin') return null;
1463
+ const appBundle = chromeAppBundleForExecutable(chromeBin);
1464
+ if (!appBundle) return null;
1465
+
1466
+ // The standard `open` command always makes a launched app eligible for Dock recents. Use the
1467
+ // native workspace option that opts out before Chrome registers, while retaining a new hidden
1468
+ // application instance for the isolated profile.
1469
+ const launcher = fileURLToPath(new URL('./mac-headless-launch.jxa', import.meta.url));
1470
+ const launched = spawnSync('osascript', ['-l', 'JavaScript', launcher, appBundle, ...args], {
1471
+ encoding: 'utf-8',
1472
+ });
1473
+ if (launched.error) {
1474
+ const error = new Error(`Chrome failed to launch through macOS NSWorkspace: ${launched.error.message}`);
1475
+ error.cause = launched.error;
1476
+ throw error;
1477
+ }
1478
+ if (launched.status !== 0) {
1479
+ const detail = launched.stderr.trim() || launched.stdout.trim() || `status ${launched.status}`;
1480
+ throw new Error(`Chrome failed to launch through macOS NSWorkspace: ${detail}`);
1481
+ }
1482
+
1483
+ const pid = Number.parseInt(launched.stdout.trim(), 10);
1484
+ if (!Number.isInteger(pid) || pid < 1) {
1485
+ throw new Error('Chrome launched through macOS NSWorkspace, but no process PID was returned');
1486
+ }
1487
+ return { pid };
1488
+ }
1489
+
935
1490
  export function launchChrome({ port = DEFAULT_PORT, profileName = null, userDataDir = null, ownerToken = null, ownerId = null, headless = false, includeGoogle = false } = {}) {
936
1491
  ensureCacheDir();
937
1492
  const normalizedPort = normalizePort(port);
@@ -944,15 +1499,19 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
944
1499
  assertChromeBinaryLaunchable(chromeBin);
945
1500
  const pidFile = pidFileForPort(normalizedPort);
946
1501
  const stateFile = stateFileForPort(normalizedPort);
947
- const proc = spawn(chromeBin, args, {
948
- detached: true,
949
- stdio: 'ignore',
950
- });
951
- proc.once('error', (error) => {
952
- rmSync(pidFile, { force: true });
953
- rmSync(stateFile, { force: true });
954
- console.error(`[browser-control] Chrome spawn failed: ${error.message}`);
955
- });
1502
+ let proc = headless ? launchHeadlessChromeApp({ chromeBin, args }) : null;
1503
+ if (!proc) {
1504
+ proc = spawn(chromeBin, args, {
1505
+ detached: true,
1506
+ stdio: 'ignore',
1507
+ });
1508
+ proc.once('error', (error) => {
1509
+ rmSync(pidFile, { force: true });
1510
+ rmSync(stateFile, { force: true });
1511
+ console.error(`[browser-control] Chrome spawn failed: ${error.message}`);
1512
+ });
1513
+ proc.unref();
1514
+ }
956
1515
  if (!Number.isInteger(proc.pid)) {
957
1516
  throw new Error(`Chrome failed to start: no child process PID for ${chromeBin}`);
958
1517
  }
@@ -967,10 +1526,11 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
967
1526
  includeGoogle: Boolean(includeGoogle),
968
1527
  managedToken,
969
1528
  ...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
1529
+ // Who launched this browser, so a leaked one is attributable instead of anonymous.
1530
+ launchedByPid: process.pid,
970
1531
  args,
971
1532
  startedAt: new Date().toISOString(),
972
1533
  }, null, 2));
973
- proc.unref();
974
1534
  return proc;
975
1535
  }
976
1536
 
@@ -1008,9 +1568,54 @@ export async function startChrome({
1008
1568
  const providedOwnerToken = normalizeOwnerValue(ownerToken);
1009
1569
  const effectiveOwnerToken = providedOwnerToken || generateOwnerToken();
1010
1570
  const normalizedOwnerId = normalizeOwnerValue(ownerId);
1571
+ if (!normalizedOwnerId) {
1572
+ throw new Error([
1573
+ 'Refusing to start managed Chrome without an owner id.',
1574
+ 'An unowned browser cannot be adopted or stopped by anything: its owner token exists only in the',
1575
+ 'caller that started it, so once that process exits the browser leaks with no way to reclaim it.',
1576
+ 'Pass ownerId with a stable name for the task that owns this browser, for example ownerId: "ai-chat".',
1577
+ 'From the command line, start.mjs stamps the owner for you; pass --owner-id to override it.',
1578
+ ].join(' '));
1579
+ }
1011
1580
  const { requestedProfileName, resolvedProfileName } = resolveStartProfileName({ profileName, taskName, defaultProfileName });
1012
1581
  ensureCacheDir();
1013
1582
 
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.
1585
+ const reaped = reapOrphanedChromes();
1586
+ if (reaped.reaped.length) {
1587
+ console.error(`⟳ Reaped ${reaped.reaped.length} untracked managed browser${reaped.reaped.length === 1 ? '' : 's'} (${describePorts(reaped.reaped)})`);
1588
+ try {
1589
+ pruneChromeClones({ keepPorts: [normalizedPort] });
1590
+ } catch {
1591
+ // Best-effort disk cleanup must never block a launch.
1592
+ }
1593
+ }
1594
+
1595
+ const liveBrowsers = listManagedChromeProcesses();
1596
+ for (const warning of managedBrowserStartupWarnings({ processes: liveBrowsers })) {
1597
+ console.error(`⚠ ${warning}`);
1598
+ }
1599
+ // Prefer returning a browser the caller already owns over adding another. For an auto-allocated
1600
+ // start that means searching every port, since the caller's browser may not be on DEFAULT_PORT.
1601
+ // This is the single biggest source of the leak: every bare start used to mean one more Chrome.
1602
+ let reusable = null;
1603
+ if (providedOwnerToken) {
1604
+ const candidates = autoAllocatePort ? liveBrowsers : liveBrowsers.filter((entry) => entry.port === normalizedPort);
1605
+ const found = findReusableManagedBrowser({
1606
+ ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
1607
+ profileName: resolvedProfileName, headless, forceProfileSync,
1608
+ });
1609
+ if (found && await browserWSEndpoint(found.port)) {
1610
+ reusable = found;
1611
+ normalizedPort = found.port;
1612
+ }
1613
+ }
1614
+
1615
+ // Only a genuine reuse is exempt from the cap. A browser merely occupying the port we would start
1616
+ // from is not reusable, so it must not buy a free pass past the limit.
1617
+ if (!reusable) assertManagedBrowserCapacity({ processes: liveBrowsers });
1618
+
1014
1619
  while (true) {
1015
1620
  const portLock = acquirePortLock(normalizedPort, { ownerId: normalizedOwnerId });
1016
1621
  if (!portLock) {
@@ -1024,36 +1629,58 @@ export async function startChrome({
1024
1629
 
1025
1630
  if (await browserWSEndpoint(normalizedPort)) {
1026
1631
  const safety = managedBrowserSafetyForPort(normalizedPort);
1632
+ const state = readManagedStateForPort(normalizedPort);
1633
+ const reuse = managedBrowserReuseDecision({
1634
+ safety, state, ownerToken: providedOwnerToken, includeGoogle,
1635
+ profileName: resolvedProfileName, headless, forceProfileSync,
1636
+ });
1637
+ // Reuse first, on both paths. An auto-allocated start used to skip this entirely and walk to
1638
+ // the next free port, so a session that called start twice got two browsers instead of one.
1639
+ if (reuse.ok) {
1640
+ return {
1641
+ status: 'reused',
1642
+ port: normalizedPort,
1643
+ headless: Boolean(state?.headless),
1644
+ includeGoogle: Boolean(state?.includeGoogle),
1645
+ ownerToken: effectiveOwnerToken,
1646
+ ownerId: reuse.ownerId,
1647
+ ownerTokenGenerated: false,
1648
+ };
1649
+ }
1027
1650
  if (!autoAllocatePort) {
1028
1651
  if (!safety.ok) {
1029
1652
  throw new Error(
1030
1653
  `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
1654
  );
1032
1655
  }
1033
- const state = readManagedStateForPort(normalizedPort);
1034
- const ownership = managedBrowserOwnershipSafety({ state, ownerToken: providedOwnerToken });
1035
- if (!ownership.ok) {
1656
+ if (reuse.reason === 'google-mode-mismatch') {
1036
1657
  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.`,
1658
+ `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
1659
  );
1039
1660
  }
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) {
1661
+ // A configuration mismatch is not an ownership problem: the caller owns this browser, it
1662
+ // was just built differently. Say so, rather than sending them to look for a token.
1663
+ if (reuse.reason === 'profile-mismatch') {
1043
1664
  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.`,
1665
+ `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
1666
  );
1046
1667
  }
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
- };
1668
+ if (reuse.reason === 'headless-mismatch') {
1669
+ throw new Error(
1670
+ `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.`,
1671
+ );
1672
+ }
1673
+ if (reuse.reason === 'sync-requested') {
1674
+ throw new Error(
1675
+ `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.`,
1676
+ );
1677
+ }
1678
+ throw new Error(
1679
+ `Chrome DevTools on :${normalizedPort} is owned by another Browser Tools agent (${reuse.reason}). Use a different --port or provide the correct --owner-token.`,
1680
+ );
1056
1681
  }
1682
+ // Cannot adopt it, so this really will be a new browser: it must fit under the cap.
1683
+ assertManagedBrowserCapacity();
1057
1684
  normalizedPort = await findAvailablePort(normalizedPort + 1);
1058
1685
  continue;
1059
1686
  }
@@ -1108,15 +1735,83 @@ export async function startChrome({
1108
1735
  }
1109
1736
  }
1110
1737
  }
1111
- const proc = launchChrome({
1112
- port: normalizedPort,
1113
- profileName: resolvedProfileName,
1114
- userDataDir,
1115
- ownerToken: effectiveOwnerToken,
1116
- ownerId: normalizedOwnerId,
1117
- headless,
1118
- includeGoogle,
1119
- });
1738
+ // Reserve the slot and spawn under one cache-wide lock. The earlier check is only advisory:
1739
+ // it runs before profile sync, which can take seconds, so on its own it lets two concurrent
1740
+ // starts both observe 4 of 5 and both launch. This recount is the binding one, and it holds
1741
+ // until launchChrome has written the state file that makes the new browser visible to others.
1742
+ const launchLock = acquireLaunchLock();
1743
+ if (!launchLock) {
1744
+ throw new Error(
1745
+ 'Timed out waiting for the Browser Tools launch lock. Another start is reserving a browser slot; retry shortly.',
1746
+ );
1747
+ }
1748
+ let proc;
1749
+ let serializedReuse = null;
1750
+ try {
1751
+ const live = listManagedChromeProcesses();
1752
+ const occupied = occupiedManagedSlotPorts({ processes: live });
1753
+ if (autoAllocatePort && providedOwnerToken) {
1754
+ serializedReuse = findReusableManagedBrowser({
1755
+ ownerToken: providedOwnerToken,
1756
+ includeGoogle,
1757
+ profileName: resolvedProfileName,
1758
+ headless,
1759
+ forceProfileSync,
1760
+ processes: managedBrowserCandidatesForOccupiedSlots(live, occupied),
1761
+ });
1762
+ }
1763
+ if (!serializedReuse) {
1764
+ occupied.delete(normalizedPort);
1765
+ assertManagedBrowserCapacity({
1766
+ processes: [...occupied].map((p) =>
1767
+ live.find((entry) => entry.port === p)
1768
+ || { pid: readManagedState(stateFileForPort(p))?.pid ?? null, port: p, ageMs: null }),
1769
+ });
1770
+ proc = launchChrome({
1771
+ port: normalizedPort,
1772
+ profileName: resolvedProfileName,
1773
+ userDataDir,
1774
+ ownerToken: effectiveOwnerToken,
1775
+ ownerId: normalizedOwnerId,
1776
+ headless,
1777
+ includeGoogle,
1778
+ });
1779
+ }
1780
+ } finally {
1781
+ launchLock.release();
1782
+ }
1783
+ if (serializedReuse) {
1784
+ const ready = await waitForChromeReady(serializedReuse.port, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1785
+ if (!ready) {
1786
+ throw new Error(
1787
+ `Matching managed Chrome on :${serializedReuse.port} did not become ready after a concurrent start.`,
1788
+ );
1789
+ }
1790
+ const state = readManagedStateForPort(serializedReuse.port);
1791
+ const reuse = managedBrowserReuseDecision({
1792
+ safety: managedBrowserSafetyForPort(serializedReuse.port),
1793
+ state,
1794
+ ownerToken: providedOwnerToken,
1795
+ includeGoogle,
1796
+ profileName: resolvedProfileName,
1797
+ headless,
1798
+ forceProfileSync,
1799
+ });
1800
+ if (!reuse.ok) {
1801
+ throw new Error(
1802
+ `Matching managed Chrome on :${serializedReuse.port} changed while a concurrent start was completing (${reuse.reason}).`,
1803
+ );
1804
+ }
1805
+ return {
1806
+ status: 'reused',
1807
+ port: serializedReuse.port,
1808
+ headless: Boolean(state?.headless),
1809
+ includeGoogle: Boolean(state?.includeGoogle),
1810
+ ownerToken: effectiveOwnerToken,
1811
+ ownerId: reuse.ownerId,
1812
+ ownerTokenGenerated: false,
1813
+ };
1814
+ }
1120
1815
  const ready = await waitForChromeReady(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1121
1816
  if (!ready) {
1122
1817
  stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
@@ -1156,6 +1851,20 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1156
1851
  return { status: 'missing', port: normalizedPort, cleaned: false };
1157
1852
  }
1158
1853
  if (!hasPidFile || !hasStateFile) {
1854
+ // A surviving pid file for a live process is the only handle we have on that browser. Deleting
1855
+ // it strands the process where neither stop nor a future start can see it, so keep it and let
1856
+ // the reaper deal with the process itself.
1857
+ const strandedPid = hasPidFile ? Number.parseInt(readFileSync(paths.pidFile, 'utf-8').trim(), 10) : NaN;
1858
+ if (Number.isInteger(strandedPid) && processExists(strandedPid)) {
1859
+ return {
1860
+ status: 'not-managed',
1861
+ port: normalizedPort,
1862
+ pid: strandedPid,
1863
+ cleaned: false,
1864
+ reason: 'incomplete-managed-state',
1865
+ hint: REAP_HINT,
1866
+ };
1867
+ }
1159
1868
  rmSync(paths.pidFile, { force: true });
1160
1869
  rmSync(paths.stateFile, { force: true });
1161
1870
  return { status: 'not-managed', port: normalizedPort, cleaned: false, reason: 'incomplete-managed-state' };
@@ -1176,7 +1885,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1176
1885
  return { status: 'already-gone', port: normalizedPort, pid, cleaned };
1177
1886
  }
1178
1887
 
1179
- const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1888
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken, allowUnowned: true });
1180
1889
  if (!ownership.ok) {
1181
1890
  return {
1182
1891
  status: 'not-owned',
@@ -1190,6 +1899,19 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1190
1899
  }
1191
1900
 
1192
1901
  if (!safety.ok) {
1902
+ // The process failed a safety check but is still running. Forgetting its lifecycle files here is
1903
+ // what previously turned mismatched browsers into permanent orphans, so keep them.
1904
+ if (processExists(pid)) {
1905
+ return {
1906
+ status: 'not-managed',
1907
+ port: normalizedPort,
1908
+ pid,
1909
+ cleaned: false,
1910
+ reason: safety.reason,
1911
+ command: safety.command,
1912
+ hint: REAP_HINT,
1913
+ };
1914
+ }
1193
1915
  rmSync(paths.pidFile, { force: true });
1194
1916
  rmSync(paths.stateFile, { force: true });
1195
1917
  return {
@@ -1203,7 +1925,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1203
1925
  }
1204
1926
 
1205
1927
  if (dryRun) {
1206
- return { status: 'would-stop', port: normalizedPort, pid, cleaned: false, command: safety.command, ownerId: ownership.ownerId };
1928
+ return { status: 'would-stop', port: normalizedPort, pid, cleaned: false, command: safety.command, ownerId: ownership.ownerId, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1207
1929
  }
1208
1930
 
1209
1931
  let status = 'stopped';
@@ -1215,8 +1937,10 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1215
1937
  const killSafety = verifyManagedChromeProcess({ pid, port: normalizedPort, state });
1216
1938
  if (killSafety.ok) {
1217
1939
  process.kill(pid, 'SIGKILL');
1218
- waitForProcessExit(pid, 1000);
1219
- status = 'killed';
1940
+ status = forcedKillStatus(waitForProcessExit(pid, 1000));
1941
+ if (status === 'failed') {
1942
+ error = new Error('Managed Chrome remained alive after SIGKILL');
1943
+ }
1220
1944
  } else {
1221
1945
  status = 'failed';
1222
1946
  error = new Error(`Refusing SIGKILL after failed safety recheck: ${killSafety.reason}`);
@@ -1230,6 +1954,13 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1230
1954
  }
1231
1955
  }
1232
1956
 
1957
+ // A failed stop means the browser may still own its process and clone. Keep every lifecycle handle
1958
+ // so the owner can retry and the process inventory can still classify it. Removing them here turns
1959
+ // a shutdown failure into the same invisible orphan this cleanup path exists to prevent.
1960
+ if (status === 'failed') {
1961
+ return { status, port: normalizedPort, pid, cleaned: false, error, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1962
+ }
1963
+
1233
1964
  rmSync(paths.pidFile, { force: true });
1234
1965
  rmSync(paths.stateFile, { force: true });
1235
1966
  let cleaned = false;
@@ -1239,14 +1970,23 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1239
1970
  cleaned = true;
1240
1971
  }
1241
1972
 
1242
- return { status, port: normalizedPort, pid, cleaned, error };
1973
+ return { status, port: normalizedPort, pid, cleaned, error, ...(ownership.reclaimedUnowned ? { reclaimedUnowned: true } : {}) };
1243
1974
  }
1244
1975
 
1245
1976
  // Sweep cached profile clones that are not currently in use by a running managed Chrome.
1246
1977
  // Removes the clone data dir plus its per-port sync-state and lifecycle files. A clone whose
1247
1978
  // user-data-dir is still owned by a live managed Chrome is kept. Never touches non-clone cache
1248
1979
  // entries (for example ai-chat data), because every path comes from the per-port helpers.
1249
- export function pruneChromeClones({ dryRun = false, keepPorts = [] } = {}) {
1980
+ export function reapExitCode(reaped = []) {
1981
+ return reaped.some((entry) => entry?.status === 'failed') ? 1 : 0;
1982
+ }
1983
+
1984
+ export function pruneChromeClones({ dryRun = false, keepPorts = [], assumeStoppedPorts = [] } = {}) {
1985
+ // Ports a preceding reap has freed, or would free in a dry run. Without this a `--prune --dry-run`
1986
+ // reports those clones as still in use and hides the removals the real command performs.
1987
+ const assumeStopped = new Set(
1988
+ (dryRun ? assumeStoppedPorts : []).map((value) => Number.parseInt(value, 10)),
1989
+ );
1250
1990
  const cacheDir = browserToolsCacheDir();
1251
1991
  const keep = new Set(keepPorts.map((value) => Number.parseInt(value, 10)));
1252
1992
  const removed = [];
@@ -1283,8 +2023,8 @@ export function pruneChromeClones({ dryRun = false, keepPorts = [] } = {}) {
1283
2023
  const freshDir = freshProfileDirForPort(port);
1284
2024
  // Both a stale profiled clone and a live fresh clone can share a port, so check each candidate
1285
2025
  // 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;
2026
+ const runningData = !assumeStopped.has(port) && existsSync(dataDir) ? managedBrowserForUserDataDir(dataDir) : null;
2027
+ const runningFresh = !assumeStopped.has(port) && existsSync(freshDir) ? managedBrowserForUserDataDir(freshDir) : null;
1288
2028
  const running = runningData || runningFresh;
1289
2029
  if (running) {
1290
2030
  kept.push({ port, reason: 'running', pid: running.pid, dir: runningData ? dataDir : freshDir });
@@ -1317,10 +2057,33 @@ function commandForPid(pid) {
1317
2057
  return command || null;
1318
2058
  }
1319
2059
 
2060
+ function processStartIdentity(pid) {
2061
+ const normalizedPid = Number(pid);
2062
+ if (!Number.isInteger(normalizedPid) || normalizedPid < 1) return null;
2063
+ const result = spawnSync(
2064
+ 'ps',
2065
+ ['-p', String(normalizedPid), '-o', 'lstart=', '-o', 'command='],
2066
+ { encoding: 'utf-8' },
2067
+ );
2068
+ if (result.error || result.status !== 0) return null;
2069
+ const identity = result.stdout.trim();
2070
+ if (!identity) return null;
2071
+ return createHash('sha256').update(identity, 'utf8').digest('hex');
2072
+ }
2073
+
2074
+ function processIsZombie(pid) {
2075
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'state='], { encoding: 'utf-8' });
2076
+ if (result.error || result.status !== 0) return false;
2077
+ return result.stdout.trim().startsWith('Z');
2078
+ }
2079
+
1320
2080
  function processExists(pid) {
1321
2081
  try {
1322
2082
  process.kill(pid, 0);
1323
- return true;
2083
+ // A directly spawned child stays in the process table as a zombie until Node's event loop can
2084
+ // reap it. Signals cannot affect it, so treating it as alive causes synchronous shutdown to
2085
+ // report failure and retain lifecycle data for a browser that has already exited.
2086
+ return !processIsZombie(pid);
1324
2087
  } catch (e) {
1325
2088
  return e.code !== 'ESRCH';
1326
2089
  }
@@ -1347,42 +2110,49 @@ function verifyManagedChromeProcess({ pid, port, state }) {
1347
2110
 
1348
2111
  export function isBrowserToolsUserDataDir(userDataDir) {
1349
2112
  if (!userDataDir || typeof userDataDir !== 'string') return false;
1350
- const cacheDir = browserToolsCacheDir();
1351
2113
  return userDataDir === PROFILE_DST ||
1352
2114
  userDataDir === FRESH_PROFILE_DIR ||
1353
2115
  userDataDir === profileDataDirForPort(DEFAULT_PORT) ||
1354
2116
  userDataDir === freshProfileDirForPort(DEFAULT_PORT) ||
1355
- userDataDir.startsWith(`${cacheDir}/chrome-data-`) ||
1356
- userDataDir.startsWith(`${cacheDir}/chrome-fresh-`);
2117
+ isManagedCloneDir(userDataDir);
1357
2118
  }
1358
2119
 
1359
- export function managedChromeCommandSafety({ pid, port, state, command }) {
2120
+ export function managedChromeLifecycleStateSafety({ pid, port, state }) {
1360
2121
  if (!state || state.managedBy !== 'browser-tools') {
1361
- return { ok: false, reason: 'missing-managed-state', command };
2122
+ return { ok: false, reason: 'missing-managed-state' };
1362
2123
  }
1363
2124
  if (Number(state.pid) !== Number(pid) || Number(state.port) !== Number(port)) {
1364
- return { ok: false, reason: 'state-mismatch', command };
2125
+ return { ok: false, reason: 'state-mismatch' };
1365
2126
  }
1366
2127
  if (!state.managedToken) {
1367
- return { ok: false, reason: 'missing-managed-token', command };
2128
+ return { ok: false, reason: 'missing-managed-token' };
1368
2129
  }
1369
2130
  if (!isBrowserToolsUserDataDir(state.userDataDir)) {
1370
- return { ok: false, reason: 'state-user-data-dir-mismatch', command };
2131
+ return { ok: false, reason: 'state-user-data-dir-mismatch' };
1371
2132
  }
1372
2133
 
1373
2134
  const expectedDebugPort = `--remote-debugging-port=${port}`;
1374
2135
  const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
1375
2136
  const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
1376
2137
  const expectedArgs = Array.isArray(state.args) ? state.args : [];
1377
- const isChrome = command.includes('Google Chrome') || command.includes(browserToolsChromeBin()) || command.includes(CHROME_BIN);
2138
+ if (!expectedArgs.includes(expectedDebugPort)) return { ok: false, reason: 'state-debug-port-missing' };
2139
+ if (!expectedArgs.includes(expectedUserDataDir)) return { ok: false, reason: 'state-user-data-dir-missing' };
2140
+ if (!expectedArgs.includes(expectedToken)) return { ok: false, reason: 'state-managed-token-missing' };
2141
+
2142
+ return { ok: true };
2143
+ }
2144
+
2145
+ export function managedChromeCommandSafety({ pid, port, state, command }) {
2146
+ const stateSafety = managedChromeLifecycleStateSafety({ pid, port, state });
2147
+ if (!stateSafety.ok) return { ...stateSafety, command };
2148
+
2149
+ const expectedDebugPort = `--remote-debugging-port=${port}`;
2150
+ const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
2151
+ const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
1378
2152
 
1379
- if (!isChrome) return { ok: false, reason: 'not-chrome-process', command };
1380
2153
  if (!command.includes(expectedDebugPort)) return { ok: false, reason: 'debug-port-mismatch', command };
1381
2154
  if (!command.includes(expectedUserDataDir)) return { ok: false, reason: 'user-data-dir-mismatch', command };
1382
2155
  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
2156
 
1387
2157
  return { ok: true, command };
1388
2158
  }