@ricsam/browser-mcp 0.3.10 → 0.3.11

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.
@@ -23,7 +23,7 @@ import { setMaxListeners } from "node:events";
23
23
  import fs3 from "node:fs/promises";
24
24
  import path3 from "node:path";
25
25
  import os2 from "node:os";
26
- import { randomUUID } from "node:crypto";
26
+ import { randomUUID as randomUUID3 } from "node:crypto";
27
27
 
28
28
  // cli/src/browser/owned-chrome.ts
29
29
  import { spawn } from "node:child_process";
@@ -51,12 +51,405 @@ function onceAsync(action) {
51
51
  return () => result ??= Promise.resolve().then(action);
52
52
  }
53
53
 
54
+ // cli/src/browser/owned-chrome.ts
55
+ import { randomUUID as randomUUID2 } from "node:crypto";
56
+ // cli/package.json
57
+ var version = "0.3.11";
58
+
59
+ // cli/src/browser/chrome-diagnostics.ts
60
+ import { constants } from "node:fs";
61
+ import { lstat, mkdir, open, readdir, unlink, rmdir } from "node:fs/promises";
62
+ import { dirname, join, parse, resolve } from "node:path";
63
+ import { randomUUID } from "node:crypto";
64
+ var CHROME_DIAGNOSTIC_LIMITS = Object.freeze({ lineCharacters: 4096, eventCount: 32 });
65
+ var CHROME_INCIDENT_LIMITS = Object.freeze({ bytes: 32768, count: 20, ageMs: 30 * 24 * 60 * 60 * 1000 });
66
+ var classifications = ["display", "sandbox", "profile-lock", "disk", "crashpad", "fatal-check", "process-crash"];
67
+ var severities = ["info", "warning", "error", "fatal", "unknown"];
68
+ var increment = (n) => Math.min(Number.MAX_SAFE_INTEGER, n + 1);
69
+ var counts = (keys) => Object.fromEntries(keys.map((k) => [k, 0]));
70
+
71
+ class ChromeDiagnostics {
72
+ pending = "";
73
+ discarding = false;
74
+ ended = false;
75
+ state = {
76
+ schemaVersion: 1,
77
+ severityCounts: counts(severities),
78
+ classifications: counts(classifications),
79
+ unknownLines: 0,
80
+ overlongLines: 0,
81
+ droppedEvents: 0,
82
+ lastEvents: [],
83
+ limits: CHROME_DIAGNOSTIC_LIMITS
84
+ };
85
+ push(chunk) {
86
+ if (this.ended)
87
+ return;
88
+ let start = 0;
89
+ while (start < chunk.length) {
90
+ const newline = chunk.indexOf(`
91
+ `, start);
92
+ const end = newline < 0 ? chunk.length : newline;
93
+ if (!this.discarding) {
94
+ if (this.pending.length + end - start > CHROME_DIAGNOSTIC_LIMITS.lineCharacters) {
95
+ this.pending = "";
96
+ this.discarding = true;
97
+ this.state.overlongLines = increment(this.state.overlongLines);
98
+ } else
99
+ this.pending += chunk.slice(start, end);
100
+ }
101
+ if (newline < 0)
102
+ break;
103
+ if (!this.discarding)
104
+ this.line(this.pending);
105
+ this.pending = "";
106
+ this.discarding = false;
107
+ start = newline + 1;
108
+ }
109
+ }
110
+ finish() {
111
+ if (this.ended)
112
+ return;
113
+ if (!this.discarding && this.pending)
114
+ this.line(this.pending);
115
+ this.pending = "";
116
+ this.discarding = false;
117
+ this.ended = true;
118
+ }
119
+ snapshot() {
120
+ return structuredClone(this.state);
121
+ }
122
+ line(line) {
123
+ if (!line.trim())
124
+ return;
125
+ const severity = /\bFATAL\b|Check failed[.:]|Received signal (?:6|11)\b/.test(line) ? "fatal" : /\bERROR\b/.test(line) ? "error" : /\bWARNING\b/.test(line) ? "warning" : /\bINFO\b/.test(line) ? "info" : "unknown";
126
+ this.state.severityCounts[severity] = increment(this.state.severityCounts[severity]);
127
+ const classification = /Check failed[.:]|CHECK failed|DCHECK failed/.test(line) ? "fatal-check" : /Missing X server|cannot open display|Failed to connect to (?:Wayland|X server)|ozone_platform_x11|WAYLAND_DISPLAY/.test(line) ? "display" : /No usable sandbox|SUID sandbox|sandbox_linux|Failed to move to new namespace|zygote_host_impl_linux/.test(line) ? "sandbox" : /ProcessSingleton|SingletonLock|profile.*(?:in use|locked)|user data directory is already in use/i.test(line) ? "profile-lock" : /No space left on device|Disk quota exceeded|ENOSPC/.test(line) ? "disk" : /crashpad|crash_report_database/i.test(line) ? "crashpad" : /Received signal (?:6|11)\b|Segmentation fault|Trace\/breakpoint trap/.test(line) ? "process-crash" : undefined;
128
+ if (!classification) {
129
+ this.state.unknownLines = increment(this.state.unknownLines);
130
+ return;
131
+ }
132
+ this.state.classifications[classification] = increment(this.state.classifications[classification]);
133
+ if (this.state.lastEvents.length === CHROME_DIAGNOSTIC_LIMITS.eventCount) {
134
+ this.state.lastEvents.shift();
135
+ this.state.droppedEvents = increment(this.state.droppedEvents);
136
+ }
137
+ this.state.lastEvents.push({ classification, severity });
138
+ }
139
+ }
140
+ var fail = () => {
141
+ throw new Error("Chrome incident storage unavailable");
142
+ };
143
+ var safeCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : fail();
144
+ function safeSnapshot(input) {
145
+ if (input.schemaVersion !== 1 || !Array.isArray(input.lastEvents) || input.lastEvents.length > CHROME_DIAGNOSTIC_LIMITS.eventCount)
146
+ fail();
147
+ return {
148
+ schemaVersion: 1,
149
+ severityCounts: Object.fromEntries(severities.map((k) => [k, safeCount(input.severityCounts[k])])),
150
+ classifications: Object.fromEntries(classifications.map((k) => [k, safeCount(input.classifications[k])])),
151
+ unknownLines: safeCount(input.unknownLines),
152
+ overlongLines: safeCount(input.overlongLines),
153
+ droppedEvents: safeCount(input.droppedEvents),
154
+ lastEvents: input.lastEvents.map((e) => {
155
+ if (!classifications.includes(e.classification) || !severities.includes(e.severity))
156
+ fail();
157
+ return { classification: e.classification, severity: e.severity };
158
+ }),
159
+ limits: CHROME_DIAGNOSTIC_LIMITS
160
+ };
161
+ }
162
+ function metadata(record) {
163
+ const text = (s) => typeof s === "string" && s.length <= 256 && /^[\x20-\x7e]*$/.test(s) ? s : fail();
164
+ const date = (s) => typeof s === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(s) && Number.isFinite(Date.parse(s)) ? s : fail();
165
+ const integer = (n) => n === null || Number.isSafeInteger(n) ? n : fail();
166
+ const bool = (b) => typeof b === "boolean" ? b : fail();
167
+ if (record.schemaVersion !== 1 || !["abnormal-exit", "startup-failure", "disconnected"].includes(record.outcome))
168
+ fail();
169
+ return {
170
+ schemaVersion: 1,
171
+ timestamp: date(record.timestamp),
172
+ startedAt: date(record.startedAt),
173
+ profile: text(record.profile),
174
+ instanceId: text(record.instanceId),
175
+ pid: integer(record.pid),
176
+ cliVersion: text(record.cliVersion),
177
+ chromeVersion: record.chromeVersion === null ? null : text(record.chromeVersion),
178
+ outcome: record.outcome,
179
+ stage: text(record.stage),
180
+ reason: text(record.reason),
181
+ exitCode: integer(record.exitCode),
182
+ signal: record.signal === null ? null : /^SIG[A-Z0-9]+$/.test(record.signal) ? record.signal : fail(),
183
+ shutdownRequested: bool(record.shutdownRequested),
184
+ shutdownReason: record.shutdownReason === null ? null : text(record.shutdownReason),
185
+ disconnectObserved: bool(record.disconnectObserved),
186
+ exitDuringCleanup: bool(record.exitDuringCleanup),
187
+ diagnostics: safeSnapshot(record.diagnostics)
188
+ };
189
+ }
190
+ async function ancestors(path) {
191
+ let current = parse(path).root;
192
+ for (const segment of path.slice(current.length).split("/").filter(Boolean)) {
193
+ current = join(current, segment);
194
+ const stat = await lstat(current);
195
+ if (!stat.isDirectory() || stat.isSymbolicLink())
196
+ fail();
197
+ }
198
+ }
199
+ async function privateDirectory(path) {
200
+ await ancestors(dirname(path));
201
+ try {
202
+ await mkdir(path, { mode: 448 });
203
+ } catch (error) {
204
+ if (error.code !== "EEXIST")
205
+ throw error;
206
+ }
207
+ const stat = await lstat(path);
208
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 448)
209
+ fail();
210
+ }
211
+ var filenamePattern = /^incident-\d{13}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/;
212
+ async function retained(path) {
213
+ const stat = await lstat(path);
214
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 384 || stat.size > CHROME_INCIDENT_LIMITS.bytes)
215
+ return null;
216
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
217
+ try {
218
+ const actual = await handle.stat();
219
+ if (actual.ino !== stat.ino || actual.dev !== stat.dev || actual.nlink !== 1 || actual.size > CHROME_INCIDENT_LIMITS.bytes || actual.uid !== process.getuid?.() || (actual.mode & 511) !== 384)
220
+ return null;
221
+ const buffer = Buffer.alloc(CHROME_INCIDENT_LIMITS.bytes + 1);
222
+ let length = 0;
223
+ while (length < buffer.length) {
224
+ const result = await handle.read(buffer, length, buffer.length - length, length);
225
+ if (!result.bytesRead)
226
+ break;
227
+ length += result.bytesRead;
228
+ }
229
+ if (length > CHROME_INCIDENT_LIMITS.bytes)
230
+ return null;
231
+ const input = JSON.parse(buffer.subarray(0, length).toString("utf8"));
232
+ if (input.diagnosticFile !== path)
233
+ return null;
234
+ const clean = metadata(input);
235
+ if (JSON.stringify(input) !== JSON.stringify({ ...clean, diagnosticFile: path }))
236
+ return null;
237
+ return { ino: stat.ino, dev: stat.dev, timestamp: Date.parse(clean.timestamp) };
238
+ } catch {
239
+ return null;
240
+ } finally {
241
+ await handle.close();
242
+ }
243
+ }
244
+ async function writeChromeIncident(root, record) {
245
+ try {
246
+ if (process.platform === "win32" || !process.getuid)
247
+ fail();
248
+ const base = resolve(root);
249
+ await privateDirectory(base);
250
+ const directory = join(base, "diagnostics");
251
+ await privateDirectory(directory);
252
+ const lock = join(directory, ".retention-lock");
253
+ let acquired = false;
254
+ for (let attempt = 0;attempt < 100; attempt++) {
255
+ try {
256
+ await mkdir(lock, { mode: 448 });
257
+ acquired = true;
258
+ break;
259
+ } catch (error) {
260
+ if (error.code !== "EEXIST")
261
+ throw error;
262
+ const stat = await lstat(lock).catch((error2) => {
263
+ if (error2.code !== "ENOENT")
264
+ throw error2;
265
+ return null;
266
+ });
267
+ if (!stat)
268
+ continue;
269
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 511) !== 448)
270
+ fail();
271
+ await new Promise((resolve2) => setTimeout(resolve2, 20));
272
+ }
273
+ }
274
+ if (!acquired)
275
+ fail();
276
+ const lockStat = await lstat(lock);
277
+ try {
278
+ await privateDirectory(base);
279
+ await privateDirectory(directory);
280
+ const path = join(directory, `incident-${Date.now()}-${randomUUID()}.json`);
281
+ const clean = metadata(record);
282
+ const json = JSON.stringify({ ...clean, diagnosticFile: path });
283
+ if (Buffer.byteLength(json) > CHROME_INCIDENT_LIMITS.bytes)
284
+ fail();
285
+ const handle = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
286
+ try {
287
+ const stat = await handle.stat();
288
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.())
289
+ fail();
290
+ await handle.chmod(384);
291
+ await handle.writeFile(json);
292
+ await handle.sync();
293
+ } finally {
294
+ await handle.close();
295
+ }
296
+ const entries = [];
297
+ for (const name of await readdir(directory)) {
298
+ if (!filenamePattern.test(name))
299
+ continue;
300
+ const candidate = join(directory, name);
301
+ const entry = await retained(candidate);
302
+ if (entry)
303
+ entries.push({ path: candidate, ...entry });
304
+ }
305
+ entries.sort((a, b) => b.timestamp - a.timestamp || b.path.localeCompare(a.path));
306
+ let kept = 0;
307
+ for (const entry of entries) {
308
+ if (entry.path === path)
309
+ continue;
310
+ kept++;
311
+ if (kept < CHROME_INCIDENT_LIMITS.count && entry.timestamp >= Date.now() - CHROME_INCIDENT_LIMITS.ageMs)
312
+ continue;
313
+ const stat = await lstat(entry.path);
314
+ if (stat.ino === entry.ino && stat.dev === entry.dev && stat.nlink === 1 && stat.uid === process.getuid?.() && (stat.mode & 511) === 384 && stat.isFile() && !stat.isSymbolicLink())
315
+ await unlink(entry.path);
316
+ }
317
+ return path;
318
+ } finally {
319
+ const current = await lstat(lock);
320
+ if (current.ino === lockStat.ino && current.dev === lockStat.dev && current.isDirectory() && !current.isSymbolicLink())
321
+ await rmdir(lock);
322
+ }
323
+ } catch {
324
+ return fail();
325
+ }
326
+ }
327
+
328
+ // cli/src/browser/chrome-lifecycle.ts
329
+ class ChromeLifecycle {
330
+ identity;
331
+ diagnostics = new ChromeDiagnostics;
332
+ startedAt = new Date().toISOString();
333
+ ended;
334
+ wake;
335
+ stage = "discovery";
336
+ pid = null;
337
+ chromeVersion = null;
338
+ ready = false;
339
+ exit;
340
+ disconnect;
341
+ failure;
342
+ shutdown;
343
+ requestedBeforeEnd = false;
344
+ cleanup = false;
345
+ reporting;
346
+ constructor(identity) {
347
+ this.identity = identity;
348
+ this.ended = new Promise((resolve2) => {
349
+ this.wake = resolve2;
350
+ });
351
+ }
352
+ setStage(stage) {
353
+ this.stage = stage;
354
+ }
355
+ setPid(pid) {
356
+ this.pid = pid ?? null;
357
+ }
358
+ setVersion(version2) {
359
+ if (/^\d{1,5}\.\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(version2))
360
+ this.chromeVersion = version2;
361
+ }
362
+ started() {
363
+ this.ready = true;
364
+ this.stage = "running";
365
+ }
366
+ observation() {
367
+ return { timestamp: new Date().toISOString(), stage: this.stage };
368
+ }
369
+ childExited(code, signal) {
370
+ this.exit ??= { ...this.observation(), code, signal, cleanup: this.cleanup };
371
+ this.wake();
372
+ }
373
+ disconnected() {
374
+ this.disconnect ??= this.observation();
375
+ this.wake();
376
+ }
377
+ fail(reason) {
378
+ if (!this.exit || this.exit.cleanup)
379
+ this.failure ??= { ...this.observation(), reason };
380
+ this.wake();
381
+ }
382
+ requestShutdown(reason) {
383
+ const ended = this.hasEnded;
384
+ if (reason === "owner-close" && ended)
385
+ return;
386
+ if (!this.shutdown) {
387
+ this.shutdown = reason;
388
+ this.requestedBeforeEnd = !ended;
389
+ }
390
+ }
391
+ beginCleanup() {
392
+ this.cleanup = true;
393
+ }
394
+ get needsExitGrace() {
395
+ return !!this.disconnect && !this.exit && !this.failure && !this.requestedBeforeEnd;
396
+ }
397
+ get hasEnded() {
398
+ return !!(this.exit || this.disconnect || this.failure);
399
+ }
400
+ report() {
401
+ return this.reporting ??= this.makeReport();
402
+ }
403
+ async makeReport() {
404
+ this.diagnostics.finish();
405
+ const nativeExit = this.exit && !this.exit.cleanup;
406
+ const abnormal = nativeExit && (this.exit.code !== 0 || this.exit.signal !== null);
407
+ const outcome = this.requestedBeforeEnd ? "requested-shutdown" : this.failure ? "startup-failure" : nativeExit && !this.ready ? "startup-failure" : abnormal ? "abnormal-exit" : nativeExit ? "normal-exit" : "disconnected";
408
+ const observation = this.failure ?? (nativeExit ? this.exit : this.disconnect) ?? this.observation();
409
+ const reason = this.failure?.reason ?? (outcome === "disconnected" ? "transport-or-context-closed-without-child-exit" : outcome === "startup-failure" ? "child-exited-before-ready" : outcome);
410
+ const failed = outcome !== "requested-shutdown" && outcome !== "normal-exit";
411
+ let location2 = "";
412
+ if (failed) {
413
+ if (this.identity.root) {
414
+ try {
415
+ const file = await writeChromeIncident(this.identity.root, {
416
+ schemaVersion: 1,
417
+ ...observation,
418
+ startedAt: this.startedAt,
419
+ profile: this.identity.profile,
420
+ instanceId: this.identity.instanceId,
421
+ pid: this.pid,
422
+ cliVersion: version,
423
+ chromeVersion: this.chromeVersion,
424
+ outcome,
425
+ reason,
426
+ exitCode: this.exit?.code ?? null,
427
+ signal: this.exit?.signal ?? null,
428
+ shutdownRequested: !!this.shutdown,
429
+ shutdownReason: this.shutdown ?? null,
430
+ disconnectObserved: !!this.disconnect,
431
+ exitDuringCleanup: this.exit?.cleanup ?? false,
432
+ diagnostics: this.diagnostics.snapshot()
433
+ });
434
+ location2 = ` Diagnostics: ${JSON.stringify(file)}.`;
435
+ } catch {
436
+ location2 = " Diagnostics could not be saved (private storage unavailable); original failure retained.";
437
+ }
438
+ } else
439
+ location2 = " Diagnostics storage was not configured.";
440
+ }
441
+ const label = outcome === "abnormal-exit" ? "Chrome terminated abnormally" : outcome === "startup-failure" ? "Chrome startup failed" : outcome === "disconnected" ? "Chrome transport/context disconnected (not proof of a Chrome crash)" : outcome === "normal-exit" ? "Chrome exited normally" : "Chrome shutdown requested";
442
+ const summary = `${observation.timestamp} ${label}; profile=${this.identity.profile} instance=${this.identity.instanceId} PID=${this.pid ?? "unavailable"} exitCode=${this.exit?.code ?? "none"} signal=${this.exit?.signal ?? "none"} shutdownRequested=${!!this.shutdown}${this.shutdown ? ` (${this.shutdown})` : ""} stage=${observation.stage} reason=${reason}.${this.exit?.cleanup ? " Child exit observed during cleanup." : ""}${location2}`;
443
+ return { outcome, failed, summary };
444
+ }
445
+ }
446
+
54
447
  // cli/src/browser/owned-chrome.ts
55
448
  var STARTUP_MS = 30000;
56
449
  var CLOSE_MS = 2000;
57
450
  var GRACEFUL_EXIT_MS = 30000;
58
451
  async function allocateChromePort() {
59
- return new Promise((resolve, reject) => {
452
+ return new Promise((resolve2, reject) => {
60
453
  const server = net.createServer();
61
454
  const timer = setTimeout(() => {
62
455
  server.close();
@@ -75,7 +468,7 @@ async function allocateChromePort() {
75
468
  else if (!address || typeof address === "string" || !address.port)
76
469
  reject(new Error("Invalid Chrome port allocation"));
77
470
  else
78
- resolve(address.port);
471
+ resolve2(address.port);
79
472
  });
80
473
  });
81
474
  });
@@ -110,38 +503,53 @@ async function bounded(promise, ms) {
110
503
  }
111
504
  }
112
505
  async function launchOwnedChrome(options) {
506
+ const lifecycle = options.lifecycle ?? new ChromeLifecycle({ profile: "standalone", instanceId: randomUUID2() });
113
507
  options.signal?.throwIfAborted();
114
508
  const artifactsDir = path.join(options.runPath, "chrome-downloads");
115
- await fs.mkdir(artifactsDir, { mode: 448 });
116
- options.signal?.throwIfAborted();
117
- const port = await allocateChromePort();
118
- options.signal?.throwIfAborted();
119
- const child = spawn(options.executablePath, ownedChromeArgs(options.profile, port), {
120
- stdio: ["ignore", "ignore", "pipe"]
121
- });
509
+ let port, child;
510
+ try {
511
+ lifecycle.setStage("artifacts");
512
+ await fs.mkdir(artifactsDir, { mode: 448 });
513
+ options.signal?.throwIfAborted();
514
+ lifecycle.setStage("port");
515
+ port = await allocateChromePort();
516
+ options.signal?.throwIfAborted();
517
+ lifecycle.setStage("spawn");
518
+ child = spawn(options.executablePath, ownedChromeArgs(options.profile, port), {
519
+ stdio: ["ignore", "ignore", "pipe"]
520
+ });
521
+ } catch {
522
+ options.signal?.throwIfAborted();
523
+ lifecycle.fail("preparation-failed");
524
+ throw new Error((await lifecycle.report()).summary);
525
+ }
526
+ lifecycle.setPid(child.pid);
122
527
  let exited = false;
123
528
  let browser;
124
529
  let closing = false;
125
530
  let resolveExit;
126
- const exit = new Promise((resolve) => {
127
- resolveExit = resolve;
531
+ const exit = new Promise((resolve2) => {
532
+ resolveExit = resolve2;
128
533
  });
129
534
  let rejectStartup;
130
535
  const failed = new Promise((_, reject) => {
131
536
  rejectStartup = reject;
132
537
  });
133
- child.once("exit", () => {
538
+ child.once("exit", (code, signal) => {
539
+ lifecycle.childExited(code, signal);
134
540
  exited = true;
135
541
  resolveExit();
136
542
  rejectStartup(new Error("Owned Chrome exited before startup completed"));
137
543
  });
138
544
  child.on("error", () => {
545
+ lifecycle.fail("spawn-failed");
139
546
  if (!child.pid) {
140
547
  exited = true;
141
548
  resolveExit();
142
549
  }
143
550
  rejectStartup(new Error("Could not start owned Chrome process"));
144
551
  });
552
+ const streamsClosed = new Promise((resolve2) => child.once("close", () => resolve2()));
145
553
  failed.catch(() => {});
146
554
  const alive = () => !exited && child.exitCode === null && child.signalCode === null && !!child.pid;
147
555
  const signalChild = (signal) => {
@@ -150,6 +558,10 @@ async function launchOwnedChrome(options) {
150
558
  };
151
559
  const close = onceAsync(async () => {
152
560
  closing = true;
561
+ if (lifecycle.needsExitGrace && alive())
562
+ await bounded(exit, CLOSE_MS).catch(() => {});
563
+ lifecycle.requestShutdown("owner-close");
564
+ lifecycle.beginCleanup();
153
565
  const requestedClose = !!browser?.isConnected() && alive();
154
566
  if (requestedClose) {
155
567
  try {
@@ -178,48 +590,89 @@ async function launchOwnedChrome(options) {
178
590
  } finally {
179
591
  if (browser)
180
592
  await bounded(browser.close(), CLOSE_MS).catch(() => {});
593
+ if (!alive())
594
+ await bounded(streamsClosed, CLOSE_MS).catch(() => {});
181
595
  child.stderr?.destroy();
596
+ lifecycle.diagnostics.finish();
182
597
  }
183
598
  if (alive())
184
599
  throw new Error("Owned Chrome did not exit; retain profile ownership");
185
600
  });
186
- let lineBuffer = "";
601
+ let lineBuffer = "", droppingLine = false, endpointPending = true;
187
602
  let resolveEndpoint;
188
- const endpoint = new Promise((resolve) => {
189
- resolveEndpoint = resolve;
603
+ const endpoint = new Promise((resolve2) => {
604
+ resolveEndpoint = resolve2;
190
605
  });
191
606
  const onData = (chunk) => {
192
- lineBuffer += chunk;
193
- let newline;
194
- while ((newline = lineBuffer.indexOf(`
195
- `)) !== -1) {
196
- const line = lineBuffer.slice(0, newline);
197
- lineBuffer = lineBuffer.slice(newline + 1);
198
- const url = chromeEndpointFromLine(line, port);
199
- if (url)
200
- resolveEndpoint(url);
201
- else if (line.startsWith("DevTools listening on "))
202
- rejectStartup(new Error("Owned Chrome announced an unexpected debugging endpoint"));
203
- }
204
- if (lineBuffer.length > 16384)
607
+ lifecycle.diagnostics.push(chunk);
608
+ if (!endpointPending)
609
+ return;
610
+ let offset = 0;
611
+ while (offset < chunk.length) {
612
+ const newline = chunk.indexOf(`
613
+ `, offset);
614
+ const end = newline === -1 ? chunk.length : newline;
615
+ if (!droppingLine) {
616
+ if (lineBuffer.length + end - offset > 16384) {
617
+ lineBuffer = "";
618
+ droppingLine = true;
619
+ } else
620
+ lineBuffer += chunk.slice(offset, end);
621
+ }
622
+ if (newline === -1)
623
+ break;
624
+ if (!droppingLine) {
625
+ const url = chromeEndpointFromLine(lineBuffer, port);
626
+ if (url) {
627
+ endpointPending = false;
628
+ lineBuffer = "";
629
+ resolveEndpoint(url);
630
+ return;
631
+ } else if (lineBuffer.startsWith("DevTools listening on ")) {
632
+ endpointPending = false;
633
+ lineBuffer = "";
634
+ lifecycle.fail("unexpected-endpoint");
635
+ rejectStartup(new Error("Owned Chrome announced an unexpected debugging endpoint"));
636
+ return;
637
+ }
638
+ }
205
639
  lineBuffer = "";
640
+ droppingLine = false;
641
+ offset = newline + 1;
642
+ }
206
643
  };
207
644
  child.stderr?.setEncoding("utf8");
208
645
  child.stderr?.on("data", onData);
209
- const onAbort = () => rejectStartup(new Error("Owned Chrome startup aborted"));
646
+ const onAbort = () => {
647
+ if (!lifecycle.hasEnded)
648
+ lifecycle.requestShutdown("group-stop");
649
+ rejectStartup(new Error("Owned Chrome startup aborted"));
650
+ };
651
+ const onDisconnect = () => {
652
+ lifecycle.disconnected();
653
+ rejectStartup(new Error("Owned Chrome transport/context disconnected"));
654
+ };
210
655
  options.signal?.addEventListener("abort", onAbort, { once: true });
211
656
  if (options.signal?.aborted)
212
657
  onAbort();
213
658
  const deadline = Date.now() + STARTUP_MS;
659
+ let failureReason = "timeout";
214
660
  const stage = (work) => bounded(Promise.race([work, failed]), Math.max(1, deadline - Date.now()));
215
661
  try {
662
+ lifecycle.setStage("endpoint");
216
663
  const url = await stage(endpoint);
664
+ lifecycle.setStage("connection");
665
+ failureReason = "connection-failed";
217
666
  const connection = chromium.connectOverCDP(url, {
218
667
  isLocal: true,
219
668
  artifactsDir,
220
669
  timeout: Math.max(1, deadline - Date.now())
221
670
  }).then(async (connected) => {
222
671
  browser = connected;
672
+ lifecycle.setVersion(connected.version());
673
+ connected.once("disconnected", onDisconnect);
674
+ if (!connected.isConnected())
675
+ onDisconnect();
223
676
  if (closing) {
224
677
  await connected.close();
225
678
  throw new Error("Owned Chrome startup cancelled");
@@ -227,38 +680,50 @@ async function launchOwnedChrome(options) {
227
680
  return connected;
228
681
  });
229
682
  await stage(connection);
683
+ lifecycle.setStage("context");
684
+ failureReason = "missing-context";
230
685
  const context = browser.contexts()[0];
231
686
  if (!context)
232
687
  throw new Error("Owned Chrome has no default context");
688
+ context.once("close", onDisconnect);
689
+ failureReason = "context-setup-failed";
233
690
  await stage(context.addInitScript("if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };"));
691
+ lifecycle.setStage("webdriver");
692
+ failureReason = "missing-blank-page";
234
693
  const page = context.pages().find((page2) => page2.url() === "about:blank");
235
694
  if (!page)
236
695
  throw new Error("Owned Chrome did not open the initial blank page");
696
+ failureReason = "webdriver-check-failed";
237
697
  if (await stage(page.evaluate(() => navigator.webdriver)) !== false) {
238
698
  throw new Error("Owned Chrome unexpectedly exposes navigator.webdriver=true");
239
699
  }
240
700
  options.signal?.throwIfAborted();
241
- if (!alive())
242
- throw new Error("Owned Chrome exited during startup");
243
- return { context, close };
701
+ if (!alive() || lifecycle.hasEnded)
702
+ throw new Error("Owned Chrome ended during startup");
703
+ lifecycle.started();
704
+ return { context, close, lifecycle };
244
705
  } catch {
706
+ if (!options.signal?.aborted && !lifecycle.hasEnded)
707
+ lifecycle.fail(Date.now() >= deadline ? "timeout" : failureReason);
708
+ let cleanupFailed = false;
245
709
  try {
246
710
  await close();
247
711
  } catch {
248
- throw new Error("Owned Chrome startup and cleanup failed; retain profile ownership");
712
+ cleanupFailed = true;
249
713
  }
714
+ const result = await lifecycle.report();
715
+ if (result.failed || cleanupFailed)
716
+ throw new Error(`${result.summary}${cleanupFailed ? " Chrome cleanup failed; retain profile ownership." : ""}`);
250
717
  options.signal?.throwIfAborted();
251
- throw new Error("Owned Chrome startup failed (process, endpoint, connection, or webdriver verification)");
718
+ throw new Error(result.summary);
252
719
  } finally {
253
720
  options.signal?.removeEventListener("abort", onAbort);
254
- child.stderr?.off("data", onData);
255
- child.stderr?.resume();
256
721
  }
257
722
  }
258
723
 
259
724
  // cli/src/browser/recovery.ts
260
725
  import fs2 from "node:fs/promises";
261
- import { constants } from "node:fs";
726
+ import { constants as constants2 } from "node:fs";
262
727
  import path2 from "node:path";
263
728
  import os from "node:os";
264
729
  import net2 from "node:net";
@@ -269,7 +734,7 @@ function controlSocketPath(root, profile) {
269
734
  return path2.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
270
735
  }
271
736
  var code = (e) => e.code;
272
- var fail = (file, reason) => {
737
+ var fail2 = (file, reason) => {
273
738
  throw new Error(`Recovery refused: ${reason}: ${file}. Stop the prior host and Chrome, verify ownership and retry browser recover; do not blindly delete artifacts.`);
274
739
  };
275
740
  async function directories(directory) {
@@ -278,14 +743,14 @@ async function directories(directory) {
278
743
  cursor = path2.join(cursor, part);
279
744
  const s = await fs2.lstat(cursor);
280
745
  if (!s.isDirectory() || s.isSymbolicLink())
281
- fail(cursor, "unsafe directory ancestor");
746
+ fail2(cursor, "unsafe directory ancestor");
282
747
  }
283
748
  }
284
749
  async function privateDir(directory) {
285
750
  await directories(directory);
286
751
  const s = await fs2.lstat(directory);
287
752
  if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
288
- fail(directory, "directory must be owned by current user with mode 0700");
753
+ fail2(directory, "directory must be owned by current user with mode 0700");
289
754
  }
290
755
  async function artifact(file, socket = false) {
291
756
  let s;
@@ -297,7 +762,7 @@ async function artifact(file, socket = false) {
297
762
  throw e;
298
763
  }
299
764
  if (s.isSymbolicLink() || !(socket ? s.isSocket() : s.isFile()) || s.nlink !== 1 || s.uid !== process.getuid?.() || (s.mode & 63) !== 0)
300
- fail(file, "unsafe artifact type, links, owner or permissions");
765
+ fail2(file, "unsafe artifact type, links, owner or permissions");
301
766
  return s;
302
767
  }
303
768
  function dead(pid, file) {
@@ -306,25 +771,25 @@ function dead(pid, file) {
306
771
  } catch (e) {
307
772
  if (code(e) === "ESRCH")
308
773
  return;
309
- fail(file, `cannot prove PID ${pid} absent (${code(e)})`);
774
+ fail2(file, `cannot prove PID ${pid} absent (${code(e)})`);
310
775
  }
311
- fail(file, `PID ${pid} exists (including possible PID reuse)`);
776
+ fail2(file, `PID ${pid} exists (including possible PID reuse)`);
312
777
  }
313
778
  async function assertProfileStopped(profile) {
314
779
  let stdout;
315
780
  try {
316
781
  ({ stdout } = await promisify(execFile)("ps", ["-axww", "-o", "pid=,command="], { timeout: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }));
317
782
  } catch {
318
- return fail(profile, "process scan failed or was truncated");
783
+ return fail2(profile, "process scan failed or was truncated");
319
784
  }
320
785
  const lines = stdout.trim().split(`
321
786
  `);
322
787
  if (!lines.length || lines.some((line) => !/^\s*\d+\s+\S/.test(line)))
323
- fail(profile, "uncertain process scan");
788
+ fail2(profile, "uncertain process scan");
324
789
  for (const line of lines) {
325
790
  const pid = Number(line.trim().split(/\s+/, 1)[0]);
326
791
  if (pid !== process.pid && (line.includes(profile) || /(?:chrome|chromium)/i.test(line) && /--user-data-dir(?:\s|=)/.test(line) && !line.includes("--user-data-dir=/"))) {
327
- fail(profile, `possible surviving profile process: PID ${pid}`);
792
+ fail2(profile, `possible surviving profile process: PID ${pid}`);
328
793
  }
329
794
  }
330
795
  const singleton = path2.join(profile, "SingletonLock");
@@ -337,18 +802,18 @@ async function assertProfileStopped(profile) {
337
802
  throw e;
338
803
  }
339
804
  if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
340
- fail(singleton, "unrecognized Chromium singleton lock");
805
+ fail2(singleton, "unrecognized Chromium singleton lock");
341
806
  const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
342
807
  if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
343
- fail(singleton, "foreign or unrecognized Chromium owner");
808
+ fail2(singleton, "foreign or unrecognized Chromium owner");
344
809
  dead(Number(match[2]), singleton);
345
810
  }
346
811
  async function refusedSocket(file) {
347
- await new Promise((resolve, reject) => {
812
+ await new Promise((resolve2, reject) => {
348
813
  const socket = net2.createConnection(file);
349
814
  const finish = (error) => {
350
815
  socket.destroy();
351
- error ? reject(error) : resolve();
816
+ error ? reject(error) : resolve2();
352
817
  };
353
818
  socket.setTimeout(1000, () => finish(new Error(`Recovery refused: socket probe timed out: ${file}`)));
354
819
  socket.once("connect", () => finish(new Error(`Recovery refused: live control listener: ${file}`)));
@@ -372,24 +837,24 @@ async function recoverProfile(root, name) {
372
837
  const original = await artifact(lock), originalSocket = await artifact(socket, true);
373
838
  if (!original) {
374
839
  if (originalSocket)
375
- fail(socket, `socket has no provenance because ${lock} is absent`);
840
+ fail2(socket, `socket has no provenance because ${lock} is absent`);
376
841
  return;
377
842
  }
378
843
  if (original.size > 16384)
379
- fail(lock, "oversized lock");
380
- const handle = await fs2.open(lock, constants.O_RDONLY | constants.O_NOFOLLOW);
844
+ fail2(lock, "oversized lock");
845
+ const handle = await fs2.open(lock, constants2.O_RDONLY | constants2.O_NOFOLLOW);
381
846
  try {
382
847
  if (!same(original, await handle.stat()))
383
- fail(lock, "lock changed while opening");
848
+ fail2(lock, "lock changed while opening");
384
849
  const raw = await handle.readFile("utf8");
385
850
  let owner;
386
851
  try {
387
852
  owner = JSON.parse(raw);
388
853
  } catch {
389
- fail(lock, "invalid lock JSON");
854
+ fail2(lock, "invalid lock JSON");
390
855
  }
391
856
  if (!owner || typeof owner !== "object" || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || owner.profile !== profile || typeof owner.ephemeral !== "boolean" || !["nonce", "instanceId"].every((k) => typeof owner[k] === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(owner[k])))
392
- fail(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
857
+ fail2(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
393
858
  const validate = async () => {
394
859
  await privateDir(root);
395
860
  await privateDir(path2.join(root, "profiles"));
@@ -397,19 +862,19 @@ async function recoverProfile(root, name) {
397
862
  dead(owner.pid, lock);
398
863
  await assertProfileStopped(profile);
399
864
  if (!same(original, await artifact(lock)) || await fs2.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
400
- fail(lock, `artifact identity changed (socket ${socket})`);
865
+ fail2(lock, `artifact identity changed (socket ${socket})`);
401
866
  if (originalSocket)
402
867
  await refusedSocket(socket);
403
868
  dead(owner.pid, lock);
404
869
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)) || !same(originalSocket, await artifact(socket, true)))
405
- fail(lock, "artifact identity changed during liveness probe");
870
+ fail2(lock, "artifact identity changed during liveness probe");
406
871
  };
407
872
  await validate();
408
873
  if (originalSocket)
409
874
  await fs2.unlink(socket);
410
875
  dead(owner.pid, lock);
411
876
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
412
- fail(lock, "lock changed before unlink");
877
+ fail2(lock, "lock changed before unlink");
413
878
  await fs2.unlink(lock);
414
879
  } finally {
415
880
  await handle.close();
@@ -423,7 +888,7 @@ async function recoverProfile(root, name) {
423
888
  function installationRoot() {
424
889
  return path3.join(os2.homedir(), ".browser-mcp");
425
890
  }
426
- async function privateDirectory(directory) {
891
+ async function privateDirectory2(directory) {
427
892
  const absolute = path3.resolve(directory);
428
893
  let cursor = path3.parse(absolute).root;
429
894
  for (const piece of absolute.slice(cursor.length).split(path3.sep)) {
@@ -464,13 +929,13 @@ async function launchDedicated(options = {}) {
464
929
  const name = options.profile ?? "default";
465
930
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
466
931
  throw new Error("Profile must be a simple name, not a path");
467
- const root = await privateDirectory(options.root ?? installationRoot());
468
- const profiles = await privateDirectory(path3.join(root, "profiles"));
469
- const profile = path3.join(profiles, options.ephemeral ? `ephemeral-${randomUUID()}` : name);
470
- await privateDirectory(profile);
932
+ const root = await privateDirectory2(options.root ?? installationRoot());
933
+ const profiles = await privateDirectory2(path3.join(root, "profiles"));
934
+ const profile = path3.join(profiles, options.ephemeral ? `ephemeral-${randomUUID3()}` : name);
935
+ await privateDirectory2(profile);
471
936
  const profileStat = await fs3.lstat(profile);
472
937
  options.signal?.throwIfAborted();
473
- const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
938
+ const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
474
939
  let lock;
475
940
  try {
476
941
  lock = await fs3.open(lockPath, "wx", 384);
@@ -480,6 +945,14 @@ async function launchDedicated(options = {}) {
480
945
  throw new Error(`Profile already locked: ${lockPath}. Use a different --profile to launch another browser. After stopping the previous CLI and Chrome, run browser-mcp browser recover --profile ${name}. Recovery refuses live or uncertain owners; never blindly remove locks or sockets.`);
481
946
  }
482
947
  const lockStat = await lock.stat();
948
+ const lifecycle = new ChromeLifecycle({ root, profile: name, instanceId });
949
+ const onAbort = () => {
950
+ if (!lifecycle.hasEnded)
951
+ lifecycle.requestShutdown("group-stop");
952
+ };
953
+ options.signal?.addEventListener("abort", onAbort, { once: true });
954
+ if (options.signal?.aborted)
955
+ onAbort();
483
956
  const runPath = path3.join(profile, `run-${instanceId}`);
484
957
  const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
485
958
  let context, launched = false, lockWritten = false;
@@ -537,6 +1010,7 @@ async function launchDedicated(options = {}) {
537
1010
  }]
538
1011
  ]);
539
1012
  } finally {
1013
+ options.signal?.removeEventListener("abort", onAbort);
540
1014
  await lock.close();
541
1015
  }
542
1016
  });
@@ -547,20 +1021,36 @@ async function launchDedicated(options = {}) {
547
1021
  runStat = await fs3.lstat(runPath);
548
1022
  await fs3.writeFile(path3.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
549
1023
  options.signal?.throwIfAborted();
550
- const executablePath = await discoverChrome(options.chromePath);
1024
+ lifecycle.setStage("discovery");
1025
+ let executablePath;
1026
+ try {
1027
+ executablePath = await discoverChrome(options.chromePath);
1028
+ } catch {
1029
+ options.signal?.throwIfAborted();
1030
+ lifecycle.fail("chrome-not-found");
1031
+ throw new Error(`${(await lifecycle.report()).summary} Install stable Google Chrome or supply --chrome-path /absolute/path.`);
1032
+ }
551
1033
  options.signal?.throwIfAborted();
552
1034
  launched = true;
553
- chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal });
1035
+ chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal, lifecycle });
554
1036
  context = chrome.context;
555
1037
  options.signal?.throwIfAborted();
556
- return { context, instanceId, profile, runPath, close, manifest };
1038
+ return { context, instanceId, profile, runPath, close, manifest, lifecycle };
557
1039
  } catch (error) {
1040
+ let cleanupError;
558
1041
  try {
559
1042
  await close();
560
- } catch (cleanupError) {
1043
+ } catch (caught) {
1044
+ cleanupError = caught;
1045
+ }
1046
+ if (chrome && lifecycle.hasEnded) {
1047
+ const result = await lifecycle.report();
1048
+ if (result.failed)
1049
+ error = new Error(result.summary);
1050
+ }
1051
+ if (cleanupError)
561
1052
  throw new AggregateError([error, cleanupError], `${error instanceof Error ? error.message : error}
562
1053
  ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
563
- }
564
1054
  throw error;
565
1055
  }
566
1056
  }
@@ -576,7 +1066,7 @@ async function listenControl(server, root, controlPath) {
576
1066
  const close = onceAsync(() => cleanupSteps([
577
1067
  ["Control listener", async () => {
578
1068
  if (server.listening)
579
- await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
1069
+ await new Promise((resolve2, reject) => server.close((error) => error ? reject(error) : resolve2()));
580
1070
  }],
581
1071
  ["Control pathname", async () => {
582
1072
  if (!published)
@@ -604,9 +1094,9 @@ async function listenControl(server, root, controlPath) {
604
1094
  ]));
605
1095
  try {
606
1096
  await fs4.writeFile(path4.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
607
- await new Promise((resolve, reject) => {
1097
+ await new Promise((resolve2, reject) => {
608
1098
  server.once("error", reject);
609
- server.listen(boundPath, resolve);
1099
+ server.listen(boundPath, resolve2);
610
1100
  });
611
1101
  socketStat = await fs4.lstat(boundPath);
612
1102
  await fs4.chmod(boundPath, 384);
@@ -1264,10 +1754,10 @@ class BrowserUploadStore {
1264
1754
  throw new Error("Invalid or duplicate upload id.");
1265
1755
  if (!Array.isArray(files) || files.length === 0 || files.length > 100)
1266
1756
  throw new Error("Upload requires between 1 and 100 files.");
1267
- const metadata = files.map(validateUploadFile);
1757
+ const metadata2 = files.map(validateUploadFile);
1268
1758
  const directory = fs6.mkdtempSync(path6.join(this.directory, "upload-"));
1269
1759
  try {
1270
- const staged = metadata.map((file, index) => {
1760
+ const staged = metadata2.map((file, index) => {
1271
1761
  const parent = path6.join(directory, String(index));
1272
1762
  fs6.mkdirSync(parent, { mode: 448 });
1273
1763
  const filePath = path6.join(parent, file.filename);
@@ -1561,7 +2051,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
1561
2051
  }
1562
2052
  if (options.frames?.length)
1563
2053
  throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
1564
- await bounded2(new Promise((resolve) => setTimeout(resolve, 50)));
2054
+ await bounded2(new Promise((resolve2) => setTimeout(resolve2, 50)));
1565
2055
  return captureFrame(currentFrame, selector, frameOptions, true);
1566
2056
  }
1567
2057
  if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
@@ -1784,8 +2274,8 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1784
2274
  let targetId;
1785
2275
  const candidates = new Map;
1786
2276
  let resolvePage, rejectPage;
1787
- const found = new Promise((resolve, reject) => {
1788
- resolvePage = resolve;
2277
+ const found = new Promise((resolve2, reject) => {
2278
+ resolvePage = resolve2;
1789
2279
  rejectPage = reject;
1790
2280
  });
1791
2281
  found.catch(() => {
@@ -1902,8 +2392,8 @@ async function waitForBrowserCondition(page, input) {
1902
2392
  url: page.url(),
1903
2393
  ...extra
1904
2394
  });
1905
- const timedOut = (counts2 = {}) => result(false, {
1906
- ...counts2,
2395
+ const timedOut = (counts3 = {}) => result(false, {
2396
+ ...counts3,
1907
2397
  code: "wait_timeout",
1908
2398
  error: `wait_for gave up after ${input.timeoutMs}ms. Current URL: ${page.url()}. Take a browser_read_page snapshot to inspect or disambiguate the target.`
1909
2399
  });
@@ -1946,7 +2436,7 @@ async function waitForBrowserCondition(page, input) {
1946
2436
  } catch {
1947
2437
  return invalidTarget();
1948
2438
  }
1949
- let counts = { matchCount: 0, satisfiedCount: 0 };
2439
+ let counts2 = { matchCount: 0, satisfiedCount: 0 };
1950
2440
  while (Date.now() < deadline) {
1951
2441
  if (page.isClosed())
1952
2442
  return result(false, { code: "wait_tab_closed", error: "The tab closed before the condition matched." });
@@ -1959,18 +2449,18 @@ async function waitForBrowserCondition(page, input) {
1959
2449
  if (input.frames.length) {
1960
2450
  const frameRoot = root.locator(":root");
1961
2451
  if (!await frameRoot.count())
1962
- return { ...counts, scopeMissing: true };
2452
+ return { ...counts2, scopeMissing: true };
1963
2453
  frameHandle = await frameRoot.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1964
2454
  if (!frameHandle)
1965
- return { ...counts, scopeMissing: true };
2455
+ return { ...counts2, scopeMissing: true };
1966
2456
  }
1967
2457
  if (scope) {
1968
2458
  const count = await scope.count();
1969
2459
  if (count !== 1)
1970
- return { ...counts, scopeMissing: count === 0, scopeCount: count };
2460
+ return { ...counts2, scopeMissing: count === 0, scopeCount: count };
1971
2461
  handle = await scope.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1972
2462
  if (!handle)
1973
- return { ...counts, scopeMissing: true };
2463
+ return { ...counts2, scopeMissing: true };
1974
2464
  elements = await handle.$$(selector);
1975
2465
  } else {
1976
2466
  elements = await root.locator(selector).elementHandles();
@@ -1995,18 +2485,18 @@ async function waitForBrowserCondition(page, input) {
1995
2485
  scopeMatchCount: observed.scopeCount,
1996
2486
  error: "Scope matched multiple elements. Narrow scope or use a unique ref from browser_read_page."
1997
2487
  });
1998
- counts = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
2488
+ counts2 = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
1999
2489
  if (!observed.scopeMissing) {
2000
- if (input.match === "unique" && counts.matchCount > 1)
2490
+ if (input.match === "unique" && counts2.matchCount > 1)
2001
2491
  return result(false, {
2002
- ...counts,
2492
+ ...counts2,
2003
2493
  code: "ambiguous_wait_target",
2004
2494
  error: "Target matched multiple elements. Narrow target/scope, or explicitly choose match: any or all."
2005
2495
  });
2006
- const absent = counts.matchCount === 0 && (input.state === "hidden" || input.state === "detached");
2007
- const matched = absent || counts.matchCount > 0 && (input.match === "any" ? counts.satisfiedCount > 0 : counts.satisfiedCount === counts.matchCount);
2496
+ const absent = counts2.matchCount === 0 && (input.state === "hidden" || input.state === "detached");
2497
+ const matched = absent || counts2.matchCount > 0 && (input.match === "any" ? counts2.satisfiedCount > 0 : counts2.satisfiedCount === counts2.matchCount);
2008
2498
  if (matched)
2009
- return result(true, { ...counts, state: input.state, match: input.match });
2499
+ return result(true, { ...counts2, state: input.state, match: input.match });
2010
2500
  }
2011
2501
  } catch (error) {
2012
2502
  const message = error instanceof Error ? error.message : String(error);
@@ -2016,13 +2506,13 @@ async function waitForBrowserCondition(page, input) {
2016
2506
  error: "A scope or frame selector matched multiple elements. Use a unique scope and frame path."
2017
2507
  });
2018
2508
  if (Date.now() >= deadline)
2019
- return timedOut(counts);
2509
+ return timedOut(counts2);
2020
2510
  if (!/Timeout|detached|frame.*not found|Failed to find frame|Execution context|navigation|Target closed/i.test(message))
2021
2511
  return invalidTarget();
2022
2512
  }
2023
- await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(50, deadline - Date.now()))));
2513
+ await new Promise((resolve2) => setTimeout(resolve2, Math.max(0, Math.min(50, deadline - Date.now()))));
2024
2514
  }
2025
- return timedOut(counts);
2515
+ return timedOut(counts2);
2026
2516
  }
2027
2517
 
2028
2518
  // cli/src/browser/navigation-observer.ts
@@ -2035,9 +2525,9 @@ function navigationUrlMatches(pattern, url) {
2035
2525
  function observeNavigation(page, input) {
2036
2526
  const started = Date.now(), deadline = started + input.timeoutMs;
2037
2527
  let settled = false;
2038
- let resolve;
2528
+ let resolve2;
2039
2529
  const result = new Promise((done) => {
2040
- resolve = done;
2530
+ resolve2 = done;
2041
2531
  });
2042
2532
  const finish = (matched, code2, error) => {
2043
2533
  if (settled)
@@ -2047,7 +2537,7 @@ function observeNavigation(page, input) {
2047
2537
  page.off("framenavigated", onNavigation);
2048
2538
  page.off("close", onClose);
2049
2539
  page.off("crash", onClose);
2050
- resolve({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
2540
+ resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
2051
2541
  };
2052
2542
  const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
2053
2543
  const onNavigation = (frame) => {
@@ -2272,14 +2762,14 @@ class BrowserPageEvents {
2272
2762
  return first;
2273
2763
  let timer, changed;
2274
2764
  try {
2275
- return await new Promise((resolve) => {
2765
+ return await new Promise((resolve2) => {
2276
2766
  changed = () => {
2277
2767
  const result = this.query(input, false);
2278
2768
  if (result.entries.length)
2279
- resolve(result);
2769
+ resolve2(result);
2280
2770
  };
2281
2771
  this.changes.add(changed);
2282
- timer = setTimeout(() => resolve(this.query(input, false)), Number(input.timeoutMs));
2772
+ timer = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
2283
2773
  changed();
2284
2774
  });
2285
2775
  } finally {
@@ -2319,8 +2809,8 @@ class BrowserPageEvents {
2319
2809
  try {
2320
2810
  return await Promise.race([
2321
2811
  pending.result,
2322
- new Promise((resolve) => {
2323
- timer = setTimeout(() => resolve(undefined), ms);
2812
+ new Promise((resolve2) => {
2813
+ timer = setTimeout(() => resolve2(undefined), ms);
2324
2814
  })
2325
2815
  ]);
2326
2816
  } finally {
@@ -2337,10 +2827,10 @@ class BrowserPageEvents {
2337
2827
  this.currentAction = actionId;
2338
2828
  let interruptedByDialog = false;
2339
2829
  let wake;
2340
- const interrupted = new Promise((resolve) => {
2830
+ const interrupted = new Promise((resolve2) => {
2341
2831
  wake = () => {
2342
2832
  interruptedByDialog = true;
2343
- resolve({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2833
+ resolve2({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2344
2834
  };
2345
2835
  this.listeners.add(wake);
2346
2836
  });
@@ -2558,9 +3048,9 @@ class BrowserWebMCP {
2558
3048
  input: input.arguments
2559
3049
  });
2560
3050
  try {
2561
- const outcome = await new Promise((resolve) => {
2562
- this.responses.set(invocationId, resolve);
2563
- timer = setTimeout(() => resolve(undefined), Number(input.timeoutMs ?? 1e4));
3051
+ const outcome = await new Promise((resolve2) => {
3052
+ this.responses.set(invocationId, resolve2);
3053
+ timer = setTimeout(() => resolve2(undefined), Number(input.timeoutMs ?? 1e4));
2564
3054
  });
2565
3055
  if (!outcome) {
2566
3056
  await this.cdp.send("WebMCP.cancelInvocation", { invocationId }).catch(() => {
@@ -4155,7 +4645,7 @@ class NativeRuntime {
4155
4645
  try {
4156
4646
  return await work();
4157
4647
  } finally {
4158
- await new Promise((resolve) => setTimeout(resolve, 50));
4648
+ await new Promise((resolve2) => setTimeout(resolve2, 50));
4159
4649
  events.diagnosticsSuppressed = false;
4160
4650
  }
4161
4651
  }
@@ -4263,7 +4753,7 @@ class NativeRuntime {
4263
4753
 
4264
4754
  // cli/src/runtime/relay.ts
4265
4755
  import WebSocket2 from "ws";
4266
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
4756
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
4267
4757
  import fs9 from "node:fs/promises";
4268
4758
  import path8 from "node:path";
4269
4759
 
@@ -4521,14 +5011,14 @@ class NativeLiveProducer {
4521
5011
  const ws = new WebSocket(this.options.mediaUrl, { maxPayload: 2048, perMessageDeflate: false });
4522
5012
  this.socket = ws;
4523
5013
  try {
4524
- await new Promise((resolve, reject) => {
5014
+ await new Promise((resolve2, reject) => {
4525
5015
  const timer = setTimeout(() => {
4526
5016
  ws.terminate();
4527
5017
  reject(new Error("Media timeout"));
4528
5018
  }, 5000);
4529
5019
  const done = (error) => {
4530
5020
  clearTimeout(timer);
4531
- error ? reject(error) : resolve();
5021
+ error ? reject(error) : resolve2();
4532
5022
  };
4533
5023
  ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
4534
5024
  ws.once("error", () => done(new Error("Media unavailable")));
@@ -4716,11 +5206,11 @@ class Relay {
4716
5206
  u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
4717
5207
  const socket = new WebSocket2(u, { maxPayload: LIMIT, handshakeTimeout: 15000, followRedirects: false });
4718
5208
  this.socket = socket;
4719
- await new Promise((resolve, reject) => {
5209
+ await new Promise((resolve2, reject) => {
4720
5210
  socket.once("error", reject);
4721
5211
  socket.once("close", () => {
4722
5212
  clearInterval(heartbeat);
4723
- resolve();
5213
+ resolve2();
4724
5214
  });
4725
5215
  const heartbeat = setInterval(() => {
4726
5216
  if (socket.readyState === WebSocket2.OPEN)
@@ -4729,7 +5219,7 @@ class Relay {
4729
5219
  heartbeat.unref();
4730
5220
  socket.once("open", () => {
4731
5221
  this.state = "authenticating";
4732
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.10", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab"], capabilities: ["browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
5222
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.11", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab"], capabilities: ["browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
4733
5223
  });
4734
5224
  socket.on("message", (bytes, binary) => {
4735
5225
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -4876,7 +5366,7 @@ class Relay {
4876
5366
  async upload(bytes, role, name, mimeType) {
4877
5367
  if (bytes.length > 20 * 1024 * 1024)
4878
5368
  throw new Error("Preview exceeds 20 MiB");
4879
- const blobId = randomUUID2(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5369
+ const blobId = randomUUID4(), sha256 = createHash5("sha256").update(bytes).digest("hex");
4880
5370
  const response = await fetch(new URL(`/api/runtime/blobs/${blobId}`, this.server), { method: "PUT", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/octet-stream", "X-Runtime-Instance": this.runtime.instanceId, "X-Content-SHA256": sha256 }, body: bytes, redirect: "error", signal: AbortSignal.timeout(30000) });
4881
5371
  if (!response.ok)
4882
5372
  throw new Error("Preview upload failed");
@@ -4901,15 +5391,15 @@ class Relay {
4901
5391
  }
4902
5392
 
4903
5393
  // cli/src/data/index.ts
4904
- import { mkdir, open, rename, unlink, rmdir, chmod, lstat } from "node:fs/promises";
5394
+ import { mkdir as mkdir2, open as open2, rename, unlink as unlink2, rmdir as rmdir2, chmod, lstat as lstat2 } from "node:fs/promises";
4905
5395
  import { createReadStream, createWriteStream } from "node:fs";
4906
- import { randomUUID as randomUUID4, createHash as createHash6 } from "node:crypto";
4907
- import { join, basename } from "node:path";
5396
+ import { randomUUID as randomUUID6, createHash as createHash6 } from "node:crypto";
5397
+ import { join as join2, basename } from "node:path";
4908
5398
  import { Readable, Transform } from "node:stream";
4909
5399
  import { pipeline } from "node:stream/promises";
4910
5400
 
4911
5401
  // cli/src/data/vault.ts
4912
- import { randomUUID as randomUUID3 } from "node:crypto";
5402
+ import { randomUUID as randomUUID5 } from "node:crypto";
4913
5403
  class SecretVault {
4914
5404
  access;
4915
5405
  entries = new Map;
@@ -4976,7 +5466,7 @@ class SecretVault {
4976
5466
  }
4977
5467
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
4978
5468
  throw new Error("Vault quota exceeded");
4979
- const entry = { id: randomUUID3(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
5469
+ const entry = { id: randomUUID5(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
4980
5470
  this.entries.set(entry.id, entry);
4981
5471
  return this.metadata(entry);
4982
5472
  } catch {
@@ -5035,7 +5525,7 @@ var safeName = (s) => {
5035
5525
  async function createDataPlugin(access, options) {
5036
5526
  if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
5037
5527
  throw new Error("HTTPS data server required");
5038
- await mkdir(options.directory, { mode: 448 });
5528
+ await mkdir2(options.directory, { mode: 448 });
5039
5529
  const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
5040
5530
  let stopped = false;
5041
5531
  function meta(r) {
@@ -5054,7 +5544,7 @@ async function createDataPlugin(access, options) {
5054
5544
  }
5055
5545
  function create(scope, purpose, size, name) {
5056
5546
  reserve(scope, size);
5057
- const r = { id: randomUUID4(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
5547
+ const r = { id: randomUUID6(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
5058
5548
  resources.set(r.id, r);
5059
5549
  return r;
5060
5550
  }
@@ -5065,12 +5555,12 @@ async function createDataPlugin(access, options) {
5065
5555
  r.bytes?.fill(0);
5066
5556
  r.bytes = undefined;
5067
5557
  if (r.path && owned.has(r.path)) {
5068
- await unlink(r.path).catch(() => {});
5558
+ await unlink2(r.path).catch(() => {});
5069
5559
  owned.delete(r.path);
5070
5560
  }
5071
- const dir = join(options.directory, r.id);
5561
+ const dir = join2(options.directory, r.id);
5072
5562
  if (ownedDirs.has(dir)) {
5073
- await rmdir(dir).catch(() => {});
5563
+ await rmdir2(dir).catch(() => {});
5074
5564
  ownedDirs.delete(dir);
5075
5565
  }
5076
5566
  resources.delete(r.id);
@@ -5088,11 +5578,11 @@ async function createDataPlugin(access, options) {
5088
5578
  const response = await fetch(g.url, { method: "GET", headers: g.headers, redirect: "error", signal: r.abort.signal });
5089
5579
  if (!response.ok || !response.body)
5090
5580
  throw new Error("Transfer failed");
5091
- const dir = join(options.directory, r.id);
5092
- await mkdir(dir, { mode: 448 });
5581
+ const dir = join2(options.directory, r.id);
5582
+ await mkdir2(dir, { mode: 448 });
5093
5583
  ownedDirs.add(dir);
5094
- const part = join(options.directory, `${r.id}.partial`), dest = join(dir, r.name);
5095
- const h = await open(part, "wx", 384);
5584
+ const part = join2(options.directory, `${r.id}.partial`), dest = join2(dir, r.name);
5585
+ const h = await open2(part, "wx", 384);
5096
5586
  await h.close();
5097
5587
  owned.add(part);
5098
5588
  r.path = part;
@@ -5122,7 +5612,7 @@ async function createDataPlugin(access, options) {
5122
5612
  } else {
5123
5613
  if (!r.path)
5124
5614
  throw new Error("Missing file");
5125
- const stat = await lstat(r.path);
5615
+ const stat = await lstat2(r.path);
5126
5616
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
5127
5617
  throw new Error("Changed file");
5128
5618
  body = Readable.toWeb(createReadStream(r.path));
@@ -5135,7 +5625,7 @@ async function createDataPlugin(access, options) {
5135
5625
  } catch {
5136
5626
  r.state = "failed";
5137
5627
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
5138
- await unlink(r.path).catch(() => {});
5628
+ await unlink2(r.path).catch(() => {});
5139
5629
  owned.delete(r.path);
5140
5630
  }
5141
5631
  } finally {
@@ -5252,7 +5742,7 @@ async function createDataPlugin(access, options) {
5252
5742
  r = create(scope, "download", LIMITS.file, download.suggestedFilename());
5253
5743
  r.tabId = tabId;
5254
5744
  r.generation = generation;
5255
- const path9 = join(options.directory, r.id);
5745
+ const path9 = join2(options.directory, r.id);
5256
5746
  r.path = path9;
5257
5747
  owned.add(path9);
5258
5748
  const source = await download.createReadStream();
@@ -5273,7 +5763,7 @@ async function createDataPlugin(access, options) {
5273
5763
  clearTimeout(timeout2);
5274
5764
  }
5275
5765
  await chmod(path9, 384);
5276
- const stat = await lstat(path9);
5766
+ const stat = await lstat2(path9);
5277
5767
  if (!stat.isFile() || stat.size > LIMITS.file)
5278
5768
  throw new Error("Download limit");
5279
5769
  r.size = stat.size;
@@ -5312,13 +5802,13 @@ async function createDataPlugin(access, options) {
5312
5802
  vault.revoke(() => true);
5313
5803
  await Promise.all([...resources.values()].filter((r) => r.state !== "attached").map(remove));
5314
5804
  if (!resources.size)
5315
- await rmdir(options.directory).catch(() => {});
5805
+ await rmdir2(options.directory).catch(() => {});
5316
5806
  },
5317
5807
  async onReconnect() {
5318
5808
  if (!stopped)
5319
5809
  return;
5320
5810
  if (!resources.size)
5321
- await mkdir(options.directory, { mode: 448 });
5811
+ await mkdir2(options.directory, { mode: 448 });
5322
5812
  stopped = false;
5323
5813
  sweep = setInterval(() => {
5324
5814
  revoke((r) => r.expiresAt < Date.now() && r.state !== "attached");
@@ -5391,7 +5881,7 @@ function createForwardPlugin(options) {
5391
5881
  }
5392
5882
 
5393
5883
  // cli/src/browser/main.ts
5394
- function parse(args) {
5884
+ function parse2(args) {
5395
5885
  const options = { profiles: [] };
5396
5886
  for (let i = 0;i < args.length; i++) {
5397
5887
  const key = args[i];
@@ -5423,7 +5913,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5423
5913
  }
5424
5914
  if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
5425
5915
  throw new Error("Unknown browser command");
5426
- const options = parse(args), profiles = options.profiles.length ? options.profiles : ["default"];
5916
+ const options = parse2(args), profiles = options.profiles.length ? options.profiles : ["default"];
5427
5917
  for (const profile of profiles)
5428
5918
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(profile))
5429
5919
  throw new Error("Invalid profile name");
@@ -5434,12 +5924,13 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5434
5924
  const abort = new AbortController;
5435
5925
  setMaxListeners(0, abort.signal);
5436
5926
  const requestStop = () => abort.abort(new Error("Browser startup interrupted"));
5927
+ const signalStop = () => abort.abort(new Error("Browser shutdown signal"));
5437
5928
  const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
5438
5929
  if (command === "start")
5439
5930
  for (const signal of signals)
5440
- process.on(signal, requestStop);
5931
+ process.on(signal, signalStop);
5441
5932
  try {
5442
- const root = await privateDirectory(installationRoot());
5933
+ const root = await privateDirectory2(installationRoot());
5443
5934
  if (command !== "start") {
5444
5935
  const profile = profiles[0], controlPath = controlSocketPath(root, profile);
5445
5936
  if (command === "recover") {
@@ -5447,7 +5938,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5447
5938
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
5448
5939
  return;
5449
5940
  }
5450
- await new Promise((resolve, reject) => {
5941
+ await new Promise((resolve2, reject) => {
5451
5942
  const socket = net3.connect(controlPath);
5452
5943
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
5453
5944
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
@@ -5455,7 +5946,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5455
5946
  socket.once("data", (data) => {
5456
5947
  console.log(data.toString().trim());
5457
5948
  socket.end();
5458
- resolve();
5949
+ resolve2();
5459
5950
  });
5460
5951
  socket.once("error", (error) => reject(new Error(`${error.message}. If the CLI has exited, run browser-mcp browser recover --profile ${profile} to check the profile lock and ${controlPath}.`)));
5461
5952
  });
@@ -5491,7 +5982,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5491
5982
  } finally {
5492
5983
  if (command === "start")
5493
5984
  for (const signal of signals)
5494
- process.removeListener(signal, requestStop);
5985
+ process.removeListener(signal, signalStop);
5495
5986
  }
5496
5987
  }
5497
5988
  async function startProfile(root, server, profile, options, groupSignal) {
@@ -5503,37 +5994,47 @@ async function startProfile(root, server, profile, options, groupSignal) {
5503
5994
  const controlPath = controlSocketPath(root, profile);
5504
5995
  let stopControl;
5505
5996
  const clients = new Set;
5506
- const close = onceAsync(() => cleanupSteps([
5507
- ["Relay", async () => {
5508
- await relay?.stop();
5509
- }],
5510
- ["Download quota", async () => {
5511
- await stopQuota?.();
5512
- }],
5513
- ["Runtime", async () => {
5514
- await runtime?.shutdown();
5515
- }],
5516
- ["Local control", async () => {
5517
- for (const client of clients)
5518
- client.destroy();
5519
- await stopControl?.();
5520
- }],
5521
- ["Browser session", async () => {
5522
- await session?.close();
5523
- }]
5524
- ]));
5525
- const requestStop = () => {
5526
- abort.abort(new Error("Browser startup interrupted"));
5997
+ const runtimeCleanup = async (step) => {
5998
+ try {
5999
+ await step();
6000
+ } catch {
6001
+ throw new Error("Runtime cleanup failed (details suppressed)");
6002
+ }
6003
+ };
6004
+ const close = onceAsync(async () => {
6005
+ session?.lifecycle.requestShutdown("owner-close");
6006
+ await cleanupSteps([
6007
+ ["Relay", () => runtimeCleanup(() => relay?.stop())],
6008
+ ["Download quota", () => runtimeCleanup(() => stopQuota?.())],
6009
+ ["Runtime", () => runtimeCleanup(() => runtime?.shutdown())],
6010
+ ["Local control", async () => {
6011
+ for (const client of clients)
6012
+ client.destroy();
6013
+ await stopControl?.();
6014
+ }],
6015
+ ["Browser session", async () => {
6016
+ await session?.close();
6017
+ }]
6018
+ ]);
6019
+ });
6020
+ const endSession = () => {
6021
+ abort.abort(new Error("Browser session ended"));
5527
6022
  if (!starting)
5528
6023
  close().catch(() => {});
5529
6024
  };
5530
- groupSignal.addEventListener("abort", requestStop, { once: true });
6025
+ const requestStop = (reason) => {
6026
+ session?.lifecycle.requestShutdown(reason);
6027
+ endSession();
6028
+ };
6029
+ const groupStop = () => requestStop(groupSignal.reason?.message === "Browser shutdown signal" ? "signal" : "group-stop");
6030
+ groupSignal.addEventListener("abort", groupStop, { once: true });
5531
6031
  if (groupSignal.aborted)
5532
- requestStop();
6032
+ groupStop();
6033
+ let failure, cleanupFailure;
5533
6034
  try {
5534
6035
  abort.signal.throwIfAborted();
5535
6036
  session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
5536
- session.context.once("close", requestStop);
6037
+ session.lifecycle.ended.then(endSession);
5537
6038
  abort.signal.throwIfAborted();
5538
6039
  stopQuota = await enforceDownloadQuota(session.context, path9.join(session.runPath, "chrome-downloads"));
5539
6040
  abort.signal.throwIfAborted();
@@ -5578,11 +6079,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
5578
6079
  else if (cmd === "stop") {
5579
6080
  socket.end(`{"state":"stopping"}
5580
6081
  `);
5581
- requestStop();
6082
+ requestStop("local-stop");
5582
6083
  return;
5583
6084
  } else if (cmd !== "status")
5584
6085
  throw new Error("Invalid command");
5585
- socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.10", protocol: 3 }) + `
6086
+ socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.11", protocol: 3 }) + `
5586
6087
  `);
5587
6088
  })().catch(() => socket.destroy());
5588
6089
  });
@@ -5597,15 +6098,34 @@ async function startProfile(root, server, profile, options, groupSignal) {
5597
6098
  console.error(`Dedicated Chrome running (${profile}). Local controls: browser-mcp browser pause|resume|status|stop --profile ${profile}. Ctrl-C closes all browsers started by this command.`);
5598
6099
  await relay.start();
5599
6100
  } catch (error) {
5600
- if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
5601
- throw error;
6101
+ if (session) {
6102
+ if (!session.lifecycle.hasEnded && !abort.signal.aborted)
6103
+ failure = new Error("Browser runtime failed (details suppressed)");
6104
+ } else if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
6105
+ failure = error;
5602
6106
  } finally {
5603
6107
  try {
5604
6108
  await close();
6109
+ } catch (error) {
6110
+ cleanupFailure = error;
5605
6111
  } finally {
5606
- groupSignal.removeEventListener("abort", requestStop);
6112
+ groupSignal.removeEventListener("abort", groupStop);
5607
6113
  }
5608
6114
  }
6115
+ if (session) {
6116
+ const result = await session.lifecycle.report();
6117
+ if (result.failed)
6118
+ failure = new Error(result.summary);
6119
+ else
6120
+ console.error(result.summary);
6121
+ }
6122
+ if (failure && cleanupFailure)
6123
+ throw new AggregateError([failure, cleanupFailure], `${failure instanceof Error ? failure.message : "Browser failed"}
6124
+ ${cleanupFailure instanceof Error ? cleanupFailure.message : "Cleanup failed"}`);
6125
+ if (failure)
6126
+ throw failure;
6127
+ if (cleanupFailure)
6128
+ throw cleanupFailure;
5609
6129
  }
5610
6130
  export {
5611
6131
  runBrowser