@ricsam/browser-mcp 0.3.7 → 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.
@@ -14,16 +14,22 @@ import {
14
14
  import"./chunk-1sjcwr28.js";
15
15
 
16
16
  // cli/src/browser/main.ts
17
- import fs9 from "node:fs/promises";
18
- import path8 from "node:path";
19
- import net2 from "node:net";
17
+ import fs10 from "node:fs/promises";
18
+ import path9 from "node:path";
19
+ import net3 from "node:net";
20
20
  import { setMaxListeners } from "node:events";
21
21
 
22
22
  // cli/src/browser/lifecycle.ts
23
- import fs2 from "node:fs/promises";
24
- import path2 from "node:path";
23
+ import fs3 from "node:fs/promises";
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
+
28
+ // cli/src/browser/owned-chrome.ts
29
+ import { spawn } from "node:child_process";
30
+ import net from "node:net";
31
+ import fs from "node:fs/promises";
32
+ import path from "node:path";
27
33
  import { chromium } from "playwright-core";
28
34
 
29
35
  // cli/src/browser/cleanup.ts
@@ -45,48 +51,718 @@ function onceAsync(action) {
45
51
  return () => result ??= Promise.resolve().then(action);
46
52
  }
47
53
 
48
- // cli/src/browser/recovery.ts
49
- import fs from "node:fs/promises";
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
50
60
  import { constants } from "node:fs";
51
- import path from "node:path";
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
+
447
+ // cli/src/browser/owned-chrome.ts
448
+ var STARTUP_MS = 30000;
449
+ var CLOSE_MS = 2000;
450
+ var GRACEFUL_EXIT_MS = 30000;
451
+ async function allocateChromePort() {
452
+ return new Promise((resolve2, reject) => {
453
+ const server = net.createServer();
454
+ const timer = setTimeout(() => {
455
+ server.close();
456
+ reject(new Error("Chrome port allocation timed out"));
457
+ }, STARTUP_MS);
458
+ server.once("error", (error) => {
459
+ clearTimeout(timer);
460
+ reject(error);
461
+ });
462
+ server.listen(0, "127.0.0.1", () => {
463
+ const address = server.address();
464
+ server.close((error) => {
465
+ clearTimeout(timer);
466
+ if (error)
467
+ reject(error);
468
+ else if (!address || typeof address === "string" || !address.port)
469
+ reject(new Error("Invalid Chrome port allocation"));
470
+ else
471
+ resolve2(address.port);
472
+ });
473
+ });
474
+ });
475
+ }
476
+ function ownedChromeArgs(profile, port) {
477
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
478
+ throw new Error("Chrome requires a nonzero TCP port");
479
+ return [
480
+ `--user-data-dir=${profile}`,
481
+ "--remote-debugging-address=127.0.0.1",
482
+ `--remote-debugging-port=${port}`,
483
+ "--no-first-run",
484
+ "--no-default-browser-check",
485
+ "--disable-extensions",
486
+ "--disable-component-extensions-with-background-pages",
487
+ "--disable-sync",
488
+ "about:blank"
489
+ ];
490
+ }
491
+ function chromeEndpointFromLine(line, port) {
492
+ const match = /^DevTools listening on (ws:\/\/127\.0\.0\.1:([1-9][0-9]*)\/devtools\/browser\/[a-zA-Z0-9-]+)\r?$/.exec(line);
493
+ return match && Number(match[2]) === port ? match[1] : undefined;
494
+ }
495
+ async function bounded(promise, ms) {
496
+ let timer;
497
+ try {
498
+ return await Promise.race([promise, new Promise((_, reject) => {
499
+ timer = setTimeout(() => reject(new Error("Owned Chrome operation timed out")), ms);
500
+ })]);
501
+ } finally {
502
+ clearTimeout(timer);
503
+ }
504
+ }
505
+ async function launchOwnedChrome(options) {
506
+ const lifecycle = options.lifecycle ?? new ChromeLifecycle({ profile: "standalone", instanceId: randomUUID2() });
507
+ options.signal?.throwIfAborted();
508
+ const artifactsDir = path.join(options.runPath, "chrome-downloads");
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);
527
+ let exited = false;
528
+ let browser;
529
+ let closing = false;
530
+ let resolveExit;
531
+ const exit = new Promise((resolve2) => {
532
+ resolveExit = resolve2;
533
+ });
534
+ let rejectStartup;
535
+ const failed = new Promise((_, reject) => {
536
+ rejectStartup = reject;
537
+ });
538
+ child.once("exit", (code, signal) => {
539
+ lifecycle.childExited(code, signal);
540
+ exited = true;
541
+ resolveExit();
542
+ rejectStartup(new Error("Owned Chrome exited before startup completed"));
543
+ });
544
+ child.on("error", () => {
545
+ lifecycle.fail("spawn-failed");
546
+ if (!child.pid) {
547
+ exited = true;
548
+ resolveExit();
549
+ }
550
+ rejectStartup(new Error("Could not start owned Chrome process"));
551
+ });
552
+ const streamsClosed = new Promise((resolve2) => child.once("close", () => resolve2()));
553
+ failed.catch(() => {});
554
+ const alive = () => !exited && child.exitCode === null && child.signalCode === null && !!child.pid;
555
+ const signalChild = (signal) => {
556
+ if (alive())
557
+ child.kill(signal);
558
+ };
559
+ const close = onceAsync(async () => {
560
+ closing = true;
561
+ if (lifecycle.needsExitGrace && alive())
562
+ await bounded(exit, CLOSE_MS).catch(() => {});
563
+ lifecycle.requestShutdown("owner-close");
564
+ lifecycle.beginCleanup();
565
+ const requestedClose = !!browser?.isConnected() && alive();
566
+ if (requestedClose) {
567
+ try {
568
+ await bounded((async () => {
569
+ const session = await browser.newBrowserCDPSession();
570
+ try {
571
+ await session.send("Browser.close");
572
+ } finally {
573
+ await session.detach().catch(() => {});
574
+ }
575
+ })(), CLOSE_MS);
576
+ } catch {}
577
+ }
578
+ try {
579
+ if (requestedClose && alive())
580
+ await bounded(exit, GRACEFUL_EXIT_MS).catch(() => {});
581
+ if (alive()) {
582
+ signalChild("SIGTERM");
583
+ try {
584
+ await bounded(exit, CLOSE_MS);
585
+ } catch {
586
+ signalChild("SIGKILL");
587
+ await bounded(exit, CLOSE_MS);
588
+ }
589
+ }
590
+ } finally {
591
+ if (browser)
592
+ await bounded(browser.close(), CLOSE_MS).catch(() => {});
593
+ if (!alive())
594
+ await bounded(streamsClosed, CLOSE_MS).catch(() => {});
595
+ child.stderr?.destroy();
596
+ lifecycle.diagnostics.finish();
597
+ }
598
+ if (alive())
599
+ throw new Error("Owned Chrome did not exit; retain profile ownership");
600
+ });
601
+ let lineBuffer = "", droppingLine = false, endpointPending = true;
602
+ let resolveEndpoint;
603
+ const endpoint = new Promise((resolve2) => {
604
+ resolveEndpoint = resolve2;
605
+ });
606
+ const onData = (chunk) => {
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
+ }
639
+ lineBuffer = "";
640
+ droppingLine = false;
641
+ offset = newline + 1;
642
+ }
643
+ };
644
+ child.stderr?.setEncoding("utf8");
645
+ child.stderr?.on("data", onData);
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
+ };
655
+ options.signal?.addEventListener("abort", onAbort, { once: true });
656
+ if (options.signal?.aborted)
657
+ onAbort();
658
+ const deadline = Date.now() + STARTUP_MS;
659
+ let failureReason = "timeout";
660
+ const stage = (work) => bounded(Promise.race([work, failed]), Math.max(1, deadline - Date.now()));
661
+ try {
662
+ lifecycle.setStage("endpoint");
663
+ const url = await stage(endpoint);
664
+ lifecycle.setStage("connection");
665
+ failureReason = "connection-failed";
666
+ const connection = chromium.connectOverCDP(url, {
667
+ isLocal: true,
668
+ artifactsDir,
669
+ timeout: Math.max(1, deadline - Date.now())
670
+ }).then(async (connected) => {
671
+ browser = connected;
672
+ lifecycle.setVersion(connected.version());
673
+ connected.once("disconnected", onDisconnect);
674
+ if (!connected.isConnected())
675
+ onDisconnect();
676
+ if (closing) {
677
+ await connected.close();
678
+ throw new Error("Owned Chrome startup cancelled");
679
+ }
680
+ return connected;
681
+ });
682
+ await stage(connection);
683
+ lifecycle.setStage("context");
684
+ failureReason = "missing-context";
685
+ const context = browser.contexts()[0];
686
+ if (!context)
687
+ throw new Error("Owned Chrome has no default context");
688
+ context.once("close", onDisconnect);
689
+ failureReason = "context-setup-failed";
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";
693
+ const page = context.pages().find((page2) => page2.url() === "about:blank");
694
+ if (!page)
695
+ throw new Error("Owned Chrome did not open the initial blank page");
696
+ failureReason = "webdriver-check-failed";
697
+ if (await stage(page.evaluate(() => navigator.webdriver)) !== false) {
698
+ throw new Error("Owned Chrome unexpectedly exposes navigator.webdriver=true");
699
+ }
700
+ options.signal?.throwIfAborted();
701
+ if (!alive() || lifecycle.hasEnded)
702
+ throw new Error("Owned Chrome ended during startup");
703
+ lifecycle.started();
704
+ return { context, close, lifecycle };
705
+ } catch {
706
+ if (!options.signal?.aborted && !lifecycle.hasEnded)
707
+ lifecycle.fail(Date.now() >= deadline ? "timeout" : failureReason);
708
+ let cleanupFailed = false;
709
+ try {
710
+ await close();
711
+ } catch {
712
+ cleanupFailed = true;
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." : ""}`);
717
+ options.signal?.throwIfAborted();
718
+ throw new Error(result.summary);
719
+ } finally {
720
+ options.signal?.removeEventListener("abort", onAbort);
721
+ }
722
+ }
723
+
724
+ // cli/src/browser/recovery.ts
725
+ import fs2 from "node:fs/promises";
726
+ import { constants as constants2 } from "node:fs";
727
+ import path2 from "node:path";
52
728
  import os from "node:os";
53
- import net from "node:net";
729
+ import net2 from "node:net";
54
730
  import { createHash } from "node:crypto";
55
731
  import { execFile } from "node:child_process";
56
732
  import { promisify } from "node:util";
57
733
  function controlSocketPath(root, profile) {
58
- return path.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
734
+ return path2.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
59
735
  }
60
736
  var code = (e) => e.code;
61
- var fail = (file, reason) => {
737
+ var fail2 = (file, reason) => {
62
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.`);
63
739
  };
64
740
  async function directories(directory) {
65
- let cursor = path.parse(directory).root;
66
- for (const part of directory.slice(cursor.length).split(path.sep).filter(Boolean)) {
67
- cursor = path.join(cursor, part);
68
- const s = await fs.lstat(cursor);
741
+ let cursor = path2.parse(directory).root;
742
+ for (const part of directory.slice(cursor.length).split(path2.sep).filter(Boolean)) {
743
+ cursor = path2.join(cursor, part);
744
+ const s = await fs2.lstat(cursor);
69
745
  if (!s.isDirectory() || s.isSymbolicLink())
70
- fail(cursor, "unsafe directory ancestor");
746
+ fail2(cursor, "unsafe directory ancestor");
71
747
  }
72
748
  }
73
749
  async function privateDir(directory) {
74
750
  await directories(directory);
75
- const s = await fs.lstat(directory);
751
+ const s = await fs2.lstat(directory);
76
752
  if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
77
- 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");
78
754
  }
79
755
  async function artifact(file, socket = false) {
80
756
  let s;
81
757
  try {
82
- s = await fs.lstat(file);
758
+ s = await fs2.lstat(file);
83
759
  } catch (e) {
84
760
  if (code(e) === "ENOENT")
85
761
  return;
86
762
  throw e;
87
763
  }
88
764
  if (s.isSymbolicLink() || !(socket ? s.isSocket() : s.isFile()) || s.nlink !== 1 || s.uid !== process.getuid?.() || (s.mode & 63) !== 0)
89
- fail(file, "unsafe artifact type, links, owner or permissions");
765
+ fail2(file, "unsafe artifact type, links, owner or permissions");
90
766
  return s;
91
767
  }
92
768
  function dead(pid, file) {
@@ -95,49 +771,49 @@ function dead(pid, file) {
95
771
  } catch (e) {
96
772
  if (code(e) === "ESRCH")
97
773
  return;
98
- fail(file, `cannot prove PID ${pid} absent (${code(e)})`);
774
+ fail2(file, `cannot prove PID ${pid} absent (${code(e)})`);
99
775
  }
100
- fail(file, `PID ${pid} exists (including possible PID reuse)`);
776
+ fail2(file, `PID ${pid} exists (including possible PID reuse)`);
101
777
  }
102
778
  async function assertProfileStopped(profile) {
103
779
  let stdout;
104
780
  try {
105
781
  ({ stdout } = await promisify(execFile)("ps", ["-axww", "-o", "pid=,command="], { timeout: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }));
106
782
  } catch {
107
- return fail(profile, "process scan failed or was truncated");
783
+ return fail2(profile, "process scan failed or was truncated");
108
784
  }
109
785
  const lines = stdout.trim().split(`
110
786
  `);
111
787
  if (!lines.length || lines.some((line) => !/^\s*\d+\s+\S/.test(line)))
112
- fail(profile, "uncertain process scan");
788
+ fail2(profile, "uncertain process scan");
113
789
  for (const line of lines) {
114
790
  const pid = Number(line.trim().split(/\s+/, 1)[0]);
115
791
  if (pid !== process.pid && (line.includes(profile) || /(?:chrome|chromium)/i.test(line) && /--user-data-dir(?:\s|=)/.test(line) && !line.includes("--user-data-dir=/"))) {
116
- fail(profile, `possible surviving profile process: PID ${pid}`);
792
+ fail2(profile, `possible surviving profile process: PID ${pid}`);
117
793
  }
118
794
  }
119
- const singleton = path.join(profile, "SingletonLock");
795
+ const singleton = path2.join(profile, "SingletonLock");
120
796
  let s;
121
797
  try {
122
- s = await fs.lstat(singleton);
798
+ s = await fs2.lstat(singleton);
123
799
  } catch (e) {
124
800
  if (code(e) === "ENOENT")
125
801
  return;
126
802
  throw e;
127
803
  }
128
804
  if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
129
- fail(singleton, "unrecognized Chromium singleton lock");
130
- const target = await fs.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
805
+ fail2(singleton, "unrecognized Chromium singleton lock");
806
+ const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
131
807
  if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
132
- fail(singleton, "foreign or unrecognized Chromium owner");
808
+ fail2(singleton, "foreign or unrecognized Chromium owner");
133
809
  dead(Number(match[2]), singleton);
134
810
  }
135
811
  async function refusedSocket(file) {
136
- await new Promise((resolve, reject) => {
137
- const socket = net.createConnection(file);
812
+ await new Promise((resolve2, reject) => {
813
+ const socket = net2.createConnection(file);
138
814
  const finish = (error) => {
139
815
  socket.destroy();
140
- error ? reject(error) : resolve();
816
+ error ? reject(error) : resolve2();
141
817
  };
142
818
  socket.setTimeout(1000, () => finish(new Error(`Recovery refused: socket probe timed out: ${file}`)));
143
819
  socket.once("connect", () => finish(new Error(`Recovery refused: live control listener: ${file}`)));
@@ -152,54 +828,54 @@ async function recoverProfile(root, name) {
152
828
  throw new Error("Recovery is supported only on Linux and macOS");
153
829
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
154
830
  throw new Error("Profile must be a simple name, not a path");
155
- root = path.resolve(root);
156
- const profile = path.join(root, "profiles", name), lock = path.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
831
+ root = path2.resolve(root);
832
+ const profile = path2.join(root, "profiles", name), lock = path2.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
157
833
  try {
158
834
  await privateDir(root);
159
- await privateDir(path.join(root, "profiles"));
835
+ await privateDir(path2.join(root, "profiles"));
160
836
  await privateDir(profile);
161
837
  const original = await artifact(lock), originalSocket = await artifact(socket, true);
162
838
  if (!original) {
163
839
  if (originalSocket)
164
- fail(socket, `socket has no provenance because ${lock} is absent`);
840
+ fail2(socket, `socket has no provenance because ${lock} is absent`);
165
841
  return;
166
842
  }
167
843
  if (original.size > 16384)
168
- fail(lock, "oversized lock");
169
- const handle = await fs.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);
170
846
  try {
171
847
  if (!same(original, await handle.stat()))
172
- fail(lock, "lock changed while opening");
848
+ fail2(lock, "lock changed while opening");
173
849
  const raw = await handle.readFile("utf8");
174
850
  let owner;
175
851
  try {
176
852
  owner = JSON.parse(raw);
177
853
  } catch {
178
- fail(lock, "invalid lock JSON");
854
+ fail2(lock, "invalid lock JSON");
179
855
  }
180
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])))
181
- 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)");
182
858
  const validate = async () => {
183
859
  await privateDir(root);
184
- await privateDir(path.join(root, "profiles"));
860
+ await privateDir(path2.join(root, "profiles"));
185
861
  await privateDir(profile);
186
862
  dead(owner.pid, lock);
187
863
  await assertProfileStopped(profile);
188
- if (!same(original, await artifact(lock)) || await fs.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
189
- fail(lock, `artifact identity changed (socket ${socket})`);
864
+ if (!same(original, await artifact(lock)) || await fs2.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
865
+ fail2(lock, `artifact identity changed (socket ${socket})`);
190
866
  if (originalSocket)
191
867
  await refusedSocket(socket);
192
868
  dead(owner.pid, lock);
193
869
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)) || !same(originalSocket, await artifact(socket, true)))
194
- fail(lock, "artifact identity changed during liveness probe");
870
+ fail2(lock, "artifact identity changed during liveness probe");
195
871
  };
196
872
  await validate();
197
873
  if (originalSocket)
198
- await fs.unlink(socket);
874
+ await fs2.unlink(socket);
199
875
  dead(owner.pid, lock);
200
876
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
201
- fail(lock, "lock changed before unlink");
202
- await fs.unlink(lock);
877
+ fail2(lock, "lock changed before unlink");
878
+ await fs2.unlink(lock);
203
879
  } finally {
204
880
  await handle.close();
205
881
  }
@@ -210,38 +886,38 @@ async function recoverProfile(root, name) {
210
886
 
211
887
  // cli/src/browser/lifecycle.ts
212
888
  function installationRoot() {
213
- return path2.join(os2.homedir(), ".browser-mcp");
889
+ return path3.join(os2.homedir(), ".browser-mcp");
214
890
  }
215
- async function privateDirectory(directory) {
216
- const absolute = path2.resolve(directory);
217
- let cursor = path2.parse(absolute).root;
218
- for (const piece of absolute.slice(cursor.length).split(path2.sep)) {
219
- cursor = path2.join(cursor, piece);
891
+ async function privateDirectory2(directory) {
892
+ const absolute = path3.resolve(directory);
893
+ let cursor = path3.parse(absolute).root;
894
+ for (const piece of absolute.slice(cursor.length).split(path3.sep)) {
895
+ cursor = path3.join(cursor, piece);
220
896
  try {
221
- await fs2.mkdir(cursor, { mode: 448 });
897
+ await fs3.mkdir(cursor, { mode: 448 });
222
898
  } catch (e) {
223
899
  if (e.code !== "EEXIST")
224
900
  throw e;
225
901
  }
226
- const stat2 = await fs2.lstat(cursor);
902
+ const stat2 = await fs3.lstat(cursor);
227
903
  if (stat2.isSymbolicLink() || !stat2.isDirectory())
228
904
  throw new Error("Unsafe directory path");
229
905
  }
230
- const stat = await fs2.stat(absolute);
906
+ const stat = await fs3.stat(absolute);
231
907
  if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
232
908
  throw new Error("Private directory must be owned by current user with mode 0700");
233
909
  return absolute;
234
910
  }
235
911
  async function discoverChrome(override) {
236
- const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path2.join(os2.homedir(), "Applications/Google Chrome.app/Contents/MacOS/Google Chrome")] : process.platform === "win32" ? [process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter(Boolean).map((p) => path2.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
912
+ const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path3.join(os2.homedir(), "Applications/Google Chrome.app/Contents/MacOS/Google Chrome")] : process.platform === "win32" ? [process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter(Boolean).map((p) => path3.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
237
913
  for (const candidate of candidates) {
238
- if (!path2.isAbsolute(candidate))
914
+ if (!path3.isAbsolute(candidate))
239
915
  throw new Error("Chrome override must be an absolute executable path");
240
916
  try {
241
- const real = await fs2.realpath(candidate), stat = await fs2.stat(real);
917
+ const real = await fs3.realpath(candidate), stat = await fs3.stat(real);
242
918
  if (!stat.isFile())
243
919
  continue;
244
- await fs2.access(real, fs2.constants.X_OK);
920
+ await fs3.access(real, fs3.constants.X_OK);
245
921
  return real;
246
922
  } catch {}
247
923
  }
@@ -253,38 +929,47 @@ async function launchDedicated(options = {}) {
253
929
  const name = options.profile ?? "default";
254
930
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
255
931
  throw new Error("Profile must be a simple name, not a path");
256
- const root = await privateDirectory(options.root ?? installationRoot());
257
- const profiles = await privateDirectory(path2.join(root, "profiles"));
258
- const profile = path2.join(profiles, options.ephemeral ? `ephemeral-${randomUUID()}` : name);
259
- await privateDirectory(profile);
260
- const profileStat = await fs2.lstat(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);
936
+ const profileStat = await fs3.lstat(profile);
261
937
  options.signal?.throwIfAborted();
262
- const lockPath = path2.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
938
+ const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
263
939
  let lock;
264
940
  try {
265
- lock = await fs2.open(lockPath, "wx", 384);
941
+ lock = await fs3.open(lockPath, "wx", 384);
266
942
  } catch (error) {
267
943
  if (error.code !== "EEXIST")
268
944
  throw error;
269
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.`);
270
946
  }
271
947
  const lockStat = await lock.stat();
272
- const runPath = path2.join(profile, `run-${instanceId}`);
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();
956
+ const runPath = path3.join(profile, `run-${instanceId}`);
273
957
  const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
274
958
  let context, launched = false, lockWritten = false;
959
+ let chrome;
275
960
  let runStat;
276
961
  const verifyProfile = async () => {
277
- const stat = await fs2.lstat(profile);
278
- if (await fs2.realpath(profile) !== profile || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== profileStat.dev || stat.ino !== profileStat.ino || stat.uid !== profileStat.uid || stat.mode & 63)
962
+ const stat = await fs3.lstat(profile);
963
+ if (await fs3.realpath(profile) !== profile || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== profileStat.dev || stat.ino !== profileStat.ino || stat.uid !== profileStat.uid || stat.mode & 63)
279
964
  throw new Error("Profile directory ownership changed; retained owned paths");
280
965
  };
281
966
  const verifyLock = async () => {
282
967
  await verifyProfile();
283
- const stat = await fs2.lstat(lockPath);
968
+ const stat = await fs3.lstat(lockPath);
284
969
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.dev !== lockStat.dev || stat.ino !== lockStat.ino || stat.uid !== lockStat.uid || stat.mode & 63)
285
970
  throw new Error("Profile lock ownership changed; retained owned paths");
286
971
  if (lockWritten) {
287
- const stored = JSON.parse(await fs2.readFile(lockPath, "utf8"));
972
+ const stored = JSON.parse(await fs3.readFile(lockPath, "utf8"));
288
973
  if (stored.nonce !== nonce || stored.instanceId !== instanceId || stored.pid !== process.pid || stored.profile !== profile)
289
974
  throw new Error("Profile lock ownership changed; retained owned paths");
290
975
  }
@@ -294,8 +979,9 @@ async function launchDedicated(options = {}) {
294
979
  try {
295
980
  await cleanupSteps([
296
981
  ["Chrome close", async () => {
297
- if (context) {
298
- await context.close();
982
+ if (chrome) {
983
+ await chrome.close();
984
+ await assertProfileStopped(profile);
299
985
  stopped = true;
300
986
  }
301
987
  }],
@@ -307,70 +993,88 @@ async function launchDedicated(options = {}) {
307
993
  ["Run directory", async () => {
308
994
  if (!runStat)
309
995
  return;
310
- const stat = await fs2.lstat(runPath);
996
+ const stat = await fs3.lstat(runPath);
311
997
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== runStat.dev || stat.ino !== runStat.ino || stat.uid !== runStat.uid)
312
998
  throw new Error("Run directory ownership changed; retained path");
313
- await fs2.rm(runPath, { recursive: true, force: true });
999
+ await fs3.rm(runPath, { recursive: true, force: true });
314
1000
  }],
315
1001
  ["Profile lock", async () => {
316
1002
  await verifyLock();
317
- await fs2.unlink(lockPath);
1003
+ await fs3.unlink(lockPath);
318
1004
  }]
319
1005
  ]);
320
1006
  if (options.ephemeral) {
321
1007
  await verifyProfile();
322
- await fs2.rm(profile, { recursive: true, force: true });
1008
+ await fs3.rm(profile, { recursive: true, force: true });
323
1009
  }
324
1010
  }]
325
1011
  ]);
326
1012
  } finally {
1013
+ options.signal?.removeEventListener("abort", onAbort);
327
1014
  await lock.close();
328
1015
  }
329
1016
  });
330
1017
  try {
331
1018
  await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, instanceId, profile, ephemeral: !!options.ephemeral }));
332
1019
  lockWritten = true;
333
- await fs2.mkdir(runPath, { mode: 448 });
334
- runStat = await fs2.lstat(runPath);
335
- await fs2.writeFile(path2.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
1020
+ await fs3.mkdir(runPath, { mode: 448 });
1021
+ runStat = await fs3.lstat(runPath);
1022
+ await fs3.writeFile(path3.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
336
1023
  options.signal?.throwIfAborted();
337
- 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
+ }
338
1033
  options.signal?.throwIfAborted();
339
1034
  launched = true;
340
- context = await chromium.launchPersistentContext(profile, { executablePath, headless: options.headless ?? false, chromiumSandbox: true, timeout: 30000, handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false, ignoreDefaultArgs: ["--password-store=basic", "--use-mock-keychain"], acceptDownloads: true, downloadsPath: path2.join(runPath, "chrome-downloads"), viewport: null, serviceWorkers: "block", args: ["--no-first-run", "--no-default-browser-check"] });
1035
+ chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal, lifecycle });
1036
+ context = chrome.context;
341
1037
  options.signal?.throwIfAborted();
342
- return { context, instanceId, profile, runPath, close, manifest };
1038
+ return { context, instanceId, profile, runPath, close, manifest, lifecycle };
343
1039
  } catch (error) {
1040
+ let cleanupError;
344
1041
  try {
345
1042
  await close();
346
- } 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)
347
1052
  throw new AggregateError([error, cleanupError], `${error instanceof Error ? error.message : error}
348
1053
  ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
349
- }
350
1054
  throw error;
351
1055
  }
352
1056
  }
353
1057
 
354
1058
  // cli/src/browser/control.ts
355
- import fs3 from "node:fs/promises";
356
- import path3 from "node:path";
1059
+ import fs4 from "node:fs/promises";
1060
+ import path4 from "node:path";
357
1061
  async function listenControl(server, root, controlPath) {
358
- const rootStat = await fs3.lstat(root);
359
- const directory = await fs3.mkdtemp(path3.join(root, "c-"));
360
- const dirStat = await fs3.lstat(directory), boundPath = path3.join(directory, "s");
1062
+ const rootStat = await fs4.lstat(root);
1063
+ const directory = await fs4.mkdtemp(path4.join(root, "c-"));
1064
+ const dirStat = await fs4.lstat(directory), boundPath = path4.join(directory, "s");
361
1065
  let socketStat, published = false;
362
1066
  const close = onceAsync(() => cleanupSteps([
363
1067
  ["Control listener", async () => {
364
1068
  if (server.listening)
365
- 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()));
366
1070
  }],
367
1071
  ["Control pathname", async () => {
368
1072
  if (!published)
369
1073
  return;
370
- const parent = await fs3.lstat(root);
371
- if (await fs3.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
1074
+ const parent = await fs4.lstat(root);
1075
+ if (await fs4.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
372
1076
  throw new Error(`Control root ownership changed; retained ${controlPath}`);
373
- const stat = await fs3.lstat(controlPath).catch((error) => {
1077
+ const stat = await fs4.lstat(controlPath).catch((error) => {
374
1078
  if (error.code !== "ENOENT")
375
1079
  throw error;
376
1080
  });
@@ -378,28 +1082,28 @@ async function listenControl(server, root, controlPath) {
378
1082
  return;
379
1083
  if (!stat.isSocket() || !socketStat || stat.nlink !== 1 || stat.dev !== socketStat.dev || stat.ino !== socketStat.ino || stat.ctimeMs !== socketStat.ctimeMs || stat.mode !== socketStat.mode || stat.uid !== socketStat.uid)
380
1084
  throw new Error(`Control socket ownership changed; retained ${controlPath}`);
381
- await fs3.unlink(controlPath);
1085
+ await fs4.unlink(controlPath);
382
1086
  }],
383
1087
  ["Private control directory", async () => {
384
- const stat = await fs3.lstat(directory);
385
- if (await fs3.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
1088
+ const stat = await fs4.lstat(directory);
1089
+ if (await fs4.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
386
1090
  throw new Error(`Control directory ownership changed; retained ${directory}`);
387
- await fs3.unlink(path3.join(directory, "ownership.json"));
388
- await fs3.rmdir(directory);
1091
+ await fs4.unlink(path4.join(directory, "ownership.json"));
1092
+ await fs4.rmdir(directory);
389
1093
  }]
390
1094
  ]));
391
1095
  try {
392
- await fs3.writeFile(path3.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
393
- await new Promise((resolve, reject) => {
1096
+ await fs4.writeFile(path4.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
1097
+ await new Promise((resolve2, reject) => {
394
1098
  server.once("error", reject);
395
- server.listen(boundPath, resolve);
1099
+ server.listen(boundPath, resolve2);
396
1100
  });
397
- socketStat = await fs3.lstat(boundPath);
398
- await fs3.chmod(boundPath, 384);
399
- await fs3.link(boundPath, controlPath);
1101
+ socketStat = await fs4.lstat(boundPath);
1102
+ await fs4.chmod(boundPath, 384);
1103
+ await fs4.link(boundPath, controlPath);
400
1104
  published = true;
401
- await fs3.unlink(boundPath);
402
- socketStat = await fs3.lstat(controlPath);
1105
+ await fs4.unlink(boundPath);
1106
+ socketStat = await fs4.lstat(controlPath);
403
1107
  return close;
404
1108
  } catch (error) {
405
1109
  try {
@@ -413,8 +1117,8 @@ ${cleanupError}`);
413
1117
  }
414
1118
 
415
1119
  // cli/src/browser/pairing.ts
416
- import fs4 from "node:fs/promises";
417
- import path4 from "node:path";
1120
+ import fs5 from "node:fs/promises";
1121
+ import path5 from "node:path";
418
1122
  import { randomBytes, createHash as createHash2 } from "node:crypto";
419
1123
  import { setTimeout as delay } from "node:timers/promises";
420
1124
  function serverURL(raw) {
@@ -427,13 +1131,13 @@ function serverURL(raw) {
427
1131
  }
428
1132
  async function credential(root, server, profile, signal) {
429
1133
  signal?.throwIfAborted();
430
- const filename = path4.join(root, `credential-${createHash2("sha256").update(`${server}
1134
+ const filename = path5.join(root, `credential-${createHash2("sha256").update(`${server}
431
1135
  ${profile}`).digest("hex").slice(0, 24)}.json`);
432
1136
  try {
433
- const stat = await fs4.lstat(filename);
1137
+ const stat = await fs5.lstat(filename);
434
1138
  if (!stat.isFile() || stat.isSymbolicLink() || process.platform !== "win32" && stat.mode & 63)
435
1139
  throw new Error("Unsafe credential file");
436
- const value = JSON.parse(await fs4.readFile(filename, "utf8"));
1140
+ const value = JSON.parse(await fs5.readFile(filename, "utf8"));
437
1141
  if (value.server !== server || !/^br_[\w-]+$/.test(value.token))
438
1142
  throw new Error("Invalid credential file");
439
1143
  return value.token;
@@ -463,7 +1167,7 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
463
1167
  if (typeof token !== "string" || !/^br_[\w-]+$/.test(token))
464
1168
  throw new Error("Pairing did not return a browser credential");
465
1169
  signal?.throwIfAborted();
466
- await fs4.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
1170
+ await fs5.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
467
1171
  return token;
468
1172
  }
469
1173
  throw new Error("Pairing expired");
@@ -528,8 +1232,8 @@ function screenshotPoint(transform, current, delivered, point) {
528
1232
  }
529
1233
 
530
1234
  // cli/src/browser/browser-runtime.ts
531
- import fs7 from "node:fs";
532
- import path6 from "node:path";
1235
+ import fs8 from "node:fs";
1236
+ import path7 from "node:path";
533
1237
 
534
1238
  // cli/src/browser/upload-input.ts
535
1239
  var BROWSER_UPLOAD_CHUNK_BYTES = 1024 * 1024;
@@ -1031,8 +1735,8 @@ function preflightBrowserInput(action, raw) {
1031
1735
  }
1032
1736
 
1033
1737
  // cli/src/browser/upload-store.ts
1034
- import fs5 from "node:fs";
1035
- import path5 from "node:path";
1738
+ import fs6 from "node:fs";
1739
+ import path6 from "node:path";
1036
1740
  import { createHash as createHash3 } from "node:crypto";
1037
1741
  class BrowserUploadStore {
1038
1742
  releaseTarget;
@@ -1042,29 +1746,29 @@ class BrowserUploadStore {
1042
1746
  return;
1043
1747
  }) {
1044
1748
  this.releaseTarget = releaseTarget;
1045
- fs5.mkdirSync(root, { recursive: true, mode: 448 });
1046
- this.directory = fs5.mkdtempSync(path5.join(root, "run-"));
1749
+ fs6.mkdirSync(root, { recursive: true, mode: 448 });
1750
+ this.directory = fs6.mkdtempSync(path6.join(root, "run-"));
1047
1751
  }
1048
1752
  begin(id, tabId, files, target2) {
1049
1753
  if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
1050
1754
  throw new Error("Invalid or duplicate upload id.");
1051
1755
  if (!Array.isArray(files) || files.length === 0 || files.length > 100)
1052
1756
  throw new Error("Upload requires between 1 and 100 files.");
1053
- const metadata = files.map(validateUploadFile);
1054
- const directory = fs5.mkdtempSync(path5.join(this.directory, "upload-"));
1757
+ const metadata2 = files.map(validateUploadFile);
1758
+ const directory = fs6.mkdtempSync(path6.join(this.directory, "upload-"));
1055
1759
  try {
1056
- const staged = metadata.map((file, index) => {
1057
- const parent = path5.join(directory, String(index));
1058
- fs5.mkdirSync(parent, { mode: 448 });
1059
- const filePath = path5.join(parent, file.filename);
1060
- fs5.closeSync(fs5.openSync(filePath, "wx", 384));
1760
+ const staged = metadata2.map((file, index) => {
1761
+ const parent = path6.join(directory, String(index));
1762
+ fs6.mkdirSync(parent, { mode: 448 });
1763
+ const filePath = path6.join(parent, file.filename);
1764
+ fs6.closeSync(fs6.openSync(filePath, "wx", 384));
1061
1765
  return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
1062
1766
  });
1063
1767
  const timer = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
1064
1768
  timer.unref();
1065
1769
  this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer });
1066
1770
  } catch (error) {
1067
- fs5.rmSync(directory, { recursive: true, force: true });
1771
+ fs6.rmSync(directory, { recursive: true, force: true });
1068
1772
  throw error;
1069
1773
  }
1070
1774
  }
@@ -1085,17 +1789,17 @@ class BrowserUploadStore {
1085
1789
  const bytes = decodeUploadChunk(base64);
1086
1790
  if (bytes.length === 0 || file.offset + bytes.length > file.size)
1087
1791
  throw new Error("Upload chunk does not match the declared file size.");
1088
- const fd = fs5.openSync(file.path, fs5.constants.O_WRONLY | fs5.constants.O_NOFOLLOW);
1792
+ const fd = fs6.openSync(file.path, fs6.constants.O_WRONLY | fs6.constants.O_NOFOLLOW);
1089
1793
  try {
1090
1794
  let written = 0;
1091
1795
  while (written < bytes.length) {
1092
- const count = fs5.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
1796
+ const count = fs6.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
1093
1797
  if (!count)
1094
1798
  throw new Error("Could not write upload chunk.");
1095
1799
  written += count;
1096
1800
  }
1097
1801
  } finally {
1098
- fs5.closeSync(fd);
1802
+ fs6.closeSync(fd);
1099
1803
  }
1100
1804
  file.hash.update(bytes);
1101
1805
  file.offset += bytes.length;
@@ -1129,7 +1833,7 @@ class BrowserUploadStore {
1129
1833
  clearTimeout(upload.timer);
1130
1834
  this.uploads.delete(id);
1131
1835
  this.releaseTarget(upload.target);
1132
- fs5.rmSync(upload.directory, { recursive: true, force: true });
1836
+ fs6.rmSync(upload.directory, { recursive: true, force: true });
1133
1837
  }
1134
1838
  closeTab(tabId) {
1135
1839
  for (const [id, upload] of this.uploads)
@@ -1139,7 +1843,7 @@ class BrowserUploadStore {
1139
1843
  close() {
1140
1844
  for (const [id, upload] of this.uploads)
1141
1845
  this.remove(id, upload);
1142
- fs5.rmSync(this.directory, { recursive: true, force: true });
1846
+ fs6.rmSync(this.directory, { recursive: true, force: true });
1143
1847
  }
1144
1848
  }
1145
1849
 
@@ -1317,7 +2021,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
1317
2021
  };
1318
2022
  const document2 = { text: "", priorityRefs: [], matchRefs: [], matchCount: 0, frames: [], unavailableFrames: [] };
1319
2023
  const timeoutError = () => new Error(`Timeout ${timeout2}ms exceeded building a password-safe browser snapshot.`);
1320
- const bounded = async (operation) => {
2024
+ const bounded2 = async (operation) => {
1321
2025
  let timer;
1322
2026
  try {
1323
2027
  return await Promise.race([
@@ -1335,7 +2039,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
1335
2039
  throw new Error(UNAVAILABLE);
1336
2040
  if (Date.now() >= deadline)
1337
2041
  throw timeoutError();
1338
- const captured = await bounded(currentFrame.selectors.callOnSelector(selector, { strict: true }, captureInUtilityWorld, frameOptions));
2042
+ const captured = await bounded2(currentFrame.selectors.callOnSelector(selector, { strict: true }, captureInUtilityWorld, frameOptions));
1339
2043
  if (!captured) {
1340
2044
  if (!isMainFrame) {
1341
2045
  document2.unavailableFrames.push(framePath.at(-1));
@@ -1347,7 +2051,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
1347
2051
  }
1348
2052
  if (options.frames?.length)
1349
2053
  throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
1350
- await bounded(new Promise((resolve) => setTimeout(resolve, 50)));
2054
+ await bounded2(new Promise((resolve2) => setTimeout(resolve2, 50)));
1351
2055
  return captureFrame(currentFrame, selector, frameOptions, true);
1352
2056
  }
1353
2057
  if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
@@ -1537,7 +2241,7 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1537
2241
  const deadline = Date.now() + timeoutMs;
1538
2242
  const sessions = new Set;
1539
2243
  let stopped = false;
1540
- const bounded = async (operation) => {
2244
+ const bounded2 = async (operation) => {
1541
2245
  let timer;
1542
2246
  try {
1543
2247
  return await Promise.race([
@@ -1570,8 +2274,8 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1570
2274
  let targetId;
1571
2275
  const candidates = new Map;
1572
2276
  let resolvePage, rejectPage;
1573
- const found = new Promise((resolve, reject) => {
1574
- resolvePage = resolve;
2277
+ const found = new Promise((resolve2, reject) => {
2278
+ resolvePage = resolve2;
1575
2279
  rejectPage = reject;
1576
2280
  });
1577
2281
  found.catch(() => {
@@ -1584,9 +2288,9 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1584
2288
  };
1585
2289
  const onPage = (page) => {
1586
2290
  (async () => {
1587
- const session = await bounded(attach(page));
2291
+ const session = await bounded2(attach(page));
1588
2292
  try {
1589
- const { targetInfo } = await bounded(session.send("Target.getTargetInfo"));
2293
+ const { targetInfo } = await bounded2(session.send("Target.getTargetInfo"));
1590
2294
  if (!stopped && !page.isClosed()) {
1591
2295
  candidates.set(targetInfo.targetId, page);
1592
2296
  select();
@@ -1604,10 +2308,10 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1604
2308
  try {
1605
2309
  const previous = context.pages().findLast((page) => !page.isClosed());
1606
2310
  if (!previous)
1607
- return await bounded(context.newPage());
1608
- const controller = await bounded(attach(previous));
1609
- const { targetInfo } = await bounded(controller.send("Target.getTargetInfo"));
1610
- const created = await bounded(controller.send("Target.createTarget", {
2311
+ return await bounded2(context.newPage());
2312
+ const controller = await bounded2(attach(previous));
2313
+ const { targetInfo } = await bounded2(controller.send("Target.getTargetInfo"));
2314
+ const created = await bounded2(controller.send("Target.createTarget", {
1611
2315
  url: "about:blank",
1612
2316
  background: true,
1613
2317
  newWindow,
@@ -1616,12 +2320,12 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
1616
2320
  }));
1617
2321
  targetId = created.targetId;
1618
2322
  select();
1619
- return await bounded(found);
2323
+ return await bounded2(found);
1620
2324
  } finally {
1621
2325
  stopped = true;
1622
2326
  context.off("page", onPage);
1623
2327
  context.off("close", onClose);
1624
- await bounded(Promise.allSettled([...sessions].map(detach))).catch(() => {
2328
+ await bounded2(Promise.allSettled([...sessions].map(detach))).catch(() => {
1625
2329
  return;
1626
2330
  });
1627
2331
  }
@@ -1688,8 +2392,8 @@ async function waitForBrowserCondition(page, input) {
1688
2392
  url: page.url(),
1689
2393
  ...extra
1690
2394
  });
1691
- const timedOut = (counts2 = {}) => result(false, {
1692
- ...counts2,
2395
+ const timedOut = (counts3 = {}) => result(false, {
2396
+ ...counts3,
1693
2397
  code: "wait_timeout",
1694
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.`
1695
2399
  });
@@ -1697,7 +2401,7 @@ async function waitForBrowserCondition(page, input) {
1697
2401
  code: "invalid_wait_target",
1698
2402
  error: "Cannot resolve the wait target. Check target, scope and frame selectors with browser_read_page."
1699
2403
  });
1700
- const bounded = async (promise) => {
2404
+ const bounded2 = async (promise) => {
1701
2405
  let timer;
1702
2406
  try {
1703
2407
  return await Promise.race([
@@ -1732,12 +2436,12 @@ async function waitForBrowserCondition(page, input) {
1732
2436
  } catch {
1733
2437
  return invalidTarget();
1734
2438
  }
1735
- let counts = { matchCount: 0, satisfiedCount: 0 };
2439
+ let counts2 = { matchCount: 0, satisfiedCount: 0 };
1736
2440
  while (Date.now() < deadline) {
1737
2441
  if (page.isClosed())
1738
2442
  return result(false, { code: "wait_tab_closed", error: "The tab closed before the condition matched." });
1739
2443
  try {
1740
- const observed = await bounded((async () => {
2444
+ const observed = await bounded2((async () => {
1741
2445
  let handle = null;
1742
2446
  let frameHandle = null;
1743
2447
  let elements = [];
@@ -1745,18 +2449,18 @@ async function waitForBrowserCondition(page, input) {
1745
2449
  if (input.frames.length) {
1746
2450
  const frameRoot = root.locator(":root");
1747
2451
  if (!await frameRoot.count())
1748
- return { ...counts, scopeMissing: true };
2452
+ return { ...counts2, scopeMissing: true };
1749
2453
  frameHandle = await frameRoot.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1750
2454
  if (!frameHandle)
1751
- return { ...counts, scopeMissing: true };
2455
+ return { ...counts2, scopeMissing: true };
1752
2456
  }
1753
2457
  if (scope) {
1754
2458
  const count = await scope.count();
1755
2459
  if (count !== 1)
1756
- return { ...counts, scopeMissing: count === 0, scopeCount: count };
2460
+ return { ...counts2, scopeMissing: count === 0, scopeCount: count };
1757
2461
  handle = await scope.elementHandle({ timeout: Math.max(1, Math.min(250, deadline - Date.now())) });
1758
2462
  if (!handle)
1759
- return { ...counts, scopeMissing: true };
2463
+ return { ...counts2, scopeMissing: true };
1760
2464
  elements = await handle.$$(selector);
1761
2465
  } else {
1762
2466
  elements = await root.locator(selector).elementHandles();
@@ -1781,18 +2485,18 @@ async function waitForBrowserCondition(page, input) {
1781
2485
  scopeMatchCount: observed.scopeCount,
1782
2486
  error: "Scope matched multiple elements. Narrow scope or use a unique ref from browser_read_page."
1783
2487
  });
1784
- counts = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
2488
+ counts2 = { matchCount: observed.matchCount, satisfiedCount: observed.satisfiedCount };
1785
2489
  if (!observed.scopeMissing) {
1786
- if (input.match === "unique" && counts.matchCount > 1)
2490
+ if (input.match === "unique" && counts2.matchCount > 1)
1787
2491
  return result(false, {
1788
- ...counts,
2492
+ ...counts2,
1789
2493
  code: "ambiguous_wait_target",
1790
2494
  error: "Target matched multiple elements. Narrow target/scope, or explicitly choose match: any or all."
1791
2495
  });
1792
- const absent = counts.matchCount === 0 && (input.state === "hidden" || input.state === "detached");
1793
- 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);
1794
2498
  if (matched)
1795
- return result(true, { ...counts, state: input.state, match: input.match });
2499
+ return result(true, { ...counts2, state: input.state, match: input.match });
1796
2500
  }
1797
2501
  } catch (error) {
1798
2502
  const message = error instanceof Error ? error.message : String(error);
@@ -1802,13 +2506,13 @@ async function waitForBrowserCondition(page, input) {
1802
2506
  error: "A scope or frame selector matched multiple elements. Use a unique scope and frame path."
1803
2507
  });
1804
2508
  if (Date.now() >= deadline)
1805
- return timedOut(counts);
2509
+ return timedOut(counts2);
1806
2510
  if (!/Timeout|detached|frame.*not found|Failed to find frame|Execution context|navigation|Target closed/i.test(message))
1807
2511
  return invalidTarget();
1808
2512
  }
1809
- 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()))));
1810
2514
  }
1811
- return timedOut(counts);
2515
+ return timedOut(counts2);
1812
2516
  }
1813
2517
 
1814
2518
  // cli/src/browser/navigation-observer.ts
@@ -1821,9 +2525,9 @@ function navigationUrlMatches(pattern, url) {
1821
2525
  function observeNavigation(page, input) {
1822
2526
  const started = Date.now(), deadline = started + input.timeoutMs;
1823
2527
  let settled = false;
1824
- let resolve;
2528
+ let resolve2;
1825
2529
  const result = new Promise((done) => {
1826
- resolve = done;
2530
+ resolve2 = done;
1827
2531
  });
1828
2532
  const finish = (matched, code2, error) => {
1829
2533
  if (settled)
@@ -1833,7 +2537,7 @@ function observeNavigation(page, input) {
1833
2537
  page.off("framenavigated", onNavigation);
1834
2538
  page.off("close", onClose);
1835
2539
  page.off("crash", onClose);
1836
- 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 } : {} });
1837
2541
  };
1838
2542
  const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
1839
2543
  const onNavigation = (frame) => {
@@ -2058,14 +2762,14 @@ class BrowserPageEvents {
2058
2762
  return first;
2059
2763
  let timer, changed;
2060
2764
  try {
2061
- return await new Promise((resolve) => {
2765
+ return await new Promise((resolve2) => {
2062
2766
  changed = () => {
2063
2767
  const result = this.query(input, false);
2064
2768
  if (result.entries.length)
2065
- resolve(result);
2769
+ resolve2(result);
2066
2770
  };
2067
2771
  this.changes.add(changed);
2068
- timer = setTimeout(() => resolve(this.query(input, false)), Number(input.timeoutMs));
2772
+ timer = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
2069
2773
  changed();
2070
2774
  });
2071
2775
  } finally {
@@ -2105,8 +2809,8 @@ class BrowserPageEvents {
2105
2809
  try {
2106
2810
  return await Promise.race([
2107
2811
  pending.result,
2108
- new Promise((resolve) => {
2109
- timer = setTimeout(() => resolve(undefined), ms);
2812
+ new Promise((resolve2) => {
2813
+ timer = setTimeout(() => resolve2(undefined), ms);
2110
2814
  })
2111
2815
  ]);
2112
2816
  } finally {
@@ -2123,10 +2827,10 @@ class BrowserPageEvents {
2123
2827
  this.currentAction = actionId;
2124
2828
  let interruptedByDialog = false;
2125
2829
  let wake;
2126
- const interrupted = new Promise((resolve) => {
2830
+ const interrupted = new Promise((resolve2) => {
2127
2831
  wake = () => {
2128
2832
  interruptedByDialog = true;
2129
- resolve({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2833
+ resolve2({ dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
2130
2834
  };
2131
2835
  this.listeners.add(wake);
2132
2836
  });
@@ -2344,9 +3048,9 @@ class BrowserWebMCP {
2344
3048
  input: input.arguments
2345
3049
  });
2346
3050
  try {
2347
- const outcome = await new Promise((resolve) => {
2348
- this.responses.set(invocationId, resolve);
2349
- 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));
2350
3054
  });
2351
3055
  if (!outcome) {
2352
3056
  await this.cdp.send("WebMCP.cancelInvocation", { invocationId }).catch(() => {
@@ -2576,13 +3280,13 @@ async function exportDocument(page, format) {
2576
3280
  }
2577
3281
  }
2578
3282
  const text = await page.evaluate((format2) => {
2579
- const bounded = (text2) => {
3283
+ const bounded2 = (text2) => {
2580
3284
  if (text2.length > 20 * 1024 * 1024 || new TextEncoder().encode(text2).length > 20 * 1024 * 1024)
2581
3285
  throw new Error("Document export exceeds 20 MiB.");
2582
3286
  return text2;
2583
3287
  };
2584
3288
  if (format2 === "text")
2585
- return bounded(document.body.innerText);
3289
+ return bounded2(document.body.innerText);
2586
3290
  const clone = document.documentElement.cloneNode(true);
2587
3291
  for (const el of clone.querySelectorAll('input[type="password"]'))
2588
3292
  el.setAttribute("value", "[password]");
@@ -2592,7 +3296,7 @@ async function exportDocument(page, format) {
2592
3296
  for (const attr of [...el.attributes])
2593
3297
  if (/^on/i.test(attr.name) || attr.name === "srcdoc" || /^[\s\u0000-\u0020]*(javascript|vbscript):/i.test(attr.value))
2594
3298
  el.removeAttribute(attr.name);
2595
- return bounded(`<!doctype html>
3299
+ return bounded2(`<!doctype html>
2596
3300
  ` + clone.outerHTML);
2597
3301
  }, format);
2598
3302
  return {
@@ -2603,7 +3307,7 @@ async function exportDocument(page, format) {
2603
3307
  }
2604
3308
 
2605
3309
  // cli/src/browser/browser-tab-state.ts
2606
- import fs6 from "node:fs";
3310
+ import fs7 from "node:fs";
2607
3311
 
2608
3312
  class BrowserTabState {
2609
3313
  context;
@@ -2614,8 +3318,8 @@ class BrowserTabState {
2614
3318
  constructor(context, filename) {
2615
3319
  this.context = context;
2616
3320
  this.filename = filename;
2617
- if (fs6.existsSync(filename)) {
2618
- const value = JSON.parse(fs6.readFileSync(filename, "utf8"));
3321
+ if (fs7.existsSync(filename)) {
3322
+ const value = JSON.parse(fs7.readFileSync(filename, "utf8"));
2619
3323
  if (value.version !== 1 || !value.targets || typeof value.targets !== "object")
2620
3324
  throw new Error("Invalid browser tab state.");
2621
3325
  this.stored = value.targets;
@@ -2623,8 +3327,8 @@ class BrowserTabState {
2623
3327
  }
2624
3328
  save() {
2625
3329
  const tmp = `${this.filename}.${crypto.randomUUID()}.tmp`;
2626
- fs6.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
2627
- fs6.renameSync(tmp, this.filename);
3330
+ fs7.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
3331
+ fs7.renameSync(tmp, this.filename);
2628
3332
  }
2629
3333
  resolve(page) {
2630
3334
  let pending = this.pages.get(page);
@@ -2736,7 +3440,7 @@ class BrowserRuntime {
2736
3440
  return;
2737
3441
  });
2738
3442
  });
2739
- fs7.mkdirSync(downloadsPath, { recursive: true });
3443
+ fs8.mkdirSync(downloadsPath, { recursive: true });
2740
3444
  this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
2741
3445
  for (const page of context.pages())
2742
3446
  this.track(page);
@@ -2795,23 +3499,23 @@ class BrowserRuntime {
2795
3499
  return id;
2796
3500
  }
2797
3501
  safeDownloadFilename(suggestedFilename) {
2798
- const basename = path6.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
3502
+ const basename = path7.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
2799
3503
  if (!basename || basename === "." || basename === "..")
2800
3504
  return "download";
2801
- const extension = path6.extname(basename).slice(0, 30);
2802
- let stem = basename.slice(0, basename.length - path6.extname(basename).length) || "download";
3505
+ const extension = path7.extname(basename).slice(0, 30);
3506
+ let stem = basename.slice(0, basename.length - path7.extname(basename).length) || "download";
2803
3507
  while (Buffer.byteLength(`${stem}${extension}`) > 200)
2804
3508
  stem = stem.slice(0, -1);
2805
3509
  return `${stem || "download"}${extension}`;
2806
3510
  }
2807
3511
  availableDownloadPath(suggestedFilename) {
2808
3512
  const filename = this.safeDownloadFilename(suggestedFilename);
2809
- const extension = path6.extname(filename);
3513
+ const extension = path7.extname(filename);
2810
3514
  const stem = filename.slice(0, filename.length - extension.length) || "download";
2811
3515
  for (let suffix = 1;; suffix += 1) {
2812
3516
  const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
2813
- const candidatePath = path6.join(this.downloadsPath, candidate);
2814
- if (!fs7.existsSync(candidatePath))
3517
+ const candidatePath = path7.join(this.downloadsPath, candidate);
3518
+ if (!fs8.existsSync(candidatePath))
2815
3519
  return candidatePath;
2816
3520
  }
2817
3521
  }
@@ -2819,18 +3523,18 @@ class BrowserRuntime {
2819
3523
  const failure = await download.failure();
2820
3524
  if (failure)
2821
3525
  throw new Error(failure);
2822
- const temporary = path6.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
3526
+ const temporary = path7.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
2823
3527
  let targetPath;
2824
3528
  try {
2825
3529
  await download.saveAs(temporary);
2826
3530
  targetPath = this.availableDownloadPath(download.suggestedFilename());
2827
- fs7.renameSync(temporary, targetPath);
3531
+ fs8.renameSync(temporary, targetPath);
2828
3532
  } finally {
2829
- fs7.rmSync(temporary, { force: true });
3533
+ fs8.rmSync(temporary, { force: true });
2830
3534
  }
2831
- process.stdout.write(`[r5d-browser] downloaded ${path6.basename(targetPath)}
3535
+ process.stdout.write(`[r5d-browser] downloaded ${path7.basename(targetPath)}
2832
3536
  `);
2833
- return { downloadId: this.downloadId(path6.basename(targetPath)) };
3537
+ return { downloadId: this.downloadId(path7.basename(targetPath)) };
2834
3538
  }
2835
3539
  downloadId(filename) {
2836
3540
  return Buffer.from(filename, "utf8").toString("base64url");
@@ -2839,13 +3543,13 @@ class BrowserRuntime {
2839
3543
  if (typeof downloadId !== "string" || !downloadId)
2840
3544
  throw new Error("downloadId is required.");
2841
3545
  const filename = Buffer.from(downloadId, "base64url").toString("utf8");
2842
- if (this.downloadId(filename) !== downloadId || filename !== path6.basename(filename) || filename.includes("\x00")) {
3546
+ if (this.downloadId(filename) !== downloadId || filename !== path7.basename(filename) || filename.includes("\x00")) {
2843
3547
  throw new Error("Invalid downloadId.");
2844
3548
  }
2845
- const filePath = path6.join(this.downloadsPath, filename);
3549
+ const filePath = path7.join(this.downloadsPath, filename);
2846
3550
  let stats;
2847
3551
  try {
2848
- stats = fs7.lstatSync(filePath);
3552
+ stats = fs8.lstatSync(filePath);
2849
3553
  } catch {
2850
3554
  throw new Error(`Browser download ${downloadId} no longer exists.`);
2851
3555
  }
@@ -2854,7 +3558,7 @@ class BrowserRuntime {
2854
3558
  return { filename, filePath, stats };
2855
3559
  }
2856
3560
  async listDownloads() {
2857
- return fs7.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
3561
+ return fs8.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
2858
3562
  if (!entry.isFile() || entry.name.startsWith("."))
2859
3563
  return [];
2860
3564
  const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
@@ -2878,20 +3582,20 @@ class BrowserRuntime {
2878
3582
  throw new Error("Invalid download chunk size.");
2879
3583
  const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
2880
3584
  const bytes = Buffer.alloc(chunkSize);
2881
- const handle = fs7.openSync(filePath, fs7.constants.O_RDONLY | fs7.constants.O_NOFOLLOW);
3585
+ const handle = fs8.openSync(filePath, fs8.constants.O_RDONLY | fs8.constants.O_NOFOLLOW);
2882
3586
  let bytesRead = 0;
2883
3587
  try {
2884
- const openedStats = fs7.fstatSync(handle);
3588
+ const openedStats = fs8.fstatSync(handle);
2885
3589
  if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
2886
3590
  throw new Error("Browser download changed before it could be read.");
2887
3591
  }
2888
- bytesRead = fs7.readSync(handle, bytes, 0, chunkSize, offset);
2889
- const completedStats = fs7.fstatSync(handle);
3592
+ bytesRead = fs8.readSync(handle, bytes, 0, chunkSize, offset);
3593
+ const completedStats = fs8.fstatSync(handle);
2890
3594
  if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
2891
3595
  throw new Error("Browser download changed while it was being read.");
2892
3596
  }
2893
3597
  } finally {
2894
- fs7.closeSync(handle);
3598
+ fs8.closeSync(handle);
2895
3599
  }
2896
3600
  const nextOffset = offset + bytesRead;
2897
3601
  return {
@@ -3313,9 +4017,9 @@ class BrowserRuntime {
3313
4017
  return { tabId, exported: false, code: "export_too_large" };
3314
4018
  const exports = files.map((file) => {
3315
4019
  const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
3316
- fs7.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
4020
+ fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
3317
4021
  return {
3318
- downloadId: this.downloadId(path6.basename(target2)),
4022
+ downloadId: this.downloadId(path7.basename(target2)),
3319
4023
  filename: file.filename,
3320
4024
  size: file.bytes.length,
3321
4025
  mimeType: file.mimeType
@@ -3941,7 +4645,7 @@ class NativeRuntime {
3941
4645
  try {
3942
4646
  return await work();
3943
4647
  } finally {
3944
- await new Promise((resolve) => setTimeout(resolve, 50));
4648
+ await new Promise((resolve2) => setTimeout(resolve2, 50));
3945
4649
  events.diagnosticsSuppressed = false;
3946
4650
  }
3947
4651
  }
@@ -4049,9 +4753,9 @@ class NativeRuntime {
4049
4753
 
4050
4754
  // cli/src/runtime/relay.ts
4051
4755
  import WebSocket2 from "ws";
4052
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
4053
- import fs8 from "node:fs/promises";
4054
- import path7 from "node:path";
4756
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
4757
+ import fs9 from "node:fs/promises";
4758
+ import path8 from "node:path";
4055
4759
 
4056
4760
  // cli/src/live/producer.ts
4057
4761
  import WebSocket from "ws";
@@ -4151,7 +4855,7 @@ class CaptureTimeout extends Error {
4151
4855
  this.stage = stage;
4152
4856
  }
4153
4857
  }
4154
- async function bounded(stage, operation) {
4858
+ async function bounded2(stage, operation) {
4155
4859
  let timer;
4156
4860
  try {
4157
4861
  return await Promise.race([operation, new Promise((_, reject) => {
@@ -4257,8 +4961,8 @@ class NativeLiveProducer {
4257
4961
  const cdp = this.cdp;
4258
4962
  this.cdp = undefined;
4259
4963
  if (cdp) {
4260
- await bounded("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
4261
- await bounded("detach", cdp.detach()).catch(() => {});
4964
+ await bounded2("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
4965
+ await bounded2("detach", cdp.detach()).catch(() => {});
4262
4966
  }
4263
4967
  }
4264
4968
  async reconcile(generation) {
@@ -4287,7 +4991,7 @@ class NativeLiveProducer {
4287
4991
  const initialNav = this.navSeq;
4288
4992
  let authorized = false;
4289
4993
  try {
4290
- authorized = await bounded("authorize", this.options.authorizePage(page));
4994
+ authorized = await bounded2("authorize", this.options.authorizePage(page));
4291
4995
  } catch (error) {
4292
4996
  await this.teardown();
4293
4997
  if (generation === this.generation)
@@ -4307,14 +5011,14 @@ class NativeLiveProducer {
4307
5011
  const ws = new WebSocket(this.options.mediaUrl, { maxPayload: 2048, perMessageDeflate: false });
4308
5012
  this.socket = ws;
4309
5013
  try {
4310
- await new Promise((resolve, reject) => {
5014
+ await new Promise((resolve2, reject) => {
4311
5015
  const timer = setTimeout(() => {
4312
5016
  ws.terminate();
4313
5017
  reject(new Error("Media timeout"));
4314
5018
  }, 5000);
4315
5019
  const done = (error) => {
4316
5020
  clearTimeout(timer);
4317
- error ? reject(error) : resolve();
5021
+ error ? reject(error) : resolve2();
4318
5022
  };
4319
5023
  ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
4320
5024
  ws.once("error", () => done(new Error("Media unavailable")));
@@ -4350,12 +5054,12 @@ class NativeLiveProducer {
4350
5054
  let abandoned = false;
4351
5055
  const attaching = this.options.context.newCDPSession(page).then((session) => {
4352
5056
  if (abandoned)
4353
- bounded("detach", session.detach()).catch(() => {});
5057
+ bounded2("detach", session.detach()).catch(() => {});
4354
5058
  return session;
4355
5059
  });
4356
5060
  let cdp;
4357
5061
  try {
4358
- cdp = await bounded("attach", attaching);
5062
+ cdp = await bounded2("attach", attaching);
4359
5063
  } catch (error) {
4360
5064
  abandoned = true;
4361
5065
  throw error;
@@ -4389,7 +5093,7 @@ class NativeLiveProducer {
4389
5093
  const nav = this.navSeq;
4390
5094
  (async () => {
4391
5095
  try {
4392
- const allowed2 = await bounded("frame_authorize", this.options.authorizePage(page));
5096
+ const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
4393
5097
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
4394
5098
  return;
4395
5099
  if (!allowed2 || this.options.getPage(tab) !== page) {
@@ -4405,11 +5109,11 @@ class NativeLiveProducer {
4405
5109
  })();
4406
5110
  });
4407
5111
  const startNav = this.navSeq;
4408
- if (!await bounded("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
5112
+ if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
4409
5113
  await this.teardown();
4410
5114
  return;
4411
5115
  }
4412
- await bounded("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
5116
+ await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
4413
5117
  if (generation !== this.generation) {
4414
5118
  await this.teardown();
4415
5119
  return;
@@ -4502,11 +5206,11 @@ class Relay {
4502
5206
  u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
4503
5207
  const socket = new WebSocket2(u, { maxPayload: LIMIT, handshakeTimeout: 15000, followRedirects: false });
4504
5208
  this.socket = socket;
4505
- await new Promise((resolve, reject) => {
5209
+ await new Promise((resolve2, reject) => {
4506
5210
  socket.once("error", reject);
4507
5211
  socket.once("close", () => {
4508
5212
  clearInterval(heartbeat);
4509
- resolve();
5213
+ resolve2();
4510
5214
  });
4511
5215
  const heartbeat = setInterval(() => {
4512
5216
  if (socket.readyState === WebSocket2.OPEN)
@@ -4515,7 +5219,7 @@ class Relay {
4515
5219
  heartbeat.unref();
4516
5220
  socket.once("open", () => {
4517
5221
  this.state = "authenticating";
4518
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.7", 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 } } }));
4519
5223
  });
4520
5224
  socket.on("message", (bytes, binary) => {
4521
5225
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -4634,20 +5338,20 @@ class Relay {
4634
5338
  if (message.op === "export_page" && Array.isArray(result?.exports))
4635
5339
  for (const item of result.exports) {
4636
5340
  const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
4637
- if (path7.basename(filename) !== filename)
5341
+ if (path8.basename(filename) !== filename)
4638
5342
  throw new Error("Invalid export file");
4639
- const filenamePath = path7.join(this.previewDirectory, filename);
4640
- const stat = await fs8.lstat(filenamePath);
5343
+ const filenamePath = path8.join(this.previewDirectory, filename);
5344
+ const stat = await fs9.lstat(filenamePath);
4641
5345
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
4642
5346
  throw new Error("Invalid export file");
4643
- blobs.push(await this.upload(await fs8.readFile(filenamePath), "export", item.filename, item.mimeType));
4644
- await fs8.unlink(filenamePath);
5347
+ blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
5348
+ await fs9.unlink(filenamePath);
4645
5349
  delete item.downloadId;
4646
5350
  }
4647
5351
  if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
4648
5352
  for (const artifact2 of result.artifacts)
4649
- blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact", path7.basename(artifact2.filename), "text/plain"));
4650
- result.artifacts = result.artifacts.map((a) => ({ filename: path7.basename(a.filename) }));
5353
+ blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact", path8.basename(artifact2.filename), "text/plain"));
5354
+ result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
4651
5355
  }
4652
5356
  if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
4653
5357
  throw new Error("Result budget exceeded");
@@ -4662,7 +5366,7 @@ class Relay {
4662
5366
  async upload(bytes, role, name, mimeType) {
4663
5367
  if (bytes.length > 20 * 1024 * 1024)
4664
5368
  throw new Error("Preview exceeds 20 MiB");
4665
- const blobId = randomUUID2(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5369
+ const blobId = randomUUID4(), sha256 = createHash5("sha256").update(bytes).digest("hex");
4666
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) });
4667
5371
  if (!response.ok)
4668
5372
  throw new Error("Preview upload failed");
@@ -4687,15 +5391,15 @@ class Relay {
4687
5391
  }
4688
5392
 
4689
5393
  // cli/src/data/index.ts
4690
- 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";
4691
5395
  import { createReadStream, createWriteStream } from "node:fs";
4692
- import { randomUUID as randomUUID4, createHash as createHash6 } from "node:crypto";
4693
- 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";
4694
5398
  import { Readable, Transform } from "node:stream";
4695
5399
  import { pipeline } from "node:stream/promises";
4696
5400
 
4697
5401
  // cli/src/data/vault.ts
4698
- import { randomUUID as randomUUID3 } from "node:crypto";
5402
+ import { randomUUID as randomUUID5 } from "node:crypto";
4699
5403
  class SecretVault {
4700
5404
  access;
4701
5405
  entries = new Map;
@@ -4762,7 +5466,7 @@ class SecretVault {
4762
5466
  }
4763
5467
  if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
4764
5468
  throw new Error("Vault quota exceeded");
4765
- 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 };
4766
5470
  this.entries.set(entry.id, entry);
4767
5471
  return this.metadata(entry);
4768
5472
  } catch {
@@ -4821,7 +5525,7 @@ var safeName = (s) => {
4821
5525
  async function createDataPlugin(access, options) {
4822
5526
  if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
4823
5527
  throw new Error("HTTPS data server required");
4824
- await mkdir(options.directory, { mode: 448 });
5528
+ await mkdir2(options.directory, { mode: 448 });
4825
5529
  const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
4826
5530
  let stopped = false;
4827
5531
  function meta(r) {
@@ -4840,7 +5544,7 @@ async function createDataPlugin(access, options) {
4840
5544
  }
4841
5545
  function create(scope, purpose, size, name) {
4842
5546
  reserve(scope, size);
4843
- 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 };
4844
5548
  resources.set(r.id, r);
4845
5549
  return r;
4846
5550
  }
@@ -4851,12 +5555,12 @@ async function createDataPlugin(access, options) {
4851
5555
  r.bytes?.fill(0);
4852
5556
  r.bytes = undefined;
4853
5557
  if (r.path && owned.has(r.path)) {
4854
- await unlink(r.path).catch(() => {});
5558
+ await unlink2(r.path).catch(() => {});
4855
5559
  owned.delete(r.path);
4856
5560
  }
4857
- const dir = join(options.directory, r.id);
5561
+ const dir = join2(options.directory, r.id);
4858
5562
  if (ownedDirs.has(dir)) {
4859
- await rmdir(dir).catch(() => {});
5563
+ await rmdir2(dir).catch(() => {});
4860
5564
  ownedDirs.delete(dir);
4861
5565
  }
4862
5566
  resources.delete(r.id);
@@ -4874,11 +5578,11 @@ async function createDataPlugin(access, options) {
4874
5578
  const response = await fetch(g.url, { method: "GET", headers: g.headers, redirect: "error", signal: r.abort.signal });
4875
5579
  if (!response.ok || !response.body)
4876
5580
  throw new Error("Transfer failed");
4877
- const dir = join(options.directory, r.id);
4878
- await mkdir(dir, { mode: 448 });
5581
+ const dir = join2(options.directory, r.id);
5582
+ await mkdir2(dir, { mode: 448 });
4879
5583
  ownedDirs.add(dir);
4880
- const part = join(options.directory, `${r.id}.partial`), dest = join(dir, r.name);
4881
- 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);
4882
5586
  await h.close();
4883
5587
  owned.add(part);
4884
5588
  r.path = part;
@@ -4908,7 +5612,7 @@ async function createDataPlugin(access, options) {
4908
5612
  } else {
4909
5613
  if (!r.path)
4910
5614
  throw new Error("Missing file");
4911
- const stat = await lstat(r.path);
5615
+ const stat = await lstat2(r.path);
4912
5616
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
4913
5617
  throw new Error("Changed file");
4914
5618
  body = Readable.toWeb(createReadStream(r.path));
@@ -4921,7 +5625,7 @@ async function createDataPlugin(access, options) {
4921
5625
  } catch {
4922
5626
  r.state = "failed";
4923
5627
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
4924
- await unlink(r.path).catch(() => {});
5628
+ await unlink2(r.path).catch(() => {});
4925
5629
  owned.delete(r.path);
4926
5630
  }
4927
5631
  } finally {
@@ -5038,9 +5742,9 @@ async function createDataPlugin(access, options) {
5038
5742
  r = create(scope, "download", LIMITS.file, download.suggestedFilename());
5039
5743
  r.tabId = tabId;
5040
5744
  r.generation = generation;
5041
- const path8 = join(options.directory, r.id);
5042
- r.path = path8;
5043
- owned.add(path8);
5745
+ const path9 = join2(options.directory, r.id);
5746
+ r.path = path9;
5747
+ owned.add(path9);
5044
5748
  const source = await download.createReadStream();
5045
5749
  if (!source)
5046
5750
  throw new Error("Download unavailable");
@@ -5054,17 +5758,17 @@ async function createDataPlugin(access, options) {
5054
5758
  const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
5055
5759
  timeout2.unref?.();
5056
5760
  try {
5057
- await pipeline(source, bound, createWriteStream(path8, { flags: "wx", mode: 384 }), { signal: r.abort.signal });
5761
+ await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: r.abort.signal });
5058
5762
  } finally {
5059
5763
  clearTimeout(timeout2);
5060
5764
  }
5061
- await chmod(path8, 384);
5062
- const stat = await lstat(path8);
5765
+ await chmod(path9, 384);
5766
+ const stat = await lstat2(path9);
5063
5767
  if (!stat.isFile() || stat.size > LIMITS.file)
5064
5768
  throw new Error("Download limit");
5065
5769
  r.size = stat.size;
5066
5770
  const hash = createHash6("sha256");
5067
- for await (const chunk of createReadStream(path8))
5771
+ for await (const chunk of createReadStream(path9))
5068
5772
  hash.update(chunk);
5069
5773
  r.hash = hash.digest("hex");
5070
5774
  if (r.abort.signal.aborted)
@@ -5098,13 +5802,13 @@ async function createDataPlugin(access, options) {
5098
5802
  vault.revoke(() => true);
5099
5803
  await Promise.all([...resources.values()].filter((r) => r.state !== "attached").map(remove));
5100
5804
  if (!resources.size)
5101
- await rmdir(options.directory).catch(() => {});
5805
+ await rmdir2(options.directory).catch(() => {});
5102
5806
  },
5103
5807
  async onReconnect() {
5104
5808
  if (!stopped)
5105
5809
  return;
5106
5810
  if (!resources.size)
5107
- await mkdir(options.directory, { mode: 448 });
5811
+ await mkdir2(options.directory, { mode: 448 });
5108
5812
  stopped = false;
5109
5813
  sweep = setInterval(() => {
5110
5814
  revoke((r) => r.expiresAt < Date.now() && r.state !== "attached");
@@ -5177,7 +5881,7 @@ function createForwardPlugin(options) {
5177
5881
  }
5178
5882
 
5179
5883
  // cli/src/browser/main.ts
5180
- function parse(args) {
5884
+ function parse2(args) {
5181
5885
  const options = { profiles: [] };
5182
5886
  for (let i = 0;i < args.length; i++) {
5183
5887
  const key = args[i];
@@ -5204,12 +5908,12 @@ async function runBrowser(args) {
5204
5908
  console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
5205
5909
  browser-mcp browser status|pause|resume|stop|recover [--profile work]
5206
5910
  Repeat --profile to launch multiple isolated browsers. Without --profile, uses default. Approve each new profile separately. Local controls target one profile; Ctrl-C closes all browsers started by this command. A launch/runtime failure stops the group.
5207
- Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome; no detach/reattach. recover removes only verified stale lock/socket artifacts, never profile data. Live view requires local --live-view opt-in (screenshots may expose secrets). Windows browser host is not yet supported.`);
5911
+ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI closes Chrome; no detach/reattach. recover removes only verified stale lock/socket artifacts, never profile data. Live view requires local --live-view opt-in (screenshots may expose secrets). Windows browser host is not yet supported.`);
5208
5912
  return;
5209
5913
  }
5210
5914
  if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
5211
5915
  throw new Error("Unknown browser command");
5212
- const options = parse(args), profiles = options.profiles.length ? options.profiles : ["default"];
5916
+ const options = parse2(args), profiles = options.profiles.length ? options.profiles : ["default"];
5213
5917
  for (const profile of profiles)
5214
5918
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(profile))
5215
5919
  throw new Error("Invalid profile name");
@@ -5220,12 +5924,13 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
5220
5924
  const abort = new AbortController;
5221
5925
  setMaxListeners(0, abort.signal);
5222
5926
  const requestStop = () => abort.abort(new Error("Browser startup interrupted"));
5927
+ const signalStop = () => abort.abort(new Error("Browser shutdown signal"));
5223
5928
  const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
5224
5929
  if (command === "start")
5225
5930
  for (const signal of signals)
5226
- process.on(signal, requestStop);
5931
+ process.on(signal, signalStop);
5227
5932
  try {
5228
- const root = await privateDirectory(installationRoot());
5933
+ const root = await privateDirectory2(installationRoot());
5229
5934
  if (command !== "start") {
5230
5935
  const profile = profiles[0], controlPath = controlSocketPath(root, profile);
5231
5936
  if (command === "recover") {
@@ -5233,15 +5938,15 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
5233
5938
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
5234
5939
  return;
5235
5940
  }
5236
- await new Promise((resolve, reject) => {
5237
- const socket = net2.connect(controlPath);
5941
+ await new Promise((resolve2, reject) => {
5942
+ const socket = net3.connect(controlPath);
5238
5943
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
5239
5944
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
5240
5945
  `));
5241
5946
  socket.once("data", (data) => {
5242
5947
  console.log(data.toString().trim());
5243
5948
  socket.end();
5244
- resolve();
5949
+ resolve2();
5245
5950
  });
5246
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}.`)));
5247
5952
  });
@@ -5251,7 +5956,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
5251
5956
  const server = serverURL(options.server ?? "https://browser-mcp.click");
5252
5957
  for (const profile of profiles) {
5253
5958
  const controlPath = controlSocketPath(root, profile);
5254
- const previousSocket = await fs9.lstat(controlPath).catch((error) => {
5959
+ const previousSocket = await fs10.lstat(controlPath).catch((error) => {
5255
5960
  if (error.code !== "ENOENT")
5256
5961
  throw error;
5257
5962
  });
@@ -5277,7 +5982,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
5277
5982
  } finally {
5278
5983
  if (command === "start")
5279
5984
  for (const signal of signals)
5280
- process.removeListener(signal, requestStop);
5985
+ process.removeListener(signal, signalStop);
5281
5986
  }
5282
5987
  }
5283
5988
  async function startProfile(root, server, profile, options, groupSignal) {
@@ -5289,45 +5994,55 @@ async function startProfile(root, server, profile, options, groupSignal) {
5289
5994
  const controlPath = controlSocketPath(root, profile);
5290
5995
  let stopControl;
5291
5996
  const clients = new Set;
5292
- const close = onceAsync(() => cleanupSteps([
5293
- ["Relay", async () => {
5294
- await relay?.stop();
5295
- }],
5296
- ["Download quota", async () => {
5297
- await stopQuota?.();
5298
- }],
5299
- ["Runtime", async () => {
5300
- await runtime?.shutdown();
5301
- }],
5302
- ["Local control", async () => {
5303
- for (const client of clients)
5304
- client.destroy();
5305
- await stopControl?.();
5306
- }],
5307
- ["Browser session", async () => {
5308
- await session?.close();
5309
- }]
5310
- ]));
5311
- const requestStop = () => {
5312
- 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"));
5313
6022
  if (!starting)
5314
6023
  close().catch(() => {});
5315
6024
  };
5316
- 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 });
5317
6031
  if (groupSignal.aborted)
5318
- requestStop();
6032
+ groupStop();
6033
+ let failure, cleanupFailure;
5319
6034
  try {
5320
6035
  abort.signal.throwIfAborted();
5321
6036
  session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
5322
- session.context.once("close", requestStop);
6037
+ session.lifecycle.ended.then(endSession);
5323
6038
  abort.signal.throwIfAborted();
5324
- stopQuota = await enforceDownloadQuota(session.context, path8.join(session.runPath, "chrome-downloads"));
6039
+ stopQuota = await enforceDownloadQuota(session.context, path9.join(session.runPath, "chrome-downloads"));
5325
6040
  abort.signal.throwIfAborted();
5326
6041
  const token = await credential(root, server, profile, abort.signal);
5327
6042
  abort.signal.throwIfAborted();
5328
- const previews = path8.join(session.runPath, "previews");
6043
+ const previews = path9.join(session.runPath, "previews");
5329
6044
  runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
5330
- runtime.plugins.push(await createDataPlugin(runtime, { directory: path8.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
6045
+ runtime.plugins.push(await createDataPlugin(runtime, { directory: path9.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
5331
6046
  abort.signal.throwIfAborted();
5332
6047
  runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
5333
6048
  relay = new Relay(runtime, server, token, previews, !!options.liveView);
@@ -5338,7 +6053,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
5338
6053
  await route.continue();
5339
6054
  });
5340
6055
  abort.signal.throwIfAborted();
5341
- local = net2.createServer((socket) => {
6056
+ local = net3.createServer((socket) => {
5342
6057
  clients.add(socket);
5343
6058
  socket.once("close", () => clients.delete(socket));
5344
6059
  socket.setTimeout(2000, () => socket.destroy());
@@ -5364,11 +6079,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
5364
6079
  else if (cmd === "stop") {
5365
6080
  socket.end(`{"state":"stopping"}
5366
6081
  `);
5367
- requestStop();
6082
+ requestStop("local-stop");
5368
6083
  return;
5369
6084
  } else if (cmd !== "status")
5370
6085
  throw new Error("Invalid command");
5371
- socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.7", protocol: 3 }) + `
6086
+ socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.11", protocol: 3 }) + `
5372
6087
  `);
5373
6088
  })().catch(() => socket.destroy());
5374
6089
  });
@@ -5383,15 +6098,34 @@ async function startProfile(root, server, profile, options, groupSignal) {
5383
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.`);
5384
6099
  await relay.start();
5385
6100
  } catch (error) {
5386
- if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
5387
- 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;
5388
6106
  } finally {
5389
6107
  try {
5390
6108
  await close();
6109
+ } catch (error) {
6110
+ cleanupFailure = error;
5391
6111
  } finally {
5392
- groupSignal.removeEventListener("abort", requestStop);
6112
+ groupSignal.removeEventListener("abort", groupStop);
5393
6113
  }
5394
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;
5395
6129
  }
5396
6130
  export {
5397
6131
  runBrowser