@ricsam/browser-mcp 0.3.10 → 0.3.12

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.12";
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
  });
@@ -89,6 +482,7 @@ function ownedChromeArgs(profile, port) {
89
482
  `--remote-debugging-port=${port}`,
90
483
  "--no-first-run",
91
484
  "--no-default-browser-check",
485
+ "--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
92
486
  "--disable-extensions",
93
487
  "--disable-component-extensions-with-background-pages",
94
488
  "--disable-sync",
@@ -110,38 +504,53 @@ async function bounded(promise, ms) {
110
504
  }
111
505
  }
112
506
  async function launchOwnedChrome(options) {
507
+ const lifecycle = options.lifecycle ?? new ChromeLifecycle({ profile: "standalone", instanceId: randomUUID2() });
113
508
  options.signal?.throwIfAborted();
114
509
  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
- });
510
+ let port, child;
511
+ try {
512
+ lifecycle.setStage("artifacts");
513
+ await fs.mkdir(artifactsDir, { mode: 448 });
514
+ options.signal?.throwIfAborted();
515
+ lifecycle.setStage("port");
516
+ port = await allocateChromePort();
517
+ options.signal?.throwIfAborted();
518
+ lifecycle.setStage("spawn");
519
+ child = spawn(options.executablePath, ownedChromeArgs(options.profile, port), {
520
+ stdio: ["ignore", "ignore", "pipe"]
521
+ });
522
+ } catch {
523
+ options.signal?.throwIfAborted();
524
+ lifecycle.fail("preparation-failed");
525
+ throw new Error((await lifecycle.report()).summary);
526
+ }
527
+ lifecycle.setPid(child.pid);
122
528
  let exited = false;
123
529
  let browser;
124
530
  let closing = false;
125
531
  let resolveExit;
126
- const exit = new Promise((resolve) => {
127
- resolveExit = resolve;
532
+ const exit = new Promise((resolve2) => {
533
+ resolveExit = resolve2;
128
534
  });
129
535
  let rejectStartup;
130
536
  const failed = new Promise((_, reject) => {
131
537
  rejectStartup = reject;
132
538
  });
133
- child.once("exit", () => {
539
+ child.once("exit", (code, signal) => {
540
+ lifecycle.childExited(code, signal);
134
541
  exited = true;
135
542
  resolveExit();
136
543
  rejectStartup(new Error("Owned Chrome exited before startup completed"));
137
544
  });
138
545
  child.on("error", () => {
546
+ lifecycle.fail("spawn-failed");
139
547
  if (!child.pid) {
140
548
  exited = true;
141
549
  resolveExit();
142
550
  }
143
551
  rejectStartup(new Error("Could not start owned Chrome process"));
144
552
  });
553
+ const streamsClosed = new Promise((resolve2) => child.once("close", () => resolve2()));
145
554
  failed.catch(() => {});
146
555
  const alive = () => !exited && child.exitCode === null && child.signalCode === null && !!child.pid;
147
556
  const signalChild = (signal) => {
@@ -150,6 +559,10 @@ async function launchOwnedChrome(options) {
150
559
  };
151
560
  const close = onceAsync(async () => {
152
561
  closing = true;
562
+ if (lifecycle.needsExitGrace && alive())
563
+ await bounded(exit, CLOSE_MS).catch(() => {});
564
+ lifecycle.requestShutdown("owner-close");
565
+ lifecycle.beginCleanup();
153
566
  const requestedClose = !!browser?.isConnected() && alive();
154
567
  if (requestedClose) {
155
568
  try {
@@ -178,48 +591,89 @@ async function launchOwnedChrome(options) {
178
591
  } finally {
179
592
  if (browser)
180
593
  await bounded(browser.close(), CLOSE_MS).catch(() => {});
594
+ if (!alive())
595
+ await bounded(streamsClosed, CLOSE_MS).catch(() => {});
181
596
  child.stderr?.destroy();
597
+ lifecycle.diagnostics.finish();
182
598
  }
183
599
  if (alive())
184
600
  throw new Error("Owned Chrome did not exit; retain profile ownership");
185
601
  });
186
- let lineBuffer = "";
602
+ let lineBuffer = "", droppingLine = false, endpointPending = true;
187
603
  let resolveEndpoint;
188
- const endpoint = new Promise((resolve) => {
189
- resolveEndpoint = resolve;
604
+ const endpoint = new Promise((resolve2) => {
605
+ resolveEndpoint = resolve2;
190
606
  });
191
607
  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)
608
+ lifecycle.diagnostics.push(chunk);
609
+ if (!endpointPending)
610
+ return;
611
+ let offset = 0;
612
+ while (offset < chunk.length) {
613
+ const newline = chunk.indexOf(`
614
+ `, offset);
615
+ const end = newline === -1 ? chunk.length : newline;
616
+ if (!droppingLine) {
617
+ if (lineBuffer.length + end - offset > 16384) {
618
+ lineBuffer = "";
619
+ droppingLine = true;
620
+ } else
621
+ lineBuffer += chunk.slice(offset, end);
622
+ }
623
+ if (newline === -1)
624
+ break;
625
+ if (!droppingLine) {
626
+ const url = chromeEndpointFromLine(lineBuffer, port);
627
+ if (url) {
628
+ endpointPending = false;
629
+ lineBuffer = "";
630
+ resolveEndpoint(url);
631
+ return;
632
+ } else if (lineBuffer.startsWith("DevTools listening on ")) {
633
+ endpointPending = false;
634
+ lineBuffer = "";
635
+ lifecycle.fail("unexpected-endpoint");
636
+ rejectStartup(new Error("Owned Chrome announced an unexpected debugging endpoint"));
637
+ return;
638
+ }
639
+ }
205
640
  lineBuffer = "";
641
+ droppingLine = false;
642
+ offset = newline + 1;
643
+ }
206
644
  };
207
645
  child.stderr?.setEncoding("utf8");
208
646
  child.stderr?.on("data", onData);
209
- const onAbort = () => rejectStartup(new Error("Owned Chrome startup aborted"));
647
+ const onAbort = () => {
648
+ if (!lifecycle.hasEnded)
649
+ lifecycle.requestShutdown("group-stop");
650
+ rejectStartup(new Error("Owned Chrome startup aborted"));
651
+ };
652
+ const onDisconnect = () => {
653
+ lifecycle.disconnected();
654
+ rejectStartup(new Error("Owned Chrome transport/context disconnected"));
655
+ };
210
656
  options.signal?.addEventListener("abort", onAbort, { once: true });
211
657
  if (options.signal?.aborted)
212
658
  onAbort();
213
659
  const deadline = Date.now() + STARTUP_MS;
660
+ let failureReason = "timeout";
214
661
  const stage = (work) => bounded(Promise.race([work, failed]), Math.max(1, deadline - Date.now()));
215
662
  try {
663
+ lifecycle.setStage("endpoint");
216
664
  const url = await stage(endpoint);
665
+ lifecycle.setStage("connection");
666
+ failureReason = "connection-failed";
217
667
  const connection = chromium.connectOverCDP(url, {
218
668
  isLocal: true,
219
669
  artifactsDir,
220
670
  timeout: Math.max(1, deadline - Date.now())
221
671
  }).then(async (connected) => {
222
672
  browser = connected;
673
+ lifecycle.setVersion(connected.version());
674
+ connected.once("disconnected", onDisconnect);
675
+ if (!connected.isConnected())
676
+ onDisconnect();
223
677
  if (closing) {
224
678
  await connected.close();
225
679
  throw new Error("Owned Chrome startup cancelled");
@@ -227,38 +681,50 @@ async function launchOwnedChrome(options) {
227
681
  return connected;
228
682
  });
229
683
  await stage(connection);
684
+ lifecycle.setStage("context");
685
+ failureReason = "missing-context";
230
686
  const context = browser.contexts()[0];
231
687
  if (!context)
232
688
  throw new Error("Owned Chrome has no default context");
689
+ context.once("close", onDisconnect);
690
+ failureReason = "context-setup-failed";
233
691
  await stage(context.addInitScript("if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };"));
692
+ lifecycle.setStage("webdriver");
693
+ failureReason = "missing-blank-page";
234
694
  const page = context.pages().find((page2) => page2.url() === "about:blank");
235
695
  if (!page)
236
696
  throw new Error("Owned Chrome did not open the initial blank page");
697
+ failureReason = "webdriver-check-failed";
237
698
  if (await stage(page.evaluate(() => navigator.webdriver)) !== false) {
238
699
  throw new Error("Owned Chrome unexpectedly exposes navigator.webdriver=true");
239
700
  }
240
701
  options.signal?.throwIfAborted();
241
- if (!alive())
242
- throw new Error("Owned Chrome exited during startup");
243
- return { context, close };
702
+ if (!alive() || lifecycle.hasEnded)
703
+ throw new Error("Owned Chrome ended during startup");
704
+ lifecycle.started();
705
+ return { context, close, lifecycle };
244
706
  } catch {
707
+ if (!options.signal?.aborted && !lifecycle.hasEnded)
708
+ lifecycle.fail(Date.now() >= deadline ? "timeout" : failureReason);
709
+ let cleanupFailed = false;
245
710
  try {
246
711
  await close();
247
712
  } catch {
248
- throw new Error("Owned Chrome startup and cleanup failed; retain profile ownership");
713
+ cleanupFailed = true;
249
714
  }
715
+ const result = await lifecycle.report();
716
+ if (result.failed || cleanupFailed)
717
+ throw new Error(`${result.summary}${cleanupFailed ? " Chrome cleanup failed; retain profile ownership." : ""}`);
250
718
  options.signal?.throwIfAborted();
251
- throw new Error("Owned Chrome startup failed (process, endpoint, connection, or webdriver verification)");
719
+ throw new Error(result.summary);
252
720
  } finally {
253
721
  options.signal?.removeEventListener("abort", onAbort);
254
- child.stderr?.off("data", onData);
255
- child.stderr?.resume();
256
722
  }
257
723
  }
258
724
 
259
725
  // cli/src/browser/recovery.ts
260
726
  import fs2 from "node:fs/promises";
261
- import { constants } from "node:fs";
727
+ import { constants as constants2 } from "node:fs";
262
728
  import path2 from "node:path";
263
729
  import os from "node:os";
264
730
  import net2 from "node:net";
@@ -269,7 +735,7 @@ function controlSocketPath(root, profile) {
269
735
  return path2.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
270
736
  }
271
737
  var code = (e) => e.code;
272
- var fail = (file, reason) => {
738
+ var fail2 = (file, reason) => {
273
739
  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
740
  };
275
741
  async function directories(directory) {
@@ -278,14 +744,14 @@ async function directories(directory) {
278
744
  cursor = path2.join(cursor, part);
279
745
  const s = await fs2.lstat(cursor);
280
746
  if (!s.isDirectory() || s.isSymbolicLink())
281
- fail(cursor, "unsafe directory ancestor");
747
+ fail2(cursor, "unsafe directory ancestor");
282
748
  }
283
749
  }
284
750
  async function privateDir(directory) {
285
751
  await directories(directory);
286
752
  const s = await fs2.lstat(directory);
287
753
  if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
288
- fail(directory, "directory must be owned by current user with mode 0700");
754
+ fail2(directory, "directory must be owned by current user with mode 0700");
289
755
  }
290
756
  async function artifact(file, socket = false) {
291
757
  let s;
@@ -297,7 +763,7 @@ async function artifact(file, socket = false) {
297
763
  throw e;
298
764
  }
299
765
  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");
766
+ fail2(file, "unsafe artifact type, links, owner or permissions");
301
767
  return s;
302
768
  }
303
769
  function dead(pid, file) {
@@ -306,25 +772,25 @@ function dead(pid, file) {
306
772
  } catch (e) {
307
773
  if (code(e) === "ESRCH")
308
774
  return;
309
- fail(file, `cannot prove PID ${pid} absent (${code(e)})`);
775
+ fail2(file, `cannot prove PID ${pid} absent (${code(e)})`);
310
776
  }
311
- fail(file, `PID ${pid} exists (including possible PID reuse)`);
777
+ fail2(file, `PID ${pid} exists (including possible PID reuse)`);
312
778
  }
313
779
  async function assertProfileStopped(profile) {
314
780
  let stdout;
315
781
  try {
316
782
  ({ stdout } = await promisify(execFile)("ps", ["-axww", "-o", "pid=,command="], { timeout: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }));
317
783
  } catch {
318
- return fail(profile, "process scan failed or was truncated");
784
+ return fail2(profile, "process scan failed or was truncated");
319
785
  }
320
786
  const lines = stdout.trim().split(`
321
787
  `);
322
788
  if (!lines.length || lines.some((line) => !/^\s*\d+\s+\S/.test(line)))
323
- fail(profile, "uncertain process scan");
789
+ fail2(profile, "uncertain process scan");
324
790
  for (const line of lines) {
325
791
  const pid = Number(line.trim().split(/\s+/, 1)[0]);
326
792
  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}`);
793
+ fail2(profile, `possible surviving profile process: PID ${pid}`);
328
794
  }
329
795
  }
330
796
  const singleton = path2.join(profile, "SingletonLock");
@@ -337,18 +803,18 @@ async function assertProfileStopped(profile) {
337
803
  throw e;
338
804
  }
339
805
  if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
340
- fail(singleton, "unrecognized Chromium singleton lock");
806
+ fail2(singleton, "unrecognized Chromium singleton lock");
341
807
  const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
342
808
  if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
343
- fail(singleton, "foreign or unrecognized Chromium owner");
809
+ fail2(singleton, "foreign or unrecognized Chromium owner");
344
810
  dead(Number(match[2]), singleton);
345
811
  }
346
812
  async function refusedSocket(file) {
347
- await new Promise((resolve, reject) => {
813
+ await new Promise((resolve2, reject) => {
348
814
  const socket = net2.createConnection(file);
349
815
  const finish = (error) => {
350
816
  socket.destroy();
351
- error ? reject(error) : resolve();
817
+ error ? reject(error) : resolve2();
352
818
  };
353
819
  socket.setTimeout(1000, () => finish(new Error(`Recovery refused: socket probe timed out: ${file}`)));
354
820
  socket.once("connect", () => finish(new Error(`Recovery refused: live control listener: ${file}`)));
@@ -372,24 +838,24 @@ async function recoverProfile(root, name) {
372
838
  const original = await artifact(lock), originalSocket = await artifact(socket, true);
373
839
  if (!original) {
374
840
  if (originalSocket)
375
- fail(socket, `socket has no provenance because ${lock} is absent`);
841
+ fail2(socket, `socket has no provenance because ${lock} is absent`);
376
842
  return;
377
843
  }
378
844
  if (original.size > 16384)
379
- fail(lock, "oversized lock");
380
- const handle = await fs2.open(lock, constants.O_RDONLY | constants.O_NOFOLLOW);
845
+ fail2(lock, "oversized lock");
846
+ const handle = await fs2.open(lock, constants2.O_RDONLY | constants2.O_NOFOLLOW);
381
847
  try {
382
848
  if (!same(original, await handle.stat()))
383
- fail(lock, "lock changed while opening");
849
+ fail2(lock, "lock changed while opening");
384
850
  const raw = await handle.readFile("utf8");
385
851
  let owner;
386
852
  try {
387
853
  owner = JSON.parse(raw);
388
854
  } catch {
389
- fail(lock, "invalid lock JSON");
855
+ fail2(lock, "invalid lock JSON");
390
856
  }
391
857
  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)");
858
+ fail2(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
393
859
  const validate = async () => {
394
860
  await privateDir(root);
395
861
  await privateDir(path2.join(root, "profiles"));
@@ -397,19 +863,19 @@ async function recoverProfile(root, name) {
397
863
  dead(owner.pid, lock);
398
864
  await assertProfileStopped(profile);
399
865
  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})`);
866
+ fail2(lock, `artifact identity changed (socket ${socket})`);
401
867
  if (originalSocket)
402
868
  await refusedSocket(socket);
403
869
  dead(owner.pid, lock);
404
870
  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");
871
+ fail2(lock, "artifact identity changed during liveness probe");
406
872
  };
407
873
  await validate();
408
874
  if (originalSocket)
409
875
  await fs2.unlink(socket);
410
876
  dead(owner.pid, lock);
411
877
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
412
- fail(lock, "lock changed before unlink");
878
+ fail2(lock, "lock changed before unlink");
413
879
  await fs2.unlink(lock);
414
880
  } finally {
415
881
  await handle.close();
@@ -423,7 +889,7 @@ async function recoverProfile(root, name) {
423
889
  function installationRoot() {
424
890
  return path3.join(os2.homedir(), ".browser-mcp");
425
891
  }
426
- async function privateDirectory(directory) {
892
+ async function privateDirectory2(directory) {
427
893
  const absolute = path3.resolve(directory);
428
894
  let cursor = path3.parse(absolute).root;
429
895
  for (const piece of absolute.slice(cursor.length).split(path3.sep)) {
@@ -464,13 +930,13 @@ async function launchDedicated(options = {}) {
464
930
  const name = options.profile ?? "default";
465
931
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
466
932
  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);
933
+ const root = await privateDirectory2(options.root ?? installationRoot());
934
+ const profiles = await privateDirectory2(path3.join(root, "profiles"));
935
+ const profile = path3.join(profiles, options.ephemeral ? `ephemeral-${randomUUID3()}` : name);
936
+ await privateDirectory2(profile);
471
937
  const profileStat = await fs3.lstat(profile);
472
938
  options.signal?.throwIfAborted();
473
- const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
939
+ const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
474
940
  let lock;
475
941
  try {
476
942
  lock = await fs3.open(lockPath, "wx", 384);
@@ -480,6 +946,14 @@ async function launchDedicated(options = {}) {
480
946
  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
947
  }
482
948
  const lockStat = await lock.stat();
949
+ const lifecycle = new ChromeLifecycle({ root, profile: name, instanceId });
950
+ const onAbort = () => {
951
+ if (!lifecycle.hasEnded)
952
+ lifecycle.requestShutdown("group-stop");
953
+ };
954
+ options.signal?.addEventListener("abort", onAbort, { once: true });
955
+ if (options.signal?.aborted)
956
+ onAbort();
483
957
  const runPath = path3.join(profile, `run-${instanceId}`);
484
958
  const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
485
959
  let context, launched = false, lockWritten = false;
@@ -537,6 +1011,7 @@ async function launchDedicated(options = {}) {
537
1011
  }]
538
1012
  ]);
539
1013
  } finally {
1014
+ options.signal?.removeEventListener("abort", onAbort);
540
1015
  await lock.close();
541
1016
  }
542
1017
  });
@@ -547,20 +1022,36 @@ async function launchDedicated(options = {}) {
547
1022
  runStat = await fs3.lstat(runPath);
548
1023
  await fs3.writeFile(path3.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
549
1024
  options.signal?.throwIfAborted();
550
- const executablePath = await discoverChrome(options.chromePath);
1025
+ lifecycle.setStage("discovery");
1026
+ let executablePath;
1027
+ try {
1028
+ executablePath = await discoverChrome(options.chromePath);
1029
+ } catch {
1030
+ options.signal?.throwIfAborted();
1031
+ lifecycle.fail("chrome-not-found");
1032
+ throw new Error(`${(await lifecycle.report()).summary} Install stable Google Chrome or supply --chrome-path /absolute/path.`);
1033
+ }
551
1034
  options.signal?.throwIfAborted();
552
1035
  launched = true;
553
- chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal });
1036
+ chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal, lifecycle });
554
1037
  context = chrome.context;
555
1038
  options.signal?.throwIfAborted();
556
- return { context, instanceId, profile, runPath, close, manifest };
1039
+ return { context, instanceId, profile, runPath, close, manifest, lifecycle };
557
1040
  } catch (error) {
1041
+ let cleanupError;
558
1042
  try {
559
1043
  await close();
560
- } catch (cleanupError) {
1044
+ } catch (caught) {
1045
+ cleanupError = caught;
1046
+ }
1047
+ if (chrome && lifecycle.hasEnded) {
1048
+ const result = await lifecycle.report();
1049
+ if (result.failed)
1050
+ error = new Error(result.summary);
1051
+ }
1052
+ if (cleanupError)
561
1053
  throw new AggregateError([error, cleanupError], `${error instanceof Error ? error.message : error}
562
1054
  ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
563
- }
564
1055
  throw error;
565
1056
  }
566
1057
  }
@@ -576,7 +1067,7 @@ async function listenControl(server, root, controlPath) {
576
1067
  const close = onceAsync(() => cleanupSteps([
577
1068
  ["Control listener", async () => {
578
1069
  if (server.listening)
579
- await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
1070
+ await new Promise((resolve2, reject) => server.close((error) => error ? reject(error) : resolve2()));
580
1071
  }],
581
1072
  ["Control pathname", async () => {
582
1073
  if (!published)
@@ -604,9 +1095,9 @@ async function listenControl(server, root, controlPath) {
604
1095
  ]));
605
1096
  try {
606
1097
  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) => {
1098
+ await new Promise((resolve2, reject) => {
608
1099
  server.once("error", reject);
609
- server.listen(boundPath, resolve);
1100
+ server.listen(boundPath, resolve2);
610
1101
  });
611
1102
  socketStat = await fs4.lstat(boundPath);
612
1103
  await fs4.chmod(boundPath, 384);
@@ -1264,10 +1755,10 @@ class BrowserUploadStore {
1264
1755
  throw new Error("Invalid or duplicate upload id.");
1265
1756
  if (!Array.isArray(files) || files.length === 0 || files.length > 100)
1266
1757
  throw new Error("Upload requires between 1 and 100 files.");
1267
- const metadata = files.map(validateUploadFile);
1758
+ const metadata2 = files.map(validateUploadFile);
1268
1759
  const directory = fs6.mkdtempSync(path6.join(this.directory, "upload-"));
1269
1760
  try {
1270
- const staged = metadata.map((file, index) => {
1761
+ const staged = metadata2.map((file, index) => {
1271
1762
  const parent = path6.join(directory, String(index));
1272
1763
  fs6.mkdirSync(parent, { mode: 448 });
1273
1764
  const filePath = path6.join(parent, file.filename);
@@ -1561,7 +2052,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
1561
2052
  }
1562
2053
  if (options.frames?.length)
1563
2054
  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)));
2055
+ await bounded2(new Promise((resolve2) => setTimeout(resolve2, 50)));
1565
2056
  return captureFrame(currentFrame, selector, frameOptions, true);
1566
2057
  }
1567
2058
  if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
@@ -1784,8 +2275,8 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1784
2275
  let targetId;
1785
2276
  const candidates = new Map;
1786
2277
  let resolvePage, rejectPage;
1787
- const found = new Promise((resolve, reject) => {
1788
- resolvePage = resolve;
2278
+ const found = new Promise((resolve2, reject) => {
2279
+ resolvePage = resolve2;
1789
2280
  rejectPage = reject;
1790
2281
  });
1791
2282
  found.catch(() => {
@@ -1902,8 +2393,8 @@ async function waitForBrowserCondition(page, input) {
1902
2393
  url: page.url(),
1903
2394
  ...extra
1904
2395
  });
1905
- const timedOut = (counts2 = {}) => result(false, {
1906
- ...counts2,
2396
+ const timedOut = (counts3 = {}) => result(false, {
2397
+ ...counts3,
1907
2398
  code: "wait_timeout",
1908
2399
  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
2400
  });
@@ -1946,7 +2437,7 @@ async function waitForBrowserCondition(page, input) {
1946
2437
  } catch {
1947
2438
  return invalidTarget();
1948
2439
  }
1949
- let counts = { matchCount: 0, satisfiedCount: 0 };
2440
+ let counts2 = { matchCount: 0, satisfiedCount: 0 };
1950
2441
  while (Date.now() < deadline) {
1951
2442
  if (page.isClosed())
1952
2443
  return result(false, { code: "wait_tab_closed", error: "The tab closed before the condition matched." });
@@ -1959,18 +2450,18 @@ async function waitForBrowserCondition(page, input) {
1959
2450
  if (input.frames.length) {
1960
2451
  const frameRoot = root.locator(":root");
1961
2452
  if (!await frameRoot.count())
1962
- return { ...counts, scopeMissing: true };
2453
+ return { ...counts2, scopeMissing: true };
1963
2454
  frameHandle = await frameRoot.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1964
2455
  if (!frameHandle)
1965
- return { ...counts, scopeMissing: true };
2456
+ return { ...counts2, scopeMissing: true };
1966
2457
  }
1967
2458
  if (scope) {
1968
2459
  const count = await scope.count();
1969
2460
  if (count !== 1)
1970
- return { ...counts, scopeMissing: count === 0, scopeCount: count };
2461
+ return { ...counts2, scopeMissing: count === 0, scopeCount: count };
1971
2462
  handle = await scope.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1972
2463
  if (!handle)
1973
- return { ...counts, scopeMissing: true };
2464
+ return { ...counts2, scopeMissing: true };
1974
2465
  elements = await handle.$$(selector);
1975
2466
  } else {
1976
2467
  elements = await root.locator(selector).elementHandles();
@@ -1995,18 +2486,18 @@ async function waitForBrowserCondition(page, input) {
1995
2486
  scopeMatchCount: observed.scopeCount,
1996
2487
  error: "Scope matched multiple elements. Narrow scope or use a unique ref from browser_read_page."
1997
2488
  });
1998
- counts = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
2489
+ counts2 = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
1999
2490
  if (!observed.scopeMissing) {
2000
- if (input.match === "unique" && counts.matchCount > 1)
2491
+ if (input.match === "unique" && counts2.matchCount > 1)
2001
2492
  return result(false, {
2002
- ...counts,
2493
+ ...counts2,
2003
2494
  code: "ambiguous_wait_target",
2004
2495
  error: "Target matched multiple elements. Narrow target/scope, or explicitly choose match: any or all."
2005
2496
  });
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);
2497
+ const absent = counts2.matchCount === 0 && (input.state === "hidden" || input.state === "detached");
2498
+ const matched = absent || counts2.matchCount > 0 && (input.match === "any" ? counts2.satisfiedCount > 0 : counts2.satisfiedCount === counts2.matchCount);
2008
2499
  if (matched)
2009
- return result(true, { ...counts, state: input.state, match: input.match });
2500
+ return result(true, { ...counts2, state: input.state, match: input.match });
2010
2501
  }
2011
2502
  } catch (error) {
2012
2503
  const message = error instanceof Error ? error.message : String(error);
@@ -2016,13 +2507,13 @@ async function waitForBrowserCondition(page, input) {
2016
2507
  error: "A scope or frame selector matched multiple elements. Use a unique scope and frame path."
2017
2508
  });
2018
2509
  if (Date.now() >= deadline)
2019
- return timedOut(counts);
2510
+ return timedOut(counts2);
2020
2511
  if (!/Timeout|detached|frame.*not found|Failed to find frame|Execution context|navigation|Target closed/i.test(message))
2021
2512
  return invalidTarget();
2022
2513
  }
2023
- await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(50, deadline - Date.now()))));
2514
+ await new Promise((resolve2) => setTimeout(resolve2, Math.max(0, Math.min(50, deadline - Date.now()))));
2024
2515
  }
2025
- return timedOut(counts);
2516
+ return timedOut(counts2);
2026
2517
  }
2027
2518
 
2028
2519
  // cli/src/browser/navigation-observer.ts
@@ -2035,9 +2526,9 @@ function navigationUrlMatches(pattern, url) {
2035
2526
  function observeNavigation(page, input) {
2036
2527
  const started = Date.now(), deadline = started + input.timeoutMs;
2037
2528
  let settled = false;
2038
- let resolve;
2529
+ let resolve2;
2039
2530
  const result = new Promise((done) => {
2040
- resolve = done;
2531
+ resolve2 = done;
2041
2532
  });
2042
2533
  const finish = (matched, code2, error) => {
2043
2534
  if (settled)
@@ -2047,7 +2538,7 @@ function observeNavigation(page, input) {
2047
2538
  page.off("framenavigated", onNavigation);
2048
2539
  page.off("close", onClose);
2049
2540
  page.off("crash", onClose);
2050
- resolve({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
2541
+ resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
2051
2542
  };
2052
2543
  const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
2053
2544
  const onNavigation = (frame) => {
@@ -2272,14 +2763,14 @@ class BrowserPageEvents {
2272
2763
  return first;
2273
2764
  let timer, changed;
2274
2765
  try {
2275
- return await new Promise((resolve) => {
2766
+ return await new Promise((resolve2) => {
2276
2767
  changed = () => {
2277
2768
  const result = this.query(input, false);
2278
2769
  if (result.entries.length)
2279
- resolve(result);
2770
+ resolve2(result);
2280
2771
  };
2281
2772
  this.changes.add(changed);
2282
- timer = setTimeout(() => resolve(this.query(input, false)), Number(input.timeoutMs));
2773
+ timer = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
2283
2774
  changed();
2284
2775
  });
2285
2776
  } finally {
@@ -2319,8 +2810,8 @@ class BrowserPageEvents {
2319
2810
  try {
2320
2811
  return await Promise.race([
2321
2812
  pending.result,
2322
- new Promise((resolve) => {
2323
- timer = setTimeout(() => resolve(undefined), ms);
2813
+ new Promise((resolve2) => {
2814
+ timer = setTimeout(() => resolve2(undefined), ms);
2324
2815
  })
2325
2816
  ]);
2326
2817
  } finally {
@@ -2337,10 +2828,10 @@ class BrowserPageEvents {
2337
2828
  this.currentAction = actionId;
2338
2829
  let interruptedByDialog = false;
2339
2830
  let wake;
2340
- const interrupted = new Promise((resolve) => {
2831
+ const interrupted = new Promise((resolve2) => {
2341
2832
  wake = () => {
2342
2833
  interruptedByDialog = true;
2343
- resolve({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2834
+ resolve2({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2344
2835
  };
2345
2836
  this.listeners.add(wake);
2346
2837
  });
@@ -2558,9 +3049,9 @@ class BrowserWebMCP {
2558
3049
  input: input.arguments
2559
3050
  });
2560
3051
  try {
2561
- const outcome = await new Promise((resolve) => {
2562
- this.responses.set(invocationId, resolve);
2563
- timer = setTimeout(() => resolve(undefined), Number(input.timeoutMs ?? 1e4));
3052
+ const outcome = await new Promise((resolve2) => {
3053
+ this.responses.set(invocationId, resolve2);
3054
+ timer = setTimeout(() => resolve2(undefined), Number(input.timeoutMs ?? 1e4));
2564
3055
  });
2565
3056
  if (!outcome) {
2566
3057
  await this.cdp.send("WebMCP.cancelInvocation", { invocationId }).catch(() => {
@@ -4155,7 +4646,7 @@ class NativeRuntime {
4155
4646
  try {
4156
4647
  return await work();
4157
4648
  } finally {
4158
- await new Promise((resolve) => setTimeout(resolve, 50));
4649
+ await new Promise((resolve2) => setTimeout(resolve2, 50));
4159
4650
  events.diagnosticsSuppressed = false;
4160
4651
  }
4161
4652
  }
@@ -4263,7 +4754,7 @@ class NativeRuntime {
4263
4754
 
4264
4755
  // cli/src/runtime/relay.ts
4265
4756
  import WebSocket2 from "ws";
4266
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
4757
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
4267
4758
  import fs9 from "node:fs/promises";
4268
4759
  import path8 from "node:path";
4269
4760
 
@@ -4521,14 +5012,14 @@ class NativeLiveProducer {
4521
5012
  const ws = new WebSocket(this.options.mediaUrl, { maxPayload: 2048, perMessageDeflate: false });
4522
5013
  this.socket = ws;
4523
5014
  try {
4524
- await new Promise((resolve, reject) => {
5015
+ await new Promise((resolve2, reject) => {
4525
5016
  const timer = setTimeout(() => {
4526
5017
  ws.terminate();
4527
5018
  reject(new Error("Media timeout"));
4528
5019
  }, 5000);
4529
5020
  const done = (error) => {
4530
5021
  clearTimeout(timer);
4531
- error ? reject(error) : resolve();
5022
+ error ? reject(error) : resolve2();
4532
5023
  };
4533
5024
  ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
4534
5025
  ws.once("error", () => done(new Error("Media unavailable")));
@@ -4716,11 +5207,11 @@ class Relay {
4716
5207
  u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
4717
5208
  const socket = new WebSocket2(u, { maxPayload: LIMIT, handshakeTimeout: 15000, followRedirects: false });
4718
5209
  this.socket = socket;
4719
- await new Promise((resolve, reject) => {
5210
+ await new Promise((resolve2, reject) => {
4720
5211
  socket.once("error", reject);
4721
5212
  socket.once("close", () => {
4722
5213
  clearInterval(heartbeat);
4723
- resolve();
5214
+ resolve2();
4724
5215
  });
4725
5216
  const heartbeat = setInterval(() => {
4726
5217
  if (socket.readyState === WebSocket2.OPEN)
@@ -4729,7 +5220,7 @@ class Relay {
4729
5220
  heartbeat.unref();
4730
5221
  socket.once("open", () => {
4731
5222
  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 } } }));
5223
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.12", 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
5224
  });
4734
5225
  socket.on("message", (bytes, binary) => {
4735
5226
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -4876,7 +5367,7 @@ class Relay {
4876
5367
  async upload(bytes, role, name, mimeType) {
4877
5368
  if (bytes.length > 20 * 1024 * 1024)
4878
5369
  throw new Error("Preview exceeds 20 MiB");
4879
- const blobId = randomUUID2(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5370
+ const blobId = randomUUID4(), sha256 = createHash5("sha256").update(bytes).digest("hex");
4880
5371
  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
5372
  if (!response.ok)
4882
5373
  throw new Error("Preview upload failed");
@@ -4901,15 +5392,15 @@ class Relay {
4901
5392
  }
4902
5393
 
4903
5394
  // cli/src/data/index.ts
4904
- import { mkdir, open, rename, unlink, rmdir, chmod, lstat } from "node:fs/promises";
5395
+ import { mkdir as mkdir2, open as open2, rename, unlink as unlink2, rmdir as rmdir2, chmod, lstat as lstat2 } from "node:fs/promises";
4905
5396
  import { createReadStream, createWriteStream } from "node:fs";
4906
- import { randomUUID as randomUUID4, createHash as createHash6 } from "node:crypto";
4907
- import { join, basename } from "node:path";
5397
+ import { randomUUID as randomUUID6, createHash as createHash6 } from "node:crypto";
5398
+ import { join as join2, basename } from "node:path";
4908
5399
  import { Readable, Transform } from "node:stream";
4909
5400
  import { pipeline } from "node:stream/promises";
4910
5401
 
4911
5402
  // cli/src/data/vault.ts
4912
- import { randomUUID as randomUUID3 } from "node:crypto";
5403
+ import { randomUUID as randomUUID5 } from "node:crypto";
4913
5404
  class SecretVault {
4914
5405
  access;
4915
5406
  entries = new Map;
@@ -4976,7 +5467,7 @@ class SecretVault {
4976
5467
  }
4977
5468
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
4978
5469
  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 };
5470
+ 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
5471
  this.entries.set(entry.id, entry);
4981
5472
  return this.metadata(entry);
4982
5473
  } catch {
@@ -5035,7 +5526,7 @@ var safeName = (s) => {
5035
5526
  async function createDataPlugin(access, options) {
5036
5527
  if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
5037
5528
  throw new Error("HTTPS data server required");
5038
- await mkdir(options.directory, { mode: 448 });
5529
+ await mkdir2(options.directory, { mode: 448 });
5039
5530
  const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
5040
5531
  let stopped = false;
5041
5532
  function meta(r) {
@@ -5054,7 +5545,7 @@ async function createDataPlugin(access, options) {
5054
5545
  }
5055
5546
  function create(scope, purpose, size, name) {
5056
5547
  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 };
5548
+ const r = { id: randomUUID6(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
5058
5549
  resources.set(r.id, r);
5059
5550
  return r;
5060
5551
  }
@@ -5065,12 +5556,12 @@ async function createDataPlugin(access, options) {
5065
5556
  r.bytes?.fill(0);
5066
5557
  r.bytes = undefined;
5067
5558
  if (r.path && owned.has(r.path)) {
5068
- await unlink(r.path).catch(() => {});
5559
+ await unlink2(r.path).catch(() => {});
5069
5560
  owned.delete(r.path);
5070
5561
  }
5071
- const dir = join(options.directory, r.id);
5562
+ const dir = join2(options.directory, r.id);
5072
5563
  if (ownedDirs.has(dir)) {
5073
- await rmdir(dir).catch(() => {});
5564
+ await rmdir2(dir).catch(() => {});
5074
5565
  ownedDirs.delete(dir);
5075
5566
  }
5076
5567
  resources.delete(r.id);
@@ -5088,11 +5579,11 @@ async function createDataPlugin(access, options) {
5088
5579
  const response = await fetch(g.url, { method: "GET", headers: g.headers, redirect: "error", signal: r.abort.signal });
5089
5580
  if (!response.ok || !response.body)
5090
5581
  throw new Error("Transfer failed");
5091
- const dir = join(options.directory, r.id);
5092
- await mkdir(dir, { mode: 448 });
5582
+ const dir = join2(options.directory, r.id);
5583
+ await mkdir2(dir, { mode: 448 });
5093
5584
  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);
5585
+ const part = join2(options.directory, `${r.id}.partial`), dest = join2(dir, r.name);
5586
+ const h = await open2(part, "wx", 384);
5096
5587
  await h.close();
5097
5588
  owned.add(part);
5098
5589
  r.path = part;
@@ -5122,7 +5613,7 @@ async function createDataPlugin(access, options) {
5122
5613
  } else {
5123
5614
  if (!r.path)
5124
5615
  throw new Error("Missing file");
5125
- const stat = await lstat(r.path);
5616
+ const stat = await lstat2(r.path);
5126
5617
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
5127
5618
  throw new Error("Changed file");
5128
5619
  body = Readable.toWeb(createReadStream(r.path));
@@ -5135,7 +5626,7 @@ async function createDataPlugin(access, options) {
5135
5626
  } catch {
5136
5627
  r.state = "failed";
5137
5628
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
5138
- await unlink(r.path).catch(() => {});
5629
+ await unlink2(r.path).catch(() => {});
5139
5630
  owned.delete(r.path);
5140
5631
  }
5141
5632
  } finally {
@@ -5252,7 +5743,7 @@ async function createDataPlugin(access, options) {
5252
5743
  r = create(scope, "download", LIMITS.file, download.suggestedFilename());
5253
5744
  r.tabId = tabId;
5254
5745
  r.generation = generation;
5255
- const path9 = join(options.directory, r.id);
5746
+ const path9 = join2(options.directory, r.id);
5256
5747
  r.path = path9;
5257
5748
  owned.add(path9);
5258
5749
  const source = await download.createReadStream();
@@ -5273,7 +5764,7 @@ async function createDataPlugin(access, options) {
5273
5764
  clearTimeout(timeout2);
5274
5765
  }
5275
5766
  await chmod(path9, 384);
5276
- const stat = await lstat(path9);
5767
+ const stat = await lstat2(path9);
5277
5768
  if (!stat.isFile() || stat.size > LIMITS.file)
5278
5769
  throw new Error("Download limit");
5279
5770
  r.size = stat.size;
@@ -5312,13 +5803,13 @@ async function createDataPlugin(access, options) {
5312
5803
  vault.revoke(() => true);
5313
5804
  await Promise.all([...resources.values()].filter((r) => r.state !== "attached").map(remove));
5314
5805
  if (!resources.size)
5315
- await rmdir(options.directory).catch(() => {});
5806
+ await rmdir2(options.directory).catch(() => {});
5316
5807
  },
5317
5808
  async onReconnect() {
5318
5809
  if (!stopped)
5319
5810
  return;
5320
5811
  if (!resources.size)
5321
- await mkdir(options.directory, { mode: 448 });
5812
+ await mkdir2(options.directory, { mode: 448 });
5322
5813
  stopped = false;
5323
5814
  sweep = setInterval(() => {
5324
5815
  revoke((r) => r.expiresAt < Date.now() && r.state !== "attached");
@@ -5391,7 +5882,7 @@ function createForwardPlugin(options) {
5391
5882
  }
5392
5883
 
5393
5884
  // cli/src/browser/main.ts
5394
- function parse(args) {
5885
+ function parse2(args) {
5395
5886
  const options = { profiles: [] };
5396
5887
  for (let i = 0;i < args.length; i++) {
5397
5888
  const key = args[i];
@@ -5423,7 +5914,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5423
5914
  }
5424
5915
  if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
5425
5916
  throw new Error("Unknown browser command");
5426
- const options = parse(args), profiles = options.profiles.length ? options.profiles : ["default"];
5917
+ const options = parse2(args), profiles = options.profiles.length ? options.profiles : ["default"];
5427
5918
  for (const profile of profiles)
5428
5919
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(profile))
5429
5920
  throw new Error("Invalid profile name");
@@ -5434,12 +5925,13 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5434
5925
  const abort = new AbortController;
5435
5926
  setMaxListeners(0, abort.signal);
5436
5927
  const requestStop = () => abort.abort(new Error("Browser startup interrupted"));
5928
+ const signalStop = () => abort.abort(new Error("Browser shutdown signal"));
5437
5929
  const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
5438
5930
  if (command === "start")
5439
5931
  for (const signal of signals)
5440
- process.on(signal, requestStop);
5932
+ process.on(signal, signalStop);
5441
5933
  try {
5442
- const root = await privateDirectory(installationRoot());
5934
+ const root = await privateDirectory2(installationRoot());
5443
5935
  if (command !== "start") {
5444
5936
  const profile = profiles[0], controlPath = controlSocketPath(root, profile);
5445
5937
  if (command === "recover") {
@@ -5447,7 +5939,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5447
5939
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
5448
5940
  return;
5449
5941
  }
5450
- await new Promise((resolve, reject) => {
5942
+ await new Promise((resolve2, reject) => {
5451
5943
  const socket = net3.connect(controlPath);
5452
5944
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
5453
5945
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
@@ -5455,7 +5947,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5455
5947
  socket.once("data", (data) => {
5456
5948
  console.log(data.toString().trim());
5457
5949
  socket.end();
5458
- resolve();
5950
+ resolve2();
5459
5951
  });
5460
5952
  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
5953
  });
@@ -5491,7 +5983,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
5491
5983
  } finally {
5492
5984
  if (command === "start")
5493
5985
  for (const signal of signals)
5494
- process.removeListener(signal, requestStop);
5986
+ process.removeListener(signal, signalStop);
5495
5987
  }
5496
5988
  }
5497
5989
  async function startProfile(root, server, profile, options, groupSignal) {
@@ -5503,37 +5995,47 @@ async function startProfile(root, server, profile, options, groupSignal) {
5503
5995
  const controlPath = controlSocketPath(root, profile);
5504
5996
  let stopControl;
5505
5997
  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"));
5998
+ const runtimeCleanup = async (step) => {
5999
+ try {
6000
+ await step();
6001
+ } catch {
6002
+ throw new Error("Runtime cleanup failed (details suppressed)");
6003
+ }
6004
+ };
6005
+ const close = onceAsync(async () => {
6006
+ session?.lifecycle.requestShutdown("owner-close");
6007
+ await cleanupSteps([
6008
+ ["Relay", () => runtimeCleanup(() => relay?.stop())],
6009
+ ["Download quota", () => runtimeCleanup(() => stopQuota?.())],
6010
+ ["Runtime", () => runtimeCleanup(() => runtime?.shutdown())],
6011
+ ["Local control", async () => {
6012
+ for (const client of clients)
6013
+ client.destroy();
6014
+ await stopControl?.();
6015
+ }],
6016
+ ["Browser session", async () => {
6017
+ await session?.close();
6018
+ }]
6019
+ ]);
6020
+ });
6021
+ const endSession = () => {
6022
+ abort.abort(new Error("Browser session ended"));
5527
6023
  if (!starting)
5528
6024
  close().catch(() => {});
5529
6025
  };
5530
- groupSignal.addEventListener("abort", requestStop, { once: true });
6026
+ const requestStop = (reason) => {
6027
+ session?.lifecycle.requestShutdown(reason);
6028
+ endSession();
6029
+ };
6030
+ const groupStop = () => requestStop(groupSignal.reason?.message === "Browser shutdown signal" ? "signal" : "group-stop");
6031
+ groupSignal.addEventListener("abort", groupStop, { once: true });
5531
6032
  if (groupSignal.aborted)
5532
- requestStop();
6033
+ groupStop();
6034
+ let failure, cleanupFailure;
5533
6035
  try {
5534
6036
  abort.signal.throwIfAborted();
5535
6037
  session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
5536
- session.context.once("close", requestStop);
6038
+ session.lifecycle.ended.then(endSession);
5537
6039
  abort.signal.throwIfAborted();
5538
6040
  stopQuota = await enforceDownloadQuota(session.context, path9.join(session.runPath, "chrome-downloads"));
5539
6041
  abort.signal.throwIfAborted();
@@ -5578,11 +6080,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
5578
6080
  else if (cmd === "stop") {
5579
6081
  socket.end(`{"state":"stopping"}
5580
6082
  `);
5581
- requestStop();
6083
+ requestStop("local-stop");
5582
6084
  return;
5583
6085
  } else if (cmd !== "status")
5584
6086
  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 }) + `
6087
+ socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.12", protocol: 3 }) + `
5586
6088
  `);
5587
6089
  })().catch(() => socket.destroy());
5588
6090
  });
@@ -5597,15 +6099,34 @@ async function startProfile(root, server, profile, options, groupSignal) {
5597
6099
  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
6100
  await relay.start();
5599
6101
  } catch (error) {
5600
- if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
5601
- throw error;
6102
+ if (session) {
6103
+ if (!session.lifecycle.hasEnded && !abort.signal.aborted)
6104
+ failure = new Error("Browser runtime failed (details suppressed)");
6105
+ } else if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
6106
+ failure = error;
5602
6107
  } finally {
5603
6108
  try {
5604
6109
  await close();
6110
+ } catch (error) {
6111
+ cleanupFailure = error;
5605
6112
  } finally {
5606
- groupSignal.removeEventListener("abort", requestStop);
6113
+ groupSignal.removeEventListener("abort", groupStop);
5607
6114
  }
5608
6115
  }
6116
+ if (session) {
6117
+ const result = await session.lifecycle.report();
6118
+ if (result.failed)
6119
+ failure = new Error(result.summary);
6120
+ else
6121
+ console.error(result.summary);
6122
+ }
6123
+ if (failure && cleanupFailure)
6124
+ throw new AggregateError([failure, cleanupFailure], `${failure instanceof Error ? failure.message : "Browser failed"}
6125
+ ${cleanupFailure instanceof Error ? cleanupFailure.message : "Cleanup failed"}`);
6126
+ if (failure)
6127
+ throw failure;
6128
+ if (cleanupFailure)
6129
+ throw cleanupFailure;
5609
6130
  }
5610
6131
  export {
5611
6132
  runBrowser