@ricsam/browser-mcp 0.3.16 → 0.3.18

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,22 +14,22 @@ import {
14
14
  import"./chunk-1sjcwr28.js";
15
15
 
16
16
  // cli/src/browser/main.ts
17
- import fs10 from "node:fs/promises";
18
- import path10 from "node:path";
17
+ import fs11 from "node:fs/promises";
18
+ import path11 from "node:path";
19
19
  import net3 from "node:net";
20
20
  import { setMaxListeners } from "node:events";
21
21
 
22
22
  // cli/src/browser/lifecycle.ts
23
- import fs3 from "node:fs/promises";
24
- import path4 from "node:path";
23
+ import fs4 from "node:fs/promises";
24
+ import path5 from "node:path";
25
25
  import os2 from "node:os";
26
26
  import { randomUUID as randomUUID3 } from "node:crypto";
27
27
 
28
28
  // cli/src/browser/owned-chrome.ts
29
29
  import { spawn } from "node:child_process";
30
30
  import net from "node:net";
31
- import fs from "node:fs/promises";
32
- import path from "node:path";
31
+ import fs2 from "node:fs/promises";
32
+ import path2 from "node:path";
33
33
  import { chromium } from "playwright-core";
34
34
 
35
35
  // cli/src/browser/cleanup.ts
@@ -54,7 +54,7 @@ function onceAsync(action) {
54
54
  // cli/src/browser/owned-chrome.ts
55
55
  import { randomUUID as randomUUID2 } from "node:crypto";
56
56
  // cli/package.json
57
- var version = "0.3.16";
57
+ var version = "0.3.18";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -444,6 +444,295 @@ class ChromeLifecycle {
444
444
  }
445
445
  }
446
446
 
447
+ // cli/src/browser/download-guard.ts
448
+ import fs from "node:fs/promises";
449
+ import path from "node:path";
450
+ var ACTIVE_LIMIT = 8;
451
+ var AGGREGATE_LIMIT = 512 * 1024 * 1024;
452
+ var DOWNLOAD_DEADLINE_MS = 10 * 60 * 1000;
453
+ var ADOPTION_GRACE_MS = 5000;
454
+ var MAX_ADOPTION_DEFERRALS = 6;
455
+ var OBSERVATION_TTL_MS = 30000;
456
+ var SETTLED_RETENTION_MS = 10 * 60 * 1000;
457
+ var PARTIAL_CLEANUP_DELAY_MS = 1000;
458
+ var MAX_ENTRIES = 512;
459
+ var key = (url, suggestedFilename) => `${url}
460
+ ${suggestedFilename}`;
461
+ var timer = (handle) => {
462
+ handle.unref?.();
463
+ return handle;
464
+ };
465
+
466
+ class DownloadGuard {
467
+ cdp;
468
+ directory;
469
+ limit;
470
+ entries = new Map;
471
+ pending = new Map;
472
+ guids = new WeakMap;
473
+ earlyClaims = new Map;
474
+ listeners = new Set;
475
+ stopped = false;
476
+ reasserting;
477
+ constructor(cdp, directory, limit) {
478
+ this.cdp = cdp;
479
+ this.directory = directory;
480
+ this.limit = limit;
481
+ }
482
+ leaf(guid) {
483
+ return path.join(this.directory, guid);
484
+ }
485
+ isSpoolPath(filePath, guid) {
486
+ return path.resolve(filePath) === path.resolve(this.directory, guid);
487
+ }
488
+ async start() {
489
+ this.cdp.on("Browser.downloadWillBegin", (event) => this.began(event));
490
+ this.cdp.on("Browser.downloadProgress", (event) => this.progressed(event));
491
+ await this.route();
492
+ }
493
+ route() {
494
+ return this.cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: this.directory, eventsEnabled: true });
495
+ }
496
+ reassert() {
497
+ this.reasserting ??= this.route().then(() => {}, () => {}).finally(() => {
498
+ this.reasserting = undefined;
499
+ });
500
+ }
501
+ activeEntries() {
502
+ return [...this.entries.values()].filter((entry) => entry.state === "inProgress");
503
+ }
504
+ began({ guid, url, suggestedFilename }) {
505
+ if (this.stopped) {
506
+ this.cancel(guid);
507
+ return;
508
+ }
509
+ let settle;
510
+ const settled = new Promise((resolve2) => {
511
+ settle = resolve2;
512
+ });
513
+ const entry = { guid, key: key(url, suggestedFilename), url, suggestedFilename, state: "inProgress", received: 0, settled, settle, claimed: this.earlyClaims.delete(guid), adopted: false, deferrals: 0 };
514
+ this.entries.set(guid, entry);
515
+ this.bound();
516
+ if (this.activeEntries().length > ACTIVE_LIMIT)
517
+ this.cancel(guid);
518
+ else
519
+ entry.deadline = timer(setTimeout(() => void this.cancel(guid), DOWNLOAD_DEADLINE_MS));
520
+ const queue = this.pending.get(entry.key);
521
+ while (queue?.length) {
522
+ const next = queue.shift();
523
+ if (Date.now() - next.at <= OBSERVATION_TTL_MS && !this.guids.has(next.observer)) {
524
+ this.match(entry, next.observer);
525
+ break;
526
+ }
527
+ }
528
+ if (queue && !queue.length)
529
+ this.pending.delete(entry.key);
530
+ }
531
+ progressed({ guid, totalBytes, receivedBytes, state, filePath }) {
532
+ const entry = this.entries.get(guid);
533
+ if (!entry) {
534
+ if (state === "inProgress" && !this.stopped)
535
+ this.cancel(guid);
536
+ return;
537
+ }
538
+ if (entry.state !== "inProgress")
539
+ return;
540
+ entry.received = receivedBytes;
541
+ if (state === "inProgress") {
542
+ const aggregate = this.activeEntries().reduce((total, item) => total + item.received, 0);
543
+ if (receivedBytes > this.limit || totalBytes > this.limit || aggregate > AGGREGATE_LIMIT)
544
+ this.cancel(guid);
545
+ return;
546
+ }
547
+ clearTimeout(entry.deadline);
548
+ entry.state = state === "completed" ? "completed" : "canceled";
549
+ entry.filePath = typeof filePath === "string" && filePath ? filePath : undefined;
550
+ entry.settle({ state: entry.state, filePath: entry.filePath });
551
+ if (entry.state === "canceled") {
552
+ timer(setTimeout(() => void this.removeLeaves(guid).catch(() => {}), PARTIAL_CLEANUP_DELAY_MS));
553
+ } else if (entry.filePath && !this.isSpoolPath(entry.filePath, guid)) {
554
+ this.reassert();
555
+ } else {
556
+ this.considerAdoption(entry);
557
+ }
558
+ entry.prune = timer(setTimeout(() => this.forget(entry), SETTLED_RETENTION_MS));
559
+ }
560
+ considerAdoption(entry) {
561
+ clearTimeout(entry.grace);
562
+ if (this.stopped || entry.observer || entry.claimed || entry.adopted || entry.state !== "completed")
563
+ return;
564
+ if (entry.filePath && !this.isSpoolPath(entry.filePath, entry.guid))
565
+ return;
566
+ entry.grace = timer(setTimeout(() => {
567
+ if (this.stopped || entry.observer || entry.claimed || entry.adopted)
568
+ return;
569
+ if (!this.listeners.size) {
570
+ this.considerAdoption(entry);
571
+ return;
572
+ }
573
+ if (this.awaitingClaim(entry) && entry.deferrals++ < MAX_ADOPTION_DEFERRALS) {
574
+ this.considerAdoption(entry);
575
+ return;
576
+ }
577
+ entry.adopted = true;
578
+ const offered = { guid: entry.guid, url: entry.url, suggestedFilename: entry.suggestedFilename };
579
+ let accepted = false;
580
+ for (const listener of this.listeners)
581
+ accepted = listener(offered) || accepted;
582
+ if (!accepted)
583
+ this.removeLeaves(entry.guid).catch(() => {});
584
+ }, ADOPTION_GRACE_MS));
585
+ }
586
+ awaitingClaim(entry) {
587
+ const now = Date.now();
588
+ if ((this.pending.get(entry.key) ?? []).some((item) => now - item.at <= OBSERVATION_TTL_MS))
589
+ return true;
590
+ for (const other of this.entries.values())
591
+ if (other !== entry && other.key === entry.key && other.observer && !other.claimed)
592
+ return true;
593
+ return false;
594
+ }
595
+ match(entry, observer) {
596
+ entry.observer = observer;
597
+ this.guids.set(observer, entry.guid);
598
+ clearTimeout(entry.grace);
599
+ }
600
+ observe(observer) {
601
+ if (this.stopped || this.guids.has(observer))
602
+ return;
603
+ const k = key(observer.url(), observer.suggestedFilename());
604
+ const entry = [...this.entries.values()].find((item) => item.key === k && !item.observer && !item.claimed && !item.adopted);
605
+ if (entry) {
606
+ this.match(entry, observer);
607
+ return;
608
+ }
609
+ const now = Date.now();
610
+ const queue = (this.pending.get(k) ?? []).filter((item) => now - item.at <= OBSERVATION_TTL_MS);
611
+ queue.push({ observer, at: now });
612
+ this.pending.set(k, queue.slice(-32));
613
+ }
614
+ claim(guid, observer) {
615
+ const entry = this.entries.get(guid);
616
+ if (!entry) {
617
+ const now = Date.now();
618
+ for (const [claimed, at] of this.earlyClaims)
619
+ if (now - at > OBSERVATION_TTL_MS)
620
+ this.earlyClaims.delete(claimed);
621
+ this.earlyClaims.set(guid, now);
622
+ if (observer)
623
+ this.guids.set(observer, guid);
624
+ return true;
625
+ }
626
+ if (entry.adopted)
627
+ return false;
628
+ entry.claimed = true;
629
+ clearTimeout(entry.grace);
630
+ if (observer && entry.observer !== observer) {
631
+ const displaced = entry.observer;
632
+ const previous = this.guids.get(observer);
633
+ const other = previous && previous !== guid ? this.entries.get(previous) : undefined;
634
+ entry.observer = observer;
635
+ this.guids.set(observer, guid);
636
+ if (other && other.observer === observer && !other.claimed) {
637
+ other.observer = displaced;
638
+ if (displaced)
639
+ this.guids.set(displaced, other.guid);
640
+ else
641
+ this.considerAdoption(other);
642
+ } else if (displaced)
643
+ this.guids.delete(displaced);
644
+ }
645
+ return true;
646
+ }
647
+ release(observer) {
648
+ for (const [k, queue] of this.pending) {
649
+ const rest = queue.filter((item) => item.observer !== observer);
650
+ if (rest.length === queue.length)
651
+ continue;
652
+ if (rest.length)
653
+ this.pending.set(k, rest);
654
+ else
655
+ this.pending.delete(k);
656
+ }
657
+ const guid = this.guids.get(observer);
658
+ const entry = guid ? this.entries.get(guid) : undefined;
659
+ if (!entry || entry.observer !== observer || entry.claimed)
660
+ return;
661
+ entry.observer = undefined;
662
+ this.guids.delete(observer);
663
+ this.considerAdoption(entry);
664
+ }
665
+ settlement(guid) {
666
+ return this.entries.get(guid)?.settled;
667
+ }
668
+ onUnattributed(listener) {
669
+ this.listeners.add(listener);
670
+ return () => {
671
+ this.listeners.delete(listener);
672
+ };
673
+ }
674
+ async cancel(guid) {
675
+ await this.cdp.send("Browser.cancelDownload", { guid }).catch(() => {});
676
+ }
677
+ async removeLeaves(guid) {
678
+ for (const leaf of [this.leaf(guid), `${this.leaf(guid)}.crdownload`])
679
+ await fs.unlink(leaf).catch((error) => {
680
+ if (error.code !== "ENOENT")
681
+ throw error;
682
+ });
683
+ }
684
+ forget(entry) {
685
+ if (entry.state === "inProgress" || this.entries.get(entry.guid) !== entry)
686
+ return;
687
+ clearTimeout(entry.grace);
688
+ this.entries.delete(entry.guid);
689
+ }
690
+ bound() {
691
+ for (const entry of this.entries.values()) {
692
+ if (this.entries.size <= MAX_ENTRIES)
693
+ break;
694
+ if (entry.state !== "inProgress") {
695
+ clearTimeout(entry.prune);
696
+ this.forget(entry);
697
+ }
698
+ }
699
+ }
700
+ async stop() {
701
+ if (this.stopped)
702
+ return;
703
+ this.stopped = true;
704
+ this.listeners.clear();
705
+ this.pending.clear();
706
+ const active = [];
707
+ for (const entry of this.entries.values()) {
708
+ clearTimeout(entry.deadline);
709
+ clearTimeout(entry.grace);
710
+ clearTimeout(entry.prune);
711
+ if (entry.state === "inProgress")
712
+ active.push(entry.guid);
713
+ }
714
+ await Promise.all(active.map((guid) => this.cancel(guid)));
715
+ }
716
+ }
717
+ async function installDownloadGuard(context, directory, limit = 256 * 1024 * 1024) {
718
+ const resolved = path.resolve(directory);
719
+ const stat = await fs.lstat(resolved);
720
+ if (!stat.isDirectory() || stat.isSymbolicLink() || await fs.realpath(resolved) !== resolved || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
721
+ throw new Error("Download spool must be a private directory owned by the current user");
722
+ const browser = context.browser();
723
+ if (!browser)
724
+ throw new Error("Download guard requires an owned browser connection");
725
+ const cdp = await browser.newBrowserCDPSession();
726
+ const guard = new DownloadGuard(cdp, resolved, limit);
727
+ try {
728
+ await guard.start();
729
+ return guard;
730
+ } catch (error) {
731
+ await cdp.detach().catch(() => {});
732
+ throw error;
733
+ }
734
+ }
735
+
447
736
  // cli/src/browser/owned-chrome.ts
448
737
  var STARTUP_MS = 30000;
449
738
  var CLOSE_MS = 2000;
@@ -451,18 +740,18 @@ var GRACEFUL_EXIT_MS = 30000;
451
740
  async function allocateChromePort() {
452
741
  return new Promise((resolve2, reject) => {
453
742
  const server = net.createServer();
454
- const timer = setTimeout(() => {
743
+ const timer2 = setTimeout(() => {
455
744
  server.close();
456
745
  reject(new Error("Chrome port allocation timed out"));
457
746
  }, STARTUP_MS);
458
747
  server.once("error", (error) => {
459
- clearTimeout(timer);
748
+ clearTimeout(timer2);
460
749
  reject(error);
461
750
  });
462
751
  server.listen(0, "127.0.0.1", () => {
463
752
  const address = server.address();
464
753
  server.close((error) => {
465
- clearTimeout(timer);
754
+ clearTimeout(timer2);
466
755
  if (error)
467
756
  reject(error);
468
757
  else if (!address || typeof address === "string" || !address.port)
@@ -482,7 +771,7 @@ function ownedChromeArgs(profile, port) {
482
771
  `--remote-debugging-port=${port}`,
483
772
  "--no-first-run",
484
773
  "--no-default-browser-check",
485
- "--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport",
774
+ "--enable-features=WebMCP,WebMCPTesting,DevToolsWebMCPSupport,CDPScreenshotNewSurface",
486
775
  "--disable-extensions",
487
776
  "--disable-component-extensions-with-background-pages",
488
777
  "--disable-sync",
@@ -494,23 +783,23 @@ function chromeEndpointFromLine(line, port) {
494
783
  return match && Number(match[2]) === port ? match[1] : undefined;
495
784
  }
496
785
  async function bounded(promise, ms) {
497
- let timer;
786
+ let timer2;
498
787
  try {
499
788
  return await Promise.race([promise, new Promise((_, reject) => {
500
- timer = setTimeout(() => reject(new Error("Owned Chrome operation timed out")), ms);
789
+ timer2 = setTimeout(() => reject(new Error("Owned Chrome operation timed out")), ms);
501
790
  })]);
502
791
  } finally {
503
- clearTimeout(timer);
792
+ clearTimeout(timer2);
504
793
  }
505
794
  }
506
795
  async function launchOwnedChrome(options) {
507
796
  const lifecycle = options.lifecycle ?? new ChromeLifecycle({ profile: "standalone", instanceId: randomUUID2() });
508
797
  options.signal?.throwIfAborted();
509
- const artifactsDir = path.join(options.runPath, "chrome-downloads");
798
+ const artifactsDir = path2.join(options.runPath, "chrome-downloads");
510
799
  let port, child;
511
800
  try {
512
801
  lifecycle.setStage("artifacts");
513
- await fs.mkdir(artifactsDir, { mode: 448 });
802
+ await fs2.mkdir(artifactsDir, { mode: 448 });
514
803
  options.signal?.throwIfAborted();
515
804
  lifecycle.setStage("port");
516
805
  port = await allocateChromePort();
@@ -527,6 +816,7 @@ async function launchOwnedChrome(options) {
527
816
  lifecycle.setPid(child.pid);
528
817
  let exited = false;
529
818
  let browser;
819
+ let downloads;
530
820
  let closing = false;
531
821
  let resolveExit;
532
822
  const exit = new Promise((resolve2) => {
@@ -563,6 +853,8 @@ async function launchOwnedChrome(options) {
563
853
  await bounded(exit, CLOSE_MS).catch(() => {});
564
854
  lifecycle.requestShutdown("owner-close");
565
855
  lifecycle.beginCleanup();
856
+ if (downloads)
857
+ await bounded(downloads.stop(), CLOSE_MS).catch(() => {});
566
858
  const requestedClose = !!browser?.isConnected() && alive();
567
859
  if (requestedClose) {
568
860
  try {
@@ -688,6 +980,10 @@ async function launchOwnedChrome(options) {
688
980
  throw new Error("Owned Chrome has no default context");
689
981
  context.once("close", onDisconnect);
690
982
  failureReason = "context-setup-failed";
983
+ const guard = await stage(installDownloadGuard(context, artifactsDir));
984
+ downloads = guard;
985
+ if (closing)
986
+ throw new Error("Owned Chrome startup cancelled");
691
987
  await stage(context.addInitScript("if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };"));
692
988
  lifecycle.setStage("webdriver");
693
989
  failureReason = "missing-blank-page";
@@ -702,7 +998,7 @@ async function launchOwnedChrome(options) {
702
998
  if (!alive() || lifecycle.hasEnded)
703
999
  throw new Error("Owned Chrome ended during startup");
704
1000
  lifecycle.started();
705
- return { context, close, lifecycle };
1001
+ return { context, close, lifecycle, downloads: guard };
706
1002
  } catch {
707
1003
  if (!options.signal?.aborted && !lifecycle.hasEnded)
708
1004
  lifecycle.fail(Date.now() >= deadline ? "timeout" : failureReason);
@@ -723,9 +1019,9 @@ async function launchOwnedChrome(options) {
723
1019
  }
724
1020
 
725
1021
  // cli/src/browser/recovery.ts
726
- import fs2 from "node:fs/promises";
1022
+ import fs3 from "node:fs/promises";
727
1023
  import { constants as constants2 } from "node:fs";
728
- import path3 from "node:path";
1024
+ import path4 from "node:path";
729
1025
  import os from "node:os";
730
1026
  import net2 from "node:net";
731
1027
  import { createHash } from "node:crypto";
@@ -733,7 +1029,7 @@ import { execFile } from "node:child_process";
733
1029
  import { promisify } from "node:util";
734
1030
 
735
1031
  // cli/src/browser/control-path.ts
736
- import path2 from "node:path";
1032
+ import path3 from "node:path";
737
1033
  var privateControlPrefix = "c-";
738
1034
  function assertControlSocketPath(socketPath) {
739
1035
  const limit = process.platform === "linux" ? 107 : process.platform === "darwin" ? 103 : undefined;
@@ -747,7 +1043,7 @@ function assertControlSocketPath(socketPath) {
747
1043
  }
748
1044
  function assertControlPaths(root, publicPath) {
749
1045
  assertControlSocketPath(publicPath);
750
- assertControlSocketPath(path2.join(root, `${privateControlPrefix}XXXXXX`, "s"));
1046
+ assertControlSocketPath(path3.join(root, `${privateControlPrefix}XXXXXX`, "s"));
751
1047
  }
752
1048
  function controlFailure(stage, error) {
753
1049
  const code = error?.code;
@@ -757,31 +1053,31 @@ function controlFailure(stage, error) {
757
1053
 
758
1054
  // cli/src/browser/recovery.ts
759
1055
  function controlSocketPath(root, profile) {
760
- return path3.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
1056
+ return path4.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
761
1057
  }
762
1058
  var code = (e) => e.code;
763
1059
  var fail2 = (file, reason) => {
764
1060
  throw new Error(`Recovery refused: ${reason}: ${file}. Stop the prior host and Chrome, verify ownership and retry browser recover; do not blindly delete artifacts.`);
765
1061
  };
766
1062
  async function directories(directory) {
767
- let cursor = path3.parse(directory).root;
768
- for (const part of directory.slice(cursor.length).split(path3.sep).filter(Boolean)) {
769
- cursor = path3.join(cursor, part);
770
- const s = await fs2.lstat(cursor);
1063
+ let cursor = path4.parse(directory).root;
1064
+ for (const part of directory.slice(cursor.length).split(path4.sep).filter(Boolean)) {
1065
+ cursor = path4.join(cursor, part);
1066
+ const s = await fs3.lstat(cursor);
771
1067
  if (!s.isDirectory() || s.isSymbolicLink())
772
1068
  fail2(cursor, "unsafe directory ancestor");
773
1069
  }
774
1070
  }
775
1071
  async function privateDir(directory) {
776
1072
  await directories(directory);
777
- const s = await fs2.lstat(directory);
1073
+ const s = await fs3.lstat(directory);
778
1074
  if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
779
1075
  fail2(directory, "directory must be owned by current user with mode 0700");
780
1076
  }
781
1077
  async function artifact(file, socket = false) {
782
1078
  let s;
783
1079
  try {
784
- s = await fs2.lstat(file);
1080
+ s = await fs3.lstat(file);
785
1081
  } catch (e) {
786
1082
  if (code(e) === "ENOENT")
787
1083
  return;
@@ -818,10 +1114,10 @@ async function assertProfileStopped(profile) {
818
1114
  fail2(profile, `possible surviving profile process: PID ${pid}`);
819
1115
  }
820
1116
  }
821
- const singleton = path3.join(profile, "SingletonLock");
1117
+ const singleton = path4.join(profile, "SingletonLock");
822
1118
  let s;
823
1119
  try {
824
- s = await fs2.lstat(singleton);
1120
+ s = await fs3.lstat(singleton);
825
1121
  } catch (e) {
826
1122
  if (code(e) === "ENOENT")
827
1123
  return;
@@ -829,7 +1125,7 @@ async function assertProfileStopped(profile) {
829
1125
  }
830
1126
  if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
831
1127
  fail2(singleton, "unrecognized Chromium singleton lock");
832
- const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
1128
+ const target = await fs3.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
833
1129
  if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
834
1130
  fail2(singleton, "foreign or unrecognized Chromium owner");
835
1131
  dead(Number(match[2]), singleton);
@@ -855,12 +1151,12 @@ async function recoverProfile(root, name) {
855
1151
  throw new Error("Recovery is supported only on Linux and macOS");
856
1152
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
857
1153
  throw new Error("Profile must be a simple name, not a path");
858
- root = path3.resolve(root);
859
- const profile = path3.join(root, "profiles", name), lock = path3.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
1154
+ root = path4.resolve(root);
1155
+ const profile = path4.join(root, "profiles", name), lock = path4.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
860
1156
  assertControlSocketPath(socket);
861
1157
  try {
862
1158
  await privateDir(root);
863
- await privateDir(path3.join(root, "profiles"));
1159
+ await privateDir(path4.join(root, "profiles"));
864
1160
  await privateDir(profile);
865
1161
  const original = await artifact(lock), originalSocket = await artifact(socket, true);
866
1162
  if (!original) {
@@ -870,7 +1166,7 @@ async function recoverProfile(root, name) {
870
1166
  }
871
1167
  if (original.size > 16384)
872
1168
  fail2(lock, "oversized lock");
873
- const handle = await fs2.open(lock, constants2.O_RDONLY | constants2.O_NOFOLLOW);
1169
+ const handle = await fs3.open(lock, constants2.O_RDONLY | constants2.O_NOFOLLOW);
874
1170
  try {
875
1171
  if (!same(original, await handle.stat()))
876
1172
  fail2(lock, "lock changed while opening");
@@ -885,11 +1181,11 @@ async function recoverProfile(root, name) {
885
1181
  fail2(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
886
1182
  const validate = async () => {
887
1183
  await privateDir(root);
888
- await privateDir(path3.join(root, "profiles"));
1184
+ await privateDir(path4.join(root, "profiles"));
889
1185
  await privateDir(profile);
890
1186
  dead(owner.pid, lock);
891
1187
  await assertProfileStopped(profile);
892
- if (!same(original, await artifact(lock)) || await fs2.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
1188
+ if (!same(original, await artifact(lock)) || await fs3.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
893
1189
  fail2(lock, `artifact identity changed (socket ${socket})`);
894
1190
  if (originalSocket)
895
1191
  await refusedSocket(socket);
@@ -899,11 +1195,11 @@ async function recoverProfile(root, name) {
899
1195
  };
900
1196
  await validate();
901
1197
  if (originalSocket)
902
- await fs2.unlink(socket);
1198
+ await fs3.unlink(socket);
903
1199
  dead(owner.pid, lock);
904
1200
  if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
905
1201
  fail2(lock, "lock changed before unlink");
906
- await fs2.unlink(lock);
1202
+ await fs3.unlink(lock);
907
1203
  } finally {
908
1204
  await handle.close();
909
1205
  }
@@ -914,38 +1210,38 @@ async function recoverProfile(root, name) {
914
1210
 
915
1211
  // cli/src/browser/lifecycle.ts
916
1212
  function installationRoot() {
917
- return path4.join(os2.homedir(), ".browser-mcp");
1213
+ return path5.join(os2.homedir(), ".browser-mcp");
918
1214
  }
919
1215
  async function privateDirectory2(directory) {
920
- const absolute = path4.resolve(directory);
921
- let cursor = path4.parse(absolute).root;
922
- for (const piece of absolute.slice(cursor.length).split(path4.sep)) {
923
- cursor = path4.join(cursor, piece);
1216
+ const absolute = path5.resolve(directory);
1217
+ let cursor = path5.parse(absolute).root;
1218
+ for (const piece of absolute.slice(cursor.length).split(path5.sep)) {
1219
+ cursor = path5.join(cursor, piece);
924
1220
  try {
925
- await fs3.mkdir(cursor, { mode: 448 });
1221
+ await fs4.mkdir(cursor, { mode: 448 });
926
1222
  } catch (e) {
927
1223
  if (e.code !== "EEXIST")
928
1224
  throw e;
929
1225
  }
930
- const stat2 = await fs3.lstat(cursor);
1226
+ const stat2 = await fs4.lstat(cursor);
931
1227
  if (stat2.isSymbolicLink() || !stat2.isDirectory())
932
1228
  throw new Error("Unsafe directory path");
933
1229
  }
934
- const stat = await fs3.stat(absolute);
1230
+ const stat = await fs4.stat(absolute);
935
1231
  if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
936
1232
  throw new Error("Private directory must be owned by current user with mode 0700");
937
1233
  return absolute;
938
1234
  }
939
1235
  async function discoverChrome(override) {
940
- const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path4.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) => path4.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
1236
+ const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path5.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) => path5.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
941
1237
  for (const candidate of candidates) {
942
- if (!path4.isAbsolute(candidate))
1238
+ if (!path5.isAbsolute(candidate))
943
1239
  throw new Error("Chrome override must be an absolute executable path");
944
1240
  try {
945
- const real = await fs3.realpath(candidate), stat = await fs3.stat(real);
1241
+ const real = await fs4.realpath(candidate), stat = await fs4.stat(real);
946
1242
  if (!stat.isFile())
947
1243
  continue;
948
- await fs3.access(real, fs3.constants.X_OK);
1244
+ await fs4.access(real, fs4.constants.X_OK);
949
1245
  return real;
950
1246
  } catch {}
951
1247
  }
@@ -958,15 +1254,15 @@ async function launchDedicated(options = {}) {
958
1254
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
959
1255
  throw new Error("Profile must be a simple name, not a path");
960
1256
  const root = await privateDirectory2(options.root ?? installationRoot());
961
- const profiles = await privateDirectory2(path4.join(root, "profiles"));
962
- const profile = path4.join(profiles, options.ephemeral ? `ephemeral-${randomUUID3()}` : name);
1257
+ const profiles = await privateDirectory2(path5.join(root, "profiles"));
1258
+ const profile = path5.join(profiles, options.ephemeral ? `ephemeral-${randomUUID3()}` : name);
963
1259
  await privateDirectory2(profile);
964
- const profileStat = await fs3.lstat(profile);
1260
+ const profileStat = await fs4.lstat(profile);
965
1261
  options.signal?.throwIfAborted();
966
- const lockPath = path4.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
1262
+ const lockPath = path5.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
967
1263
  let lock;
968
1264
  try {
969
- lock = await fs3.open(lockPath, "wx", 384);
1265
+ lock = await fs4.open(lockPath, "wx", 384);
970
1266
  } catch (error) {
971
1267
  if (error.code !== "EEXIST")
972
1268
  throw error;
@@ -981,23 +1277,23 @@ async function launchDedicated(options = {}) {
981
1277
  options.signal?.addEventListener("abort", onAbort, { once: true });
982
1278
  if (options.signal?.aborted)
983
1279
  onAbort();
984
- const runPath = path4.join(profile, `run-${instanceId}`);
1280
+ const runPath = path5.join(profile, `run-${instanceId}`);
985
1281
  const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
986
1282
  let context, launched = false, lockWritten = false;
987
1283
  let chrome;
988
1284
  let runStat;
989
1285
  const verifyProfile = async () => {
990
- const stat = await fs3.lstat(profile);
991
- 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)
1286
+ const stat = await fs4.lstat(profile);
1287
+ if (await fs4.realpath(profile) !== profile || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== profileStat.dev || stat.ino !== profileStat.ino || stat.uid !== profileStat.uid || stat.mode & 63)
992
1288
  throw new Error("Profile directory ownership changed; retained owned paths");
993
1289
  };
994
1290
  const verifyLock = async () => {
995
1291
  await verifyProfile();
996
- const stat = await fs3.lstat(lockPath);
1292
+ const stat = await fs4.lstat(lockPath);
997
1293
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.dev !== lockStat.dev || stat.ino !== lockStat.ino || stat.uid !== lockStat.uid || stat.mode & 63)
998
1294
  throw new Error("Profile lock ownership changed; retained owned paths");
999
1295
  if (lockWritten) {
1000
- const stored = JSON.parse(await fs3.readFile(lockPath, "utf8"));
1296
+ const stored = JSON.parse(await fs4.readFile(lockPath, "utf8"));
1001
1297
  if (stored.nonce !== nonce || stored.instanceId !== instanceId || stored.pid !== process.pid || stored.profile !== profile)
1002
1298
  throw new Error("Profile lock ownership changed; retained owned paths");
1003
1299
  }
@@ -1021,19 +1317,19 @@ async function launchDedicated(options = {}) {
1021
1317
  ["Run directory", async () => {
1022
1318
  if (!runStat)
1023
1319
  return;
1024
- const stat = await fs3.lstat(runPath);
1320
+ const stat = await fs4.lstat(runPath);
1025
1321
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== runStat.dev || stat.ino !== runStat.ino || stat.uid !== runStat.uid)
1026
1322
  throw new Error("Run directory ownership changed; retained path");
1027
- await fs3.rm(runPath, { recursive: true, force: true });
1323
+ await fs4.rm(runPath, { recursive: true, force: true });
1028
1324
  }],
1029
1325
  ["Profile lock", async () => {
1030
1326
  await verifyLock();
1031
- await fs3.unlink(lockPath);
1327
+ await fs4.unlink(lockPath);
1032
1328
  }]
1033
1329
  ]);
1034
1330
  if (options.ephemeral) {
1035
1331
  await verifyProfile();
1036
- await fs3.rm(profile, { recursive: true, force: true });
1332
+ await fs4.rm(profile, { recursive: true, force: true });
1037
1333
  }
1038
1334
  }]
1039
1335
  ]);
@@ -1045,9 +1341,9 @@ async function launchDedicated(options = {}) {
1045
1341
  try {
1046
1342
  await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, instanceId, profile, ephemeral: !!options.ephemeral }));
1047
1343
  lockWritten = true;
1048
- await fs3.mkdir(runPath, { mode: 448 });
1049
- runStat = await fs3.lstat(runPath);
1050
- await fs3.writeFile(path4.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
1344
+ await fs4.mkdir(runPath, { mode: 448 });
1345
+ runStat = await fs4.lstat(runPath);
1346
+ await fs4.writeFile(path5.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
1051
1347
  options.signal?.throwIfAborted();
1052
1348
  lifecycle.setStage("discovery");
1053
1349
  let executablePath;
@@ -1063,7 +1359,7 @@ async function launchDedicated(options = {}) {
1063
1359
  chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal, lifecycle });
1064
1360
  context = chrome.context;
1065
1361
  options.signal?.throwIfAborted();
1066
- return { context, instanceId, profile, runPath, close, manifest, lifecycle };
1362
+ return { context, instanceId, profile, runPath, close, manifest, lifecycle, downloads: chrome.downloads };
1067
1363
  } catch (error) {
1068
1364
  let cleanupError;
1069
1365
  try {
@@ -1084,13 +1380,13 @@ ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
1084
1380
  }
1085
1381
 
1086
1382
  // cli/src/browser/control.ts
1087
- import fs4 from "node:fs/promises";
1088
- import path5 from "node:path";
1383
+ import fs5 from "node:fs/promises";
1384
+ import path6 from "node:path";
1089
1385
  async function listenControl(server, root, controlPath) {
1090
1386
  assertControlPaths(root, controlPath);
1091
- const rootStat = await fs4.lstat(root);
1092
- const directory = await fs4.mkdtemp(path5.join(root, privateControlPrefix));
1093
- const dirStat = await fs4.lstat(directory), boundPath = path5.join(directory, "s");
1387
+ const rootStat = await fs5.lstat(root);
1388
+ const directory = await fs5.mkdtemp(path6.join(root, privateControlPrefix));
1389
+ const dirStat = await fs5.lstat(directory), boundPath = path6.join(directory, "s");
1094
1390
  let socketStat, published = false;
1095
1391
  const close = onceAsync(() => cleanupSteps([
1096
1392
  ["Control listener", async () => {
@@ -1100,10 +1396,10 @@ async function listenControl(server, root, controlPath) {
1100
1396
  ["Control pathname", async () => {
1101
1397
  if (!published)
1102
1398
  return;
1103
- const parent = await fs4.lstat(root);
1104
- if (await fs4.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
1399
+ const parent = await fs5.lstat(root);
1400
+ if (await fs5.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
1105
1401
  throw new Error(`Control root ownership changed; retained ${controlPath}`);
1106
- const stat = await fs4.lstat(controlPath).catch((error) => {
1402
+ const stat = await fs5.lstat(controlPath).catch((error) => {
1107
1403
  if (error.code !== "ENOENT")
1108
1404
  throw error;
1109
1405
  });
@@ -1111,29 +1407,29 @@ async function listenControl(server, root, controlPath) {
1111
1407
  return;
1112
1408
  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)
1113
1409
  throw new Error(`Control socket ownership changed; retained ${controlPath}`);
1114
- await fs4.unlink(controlPath);
1410
+ await fs5.unlink(controlPath);
1115
1411
  }],
1116
1412
  ["Private control directory", async () => {
1117
- const stat = await fs4.lstat(directory);
1118
- if (await fs4.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
1413
+ const stat = await fs5.lstat(directory);
1414
+ if (await fs5.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
1119
1415
  throw new Error(`Control directory ownership changed; retained ${directory}`);
1120
- await fs4.unlink(path5.join(directory, "ownership.json"));
1121
- await fs4.rmdir(directory);
1416
+ await fs5.unlink(path6.join(directory, "ownership.json"));
1417
+ await fs5.rmdir(directory);
1122
1418
  }]
1123
1419
  ]));
1124
1420
  try {
1125
- await fs4.writeFile(path5.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
1421
+ await fs5.writeFile(path6.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
1126
1422
  assertControlSocketPath(boundPath);
1127
1423
  await new Promise((resolve2, reject) => {
1128
1424
  server.once("error", reject);
1129
1425
  server.listen(boundPath, resolve2);
1130
1426
  });
1131
- socketStat = await fs4.lstat(boundPath);
1132
- await fs4.chmod(boundPath, 384);
1133
- await fs4.link(boundPath, controlPath);
1427
+ socketStat = await fs5.lstat(boundPath);
1428
+ await fs5.chmod(boundPath, 384);
1429
+ await fs5.link(boundPath, controlPath);
1134
1430
  published = true;
1135
- await fs4.unlink(boundPath);
1136
- socketStat = await fs4.lstat(controlPath);
1431
+ await fs5.unlink(boundPath);
1432
+ socketStat = await fs5.lstat(controlPath);
1137
1433
  return close;
1138
1434
  } catch (error) {
1139
1435
  try {
@@ -1147,8 +1443,8 @@ ${cleanupError}`);
1147
1443
  }
1148
1444
 
1149
1445
  // cli/src/browser/pairing.ts
1150
- import fs5 from "node:fs/promises";
1151
- import path6 from "node:path";
1446
+ import fs6 from "node:fs/promises";
1447
+ import path7 from "node:path";
1152
1448
  import { randomBytes, createHash as createHash2 } from "node:crypto";
1153
1449
  import { setTimeout as delay } from "node:timers/promises";
1154
1450
  function serverURL(raw) {
@@ -1161,13 +1457,13 @@ function serverURL(raw) {
1161
1457
  }
1162
1458
  async function credential(root, server, profile, signal) {
1163
1459
  signal?.throwIfAborted();
1164
- const filename = path6.join(root, `credential-${createHash2("sha256").update(`${server}
1460
+ const filename = path7.join(root, `credential-${createHash2("sha256").update(`${server}
1165
1461
  ${profile}`).digest("hex").slice(0, 24)}.json`);
1166
1462
  try {
1167
- const stat = await fs5.lstat(filename);
1463
+ const stat = await fs6.lstat(filename);
1168
1464
  if (!stat.isFile() || stat.isSymbolicLink() || process.platform !== "win32" && stat.mode & 63)
1169
1465
  throw new Error("Unsafe credential file");
1170
- const value = JSON.parse(await fs5.readFile(filename, "utf8"));
1466
+ const value = JSON.parse(await fs6.readFile(filename, "utf8"));
1171
1467
  if (value.server !== server || !/^br_[\w-]+$/.test(value.token))
1172
1468
  throw new Error("Invalid credential file");
1173
1469
  return value.token;
@@ -1197,55 +1493,12 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
1197
1493
  if (typeof token !== "string" || !/^br_[\w-]+$/.test(token))
1198
1494
  throw new Error("Pairing did not return a browser credential");
1199
1495
  signal?.throwIfAborted();
1200
- await fs5.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
1496
+ await fs6.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
1201
1497
  return token;
1202
1498
  }
1203
1499
  throw new Error("Pairing expired");
1204
1500
  }
1205
1501
 
1206
- // cli/src/browser/download-quota.ts
1207
- async function enforceDownloadQuota(context, directory, limit = 256 * 1024 * 1024) {
1208
- const page = context.pages()[0] ?? await context.newPage();
1209
- const cdp = await context.newCDPSession(page);
1210
- const active = new Map;
1211
- const cancel = (guid) => {
1212
- cdp.send("Browser.cancelDownload", { guid }).catch(() => {});
1213
- };
1214
- cdp.on("Browser.downloadWillBegin", ({ guid }) => {
1215
- if (active.size >= 8) {
1216
- cancel(guid);
1217
- return;
1218
- }
1219
- const timer = setTimeout(() => cancel(guid), 10 * 60 * 1000);
1220
- timer.unref();
1221
- active.set(guid, { received: 0, timer });
1222
- });
1223
- cdp.on("Browser.downloadProgress", ({ guid, receivedBytes, totalBytes, state }) => {
1224
- const item = active.get(guid);
1225
- if (!item) {
1226
- if (state === "inProgress")
1227
- cancel(guid);
1228
- return;
1229
- }
1230
- item.received = receivedBytes;
1231
- if (receivedBytes > limit || totalBytes > limit || [...active.values()].reduce((n, v) => n + v.received, 0) > 512 * 1024 * 1024)
1232
- cancel(guid);
1233
- if (state !== "inProgress") {
1234
- clearTimeout(item.timer);
1235
- active.delete(guid);
1236
- }
1237
- });
1238
- await cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: directory, eventsEnabled: true });
1239
- return async () => {
1240
- for (const [guid, item] of active) {
1241
- clearTimeout(item.timer);
1242
- await cdp.send("Browser.cancelDownload", { guid }).catch(() => {});
1243
- }
1244
- active.clear();
1245
- await cdp.detach().catch(() => {});
1246
- };
1247
- }
1248
-
1249
1502
  // cli/src/browser/screenshot-coordinates.ts
1250
1503
  function screenshotPoint(transform, current, delivered, point) {
1251
1504
  if (JSON.stringify(transform.state) !== JSON.stringify(current))
@@ -1262,8 +1515,8 @@ function screenshotPoint(transform, current, delivered, point) {
1262
1515
  }
1263
1516
 
1264
1517
  // cli/src/browser/browser-runtime.ts
1265
- import fs8 from "node:fs";
1266
- import path8 from "node:path";
1518
+ import fs9 from "node:fs";
1519
+ import path9 from "node:path";
1267
1520
 
1268
1521
  // shared/document-url.ts
1269
1522
  function validateDocumentURL(value) {
@@ -1333,15 +1586,15 @@ function target(value, field) {
1333
1586
  throw new Error(`${field} must be a locator object.`);
1334
1587
  const result = Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null));
1335
1588
  const keys = ["ref", "selector", "role", "name", "text", "label", "placeholder", "testId"];
1336
- for (const [key, item] of Object.entries(result)) {
1337
- if (key === "exact") {
1589
+ for (const [key2, item] of Object.entries(result)) {
1590
+ if (key2 === "exact") {
1338
1591
  if (typeof item !== "boolean")
1339
1592
  throw new Error(`${field}.exact must be a boolean.`);
1340
- } else if (!keys.includes(key) || typeof item !== "string" || !item.trim() || item.length > 2000) {
1593
+ } else if (!keys.includes(key2) || typeof item !== "string" || !item.trim() || item.length > 2000) {
1341
1594
  throw new Error(`${field} contains an invalid locator field.`);
1342
1595
  }
1343
1596
  }
1344
- const strategies = keys.filter((key) => result[key] !== undefined && !(key === "name" && result.role));
1597
+ const strategies = keys.filter((key2) => result[key2] !== undefined && !(key2 === "name" && result.role));
1345
1598
  if (strategies.length !== 1)
1346
1599
  throw new Error(`${field} requires one of ref, selector, role (with optional name), name, text, label, placeholder or testId.`);
1347
1600
  if (result.ref && !/^(f\d+)?e\d+$/.test(result.ref))
@@ -1351,10 +1604,10 @@ function target(value, field) {
1351
1604
  return result;
1352
1605
  }
1353
1606
  function parseSnapshotInput(input) {
1354
- const integer = (key, fallback, min, max) => {
1355
- const value = input[key] ?? fallback;
1607
+ const integer = (key2, fallback, min, max) => {
1608
+ const value = input[key2] ?? fallback;
1356
1609
  if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
1357
- throw new Error(`read_page ${key} must be an integer from ${min} to ${max}.`);
1610
+ throw new Error(`read_page ${key2} must be an integer from ${min} to ${max}.`);
1358
1611
  return value;
1359
1612
  };
1360
1613
  const scope = target(input.scope, "scope"), query = target(input.query, "query");
@@ -1404,7 +1657,7 @@ function timeout(value) {
1404
1657
  return result;
1405
1658
  }
1406
1659
  function parseWaitInput(input) {
1407
- const conditions = ["target", "url", "loadState"].filter((key) => input[key] != null);
1660
+ const conditions = ["target", "url", "loadState"].filter((key2) => input[key2] != null);
1408
1661
  if (conditions.length !== 1)
1409
1662
  throw new Error("wait_for requires exactly one of target, url, or loadState.");
1410
1663
  if (input.selector != null || input.text != null || input.ref != null)
@@ -1443,7 +1696,7 @@ function parseNavigationExpectation(value) {
1443
1696
  if (typeof value !== "object" || Array.isArray(value))
1444
1697
  throw new Error("expectNavigation must be an object.");
1445
1698
  const input = value;
1446
- if (Object.keys(input).some((key) => !["url", "waitUntil", "timeoutMs"].includes(key)))
1699
+ if (Object.keys(input).some((key2) => !["url", "waitUntil", "timeoutMs"].includes(key2)))
1447
1700
  throw new Error("Unknown expectNavigation field.");
1448
1701
  if (input.url != null && (typeof input.url !== "string" || !input.url.trim() || input.url.length > 4000))
1449
1702
  throw new Error("expectNavigation url must be a nonempty URL glob.");
@@ -1537,8 +1790,8 @@ function validateControlInput(action, input) {
1537
1790
  if (input.from !== undefined || input.to !== undefined)
1538
1791
  throw new Error("drag takes refs or coordinates, not both.");
1539
1792
  } else
1540
- for (const key of ["from", "to"]) {
1541
- const p = input[key];
1793
+ for (const key2 of ["from", "to"]) {
1794
+ const p = input[key2];
1542
1795
  if (!p || typeof p.x !== "number" || typeof p.y !== "number" || !Number.isFinite(p.x) || !Number.isFinite(p.y))
1543
1796
  throw new Error("drag requires finite from/to x/y coordinates.");
1544
1797
  }
@@ -1687,14 +1940,14 @@ function parseViewportInput(input) {
1687
1940
  }
1688
1941
  function normalizeBrowserInput(action, input) {
1689
1942
  const fields = browserInputFields[action];
1690
- for (const key of fields.required) {
1691
- if (input[key] === null || input[key] === undefined)
1692
- throw new Error(`${action} requires ${key}.`);
1943
+ for (const key2 of fields.required) {
1944
+ if (input[key2] === null || input[key2] === undefined)
1945
+ throw new Error(`${action} requires ${key2}.`);
1693
1946
  }
1694
1947
  const normalized = { ...input };
1695
- for (const key of [...fields.optional, "screenshotId", "screenshot", ...observedActions.has(action) ? ["observe", "expect"] : []]) {
1696
- if (normalized[key] === null)
1697
- delete normalized[key];
1948
+ for (const key2 of [...fields.optional, "screenshotId", "screenshot", ...observedActions.has(action) ? ["observe", "expect"] : []]) {
1949
+ if (normalized[key2] === null)
1950
+ delete normalized[key2];
1698
1951
  }
1699
1952
  return normalized;
1700
1953
  }
@@ -1708,7 +1961,7 @@ function preflightBrowserInput(action, raw) {
1708
1961
  }
1709
1962
  if (action === "screenshot" && input.crop !== undefined) {
1710
1963
  const crop = input.crop;
1711
- if (!crop || !["x", "y", "width", "height"].every((key) => Number.isInteger(crop[key]) && crop[key] >= (key === "x" || key === "y" ? 0 : 1)) || input.fullPage === true)
1964
+ if (!crop || !["x", "y", "width", "height"].every((key2) => Number.isInteger(crop[key2]) && crop[key2] >= (key2 === "x" || key2 === "y" ? 0 : 1)) || input.fullPage === true)
1712
1965
  throw new Error("crop requires nonnegative x/y and positive width/height in viewport CSS pixels; omit fullPage");
1713
1966
  }
1714
1967
  validateControlInput(action, input);
@@ -1759,7 +2012,7 @@ function preflightBrowserInput(action, raw) {
1759
2012
  }
1760
2013
  if (action === "scroll") {
1761
2014
  if (input.ref !== undefined) {
1762
- if (["direction", "amount", "x", "y"].some((key) => input[key] !== undefined))
2015
+ if (["direction", "amount", "x", "y"].some((key2) => input[key2] !== undefined))
1763
2016
  throw new Error("scroll accepts ref or wheel/pointer parameters, not both.");
1764
2017
  ref();
1765
2018
  } else {
@@ -1773,7 +2026,7 @@ function preflightBrowserInput(action, raw) {
1773
2026
  parseUploadTarget(input);
1774
2027
  if (action === "form_input") {
1775
2028
  ref();
1776
- const provided = ["value", "values", "checked"].filter((key) => input[key] !== undefined);
2029
+ const provided = ["value", "values", "checked"].filter((key2) => input[key2] !== undefined);
1777
2030
  if (provided.length !== 1)
1778
2031
  throw new Error("form_input requires exactly one of value, values, or checked.");
1779
2032
  if (provided[0] === "values" && (!Array.isArray(input.values) || input.values.some((value) => typeof value !== "string")))
@@ -1783,8 +2036,8 @@ function preflightBrowserInput(action, raw) {
1783
2036
  }
1784
2037
 
1785
2038
  // cli/src/browser/upload-store.ts
1786
- import fs6 from "node:fs";
1787
- import path7 from "node:path";
2039
+ import fs7 from "node:fs";
2040
+ import path8 from "node:path";
1788
2041
  import { createHash as createHash3 } from "node:crypto";
1789
2042
  class BrowserUploadStore {
1790
2043
  releaseTarget;
@@ -1794,8 +2047,8 @@ class BrowserUploadStore {
1794
2047
  return;
1795
2048
  }) {
1796
2049
  this.releaseTarget = releaseTarget;
1797
- fs6.mkdirSync(root, { recursive: true, mode: 448 });
1798
- this.directory = fs6.mkdtempSync(path7.join(root, "run-"));
2050
+ fs7.mkdirSync(root, { recursive: true, mode: 448 });
2051
+ this.directory = fs7.mkdtempSync(path8.join(root, "run-"));
1799
2052
  }
1800
2053
  begin(id, tabId, files, target2) {
1801
2054
  if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
@@ -1803,20 +2056,20 @@ class BrowserUploadStore {
1803
2056
  if (!Array.isArray(files) || files.length === 0 || files.length > 100)
1804
2057
  throw new Error("Upload requires between 1 and 100 files.");
1805
2058
  const metadata2 = files.map(validateUploadFile);
1806
- const directory = fs6.mkdtempSync(path7.join(this.directory, "upload-"));
2059
+ const directory = fs7.mkdtempSync(path8.join(this.directory, "upload-"));
1807
2060
  try {
1808
2061
  const staged = metadata2.map((file, index) => {
1809
- const parent = path7.join(directory, String(index));
1810
- fs6.mkdirSync(parent, { mode: 448 });
1811
- const filePath = path7.join(parent, file.filename);
1812
- fs6.closeSync(fs6.openSync(filePath, "wx", 384));
2062
+ const parent = path8.join(directory, String(index));
2063
+ fs7.mkdirSync(parent, { mode: 448 });
2064
+ const filePath = path8.join(parent, file.filename);
2065
+ fs7.closeSync(fs7.openSync(filePath, "wx", 384));
1813
2066
  return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
1814
2067
  });
1815
- const timer = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
1816
- timer.unref();
1817
- this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer });
2068
+ const timer2 = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
2069
+ timer2.unref();
2070
+ this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer: timer2 });
1818
2071
  } catch (error) {
1819
- fs6.rmSync(directory, { recursive: true, force: true });
2072
+ fs7.rmSync(directory, { recursive: true, force: true });
1820
2073
  throw error;
1821
2074
  }
1822
2075
  }
@@ -1837,17 +2090,17 @@ class BrowserUploadStore {
1837
2090
  const bytes = decodeUploadChunk(base64);
1838
2091
  if (bytes.length === 0 || file.offset + bytes.length > file.size)
1839
2092
  throw new Error("Upload chunk does not match the declared file size.");
1840
- const fd = fs6.openSync(file.path, fs6.constants.O_WRONLY | fs6.constants.O_NOFOLLOW);
2093
+ const fd = fs7.openSync(file.path, fs7.constants.O_WRONLY | fs7.constants.O_NOFOLLOW);
1841
2094
  try {
1842
2095
  let written = 0;
1843
2096
  while (written < bytes.length) {
1844
- const count = fs6.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
2097
+ const count = fs7.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
1845
2098
  if (!count)
1846
2099
  throw new Error("Could not write upload chunk.");
1847
2100
  written += count;
1848
2101
  }
1849
2102
  } finally {
1850
- fs6.closeSync(fd);
2103
+ fs7.closeSync(fd);
1851
2104
  }
1852
2105
  file.hash.update(bytes);
1853
2106
  file.offset += bytes.length;
@@ -1881,7 +2134,7 @@ class BrowserUploadStore {
1881
2134
  clearTimeout(upload.timer);
1882
2135
  this.uploads.delete(id);
1883
2136
  this.releaseTarget(upload.target);
1884
- fs6.rmSync(upload.directory, { recursive: true, force: true });
2137
+ fs7.rmSync(upload.directory, { recursive: true, force: true });
1885
2138
  }
1886
2139
  closeTab(tabId) {
1887
2140
  for (const [id, upload] of this.uploads)
@@ -1891,7 +2144,7 @@ class BrowserUploadStore {
1891
2144
  close() {
1892
2145
  for (const [id, upload] of this.uploads)
1893
2146
  this.remove(id, upload);
1894
- fs6.rmSync(this.directory, { recursive: true, force: true });
2147
+ fs7.rmSync(this.directory, { recursive: true, force: true });
1895
2148
  }
1896
2149
  }
1897
2150
 
@@ -1901,9 +2154,9 @@ import { createRequire } from "node:module";
1901
2154
  // cli/src/browser/snapshot-line.ts
1902
2155
  function snapshotLine(line) {
1903
2156
  const value = line.trimStart().replace(/^- /, "");
1904
- const key = value.startsWith("'") ? /^'((?:[^']|'')*)'/.exec(value)?.[1]?.replaceAll("''", "'") ?? "" : value.split(/: |:$/)[0];
1905
- const ref = /\[ref=((?:f\d+)?e\d+)\](?: \[cursor=pointer\])?(?: \[box=[-\d,.]+\])?$/.exec(key)?.[1];
1906
- return { key, ref, role: key.split(" ")[0] };
2157
+ const key2 = value.startsWith("'") ? /^'((?:[^']|'')*)'/.exec(value)?.[1]?.replaceAll("''", "'") ?? "" : value.split(/: |:$/)[0];
2158
+ const ref = /\[ref=((?:f\d+)?e\d+)\](?: \[cursor=pointer\])?(?: \[box=[-\d,.]+\])?$/.exec(key2)?.[1];
2159
+ return { key: key2, ref, role: key2.split(" ")[0] };
1907
2160
  }
1908
2161
 
1909
2162
  // cli/src/browser/password-safe-snapshot.ts
@@ -1956,9 +2209,9 @@ function captureInUtilityWorld({ elements, injected }, options) {
1956
2209
  let line = `${indent}- ${node.role || "generic"}`;
1957
2210
  if (node.name)
1958
2211
  line += ` ${JSON.stringify(node.name)}`;
1959
- for (const key of ["checked", "disabled", "expanded", "selected", "pressed", "level", "active"])
1960
- if (node[key] !== undefined)
1961
- line += ` [${key}=${JSON.stringify(node[key])}]`;
2212
+ for (const key2 of ["checked", "disabled", "expanded", "selected", "pressed", "level", "active"])
2213
+ if (node[key2] !== undefined)
2214
+ line += ` [${key2}=${JSON.stringify(node[key2])}]`;
1962
2215
  if (node.ref)
1963
2216
  line += ` [ref=${node.ref}]`;
1964
2217
  if (node.box)
@@ -2071,16 +2324,16 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
2071
2324
  const document2 = { text: "", priorityRefs: [], matchRefs: [], matchCount: 0, frames: [], unavailableFrames: [] };
2072
2325
  const timeoutError = () => new Error(`Timeout ${timeout2}ms exceeded building a password-safe browser snapshot.`);
2073
2326
  const bounded2 = async (operation) => {
2074
- let timer;
2327
+ let timer2;
2075
2328
  try {
2076
2329
  return await Promise.race([
2077
2330
  operation,
2078
2331
  new Promise((_, reject) => {
2079
- timer = setTimeout(() => reject(timeoutError()), Math.max(0, deadline - Date.now()));
2332
+ timer2 = setTimeout(() => reject(timeoutError()), Math.max(0, deadline - Date.now()));
2080
2333
  })
2081
2334
  ]);
2082
2335
  } finally {
2083
- clearTimeout(timer);
2336
+ clearTimeout(timer2);
2084
2337
  }
2085
2338
  };
2086
2339
  const captureFrame = async (currentFrame, selector, frameOptions, isMainFrame = false, framePath = []) => {
@@ -2155,10 +2408,10 @@ function outline(document2) {
2155
2408
  while (stack.length && stack.at(-1).indent >= indent)
2156
2409
  stack.pop();
2157
2410
  const parent = stack.at(-1)?.node;
2158
- const { key, ref } = snapshotLine(line);
2411
+ const { key: key2, ref } = snapshotLine(line);
2159
2412
  const node = {
2160
2413
  line: line.trimStart(),
2161
- key,
2414
+ key: key2,
2162
2415
  ref,
2163
2416
  children: [],
2164
2417
  parent,
@@ -2294,16 +2547,16 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
2294
2547
  const sessions = new Set;
2295
2548
  let stopped = false;
2296
2549
  const bounded2 = async (operation) => {
2297
- let timer;
2550
+ let timer2;
2298
2551
  try {
2299
2552
  return await Promise.race([
2300
2553
  operation,
2301
2554
  new Promise((_, reject) => {
2302
- timer = setTimeout(() => reject(new Error("open_tab timed out identifying its created target. Inspect tabs before retrying.")), Math.max(0, deadline - Date.now()));
2555
+ timer2 = setTimeout(() => reject(new Error("open_tab timed out identifying its created target. Inspect tabs before retrying.")), Math.max(0, deadline - Date.now()));
2303
2556
  })
2304
2557
  ]);
2305
2558
  } finally {
2306
- clearTimeout(timer);
2559
+ clearTimeout(timer2);
2307
2560
  }
2308
2561
  };
2309
2562
  const attach = async (page) => {
@@ -2454,16 +2707,16 @@ async function waitForBrowserCondition(page, input) {
2454
2707
  error: "Cannot resolve the wait target. Check target, scope and frame selectors with browser_read_page."
2455
2708
  });
2456
2709
  const bounded2 = async (promise) => {
2457
- let timer;
2710
+ let timer2;
2458
2711
  try {
2459
2712
  return await Promise.race([
2460
2713
  promise,
2461
2714
  new Promise((_, reject) => {
2462
- timer = setTimeout(() => reject(new Error("Wait deadline exceeded")), Math.max(0, deadline - Date.now()));
2715
+ timer2 = setTimeout(() => reject(new Error("Wait deadline exceeded")), Math.max(0, deadline - Date.now()));
2463
2716
  })
2464
2717
  ]);
2465
2718
  } finally {
2466
- clearTimeout(timer);
2719
+ clearTimeout(timer2);
2467
2720
  }
2468
2721
  };
2469
2722
  if (!input.target) {
@@ -2585,7 +2838,7 @@ function observeNavigation(page, input) {
2585
2838
  if (settled)
2586
2839
  return;
2587
2840
  settled = true;
2588
- clearTimeout(timer);
2841
+ clearTimeout(timer2);
2589
2842
  page.off("framenavigated", onNavigation);
2590
2843
  page.off("close", onClose);
2591
2844
  page.off("crash", onClose);
@@ -2606,7 +2859,7 @@ function observeNavigation(page, input) {
2606
2859
  return;
2607
2860
  });
2608
2861
  };
2609
- const timer = setTimeout(() => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out."), input.timeoutMs);
2862
+ const timer2 = setTimeout(() => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out."), input.timeoutMs);
2610
2863
  page.on("framenavigated", onNavigation);
2611
2864
  page.on("close", onClose);
2612
2865
  page.on("crash", onClose);
@@ -2624,8 +2877,8 @@ function diagnosticUrl(raw) {
2624
2877
  u.username = "";
2625
2878
  u.password = "";
2626
2879
  u.hash = "";
2627
- for (const key of [...u.searchParams.keys()])
2628
- u.searchParams.set(key, "[redacted]");
2880
+ for (const key2 of [...u.searchParams.keys()])
2881
+ u.searchParams.set(key2, "[redacted]");
2629
2882
  return u.href;
2630
2883
  } catch {
2631
2884
  return "[unavailable]";
@@ -2812,7 +3065,7 @@ class BrowserPageEvents {
2812
3065
  const first = this.query(input, false);
2813
3066
  if (first.entries.length || !input.timeoutMs)
2814
3067
  return first;
2815
- let timer, changed;
3068
+ let timer2, changed;
2816
3069
  try {
2817
3070
  return await new Promise((resolve2) => {
2818
3071
  changed = () => {
@@ -2821,11 +3074,11 @@ class BrowserPageEvents {
2821
3074
  resolve2(result);
2822
3075
  };
2823
3076
  this.changes.add(changed);
2824
- timer = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
3077
+ timer2 = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
2825
3078
  changed();
2826
3079
  });
2827
3080
  } finally {
2828
- clearTimeout(timer);
3081
+ clearTimeout(timer2);
2829
3082
  this.changes.delete(changed);
2830
3083
  }
2831
3084
  }
@@ -2857,16 +3110,16 @@ class BrowserPageEvents {
2857
3110
  };
2858
3111
  }
2859
3112
  async racePending(pending, ms) {
2860
- let timer;
3113
+ let timer2;
2861
3114
  try {
2862
3115
  return await Promise.race([
2863
3116
  pending.result,
2864
3117
  new Promise((resolve2) => {
2865
- timer = setTimeout(() => resolve2(undefined), ms);
3118
+ timer2 = setTimeout(() => resolve2(undefined), ms);
2866
3119
  })
2867
3120
  ]);
2868
3121
  } finally {
2869
- clearTimeout(timer);
3122
+ clearTimeout(timer2);
2870
3123
  }
2871
3124
  }
2872
3125
  async run(actionId, dispatch) {
@@ -3096,7 +3349,7 @@ class BrowserWebMCP {
3096
3349
  const find = (node) => node.frame.id === entry.tool.frameId ? node.frame : node.childFrames?.map(find).find(Boolean);
3097
3350
  if (find(tree.frameTree)?.loaderId !== entry.loaderId || this.tools.get(entry.id) !== entry)
3098
3351
  return { invoked: false, code: "stale_webmcp_tool" };
3099
- let timer;
3352
+ let timer2;
3100
3353
  const { invocationId } = await this.cdp.send("WebMCP.invokeTool", {
3101
3354
  frameId: entry.tool.frameId,
3102
3355
  toolName: entry.tool.name,
@@ -3105,7 +3358,7 @@ class BrowserWebMCP {
3105
3358
  try {
3106
3359
  const outcome = await new Promise((resolve2) => {
3107
3360
  this.responses.set(invocationId, resolve2);
3108
- timer = setTimeout(() => resolve2(undefined), Number(input.timeoutMs ?? 1e4));
3361
+ timer2 = setTimeout(() => resolve2(undefined), Number(input.timeoutMs ?? 1e4));
3109
3362
  });
3110
3363
  if (!outcome) {
3111
3364
  await this.cdp.send("WebMCP.cancelInvocation", { invocationId }).catch(() => {
@@ -3125,7 +3378,7 @@ class BrowserWebMCP {
3125
3378
  outcomeVerified: false
3126
3379
  };
3127
3380
  } finally {
3128
- clearTimeout(timer);
3381
+ clearTimeout(timer2);
3129
3382
  this.responses.delete(invocationId);
3130
3383
  }
3131
3384
  }
@@ -3362,7 +3615,7 @@ async function exportDocument(page, format) {
3362
3615
  }
3363
3616
 
3364
3617
  // cli/src/browser/browser-tab-state.ts
3365
- import fs7 from "node:fs";
3618
+ import fs8 from "node:fs";
3366
3619
 
3367
3620
  class BrowserTabState {
3368
3621
  context;
@@ -3373,8 +3626,8 @@ class BrowserTabState {
3373
3626
  constructor(context, filename) {
3374
3627
  this.context = context;
3375
3628
  this.filename = filename;
3376
- if (fs7.existsSync(filename)) {
3377
- const value = JSON.parse(fs7.readFileSync(filename, "utf8"));
3629
+ if (fs8.existsSync(filename)) {
3630
+ const value = JSON.parse(fs8.readFileSync(filename, "utf8"));
3378
3631
  if (value.version !== 1 || !value.targets || typeof value.targets !== "object")
3379
3632
  throw new Error("Invalid browser tab state.");
3380
3633
  this.stored = value.targets;
@@ -3382,8 +3635,8 @@ class BrowserTabState {
3382
3635
  }
3383
3636
  save() {
3384
3637
  const tmp = `${this.filename}.${crypto.randomUUID()}.tmp`;
3385
- fs7.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
3386
- fs7.renameSync(tmp, this.filename);
3638
+ fs8.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
3639
+ fs8.renameSync(tmp, this.filename);
3387
3640
  }
3388
3641
  resolve(page) {
3389
3642
  let pending = this.pages.get(page);
@@ -3450,21 +3703,31 @@ var messages = {
3450
3703
  runtime_disconnected: "The runtime or browser connection ended.",
3451
3704
  context_destroyed: "The document execution context changed during the operation.",
3452
3705
  execution_timeout: "The browser operation exceeded its internal wait budget.",
3706
+ screenshot_capture_timeout: "Chrome did not finish screenshot preparation/rendering/PNG capture within 15 seconds.",
3707
+ screenshot_upload_timeout: "The captured screenshot did not finish uploading within its remaining transfer budget.",
3453
3708
  script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
3454
3709
  transfer_failed: "The file transfer failed or its completion could not be confirmed.",
3455
3710
  resource_unavailable: "The requested resource is unavailable. No download link was created.",
3456
3711
  scope_rejected: "Runtime scope or tab ownership was rejected.",
3457
3712
  runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
3458
3713
  };
3459
- function failureFor(error, op, operationId, stage) {
3714
+ function failureFor(error, op, operationId, stage, timing) {
3460
3715
  const text = error instanceof Error ? error.message : "";
3461
3716
  let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : /Protocol error.*(?:not supported|not allowed|wasn't found|Method not found)|Printing is not available|not available in an isolated browser context/i.test(text) ? "browser_operation_unsupported" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
3717
+ if (op === "screenshot" && code2 === "execution_timeout") {
3718
+ if (stage === "screenshot_capture")
3719
+ code2 = "screenshot_capture_timeout";
3720
+ if (stage === "screenshot_upload")
3721
+ code2 = "screenshot_upload_timeout";
3722
+ }
3723
+ if (op === "screenshot" && stage === "screenshot_upload" && code2 === "runtime_operation_failed")
3724
+ code2 = "transfer_failed";
3462
3725
  const observation = OBSERVATION_OPERATIONS.has(op);
3463
3726
  const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
3464
- const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
3727
+ const recovery = error instanceof RuntimeFault ? error.recovery : op === "screenshot" ? "Call browser_runtime_health. A settled screenshot failure can leave admission ready; health does not probe Chrome capture. The stage identifies geometry, capture (including font/render/PNG work), encoding or upload, not a specific Chrome cause. No screenshot was delivered and no automatic retry occurred. Inspect the target before deciding on a fresh screenshot; never replay a prior mutation or recover without approval." : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
3465
3728
  const diagnosticId = randomUUID4();
3466
- console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
3467
- return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
3729
+ console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome, ...timing }));
3730
+ return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, ...timing, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
3468
3731
  }
3469
3732
 
3470
3733
  // cli/src/browser/browser-runtime.ts
@@ -3475,6 +3738,7 @@ var MAX_RUN_JS_ARTIFACT_COUNT = 32;
3475
3738
  var REF_ACTION_TIMEOUT_MS = 5000;
3476
3739
  var NAVIGATION_TIMEOUT_MS = 20000;
3477
3740
  var READ_PAGE_TIMEOUT_MS = 1e4;
3741
+ var SCREENSHOT_TIMEOUT_MS = 15000;
3478
3742
  var MAX_FULL_PAGE_HEIGHT = 4000;
3479
3743
  var MAX_FULL_PAGE_WIDTH = 4096;
3480
3744
  var MAX_TYPED_KEYS_CHARS = 500;
@@ -3534,7 +3798,7 @@ class BrowserRuntime {
3534
3798
  return;
3535
3799
  });
3536
3800
  });
3537
- fs8.mkdirSync(downloadsPath, { recursive: true });
3801
+ fs9.mkdirSync(downloadsPath, { recursive: true });
3538
3802
  this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
3539
3803
  for (const page of context.pages())
3540
3804
  this.track(page);
@@ -3593,23 +3857,23 @@ class BrowserRuntime {
3593
3857
  return id;
3594
3858
  }
3595
3859
  safeDownloadFilename(suggestedFilename) {
3596
- const basename = path8.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
3860
+ const basename = path9.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
3597
3861
  if (!basename || basename === "." || basename === "..")
3598
3862
  return "download";
3599
- const extension = path8.extname(basename).slice(0, 30);
3600
- let stem = basename.slice(0, basename.length - path8.extname(basename).length) || "download";
3863
+ const extension = path9.extname(basename).slice(0, 30);
3864
+ let stem = basename.slice(0, basename.length - path9.extname(basename).length) || "download";
3601
3865
  while (Buffer.byteLength(`${stem}${extension}`) > 200)
3602
3866
  stem = stem.slice(0, -1);
3603
3867
  return `${stem || "download"}${extension}`;
3604
3868
  }
3605
3869
  availableDownloadPath(suggestedFilename) {
3606
3870
  const filename = this.safeDownloadFilename(suggestedFilename);
3607
- const extension = path8.extname(filename);
3871
+ const extension = path9.extname(filename);
3608
3872
  const stem = filename.slice(0, filename.length - extension.length) || "download";
3609
3873
  for (let suffix = 1;; suffix += 1) {
3610
3874
  const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
3611
- const candidatePath = path8.join(this.downloadsPath, candidate);
3612
- if (!fs8.existsSync(candidatePath))
3875
+ const candidatePath = path9.join(this.downloadsPath, candidate);
3876
+ if (!fs9.existsSync(candidatePath))
3613
3877
  return candidatePath;
3614
3878
  }
3615
3879
  }
@@ -3617,18 +3881,18 @@ class BrowserRuntime {
3617
3881
  const failure = await download.failure();
3618
3882
  if (failure)
3619
3883
  throw new Error(failure);
3620
- const temporary = path8.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
3884
+ const temporary = path9.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
3621
3885
  let targetPath;
3622
3886
  try {
3623
3887
  await download.saveAs(temporary);
3624
3888
  targetPath = this.availableDownloadPath(download.suggestedFilename());
3625
- fs8.renameSync(temporary, targetPath);
3889
+ fs9.renameSync(temporary, targetPath);
3626
3890
  } finally {
3627
- fs8.rmSync(temporary, { force: true });
3891
+ fs9.rmSync(temporary, { force: true });
3628
3892
  }
3629
- process.stdout.write(`[r5d-browser] downloaded ${path8.basename(targetPath)}
3893
+ process.stdout.write(`[r5d-browser] downloaded ${path9.basename(targetPath)}
3630
3894
  `);
3631
- return { downloadId: this.downloadId(path8.basename(targetPath)) };
3895
+ return { downloadId: this.downloadId(path9.basename(targetPath)) };
3632
3896
  }
3633
3897
  downloadId(filename) {
3634
3898
  return Buffer.from(filename, "utf8").toString("base64url");
@@ -3637,13 +3901,13 @@ class BrowserRuntime {
3637
3901
  if (typeof downloadId !== "string" || !downloadId)
3638
3902
  throw new Error("downloadId is required.");
3639
3903
  const filename = Buffer.from(downloadId, "base64url").toString("utf8");
3640
- if (this.downloadId(filename) !== downloadId || filename !== path8.basename(filename) || filename.includes("\x00")) {
3904
+ if (this.downloadId(filename) !== downloadId || filename !== path9.basename(filename) || filename.includes("\x00")) {
3641
3905
  throw new Error("Invalid downloadId.");
3642
3906
  }
3643
- const filePath = path8.join(this.downloadsPath, filename);
3907
+ const filePath = path9.join(this.downloadsPath, filename);
3644
3908
  let stats;
3645
3909
  try {
3646
- stats = fs8.lstatSync(filePath);
3910
+ stats = fs9.lstatSync(filePath);
3647
3911
  } catch {
3648
3912
  throw new Error(`Browser download ${downloadId} no longer exists.`);
3649
3913
  }
@@ -3652,7 +3916,7 @@ class BrowserRuntime {
3652
3916
  return { filename, filePath, stats };
3653
3917
  }
3654
3918
  async listDownloads() {
3655
- return fs8.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
3919
+ return fs9.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
3656
3920
  if (!entry.isFile() || entry.name.startsWith("."))
3657
3921
  return [];
3658
3922
  const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
@@ -3676,20 +3940,20 @@ class BrowserRuntime {
3676
3940
  throw new Error("Invalid download chunk size.");
3677
3941
  const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
3678
3942
  const bytes = Buffer.alloc(chunkSize);
3679
- const handle = fs8.openSync(filePath, fs8.constants.O_RDONLY | fs8.constants.O_NOFOLLOW);
3943
+ const handle = fs9.openSync(filePath, fs9.constants.O_RDONLY | fs9.constants.O_NOFOLLOW);
3680
3944
  let bytesRead = 0;
3681
3945
  try {
3682
- const openedStats = fs8.fstatSync(handle);
3946
+ const openedStats = fs9.fstatSync(handle);
3683
3947
  if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
3684
3948
  throw new Error("Browser download changed before it could be read.");
3685
3949
  }
3686
- bytesRead = fs8.readSync(handle, bytes, 0, chunkSize, offset);
3687
- const completedStats = fs8.fstatSync(handle);
3950
+ bytesRead = fs9.readSync(handle, bytes, 0, chunkSize, offset);
3951
+ const completedStats = fs9.fstatSync(handle);
3688
3952
  if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
3689
3953
  throw new Error("Browser download changed while it was being read.");
3690
3954
  }
3691
3955
  } finally {
3692
- fs8.closeSync(handle);
3956
+ fs9.closeSync(handle);
3693
3957
  }
3694
3958
  const nextOffset = offset + bytesRead;
3695
3959
  return {
@@ -3727,12 +3991,15 @@ class BrowserRuntime {
3727
3991
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
3728
3992
  } catch (error) {
3729
3993
  const message = error instanceof Error ? error.message : String(error);
3994
+ if (/Download is starting/i.test(message))
3995
+ return { downloadStarted: true };
3730
3996
  if (!/ERR_ABORTED|interrupted by another navigation/i.test(message))
3731
3997
  throw new Error(stripCallLog(message));
3732
3998
  await page.waitForLoadState("domcontentloaded", { timeout: 5000 }).catch(() => {
3733
3999
  return;
3734
4000
  });
3735
4001
  }
4002
+ return {};
3736
4003
  }
3737
4004
  async tabInfo(page) {
3738
4005
  this.track(page);
@@ -3938,14 +4205,15 @@ class BrowserRuntime {
3938
4205
  ownerSessionId: execution.sessionId,
3939
4206
  retention: input.retention === "temporary" ? "temporary" : "retained"
3940
4207
  });
4208
+ execution.onTabOpened?.(this.ids.get(page2));
3941
4209
  const url = typeof input.url === "string" ? input.url : "about:blank";
3942
4210
  if (url !== "about:blank") {
3943
4211
  const events = this.events.get(page2);
3944
4212
  await events.ready;
3945
4213
  const result = await events.run(execution.operationId ?? crypto.randomUUID(), async () => {
3946
- await this.gotoSettled(page2, url);
4214
+ const settled = await this.gotoSettled(page2, url);
3947
4215
  await this.guardPage?.(page2);
3948
- return { tab: await this.tabInfo(page2) };
4216
+ return { tab: await this.tabInfo(page2), ...settled };
3949
4217
  });
3950
4218
  return { tab: await this.tabInfo(page2), ...result };
3951
4219
  }
@@ -4120,9 +4388,9 @@ class BrowserRuntime {
4120
4388
  return { tabId, exported: false, code: "export_too_large" };
4121
4389
  const exports = files.map((file) => {
4122
4390
  const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
4123
- fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
4391
+ fs9.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
4124
4392
  return {
4125
- downloadId: this.downloadId(path8.basename(target2)),
4393
+ downloadId: this.downloadId(path9.basename(target2)),
4126
4394
  filename: file.filename,
4127
4395
  size: file.bytes.length,
4128
4396
  mimeType: file.mimeType
@@ -4145,9 +4413,10 @@ class BrowserRuntime {
4145
4413
  case "close_tab":
4146
4414
  await page.close();
4147
4415
  return { closed: true, tabId };
4148
- case "navigate":
4149
- await this.gotoSettled(page, String(input.url));
4150
- return { tab: await this.tabInfo(page) };
4416
+ case "navigate": {
4417
+ const settled = await this.gotoSettled(page, String(input.url));
4418
+ return { tab: await this.tabInfo(page), ...settled };
4419
+ }
4151
4420
  case "set_viewport": {
4152
4421
  const viewport = parseViewportInput(input);
4153
4422
  const result = await this.setViewport(page, tabId, viewport);
@@ -4207,7 +4476,14 @@ class BrowserRuntime {
4207
4476
  return result;
4208
4477
  }
4209
4478
  case "screenshot": {
4479
+ execution.screenshotStage?.("screenshot_geometry");
4210
4480
  const state = await page.evaluate(() => ({ url: location.href, scrollX, scrollY, width: innerWidth, height: innerHeight, dpr: devicePixelRatio }));
4481
+ const capture = async (options = {}) => {
4482
+ execution.screenshotStage?.("screenshot_capture");
4483
+ const bytes2 = await page.screenshot({ ...options, type: "png", scale: "css", timeout: SCREENSHOT_TIMEOUT_MS });
4484
+ execution.screenshotStage?.("screenshot_encode");
4485
+ return bytes2;
4486
+ };
4211
4487
  const record = (width, height, originX, originY) => {
4212
4488
  const transform = { id: crypto.randomUUID(), state, width, height, originX, originY };
4213
4489
  this.screenshots.set(tabId, transform);
@@ -4217,10 +4493,11 @@ class BrowserRuntime {
4217
4493
  const crop = input.crop;
4218
4494
  if (crop.x + crop.width > state.width || crop.y + crop.height > state.height)
4219
4495
  throw new Error("Crop must fit the current viewport in CSS pixels");
4220
- const bytes2 = await page.screenshot({ type: "png", scale: "css", clip: crop });
4496
+ const bytes2 = await capture({ clip: crop });
4221
4497
  return { base64: bytes2.toString("base64"), width: crop.width, height: crop.height, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), crop.x + state.scrollX, crop.y + state.scrollY) };
4222
4498
  }
4223
4499
  if (input.fullPage === true) {
4500
+ execution.screenshotStage?.("screenshot_metrics");
4224
4501
  const metrics = await page.evaluate(() => ({
4225
4502
  docWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth, document.body?.scrollWidth ?? 0, document.body?.offsetWidth ?? 0, document.body?.clientWidth ?? 0),
4226
4503
  docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight, document.body?.scrollHeight ?? 0, document.body?.offsetHeight ?? 0, document.body?.clientHeight ?? 0)
@@ -4228,16 +4505,15 @@ class BrowserRuntime {
4228
4505
  const width = Math.min(metrics.docWidth, MAX_FULL_PAGE_WIDTH);
4229
4506
  const height = Math.min(metrics.docHeight, MAX_FULL_PAGE_HEIGHT);
4230
4507
  const truncated = metrics.docHeight > MAX_FULL_PAGE_HEIGHT || metrics.docWidth > MAX_FULL_PAGE_WIDTH;
4231
- const bytes2 = truncated ? await page.screenshot({ type: "png", scale: "css", timeout: 15000, fullPage: true, clip: { x: 0, y: 0, width, height } }) : await page.screenshot({ type: "png", scale: "css", timeout: 15000, fullPage: true });
4508
+ const bytes2 = await capture({ fullPage: true, ...truncated ? { clip: { x: 0, y: 0, width, height } } : {} });
4232
4509
  return { base64: bytes2.toString("base64"), width, height, fullPage: true, pageHeight: metrics.docHeight, truncated, ...record(bytes2.readUInt32BE(16), bytes2.readUInt32BE(20), 0, 0) };
4233
4510
  }
4234
- const bytes = await page.screenshot({ type: "png", scale: "css" });
4235
- const viewport = page.viewportSize();
4511
+ const bytes = await capture();
4236
4512
  const cursor = this.cursor.get(tabId);
4237
4513
  return {
4238
4514
  base64: bytes.toString("base64"),
4239
- width: viewport?.width ?? Number(await page.evaluate(() => window.innerWidth)),
4240
- height: viewport?.height ?? Number(await page.evaluate(() => window.innerHeight)),
4515
+ width: bytes.readUInt32BE(16),
4516
+ height: bytes.readUInt32BE(20),
4241
4517
  ...record(bytes.readUInt32BE(16), bytes.readUInt32BE(20), state.scrollX, state.scrollY),
4242
4518
  cursorX: cursor?.x,
4243
4519
  cursorY: cursor?.y,
@@ -4295,7 +4571,7 @@ class BrowserRuntime {
4295
4571
  }
4296
4572
  case "scroll": {
4297
4573
  if (input.ref !== undefined) {
4298
- if (["direction", "amount", "x", "y"].some((key) => input[key] !== undefined))
4574
+ if (["direction", "amount", "x", "y"].some((key2) => input[key2] !== undefined))
4299
4575
  throw new Error("scroll accepts ref or wheel/pointer parameters, not both.");
4300
4576
  const ref = requireRef(input.ref);
4301
4577
  const locator = this.refLocator(page, ref);
@@ -4371,7 +4647,7 @@ class BrowserRuntime {
4371
4647
  }
4372
4648
  case "form_input": {
4373
4649
  const ref = requireRef(input.ref);
4374
- const provided = ["value", "values", "checked"].filter((key) => input[key] !== undefined);
4650
+ const provided = ["value", "values", "checked"].filter((key2) => input[key2] !== undefined);
4375
4651
  if (provided.length !== 1)
4376
4652
  throw new Error("form_input requires exactly one of value, values, or checked.");
4377
4653
  const locator = this.refLocator(page, ref);
@@ -4451,10 +4727,10 @@ class BrowserRuntime {
4451
4727
  for (const modifier of modifiers)
4452
4728
  await page.keyboard.down(modifier);
4453
4729
  try {
4454
- for (const key of keys) {
4455
- if (typeof key !== "string")
4730
+ for (const key2 of keys) {
4731
+ if (typeof key2 !== "string")
4456
4732
  throw new Error("keyboard keys must all be strings.");
4457
- await page.keyboard.press(key);
4733
+ await page.keyboard.press(key2);
4458
4734
  }
4459
4735
  } finally {
4460
4736
  for (const modifier of modifiers.toReversed())
@@ -4598,6 +4874,7 @@ class NativeRuntime {
4598
4874
  engine;
4599
4875
  plugins = [];
4600
4876
  owners = new Map;
4877
+ closedOwners = new Map;
4601
4878
  generations = new Map;
4602
4879
  tracking = new WeakMap;
4603
4880
  ended = new Set;
@@ -4605,7 +4882,8 @@ class NativeRuntime {
4605
4882
  controllers = new Map;
4606
4883
  disconnected = false;
4607
4884
  connectionEpoch = 0;
4608
- downloadAdmissionEpoch = 0;
4885
+ pageEpochs = new WeakMap;
4886
+ revocationEpoch = 0;
4609
4887
  operations = new Map;
4610
4888
  hooks = Promise.resolve();
4611
4889
  browserId;
@@ -4653,7 +4931,11 @@ class NativeRuntime {
4653
4931
  });
4654
4932
  });
4655
4933
  page.on("close", () => {
4656
- this.downloadAdmissionEpoch++;
4934
+ const owner = this.owners.get(id);
4935
+ if (owner) {
4936
+ this.closedOwners.set(page, owner);
4937
+ setTimeout(() => this.closedOwners.delete(page), 60000).unref?.();
4938
+ }
4657
4939
  this.generations.delete(id);
4658
4940
  this.owners.delete(id);
4659
4941
  this.enqueue(async () => {
@@ -4662,24 +4944,51 @@ class NativeRuntime {
4662
4944
  });
4663
4945
  });
4664
4946
  }
4947
+ revokeOwnership(tabId) {
4948
+ this.owners.delete(tabId);
4949
+ let page;
4950
+ try {
4951
+ page = this.engine.page(tabId);
4952
+ } catch {
4953
+ return;
4954
+ }
4955
+ this.pageEpochs.set(page, (this.pageEpochs.get(page) ?? 0) + 1);
4956
+ }
4665
4957
  async download(download, page, downloadId) {
4666
- const admissionEpoch = this.downloadAdmissionEpoch, connectionEpoch = this.connectionEpoch;
4667
- await this.track(page);
4668
- const id = await this.engine.idFor(page), scope = this.owners.get(id);
4958
+ for (const plugin of this.plugins)
4959
+ plugin.observeDownload?.(download);
4960
+ const pageEpoch = this.pageEpochs.get(page) ?? 0, revocationEpoch = this.revocationEpoch, connectionEpoch = this.connectionEpoch;
4961
+ let id, owner;
4669
4962
  try {
4670
- if (!scope || page.isClosed() || admissionEpoch !== this.downloadAdmissionEpoch || connectionEpoch !== this.connectionEpoch)
4963
+ await this.track(page);
4964
+ id = await this.engine.idFor(page);
4965
+ const scope = this.owners.get(id) ?? this.closedOwners.get(page);
4966
+ if (connectionEpoch !== this.connectionEpoch || (this.pageEpochs.get(page) ?? 0) !== pageEpoch)
4967
+ throw new Error("Download ownership changed");
4968
+ if (scope) {
4969
+ this.validateScope(scope);
4970
+ owner = { kind: "session", scope: { ...scope } };
4971
+ } else if (!page.isClosed() && revocationEpoch === this.revocationEpoch && !this.disconnected)
4972
+ owner = { kind: "user" };
4973
+ else
4671
4974
  throw new Error("Download ownership changed");
4672
- this.validateScope(scope);
4673
4975
  } catch {
4674
- await download.cancel().catch(() => {});
4976
+ await this.discardDownload(download);
4675
4977
  return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
4676
4978
  }
4677
4979
  const handler = this.plugins.find((p) => p.onDownload);
4678
4980
  if (!handler) {
4679
- await download.cancel();
4981
+ await this.discardDownload(download);
4680
4982
  return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
4681
4983
  }
4682
- return handler.onDownload(download, id, scope, this.generations.get(id) ?? 0, downloadId);
4984
+ return handler.onDownload(download, id, owner, this.generations.get(id) ?? 0, downloadId);
4985
+ }
4986
+ async discardDownload(download) {
4987
+ const plugin = this.plugins.find((p) => p.discardDownload);
4988
+ if (plugin)
4989
+ await plugin.discardDownload(download).catch(() => {});
4990
+ else
4991
+ await download.cancel().catch(() => {});
4683
4992
  }
4684
4993
  scopeEpoch(scope) {
4685
4994
  this.validateScope(scope);
@@ -4843,29 +5152,29 @@ class NativeRuntime {
4843
5152
  cancelOperation(operationId) {
4844
5153
  this.operations.get(operationId)?.abort(new Error("Runtime operation interrupted; page effects remain uncertain"));
4845
5154
  }
4846
- async execute(op, args, scope, operationId, beforeDispatch) {
5155
+ async execute(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4847
5156
  if (op === "session_end") {
4848
5157
  await this.endSession(scope);
4849
5158
  return { ended: true };
4850
5159
  }
4851
- const controller = new AbortController, key = scopeKey(scope);
4852
- let set = this.controllers.get(key);
5160
+ const controller = new AbortController, key2 = scopeKey(scope);
5161
+ let set = this.controllers.get(key2);
4853
5162
  if (!set) {
4854
5163
  set = new Set;
4855
- this.controllers.set(key, set);
5164
+ this.controllers.set(key2, set);
4856
5165
  }
4857
5166
  set.add(controller);
4858
5167
  this.operations.set(operationId, controller);
4859
5168
  try {
4860
- return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch));
5169
+ return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage));
4861
5170
  } finally {
4862
5171
  this.operations.delete(operationId);
4863
5172
  set.delete(controller);
4864
5173
  if (!set.size)
4865
- this.controllers.delete(key);
5174
+ this.controllers.delete(key2);
4866
5175
  }
4867
5176
  }
4868
- async executeInner(op, args, scope, operationId, beforeDispatch) {
5177
+ async executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage) {
4869
5178
  let dispatched = false;
4870
5179
  const begin = () => {
4871
5180
  this.validateScope(scope);
@@ -4886,8 +5195,8 @@ class NativeRuntime {
4886
5195
  if (op === "release_tab") {
4887
5196
  const tabId = String(args.tabId);
4888
5197
  begin();
4889
- this.downloadAdmissionEpoch++;
4890
- this.owners.delete(tabId);
5198
+ this.revocationEpoch++;
5199
+ this.revokeOwnership(tabId);
4891
5200
  this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
4892
5201
  for (const p of this.plugins)
4893
5202
  await p.onHandoff?.(tabId, scope);
@@ -4911,7 +5220,11 @@ class NativeRuntime {
4911
5220
  return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
4912
5221
  }
4913
5222
  try {
4914
- const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin });
5223
+ const onTabOpened = (tabId) => {
5224
+ if (!this.disconnected && (this.epochs.get(scopeKey(scope)) ?? 0) === operationEpoch)
5225
+ this.owners.set(tabId, { ...scope });
5226
+ };
5227
+ const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin, screenshotStage, onTabOpened });
4915
5228
  if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
4916
5229
  throw new Error("Scope ended during execution; outcome uncertain");
4917
5230
  const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
@@ -4927,18 +5240,21 @@ class NativeRuntime {
4927
5240
  }
4928
5241
  }
4929
5242
  async endSession(scope) {
4930
- const key = scopeKey(scope);
4931
- this.ended.add(key);
4932
- this.epochs.set(key, (this.epochs.get(key) ?? 0) + 1);
4933
- for (const controller of this.controllers.get(key) ?? [])
5243
+ const key2 = scopeKey(scope);
5244
+ this.ended.add(key2);
5245
+ this.epochs.set(key2, (this.epochs.get(key2) ?? 0) + 1);
5246
+ for (const controller of this.controllers.get(key2) ?? [])
4934
5247
  controller.abort(new Error("Runtime scope revoked"));
4935
- this.downloadAdmissionEpoch++;
5248
+ this.revocationEpoch++;
4936
5249
  for (const [id, owner] of this.owners)
4937
- if (scopeKey(owner) === key)
4938
- this.owners.delete(id);
5250
+ if (scopeKey(owner) === key2)
5251
+ this.revokeOwnership(id);
5252
+ for (const [page, owner] of this.closedOwners)
5253
+ if (scopeKey(owner) === key2)
5254
+ this.closedOwners.delete(page);
4939
5255
  for (const p of this.plugins)
4940
5256
  await p.onSessionEnd?.(scope);
4941
- this.ended.delete(key);
5257
+ this.ended.delete(key2);
4942
5258
  }
4943
5259
  async shutdown() {
4944
5260
  await this.disconnect();
@@ -4969,8 +5285,8 @@ class NativeRuntime {
4969
5285
  // cli/src/runtime/relay.ts
4970
5286
  import WebSocket2 from "ws";
4971
5287
  import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
4972
- import fs9 from "node:fs/promises";
4973
- import path9 from "node:path";
5288
+ import fs10 from "node:fs/promises";
5289
+ import path10 from "node:path";
4974
5290
 
4975
5291
  // cli/src/live/producer.ts
4976
5292
  import WebSocket from "ws";
@@ -5071,13 +5387,13 @@ class CaptureTimeout extends Error {
5071
5387
  }
5072
5388
  }
5073
5389
  async function bounded2(stage, operation) {
5074
- let timer;
5390
+ let timer2;
5075
5391
  try {
5076
5392
  return await Promise.race([operation, new Promise((_, reject) => {
5077
- timer = setTimeout(() => reject(new CaptureTimeout(stage)), STAGE_TIMEOUT_MS);
5393
+ timer2 = setTimeout(() => reject(new CaptureTimeout(stage)), STAGE_TIMEOUT_MS);
5078
5394
  })]);
5079
5395
  } finally {
5080
- clearTimeout(timer);
5396
+ clearTimeout(timer2);
5081
5397
  }
5082
5398
  }
5083
5399
 
@@ -5227,12 +5543,12 @@ class NativeLiveProducer {
5227
5543
  this.socket = ws;
5228
5544
  try {
5229
5545
  await new Promise((resolve2, reject) => {
5230
- const timer = setTimeout(() => {
5546
+ const timer2 = setTimeout(() => {
5231
5547
  ws.terminate();
5232
5548
  reject(new Error("Media timeout"));
5233
5549
  }, 5000);
5234
5550
  const done = (error) => {
5235
- clearTimeout(timer);
5551
+ clearTimeout(timer2);
5236
5552
  error ? reject(error) : resolve2();
5237
5553
  };
5238
5554
  ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
@@ -5358,10 +5674,10 @@ function wireResult(op, value) {
5358
5674
  const opaque = ["output", "inputSchema", "annotations", "originalAction"];
5359
5675
  if (op === "run_js")
5360
5676
  opaque.push("result");
5361
- for (const key of opaque)
5362
- if (output[key] !== undefined) {
5363
- output[`${key}Json`] = JSON.stringify(output[key]);
5364
- delete output[key];
5677
+ for (const key2 of opaque)
5678
+ if (output[key2] !== undefined) {
5679
+ output[`${key2}Json`] = JSON.stringify(output[key2]);
5680
+ delete output[key2];
5365
5681
  }
5366
5682
  if (op === "webmcp_list" && Array.isArray(output.tools))
5367
5683
  output.tools = output.tools.map((tool) => wireResult("tool-description", tool));
@@ -5373,9 +5689,9 @@ function wireResult(op, value) {
5373
5689
  output.newRuntimeTabIds = output.newTabIds;
5374
5690
  delete output.newTabIds;
5375
5691
  }
5376
- for (const key of ["tab", "observation"])
5377
- if (output[key])
5378
- output[key] = wireResult("metadata", output[key]);
5692
+ for (const key2 of ["tab", "observation"])
5693
+ if (output[key2])
5694
+ output[key2] = wireResult("metadata", output[key2]);
5379
5695
  if (Array.isArray(output.tabs))
5380
5696
  output.tabs = output.tabs.map((tab) => wireResult("metadata", tab));
5381
5697
  if (op === "batch" && Array.isArray(output.results))
@@ -5401,7 +5717,7 @@ class Relay {
5401
5717
  const state = { quarantined, executionState: active.settled ? active.interrupted ? "settled_after_interruption" : "settled_late" : quarantined ? "unresolved" : "in_progress" };
5402
5718
  if (scope && !sameScope3(active.scope, scope))
5403
5719
  return { ...state, ownedByAnotherScope: true };
5404
- return { ...state, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
5720
+ return { ...state, ...active.screenshotStage ? { stage: active.screenshotStage } : {}, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
5405
5721
  }
5406
5722
  health(scope) {
5407
5723
  const active = this.active;
@@ -5541,7 +5857,7 @@ class Relay {
5541
5857
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5542
5858
  return;
5543
5859
  this.state = "authenticating";
5544
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.16", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "runtime-quarantine.v1", "binary-artifacts.v1", "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 } } }));
5860
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.18", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "runtime-quarantine.v1", "binary-artifacts.v1", "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 } } }));
5545
5861
  });
5546
5862
  socket.on("message", (bytes, binary) => {
5547
5863
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -5703,7 +6019,15 @@ class Relay {
5703
6019
  finish = resolve2;
5704
6020
  }), interrupt: () => interrupt(), expire: () => expire() };
5705
6021
  this.active = active;
5706
- let stage = "execute", timer;
6022
+ let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(), timer2;
6023
+ const screenshotStage = message.op === "screenshot" ? (next) => {
6024
+ stage = next;
6025
+ stageStartedAt = Date.now();
6026
+ active.screenshotStage = next;
6027
+ } : undefined;
6028
+ screenshotStage?.("screenshot_prepare");
6029
+ const timing = () => message.op === "screenshot" ? { elapsedMs: Math.max(0, Date.now() - active.startedAt), stageElapsedMs: Math.max(0, Date.now() - stageStartedAt) } : undefined;
6030
+ const screenshotUpload = new AbortController;
5707
6031
  const expired = new Promise((resolve2) => {
5708
6032
  const terminal = (cancelled) => {
5709
6033
  if (active.interrupted || active.settled)
@@ -5719,8 +6043,11 @@ class Relay {
5719
6043
  active.interrupted = true;
5720
6044
  else
5721
6045
  active.timedOut = true;
5722
- clearTimeout(timer);
5723
- send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
6046
+ clearTimeout(timer2);
6047
+ screenshotUpload.abort();
6048
+ if (message.op === "screenshot")
6049
+ console.error(JSON.stringify({ event: "runtime_failure", diagnosticId: active.id, operationId: active.id, operation: message.op, stage, code: cancelled ? "runtime_interrupted" : "runtime_timeout", outcome: active.dispatched ? "failed" : "not_dispatched", ...timing() }));
6050
+ send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, ...timing(), callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
5724
6051
  this.flushWaiting("blocked_by_prior_operation", "A prior operation timed out or was interrupted. This waiting request was never dispatched.");
5725
6052
  if (cancelled)
5726
6053
  this.runtime.cancelOperation(active.id);
@@ -5728,7 +6055,7 @@ class Relay {
5728
6055
  };
5729
6056
  interrupt = () => terminal(true);
5730
6057
  expire = () => terminal(false);
5731
- timer = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
6058
+ timer2 = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
5732
6059
  });
5733
6060
  const task = (async () => {
5734
6061
  let response;
@@ -5739,7 +6066,7 @@ class Relay {
5739
6066
  entry.guard(!active.dispatched);
5740
6067
  active.dispatched = true;
5741
6068
  };
5742
- const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch);
6069
+ const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch, screenshotStage);
5743
6070
  if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
5744
6071
  return;
5745
6072
  this.runtime.validateScope(message.scope);
@@ -5750,45 +6077,57 @@ class Relay {
5750
6077
  stage = "transfer";
5751
6078
  const blobs = [];
5752
6079
  if (result?.base64 && message.op === "screenshot") {
6080
+ screenshotStage?.("screenshot_encode");
5753
6081
  const bytes = Buffer.from(result.base64, "base64");
5754
6082
  delete result.base64;
5755
- blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
6083
+ screenshotStage?.("screenshot_upload");
6084
+ const remaining = active.deadlineAt - Date.now() - 1000;
6085
+ if (remaining <= 0)
6086
+ throw new RuntimeFault("screenshot_upload_timeout", "Call browser_runtime_health. Capture completed but there was no remaining upload budget; no image was delivered and no automatic retry occurred.");
6087
+ blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png", AbortSignal.any([screenshotUpload.signal, AbortSignal.timeout(Math.min(1e4, remaining))])));
6088
+ screenshotStage?.("screenshot_reply");
5756
6089
  }
5757
6090
  if (message.op === "export_page" && Array.isArray(result?.exports))
5758
6091
  for (const item of result.exports) {
5759
6092
  const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
5760
- if (path9.basename(filename) !== filename)
6093
+ if (path10.basename(filename) !== filename)
5761
6094
  throw new Error("Invalid export file");
5762
- const filenamePath = path9.join(this.previewDirectory, filename);
5763
- const stat = await fs9.lstat(filenamePath);
6095
+ const filenamePath = path10.join(this.previewDirectory, filename);
6096
+ const stat = await fs10.lstat(filenamePath);
5764
6097
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
5765
6098
  throw new Error("Invalid export file");
5766
- blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
5767
- await fs9.unlink(filenamePath);
6099
+ blobs.push(await this.upload(await fs10.readFile(filenamePath), "export", item.filename, item.mimeType));
6100
+ await fs10.unlink(filenamePath);
5768
6101
  delete item.downloadId;
5769
6102
  }
5770
6103
  if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
5771
6104
  for (const artifact2 of result.artifacts)
5772
- blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path9.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
5773
- result.artifacts = result.artifacts.map((a) => ({ filename: path9.basename(a.filename) }));
6105
+ blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path10.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
6106
+ result.artifacts = result.artifacts.map((a) => ({ filename: path10.basename(a.filename) }));
5774
6107
  }
5775
6108
  if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
5776
6109
  throw new Error("Result budget exceeded");
5777
6110
  response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
5778
6111
  } catch (error) {
5779
- const failure = failureFor(error, message.op, message.id, stage);
5780
- if (failure.error.code === "context_destroyed" && active.tabId) {
5781
- for (const waiting of [...this.waiting])
5782
- if (waiting.message.args.tabId === active.tabId)
5783
- this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
6112
+ if (message.op === "screenshot" && (active.timedOut || active.interrupted)) {
6113
+ console.error(JSON.stringify({ event: "screenshot_late_settlement", operationId: active.id, stage, ...timing(), callerDeadline: active.interrupted ? "interrupted" : "expired" }));
6114
+ } else {
6115
+ const failure = failureFor(error, message.op, message.id, stage, timing());
6116
+ if (message.op === "screenshot")
6117
+ this.remember(active, { operation: message.op, ...failure.result, outcome: failure.outcome });
6118
+ if (failure.error.code === "context_destroyed" && active.tabId) {
6119
+ for (const waiting of [...this.waiting])
6120
+ if (waiting.message.args.tabId === active.tabId)
6121
+ this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
6122
+ }
6123
+ response = { type: "result", id: message.id, ok: false, ...failure };
5784
6124
  }
5785
- response = { type: "result", id: message.id, ok: false, ...failure };
5786
6125
  } finally {
5787
- clearTimeout(timer);
6126
+ clearTimeout(timer2);
5788
6127
  active.settled = true;
5789
6128
  finish();
5790
6129
  if (active.timedOut || active.interrupted)
5791
- this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
6130
+ this.remember(active, { ...message.op === "screenshot" ? { operation: message.op, stage, ...timing() } : {}, callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
5792
6131
  if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
5793
6132
  this.active = undefined;
5794
6133
  }
@@ -5817,23 +6156,23 @@ class Relay {
5817
6156
  this.active = undefined;
5818
6157
  return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
5819
6158
  })();
5820
- let timer;
6159
+ let timer2;
5821
6160
  try {
5822
6161
  const result = await Promise.race([work, new Promise((_, reject2) => {
5823
- timer = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
6162
+ timer2 = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
5824
6163
  })]);
5825
6164
  send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
5826
6165
  } catch {
5827
6166
  send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "recovery_uncertain", message: "Recovery completion is unconfirmed. Do not repeat it; query browser_runtime_health or ask the user to stop and restart this dedicated runtime." }, result: { operationId: active.id, retrySafe: false, cancellationConfirmed: false } });
5828
6167
  } finally {
5829
- clearTimeout(timer);
6168
+ clearTimeout(timer2);
5830
6169
  }
5831
6170
  }
5832
- async upload(bytes, role, name, mimeType) {
6171
+ async upload(bytes, role, name, mimeType, signal = AbortSignal.timeout(30000)) {
5833
6172
  if (bytes.length > 20 * 1024 * 1024)
5834
6173
  throw new Error("Preview exceeds 20 MiB");
5835
6174
  const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
5836
- 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) });
6175
+ 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 });
5837
6176
  if (!response.ok)
5838
6177
  throw new Error("Preview upload failed");
5839
6178
  return { blobId, role, name, mimeType, size: bytes.length, sha256 };
@@ -5862,10 +6201,10 @@ class Relay {
5862
6201
  }
5863
6202
 
5864
6203
  // cli/src/data/index.ts
5865
- import { mkdir as mkdir2, open as open3, rename, unlink as unlink2, rmdir as rmdir2, lstat as lstat2 } from "node:fs/promises";
6204
+ import { mkdir as mkdir2, open as open3, rename, unlink as unlink3, rmdir as rmdir2, lstat as lstat3 } from "node:fs/promises";
5866
6205
  import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
5867
- import { randomUUID as randomUUID7, createHash as createHash7 } from "node:crypto";
5868
- import { join as join2, basename } from "node:path";
6206
+ import { randomUUID as randomUUID8, createHash as createHash7 } from "node:crypto";
6207
+ import { join as join2, basename as basename2 } from "node:path";
5869
6208
  import { Readable, Transform as Transform2 } from "node:stream";
5870
6209
  import { pipeline as pipeline2 } from "node:stream/promises";
5871
6210
 
@@ -5891,7 +6230,7 @@ class SecretVault {
5891
6230
  throw new Error("Capture rejected");
5892
6231
  const epoch = this.epoch, target2 = await this.access.resolveTarget(tabId, scope, frames);
5893
6232
  try {
5894
- let timer;
6233
+ let timer2;
5895
6234
  const values = await Promise.race([this.access.suppressDiagnostics(tabId, () => target2.frame.evaluate(async ({ code: code3, limits }) => {
5896
6235
  const values2 = Object.create(null);
5897
6236
  let bytes = 0;
@@ -5911,11 +6250,11 @@ class SecretVault {
5911
6250
  throw new Error("Capture failed");
5912
6251
  }
5913
6252
  }, { code: code2, limits: LIMITS })), new Promise((_resolve, reject) => {
5914
- timer = setTimeout(() => reject(new Error("Capture timeout")), 15000);
5915
- timer.unref?.();
6253
+ timer2 = setTimeout(() => reject(new Error("Capture timeout")), 15000);
6254
+ timer2.unref?.();
5916
6255
  })]).finally(() => {
5917
- if (timer)
5918
- clearTimeout(timer);
6256
+ if (timer2)
6257
+ clearTimeout(timer2);
5919
6258
  });
5920
6259
  target2.assertCurrent();
5921
6260
  if (epoch !== this.epoch)
@@ -5990,21 +6329,67 @@ class SecretVault {
5990
6329
 
5991
6330
  // cli/src/data/download-capture.ts
5992
6331
  import { constants as constants3, createWriteStream } from "node:fs";
5993
- import { open as open2 } from "node:fs/promises";
5994
- import { createHash as createHash6 } from "node:crypto";
6332
+ import { lstat as lstat2, open as open2, unlink as unlink2 } from "node:fs/promises";
6333
+ import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
6334
+ import { basename, dirname as dirname2, resolve as resolve2 } from "node:path";
5995
6335
  import { Transform } from "node:stream";
5996
6336
  import { pipeline } from "node:stream/promises";
6337
+ var filesystemReasons = new Set(["ENOENT", "EACCES", "EPERM", "ELOOP", "ENOTDIR", "EMFILE", "ENFILE", "EIO", "ENOSPC"]);
6338
+ var SETTLEMENT_WAIT_MS = 5000;
6339
+ function within(promise, ms) {
6340
+ if (!promise)
6341
+ return Promise.resolve(undefined);
6342
+ return new Promise((resolve3) => {
6343
+ const timer2 = setTimeout(() => resolve3(undefined), ms);
6344
+ timer2.unref?.();
6345
+ promise.then((value) => {
6346
+ clearTimeout(timer2);
6347
+ resolve3(value);
6348
+ }, () => {
6349
+ clearTimeout(timer2);
6350
+ resolve3(undefined);
6351
+ });
6352
+ });
6353
+ }
6354
+ function captureEvidence() {
6355
+ return { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
6356
+ }
6357
+ function reasonFor(error) {
6358
+ if (error instanceof CaptureError)
6359
+ return error.reason;
6360
+ const code2 = error?.code;
6361
+ return typeof code2 === "string" && filesystemReasons.has(code2) ? code2 : "unknown";
6362
+ }
6363
+ async function sourceAvailability(source) {
6364
+ if (!source.path)
6365
+ return "unconfirmed";
6366
+ try {
6367
+ const stat = await lstat2(source.path);
6368
+ if (!stat.isFile() || stat.isSymbolicLink())
6369
+ return "unsafe";
6370
+ if (source.identity && (source.identity.dev !== stat.dev || source.identity.ino !== stat.ino))
6371
+ return "unsafe";
6372
+ source.identity ??= { dev: stat.dev, ino: stat.ino };
6373
+ source.size ??= stat.size;
6374
+ return "present";
6375
+ } catch (error) {
6376
+ return ["ENOENT", "ENOTDIR"].includes(reasonFor(error)) ? "unavailable" : "unconfirmed";
6377
+ }
6378
+ }
6379
+
5997
6380
  class CaptureError extends Error {
5998
6381
  code;
5999
- constructor(code2) {
6382
+ reason;
6383
+ constructor(code2, reason = "unknown") {
6000
6384
  super(code2);
6001
6385
  this.code = code2;
6386
+ this.reason = reason;
6002
6387
  }
6003
6388
  }
6004
6389
  async function duringCapture(work, signal) {
6005
6390
  let abort;
6006
6391
  const cancelled = new Promise((_, reject) => {
6007
- abort = () => reject(new CaptureError("download_capture_cancelled"));
6392
+ abort = () => reject(new CaptureError("download_capture_cancelled", "cancelled"));
6008
6393
  signal.addEventListener("abort", abort, { once: true });
6009
6394
  if (signal.aborted)
6010
6395
  abort();
@@ -6030,32 +6415,55 @@ function contentValidation(name, size) {
6030
6415
  warning: "The completed browser file is empty. This may be intentional; no document validity is implied."
6031
6416
  };
6032
6417
  }
6033
- async function captureDownload(download, destination, signal, evidence) {
6034
- const failure = await duringCapture(download.failure(), signal);
6035
- evidence.browserCompletion = failure === null ? "completed" : "failed";
6036
- if (failure !== null)
6037
- throw new CaptureError("download_capture_browser_failed");
6038
- const path10 = await duringCapture(download.path(), signal);
6039
- signal.throwIfAborted();
6040
- evidence.stage = "browser-file";
6418
+ async function captureDownload(browserSource, destination, signal, evidence) {
6419
+ const { download } = browserSource;
6420
+ const hooks = browserSource.hooks ?? {};
6421
+ let operation = "completion";
6041
6422
  let source;
6042
6423
  let retained2;
6043
6424
  try {
6044
- source = await open2(path10, constants3.O_RDONLY | constants3.O_NOFOLLOW);
6425
+ const failure = await duringCapture(download.failure(), signal);
6426
+ evidence.browserCompletion = failure === null ? "completed" : "failed";
6427
+ if (failure !== null)
6428
+ throw new CaptureError("download_capture_browser_failed", "browser-failed");
6429
+ hooks.completed?.();
6430
+ operation = "path";
6431
+ const path11 = await duringCapture(download.path(), signal);
6432
+ signal.throwIfAborted();
6433
+ evidence.stage = "browser-file";
6434
+ if (dirname2(resolve2(path11)) !== resolve2(browserSource.directory) || browserSource.path && path11 !== browserSource.path)
6435
+ throw new CaptureError("download_capture_source_unavailable", "unsafe-path");
6436
+ browserSource.path = path11;
6437
+ const guid = basename(path11);
6438
+ if (hooks.claim && !hooks.claim(guid))
6439
+ throw new CaptureError("download_capture_source_unavailable", "source-changed");
6440
+ const settled = await duringCapture(within(hooks.settlement?.(guid), SETTLEMENT_WAIT_MS), signal);
6441
+ if (settled?.state === "completed" && settled.filePath && hooks.isSpoolPath && !hooks.isSpoolPath(settled.filePath, guid))
6442
+ throw new CaptureError("download_capture_source_unavailable", "outside-spool");
6443
+ operation = "open";
6444
+ source = await open2(path11, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
6445
+ operation = "stat";
6045
6446
  const before = await source.stat();
6046
6447
  if (!before.isFile())
6047
- throw new CaptureError("download_capture_source_unavailable");
6448
+ throw new CaptureError("download_capture_source_unavailable", "not-regular-file");
6449
+ if (browserSource.identity && (before.dev !== browserSource.identity.dev || before.ino !== browserSource.identity.ino))
6450
+ throw new CaptureError("download_capture_source_unavailable", "source-changed");
6451
+ browserSource.identity = { dev: before.dev, ino: before.ino };
6452
+ browserSource.size = before.size;
6453
+ evidence.sourceAvailability = "present";
6048
6454
  evidence.browser = { size: before.size };
6049
6455
  if (before.size > LIMITS.file)
6050
- throw new CaptureError("download_quota_exceeded");
6456
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6457
+ hooks.reserve?.(before.size);
6051
6458
  signal.throwIfAborted();
6052
6459
  evidence.stage = "copy";
6460
+ operation = "copy";
6053
6461
  let size = 0;
6054
6462
  const hash = createHash6("sha256");
6055
6463
  const bound = new Transform({ transform(chunk, _encoding, callback) {
6056
6464
  size += chunk.length;
6057
6465
  if (size > LIMITS.file)
6058
- return callback(new CaptureError("download_quota_exceeded"));
6466
+ return callback(new CaptureError("download_quota_exceeded", "quota-exceeded"));
6059
6467
  hash.update(chunk);
6060
6468
  callback(null, chunk);
6061
6469
  } });
@@ -6063,6 +6471,7 @@ async function captureDownload(download, destination, signal, evidence) {
6063
6471
  const sourceHash = hash.digest("hex");
6064
6472
  evidence.browser.sha256 = sourceHash;
6065
6473
  evidence.stage = "verification";
6474
+ operation = "verification";
6066
6475
  retained2 = await open2(destination, constants3.O_RDONLY | constants3.O_NOFOLLOW);
6067
6476
  const disk = await retained2.stat();
6068
6477
  if (!disk.isFile() || disk.size > LIMITS.file)
@@ -6072,7 +6481,7 @@ async function captureDownload(download, destination, signal, evidence) {
6072
6481
  for await (const chunk of retained2.createReadStream({ start: 0, autoClose: false, signal })) {
6073
6482
  diskSize += chunk.length;
6074
6483
  if (diskSize > LIMITS.file)
6075
- throw new CaptureError("download_quota_exceeded");
6484
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6076
6485
  diskHash.update(chunk);
6077
6486
  }
6078
6487
  evidence.retained = { size: diskSize, sha256: diskHash.digest("hex") };
@@ -6080,45 +6489,82 @@ async function captureDownload(download, destination, signal, evidence) {
6080
6489
  const diskAfter = await retained2.stat();
6081
6490
  if (size !== before.size || disk.size !== size || diskSize !== size || evidence.retained.sha256 !== sourceHash || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs || diskAfter.size !== disk.size || diskAfter.mtimeMs !== disk.mtimeMs || diskAfter.ctimeMs !== disk.ctimeMs) {
6082
6491
  evidence.comparison = "mismatched";
6083
- throw new CaptureError("download_capture_mismatch");
6492
+ throw new CaptureError("download_capture_mismatch", "source-changed");
6084
6493
  }
6085
6494
  signal.throwIfAborted();
6086
6495
  evidence.comparison = "matched";
6087
6496
  evidence.stage = "verified";
6088
6497
  return { size, sha256: sourceHash };
6498
+ } catch (error) {
6499
+ const reason = signal.aborted ? "cancelled" : reasonFor(error);
6500
+ evidence.diagnostic = { id: randomUUID7(), operation, reason };
6501
+ evidence.sourceAvailability = ["unsafe-path", "source-changed", "not-regular-file", "ELOOP"].includes(reason) ? "unsafe" : await sourceAvailability(browserSource);
6502
+ throw error instanceof CaptureError ? error : new CaptureError(signal.aborted ? "download_capture_cancelled" : ["path", "open", "stat"].includes(operation) ? "download_capture_source_unavailable" : "download_capture_failed", reason);
6089
6503
  } finally {
6090
- try {
6091
- await retained2?.close();
6092
- } finally {
6093
- await source?.close();
6094
- }
6504
+ await retained2?.close().catch(() => {});
6505
+ await source?.close().catch(() => {});
6095
6506
  }
6096
6507
  }
6097
- async function cleanupDownload(download, evidence) {
6098
- let timer;
6508
+ async function cleanupDownload(source, evidence) {
6509
+ const hooks = source.hooks ?? {};
6510
+ let timer2;
6099
6511
  try {
6100
- const deleted = await Promise.race([
6101
- download.delete().then(() => true, () => false),
6102
- new Promise((resolve2) => {
6103
- timer = setTimeout(() => resolve2(false), 2000);
6104
- timer.unref?.();
6512
+ const outcome = await Promise.race([
6513
+ (async () => {
6514
+ let failed = false;
6515
+ if (!source.path) {
6516
+ const path11 = await source.download.path().catch(() => {
6517
+ failed = true;
6518
+ return;
6519
+ });
6520
+ if (path11 && dirname2(resolve2(path11)) === resolve2(source.directory))
6521
+ source.path = path11;
6522
+ }
6523
+ if (source.path && hooks.claim && !hooks.claim(basename(source.path)))
6524
+ return true;
6525
+ await source.download.delete().catch(() => {});
6526
+ if (!source.path) {
6527
+ if (!failed || !hooks.release)
6528
+ return false;
6529
+ hooks.release();
6530
+ return true;
6531
+ }
6532
+ await unlink2(source.path).catch(() => {});
6533
+ try {
6534
+ await lstat2(source.path);
6535
+ return false;
6536
+ } catch (error) {
6537
+ return reasonFor(error) === "ENOENT";
6538
+ }
6539
+ })(),
6540
+ new Promise((resolve3) => {
6541
+ timer2 = setTimeout(() => resolve3("timeout"), 2000);
6542
+ timer2.unref?.();
6105
6543
  })
6106
6544
  ]);
6545
+ const deleted = outcome === "timeout" ? !source.path && !!hooks.release : outcome;
6107
6546
  if (evidence)
6108
6547
  evidence.cleanup = deleted ? "deleted" : "browser-context";
6548
+ return deleted;
6109
6549
  } finally {
6110
- clearTimeout(timer);
6550
+ clearTimeout(timer2);
6111
6551
  }
6112
6552
  }
6113
6553
 
6114
6554
  // cli/src/data/index.ts
6115
6555
  var safeName = (s) => {
6116
- const name = basename(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
6556
+ const name = basename2(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
6117
6557
  return !name || name === "." || name === ".." ? "file" : name;
6118
6558
  };
6559
+ var USER_SCOPE = { browserId: "", tokenId: "", sessionKey: "", instanceId: "" };
6560
+ var visible = (r, scope) => !!r.shared || sameScope(r.scope, scope);
6561
+ var OUTSIDE_SPOOL_RECOVERY = "Chrome saved this download outside Browser MCP's private download folder (in its own download location on the browser host), so no bytes are available here and capture retry cannot recover them. Browser MCP never reads other folders and has re-pinned downloads to its private folder. Ask before repeating the website action.";
6119
6562
  async function createDataPlugin(access, options) {
6120
6563
  if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
6121
6564
  throw new Error("HTTPS data server required");
6565
+ const guard = options.downloads, downloadDirectory = guard?.directory ?? options.downloadDirectory;
6566
+ if (!downloadDirectory)
6567
+ throw new Error("Download spool required");
6122
6568
  await mkdir2(options.directory, { mode: 448 });
6123
6569
  const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
6124
6570
  let stopped = false;
@@ -6126,62 +6572,122 @@ async function createDataPlugin(access, options) {
6126
6572
  function remember(r) {
6127
6573
  if (r.purpose !== "download")
6128
6574
  return;
6129
- terminal.set(r.id, { scope: r.scope, meta: { ...meta(r), state: r.terminalCode?.startsWith("download_capture") || r.terminalCode === "download_quota_exceeded" ? "failed" : r.terminalCode === "download_expired" ? "expired" : "cancelled", size: r.hash ? r.size : undefined, maxBytes: undefined, retrieval: undefined, readiness: "unavailable", code: r.terminalCode ?? "download_revoked", recovery: "Retained bytes are unavailable. Do not automatically replay the source action; ask before recreating the download." }, until: Date.now() + LIMITS.ttl });
6575
+ const outside = r.capture?.diagnostic?.reason === "outside-spool";
6576
+ terminal.set(r.id, { scope: r.scope, shared: r.shared, meta: { ...meta(r), state: r.terminalCode?.startsWith("download_capture") || r.terminalCode === "download_quota_exceeded" ? "failed" : r.terminalCode === "download_expired" ? "expired" : "cancelled", size: r.hash ? r.size : undefined, maxBytes: undefined, retrieval: undefined, retry: undefined, readiness: "unavailable", code: r.terminalCode ?? "download_revoked", recovery: outside ? OUTSIDE_SPOOL_RECOVERY : "Retained bytes are unavailable. Do not automatically replay the source action; ask before recreating the download." }, until: Date.now() + LIMITS.ttl });
6130
6577
  while (terminal.size > 128)
6131
6578
  terminal.delete(terminal.keys().next().value);
6132
6579
  }
6580
+ function failClosed() {
6581
+ stopped = true;
6582
+ options.onSourceCleanupFailure();
6583
+ }
6133
6584
  function status(scope, id) {
6134
6585
  const t = terminal.get(String(id));
6135
- if (t && t.until >= Date.now() && sameScope(t.scope, scope))
6586
+ if (t && t.until >= Date.now() && visible(t, scope))
6136
6587
  return t.meta;
6137
6588
  return meta(get(scope, id));
6138
6589
  }
6139
6590
  function meta(r) {
6140
- return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : "pending", capture: r.capture, contentValidation: r.contentValidation, retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
6591
+ const failed = r.state === "capture-failed", outside = r.capture?.diagnostic?.reason === "outside-spool";
6592
+ return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? {
6593
+ downloadId: r.id,
6594
+ mimeType: "application/octet-stream",
6595
+ sourceKind: "download",
6596
+ owner: r.shared ? "user" : "this_session",
6597
+ readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : failed ? "unavailable" : "pending",
6598
+ capture: r.capture,
6599
+ contentValidation: r.contentValidation,
6600
+ ...r.state === "ready" ? { retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {},
6601
+ ...failed ? { code: r.terminalCode, ...outside ? {} : { retry: { tool: "browser_retry_download_capture", arguments: { downloadId: r.id } } }, recovery: outside ? OUTSIDE_SPOOL_RECOVERY : r.capture?.sourceAvailability === "unavailable" ? "The completed browser source is unavailable at its original location. No bytes are ready. Capture-only retry cannot recreate missing bytes; never automatically repeat the website action." : "Only capture failed; any remaining completed browser source is held until expiresAt under the original reservation. Retry capture explicitly with this downloadId; it never repeats the website action. Source availability is not proof of readable bytes." } : {}
6602
+ } : {} };
6141
6603
  }
6142
6604
  function get(scope, id) {
6143
6605
  const r = resources.get(String(id));
6144
- if (!r || !sameScope(r.scope, scope) || r.expiresAt < Date.now())
6606
+ if (!r || !visible(r, scope) || r.expiresAt < Date.now())
6145
6607
  throw new Error("Unknown resource");
6146
6608
  return r;
6147
6609
  }
6148
- function reserve(scope, size) {
6149
- const all = [...resources.values()].filter((r) => !["failed", "cancelled"].includes(r.state));
6150
- if (stopped || !Number.isSafeInteger(size) || size < 0 || size > LIMITS.file || all.length >= 128 || all.reduce((n, r) => n + r.size, 0) + size > LIMITS.browser || all.filter((r) => sameScope(r.scope, scope)).reduce((n, r) => n + r.size, 0) + size > LIMITS.session)
6610
+ const reserved = (r) => {
6611
+ if (r.purpose !== "download")
6612
+ return r.size;
6613
+ if (!r.source)
6614
+ return r.hash ? r.size : 0;
6615
+ if (r.sourceBytes !== undefined)
6616
+ return 2 * r.sourceBytes;
6617
+ return r.state === "capture-failed" && r.capture?.sourceAvailability !== "unavailable" ? 2 * LIMITS.file : 0;
6618
+ };
6619
+ const logical = (r) => r.purpose !== "download" ? r.size : r.hash ? r.size : r.sourceBytes ?? 0;
6620
+ const diskBytes = (except) => [...resources.values()].reduce((n, r) => r === except ? n : n + reserved(r), 0);
6621
+ const sessionBytes = (scope, except) => [...resources.values()].reduce((n, r) => r === except || r.shared || !sameScope(r.scope, scope) ? n : n + logical(r), 0);
6622
+ function reserve(scope, size, purpose, shared = false) {
6623
+ const cost = purpose === "download" ? 0 : size;
6624
+ if (stopped || !Number.isSafeInteger(size) || size < 0 || size > LIMITS.file || resources.size >= LIMITS.count || diskBytes() + cost > LIMITS.browser || !shared && sessionBytes(scope) + cost > LIMITS.session)
6151
6625
  throw new Error("Local data quota exceeded");
6152
6626
  }
6153
- function create(scope, purpose, size, name) {
6154
- reserve(scope, size);
6155
- const r = { id: randomUUID7(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
6627
+ function reserveSource(r, size) {
6628
+ if (size > LIMITS.file || diskBytes(r) + 2 * size > LIMITS.browser || !r.shared && sessionBytes(r.scope, r) + size > LIMITS.session)
6629
+ throw new CaptureError("download_quota_exceeded", "quota-exceeded");
6630
+ r.sourceBytes = size;
6631
+ }
6632
+ function create(scope, purpose, size, name, shared = false) {
6633
+ reserve(scope, size, purpose, shared);
6634
+ const r = { id: randomUUID8(), scope: { ...scope }, shared: shared || undefined, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
6156
6635
  resources.set(r.id, r);
6157
6636
  return r;
6158
6637
  }
6638
+ async function discardCopy(r) {
6639
+ if (r.path && owned.has(r.path)) {
6640
+ await unlink3(r.path).catch((error) => {
6641
+ if (error.code !== "ENOENT")
6642
+ throw error;
6643
+ });
6644
+ owned.delete(r.path);
6645
+ r.path = undefined;
6646
+ }
6647
+ }
6159
6648
  async function remove(r) {
6649
+ if (r.removal)
6650
+ return r.removal;
6160
6651
  r.terminalCode ??= "download_revoked";
6161
6652
  r.abort.abort();
6162
6653
  r.state = "cancelled";
6163
- await r.task?.catch(() => {});
6164
- remember(r);
6165
- r.bytes?.fill(0);
6166
- r.bytes = undefined;
6167
- if (r.path && owned.has(r.path)) {
6168
- await unlink2(r.path).catch(() => {});
6169
- owned.delete(r.path);
6170
- }
6171
- const dir = join2(options.directory, r.id);
6172
- if (ownedDirs.has(dir)) {
6173
- await rmdir2(dir).catch(() => {});
6174
- ownedDirs.delete(dir);
6654
+ r.removal = (async () => {
6655
+ await r.task?.catch(() => {});
6656
+ const deleted = !r.source || await cleanupDownload(r.source, r.capture);
6657
+ if (deleted)
6658
+ r.source = undefined;
6659
+ else
6660
+ failClosed();
6661
+ remember(r);
6662
+ r.bytes?.fill(0);
6663
+ r.bytes = undefined;
6664
+ try {
6665
+ await discardCopy(r);
6666
+ } catch {
6667
+ failClosed();
6668
+ return;
6669
+ }
6670
+ const dir = join2(options.directory, r.id);
6671
+ if (ownedDirs.has(dir)) {
6672
+ await rmdir2(dir).catch(() => {});
6673
+ ownedDirs.delete(dir);
6674
+ }
6675
+ if (deleted)
6676
+ resources.delete(r.id);
6677
+ })();
6678
+ try {
6679
+ await r.removal;
6680
+ } finally {
6681
+ r.removal = undefined;
6175
6682
  }
6176
- resources.delete(r.id);
6177
6683
  }
6178
6684
  async function revoke(predicate) {
6179
6685
  vault.revoke(predicate);
6180
6686
  await Promise.all([...resources.values()].filter(predicate).map(remove));
6181
6687
  }
6182
6688
  async function transfer(r, g) {
6183
- const timer = setTimeout(() => r.abort.abort(), LIMITS.duration);
6184
- timer.unref?.();
6689
+ const timer2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
6690
+ timer2.unref?.();
6185
6691
  r.state = "transferring";
6186
6692
  try {
6187
6693
  if (r.purpose === "upload") {
@@ -6222,7 +6728,7 @@ async function createDataPlugin(access, options) {
6222
6728
  } else {
6223
6729
  if (!r.path)
6224
6730
  throw new Error("Missing file");
6225
- const stat = await lstat2(r.path);
6731
+ const stat = await lstat3(r.path);
6226
6732
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== r.size)
6227
6733
  throw new Error("Changed file");
6228
6734
  body = Readable.toWeb(createReadStream(r.path));
@@ -6236,11 +6742,11 @@ async function createDataPlugin(access, options) {
6236
6742
  if (r.state !== "cancelled")
6237
6743
  r.state = "failed";
6238
6744
  if (r.path && owned.has(r.path) && r.purpose === "upload") {
6239
- await unlink2(r.path).catch(() => {});
6745
+ await unlink3(r.path).catch(() => {});
6240
6746
  owned.delete(r.path);
6241
6747
  }
6242
6748
  } finally {
6243
- clearTimeout(timer);
6749
+ clearTimeout(timer2);
6244
6750
  if (r.purpose === "secret-export") {
6245
6751
  r.bytes?.fill(0);
6246
6752
  r.bytes = undefined;
@@ -6254,6 +6760,8 @@ async function createDataPlugin(access, options) {
6254
6760
  }
6255
6761
  async function sweepExpired() {
6256
6762
  await revoke((r) => {
6763
+ if (r.state === "cancelled")
6764
+ return true;
6257
6765
  if (r.expiresAt < Date.now() && r.state !== "attached") {
6258
6766
  r.terminalCode = "download_expired";
6259
6767
  return true;
@@ -6264,12 +6772,158 @@ async function createDataPlugin(access, options) {
6264
6772
  if (t.until < Date.now())
6265
6773
  terminal.delete(id);
6266
6774
  }
6775
+ function startCapture(r) {
6776
+ r.state = "capturing";
6777
+ r.terminalCode = undefined;
6778
+ r.capture = captureEvidence();
6779
+ r.abort = new AbortController;
6780
+ const source = r.source;
6781
+ const valid = () => !r.abort.signal.aborted && !stopped && resources.get(r.id) === r && r.expiresAt > Date.now();
6782
+ const cancel = () => {
6783
+ if (r.capture?.browserCompletion !== "completed")
6784
+ source.download.cancel().catch(() => {});
6785
+ };
6786
+ r.abort.signal.addEventListener("abort", cancel, { once: true });
6787
+ let timeout2;
6788
+ const arm = (ms) => {
6789
+ clearTimeout(timeout2);
6790
+ timeout2 = setTimeout(() => {
6791
+ r.terminalCode ??= "download_capture_timeout";
6792
+ r.abort.abort();
6793
+ }, Math.max(1, ms));
6794
+ timeout2.unref?.();
6795
+ };
6796
+ arm(r.completedAt === undefined ? r.expiresAt - Date.now() : Math.min(LIMITS.duration, r.expiresAt - Date.now()));
6797
+ source.hooks = { ...source.hooks, completed: () => {
6798
+ if (r.completedAt === undefined) {
6799
+ r.completedAt = Date.now();
6800
+ r.expiresAt = r.completedAt + LIMITS.ttl;
6801
+ }
6802
+ arm(Math.min(LIMITS.duration, r.expiresAt - Date.now()));
6803
+ } };
6804
+ const task = (async () => {
6805
+ try {
6806
+ await discardCopy(r);
6807
+ const path11 = join2(options.directory, r.id);
6808
+ r.path = path11;
6809
+ owned.add(path11);
6810
+ const verified = await captureDownload(source, path11, r.abort.signal, r.capture);
6811
+ if (!valid())
6812
+ throw new CaptureError("download_capture_cancelled", "cancelled");
6813
+ r.size = verified.size;
6814
+ r.hash = verified.sha256;
6815
+ r.contentValidation = contentValidation(r.name, verified.size);
6816
+ if (await cleanupDownload(source, r.capture))
6817
+ r.source = undefined;
6818
+ if (!valid())
6819
+ throw new CaptureError("download_capture_cancelled", "cancelled");
6820
+ r.state = "ready";
6821
+ } catch (error) {
6822
+ r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
6823
+ r.hash = undefined;
6824
+ r.contentValidation = undefined;
6825
+ r.size = LIMITS.file;
6826
+ let discarded = true;
6827
+ try {
6828
+ await discardCopy(r);
6829
+ } catch {
6830
+ discarded = false;
6831
+ }
6832
+ if (valid() && discarded && r.capture?.browserCompletion === "completed" && r.capture.sourceAvailability !== "unsafe" && r.terminalCode !== "download_quota_exceeded") {
6833
+ if (r.capture.sourceAvailability === "present")
6834
+ r.sourceBytes ??= source.size;
6835
+ r.capture.cleanup = "retained";
6836
+ r.state = "capture-failed";
6837
+ } else
6838
+ r.state = "cancelled";
6839
+ } finally {
6840
+ clearTimeout(timeout2);
6841
+ r.abort.signal.removeEventListener("abort", cancel);
6842
+ }
6843
+ })();
6844
+ r.task = task;
6845
+ return task.then(async () => {
6846
+ if (r.state === "cancelled")
6847
+ await remove(r);
6848
+ });
6849
+ }
6850
+ function spoolHooks(download) {
6851
+ if (!guard)
6852
+ return {};
6853
+ return { claim: (guid) => guard.claim(guid, download), release: () => guard.release(download), settlement: (guid) => guard.settlement(guid), isSpoolPath: (path11, guid) => guard.isSpoolPath(path11, guid) };
6854
+ }
6855
+ async function admit(download, name, scope, tabId, generation, downloadId, hooks) {
6856
+ const shared = !scope, owner = scope ?? USER_SCOPE;
6857
+ let r;
6858
+ try {
6859
+ r = create(owner, "download", LIMITS.file, name, shared);
6860
+ resources.delete(r.id);
6861
+ r.id = downloadId;
6862
+ resources.set(r.id, r);
6863
+ r.expiresAt = Date.now() + DOWNLOAD_DEADLINE_MS;
6864
+ r.tabId = tabId;
6865
+ r.generation = generation;
6866
+ const resource = r;
6867
+ r.source = { download, directory: downloadDirectory, hooks: { ...hooks, reserve: (size) => reserveSource(resource, size) } };
6868
+ await startCapture(r);
6869
+ if (r.state === "ready")
6870
+ return { ...meta(r), state: "completed" };
6871
+ if (r.state === "capture-failed")
6872
+ return { ...meta(r), state: "failed" };
6873
+ return status(owner, downloadId);
6874
+ } catch (error) {
6875
+ download.cancel().catch(() => {});
6876
+ if (r) {
6877
+ r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
6878
+ await remove(r);
6879
+ return status(owner, downloadId);
6880
+ }
6881
+ if (!await cleanupDownload({ download, directory: downloadDirectory, hooks }))
6882
+ failClosed();
6883
+ const failed = { downloadId, resourceId: downloadId, state: "failed", readiness: "unavailable", code: "download_capture_rejected", recovery: "Capture could not be admitted. Do not automatically repeat the website action." };
6884
+ terminal.set(downloadId, { scope: { ...owner }, shared: shared || undefined, meta: failed, until: Date.now() + LIMITS.ttl });
6885
+ while (terminal.size > 128)
6886
+ terminal.delete(terminal.keys().next().value);
6887
+ return failed;
6888
+ }
6889
+ }
6890
+ async function adopt(entry) {
6891
+ if (stopped || !guard)
6892
+ return;
6893
+ const file = guard.leaf(entry.guid);
6894
+ const settled = async () => (await guard.settlement(entry.guid))?.state;
6895
+ const handle = {
6896
+ failure: async () => await settled() === "completed" ? null : "canceled",
6897
+ path: async () => {
6898
+ if (await settled() !== "completed")
6899
+ throw new Error("Download canceled");
6900
+ return file;
6901
+ },
6902
+ cancel: async () => {
6903
+ await guard.cancel(entry.guid);
6904
+ },
6905
+ delete: async () => {
6906
+ await unlink3(file).catch(() => {});
6907
+ }
6908
+ };
6909
+ await admit(handle, entry.suggestedFilename, undefined, undefined, 0, randomUUID8(), {
6910
+ claim: () => true,
6911
+ settlement: (guid) => guard.settlement(guid),
6912
+ isSpoolPath: (path11, guid) => guard.isSpoolPath(path11, guid)
6913
+ }).catch(() => {});
6914
+ }
6915
+ guard?.onUnattributed((entry) => {
6916
+ if (stopped)
6917
+ return false;
6918
+ adopt(entry);
6919
+ return true;
6920
+ });
6267
6921
  let sweep = setInterval(() => {
6268
6922
  sweepExpired();
6269
6923
  }, 1e4);
6270
6924
  sweep.unref?.();
6271
6925
  return {
6272
- operations: ["create_upload", "create_download", "transfer_status", "cancel_transfer", "upload_files", "list_downloads", "capture_secrets", "list_secrets", "delete_secrets", "create_secret_export", "authorize_data"],
6926
+ operations: ["create_upload", "create_download", "retry_download_capture", "transfer_status", "cancel_transfer", "upload_files", "list_downloads", "capture_secrets", "list_secrets", "delete_secrets", "create_secret_export", "authorize_data"],
6273
6927
  async execute(op, args, scope) {
6274
6928
  if (stopped)
6275
6929
  throw new Error("Data runtime disconnected");
@@ -6286,10 +6940,17 @@ async function createDataPlugin(access, options) {
6286
6940
  }
6287
6941
  if (op === "create_download") {
6288
6942
  const r = resources.get(String(args.downloadId ?? args.fileId ?? args.resourceId));
6289
- if (!r || !sameScope(r.scope, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
6943
+ if (!r || !visible(r, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
6290
6944
  throw new RuntimeFault("resource_unavailable", "Use browser_list_downloads to select an available retained downloadId in this session. If no retained bytes are available, ask before recreating them; never automatically replay the website action, export or script.", true);
6291
6945
  return meta(r);
6292
6946
  }
6947
+ if (op === "retry_download_capture") {
6948
+ const r = resources.get(String(args.downloadId));
6949
+ if (!r || !visible(r, scope) || r.expiresAt <= Date.now() || r.purpose !== "download" || r.state !== "capture-failed" || !r.source)
6950
+ throw new RuntimeFault("resource_unavailable", "Use browser_list_downloads in this session to select a capture-failed source before its original expiry. Never replay the website action.", true);
6951
+ startCapture(r).catch(() => {});
6952
+ return meta(r);
6953
+ }
6293
6954
  if (op === "transfer_status") {
6294
6955
  await sweepExpired();
6295
6956
  return status(scope, args.resourceId ?? args.transferId);
@@ -6314,7 +6975,7 @@ async function createDataPlugin(access, options) {
6314
6975
  }
6315
6976
  if (op === "list_downloads") {
6316
6977
  await sweepExpired();
6317
- return { files: [...resources.values()].filter((r) => sameScope(r.scope, scope) && r.purpose === "download").map(meta), terminal: [...terminal.values()].filter((t) => sameScope(t.scope, scope)).map((t) => t.meta) };
6978
+ return { files: [...resources.values()].filter((r) => visible(r, scope) && r.purpose === "download" && r.state !== "cancelled").map(meta), terminal: [...terminal.values()].filter((t) => visible(t, scope)).map((t) => t.meta) };
6318
6979
  }
6319
6980
  if (op === "upload_files") {
6320
6981
  const ids = args.fileIds;
@@ -6369,83 +7030,29 @@ async function createDataPlugin(access, options) {
6369
7030
  }
6370
7031
  throw new Error("Unsupported data operation");
6371
7032
  },
6372
- async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
6373
- let r;
6374
- let timeout2;
6375
- let cancel;
6376
- try {
6377
- r = create(scope, "download", LIMITS.file, download.suggestedFilename());
6378
- resources.delete(r.id);
6379
- r.id = downloadId;
6380
- resources.set(r.id, r);
6381
- r.tabId = tabId;
6382
- r.generation = generation;
6383
- r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
6384
- cancel = () => {
6385
- download.cancel().catch(() => {});
6386
- };
6387
- r.abort.signal.addEventListener("abort", cancel, { once: true });
6388
- timeout2 = setTimeout(() => {
6389
- r.terminalCode ??= "download_capture_timeout";
6390
- r.abort.abort();
6391
- }, LIMITS.duration);
6392
- timeout2.unref?.();
6393
- const captured = r;
6394
- r.task = (async () => {
6395
- const path10 = join2(options.directory, captured.id);
6396
- captured.path = path10;
6397
- owned.add(path10);
6398
- try {
6399
- const verified = await captureDownload(download, path10, captured.abort.signal, captured.capture);
6400
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6401
- throw new Error("Download revoked");
6402
- captured.size = verified.size;
6403
- captured.hash = verified.sha256;
6404
- captured.contentValidation = contentValidation(captured.name, verified.size);
6405
- } finally {
6406
- await cleanupDownload(download, captured.capture);
6407
- }
6408
- if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
6409
- throw new Error("Download revoked");
6410
- captured.state = "ready";
6411
- })();
6412
- await r.task;
6413
- if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
6414
- throw new Error("Download revoked");
6415
- return { ...meta(r), state: "completed" };
6416
- } catch (error) {
6417
- download.cancel().catch(() => {});
6418
- if (r) {
6419
- r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
6420
- await remove(r);
6421
- return status(scope, downloadId);
6422
- }
6423
- await cleanupDownload(download);
6424
- const failed = { downloadId, resourceId: downloadId, state: "failed", readiness: "unavailable", code: "download_capture_rejected", recovery: "Capture could not be reserved. Do not automatically repeat the website action." };
6425
- terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
6426
- while (terminal.size > 128)
6427
- terminal.delete(terminal.keys().next().value);
6428
- return failed;
6429
- } finally {
6430
- if (timeout2)
6431
- clearTimeout(timeout2);
6432
- if (r && cancel)
6433
- r.abort.signal.removeEventListener("abort", cancel);
6434
- }
7033
+ async onDownload(download, tabId, owner, generation, downloadId = randomUUID8()) {
7034
+ return admit(download, download.suggestedFilename(), owner.kind === "session" ? owner.scope : undefined, tabId, generation, downloadId, spoolHooks(download));
7035
+ },
7036
+ observeDownload(download) {
7037
+ guard?.observe(download);
7038
+ },
7039
+ async discardDownload(download) {
7040
+ download.cancel().catch(() => {});
7041
+ await cleanupDownload({ download, directory: downloadDirectory, hooks: spoolHooks(download) });
6435
7042
  },
6436
7043
  async onNavigation(tabId, generation) {
6437
7044
  await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
6438
7045
  },
6439
7046
  async onTabClose(tabId) {
6440
- await revoke((r) => r.tabId === tabId);
7047
+ await revoke((r) => r.purpose !== "download" && r.tabId === tabId);
6441
7048
  },
6442
7049
  async onSessionEnd(scope) {
6443
7050
  vault.revoke((r) => sameScope(r.scope, scope));
6444
- await Promise.all([...resources.values()].filter((r) => sameScope(r.scope, scope) && r.state !== "attached").map(remove));
7051
+ await Promise.all([...resources.values()].filter((r) => !r.shared && sameScope(r.scope, scope) && r.state !== "attached").map(remove));
6445
7052
  },
6446
7053
  async onHandoff(tabId, scope) {
6447
7054
  vault.revoke((r) => r.tabId === tabId && sameScope(r.scope, scope));
6448
- await Promise.all([...resources.values()].filter((r) => r.tabId === tabId && sameScope(r.scope, scope) && r.state !== "attached").map(remove));
7055
+ await Promise.all([...resources.values()].filter((r) => r.purpose !== "download" && r.tabId === tabId && sameScope(r.scope, scope) && r.state !== "attached").map(remove));
6449
7056
  },
6450
7057
  async onDisconnect() {
6451
7058
  stopped = true;
@@ -6535,21 +7142,21 @@ function createForwardPlugin(options) {
6535
7142
  function parse2(args) {
6536
7143
  const options = { profiles: [] };
6537
7144
  for (let i = 0;i < args.length; i++) {
6538
- const key = args[i];
6539
- if (key === "--ephemeral")
7145
+ const key2 = args[i];
7146
+ if (key2 === "--ephemeral")
6540
7147
  options.ephemeral = true;
6541
- else if (key === "--live-view")
7148
+ else if (key2 === "--live-view")
6542
7149
  options.liveView = true;
6543
- else if (key === "--profile" || key === "--server" || key === "--chrome-path") {
7150
+ else if (key2 === "--profile" || key2 === "--server" || key2 === "--chrome-path") {
6544
7151
  if (!args[i + 1] || args[i + 1].startsWith("--"))
6545
- throw new Error(`Missing ${key} value`);
7152
+ throw new Error(`Missing ${key2} value`);
6546
7153
  const value = args[++i];
6547
- if (key === "--profile")
7154
+ if (key2 === "--profile")
6548
7155
  options.profiles.push(value);
6549
7156
  else
6550
- options[key === "--server" ? "server" : "chrome-path"] = value;
7157
+ options[key2 === "--server" ? "server" : "chrome-path"] = value;
6551
7158
  } else
6552
- throw new Error(`Unknown browser option ${key}`);
7159
+ throw new Error(`Unknown browser option ${key2}`);
6553
7160
  }
6554
7161
  return options;
6555
7162
  }
@@ -6581,7 +7188,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6581
7188
  for (const signal of signals)
6582
7189
  process.on(signal, signalStop);
6583
7190
  try {
6584
- const requestedRoot = path10.resolve(installationRoot());
7191
+ const requestedRoot = path11.resolve(installationRoot());
6585
7192
  for (const profile of profiles)
6586
7193
  assertControlPaths(requestedRoot, controlSocketPath(requestedRoot, profile));
6587
7194
  const root = await privateDirectory2(requestedRoot);
@@ -6592,7 +7199,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6592
7199
  console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
6593
7200
  return;
6594
7201
  }
6595
- await new Promise((resolve2, reject) => {
7202
+ await new Promise((resolve3, reject) => {
6596
7203
  const socket = net3.connect(controlPath);
6597
7204
  socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
6598
7205
  socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
@@ -6600,7 +7207,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6600
7207
  socket.once("data", (data) => {
6601
7208
  console.log(data.toString().trim());
6602
7209
  socket.end();
6603
- resolve2();
7210
+ resolve3();
6604
7211
  });
6605
7212
  socket.once("error", (error) => reject(controlFailure("control-connect", error)));
6606
7213
  });
@@ -6610,7 +7217,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
6610
7217
  const server = serverURL(options.server ?? "https://browser-mcp.click");
6611
7218
  for (const profile of profiles) {
6612
7219
  const controlPath = controlSocketPath(root, profile);
6613
- const previousSocket = await fs10.lstat(controlPath).catch((error) => {
7220
+ const previousSocket = await fs11.lstat(controlPath).catch((error) => {
6614
7221
  if (error.code !== "ENOENT")
6615
7222
  throw controlFailure("local-control", error);
6616
7223
  });
@@ -6644,7 +7251,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
6644
7251
  let starting = true;
6645
7252
  let session;
6646
7253
  let runtime, relay, local;
6647
- let stopQuota;
6648
7254
  const controlPath = controlSocketPath(root, profile);
6649
7255
  let stopControl;
6650
7256
  const clients = new Set;
@@ -6659,7 +7265,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
6659
7265
  session?.lifecycle.requestShutdown("owner-close");
6660
7266
  await cleanupSteps([
6661
7267
  ["Relay", () => runtimeCleanup(() => relay?.stop())],
6662
- ["Download quota", () => runtimeCleanup(() => stopQuota?.())],
6663
7268
  ["Runtime", () => runtimeCleanup(() => runtime?.shutdown())],
6664
7269
  ["Local control", async () => {
6665
7270
  for (const client of clients)
@@ -6689,21 +7294,22 @@ async function startProfile(root, server, profile, options, groupSignal) {
6689
7294
  if (groupSignal.aborted)
6690
7295
  groupStop();
6691
7296
  let failure, cleanupFailure;
6692
- let runtimeStage = "download-quota";
7297
+ let runtimeStage = "pairing";
6693
7298
  try {
6694
7299
  abort.signal.throwIfAborted();
6695
7300
  session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
6696
7301
  session.lifecycle.ended.then(endSession);
6697
7302
  abort.signal.throwIfAborted();
6698
- stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
6699
- abort.signal.throwIfAborted();
6700
7303
  runtimeStage = "pairing";
6701
7304
  const token = await credential(root, server, profile, abort.signal);
6702
7305
  abort.signal.throwIfAborted();
6703
7306
  runtimeStage = "runtime-setup";
6704
- const previews = path10.join(session.runPath, "previews");
7307
+ const previews = path11.join(session.runPath, "previews");
6705
7308
  runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
6706
- runtime.plugins.push(await createDataPlugin(runtime, { directory: path10.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
7309
+ runtime.plugins.push(await createDataPlugin(runtime, { directory: path11.join(session.runPath, "data"), downloads: session.downloads, serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:", onSourceCleanupFailure: () => {
7310
+ console.error("Download cleanup could not be verified; closing the owned browser to bound private spool retention. No website action was replayed.");
7311
+ requestStop("owner-close");
7312
+ } }));
6707
7313
  abort.signal.throwIfAborted();
6708
7314
  runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
6709
7315
  relay = new Relay(runtime, server, token, previews, !!options.liveView);
@@ -6739,7 +7345,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
6739
7345
  return;
6740
7346
  } else if (cmd !== "status")
6741
7347
  throw new Error("Invalid command");
6742
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.16", protocol: 3 }) + `
7348
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.18", protocol: 3 }) + `
6743
7349
  `);
6744
7350
  })().catch(() => socket.destroy());
6745
7351
  });