@ricsam/browser-mcp 0.3.17 → 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.
- package/README.md +2 -2
- package/dist/{chunk-kvvj8z88.js → chunk-cqqkfzmg.js} +817 -400
- package/dist/main.js +3 -3
- package/package.json +1 -1
|
@@ -14,22 +14,22 @@ import {
|
|
|
14
14
|
import"./chunk-1sjcwr28.js";
|
|
15
15
|
|
|
16
16
|
// cli/src/browser/main.ts
|
|
17
|
-
import
|
|
18
|
-
import
|
|
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
|
|
24
|
-
import
|
|
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
|
|
32
|
-
import
|
|
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.
|
|
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
|
|
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(
|
|
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(
|
|
754
|
+
clearTimeout(timer2);
|
|
466
755
|
if (error)
|
|
467
756
|
reject(error);
|
|
468
757
|
else if (!address || typeof address === "string" || !address.port)
|
|
@@ -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
|
|
786
|
+
let timer2;
|
|
498
787
|
try {
|
|
499
788
|
return await Promise.race([promise, new Promise((_, reject) => {
|
|
500
|
-
|
|
789
|
+
timer2 = setTimeout(() => reject(new Error("Owned Chrome operation timed out")), ms);
|
|
501
790
|
})]);
|
|
502
791
|
} finally {
|
|
503
|
-
clearTimeout(
|
|
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 =
|
|
798
|
+
const artifactsDir = path2.join(options.runPath, "chrome-downloads");
|
|
510
799
|
let port, child;
|
|
511
800
|
try {
|
|
512
801
|
lifecycle.setStage("artifacts");
|
|
513
|
-
await
|
|
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
|
|
1022
|
+
import fs3 from "node:fs/promises";
|
|
727
1023
|
import { constants as constants2 } from "node:fs";
|
|
728
|
-
import
|
|
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
|
|
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(
|
|
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
|
|
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 =
|
|
768
|
-
for (const part of directory.slice(cursor.length).split(
|
|
769
|
-
cursor =
|
|
770
|
-
const s = await
|
|
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
|
|
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
|
|
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 =
|
|
1117
|
+
const singleton = path4.join(profile, "SingletonLock");
|
|
822
1118
|
let s;
|
|
823
1119
|
try {
|
|
824
|
-
s = await
|
|
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
|
|
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 =
|
|
859
|
-
const profile =
|
|
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(
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
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
|
|
1213
|
+
return path5.join(os2.homedir(), ".browser-mcp");
|
|
918
1214
|
}
|
|
919
1215
|
async function privateDirectory2(directory) {
|
|
920
|
-
const absolute =
|
|
921
|
-
let cursor =
|
|
922
|
-
for (const piece of absolute.slice(cursor.length).split(
|
|
923
|
-
cursor =
|
|
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
|
|
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
|
|
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
|
|
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",
|
|
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 (!
|
|
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
|
|
1241
|
+
const real = await fs4.realpath(candidate), stat = await fs4.stat(real);
|
|
946
1242
|
if (!stat.isFile())
|
|
947
1243
|
continue;
|
|
948
|
-
await
|
|
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(
|
|
962
|
-
const profile =
|
|
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
|
|
1260
|
+
const profileStat = await fs4.lstat(profile);
|
|
965
1261
|
options.signal?.throwIfAborted();
|
|
966
|
-
const lockPath =
|
|
1262
|
+
const lockPath = path5.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
|
|
967
1263
|
let lock;
|
|
968
1264
|
try {
|
|
969
|
-
lock = await
|
|
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 =
|
|
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
|
|
991
|
-
if (await
|
|
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
|
|
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
|
|
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
|
|
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
|
|
1323
|
+
await fs4.rm(runPath, { recursive: true, force: true });
|
|
1028
1324
|
}],
|
|
1029
1325
|
["Profile lock", async () => {
|
|
1030
1326
|
await verifyLock();
|
|
1031
|
-
await
|
|
1327
|
+
await fs4.unlink(lockPath);
|
|
1032
1328
|
}]
|
|
1033
1329
|
]);
|
|
1034
1330
|
if (options.ephemeral) {
|
|
1035
1331
|
await verifyProfile();
|
|
1036
|
-
await
|
|
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
|
|
1049
|
-
runStat = await
|
|
1050
|
-
await
|
|
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
|
|
1088
|
-
import
|
|
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
|
|
1092
|
-
const directory = await
|
|
1093
|
-
const dirStat = await
|
|
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
|
|
1104
|
-
if (await
|
|
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
|
|
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
|
|
1410
|
+
await fs5.unlink(controlPath);
|
|
1115
1411
|
}],
|
|
1116
1412
|
["Private control directory", async () => {
|
|
1117
|
-
const stat = await
|
|
1118
|
-
if (await
|
|
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
|
|
1121
|
-
await
|
|
1416
|
+
await fs5.unlink(path6.join(directory, "ownership.json"));
|
|
1417
|
+
await fs5.rmdir(directory);
|
|
1122
1418
|
}]
|
|
1123
1419
|
]));
|
|
1124
1420
|
try {
|
|
1125
|
-
await
|
|
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
|
|
1132
|
-
await
|
|
1133
|
-
await
|
|
1427
|
+
socketStat = await fs5.lstat(boundPath);
|
|
1428
|
+
await fs5.chmod(boundPath, 384);
|
|
1429
|
+
await fs5.link(boundPath, controlPath);
|
|
1134
1430
|
published = true;
|
|
1135
|
-
await
|
|
1136
|
-
socketStat = await
|
|
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
|
|
1151
|
-
import
|
|
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 =
|
|
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
|
|
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
|
|
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
|
|
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
|
|
1266
|
-
import
|
|
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 [
|
|
1337
|
-
if (
|
|
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(
|
|
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((
|
|
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 = (
|
|
1355
|
-
const value = input[
|
|
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 ${
|
|
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((
|
|
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((
|
|
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
|
|
1541
|
-
const p = input[
|
|
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
|
|
1691
|
-
if (input[
|
|
1692
|
-
throw new Error(`${action} requires ${
|
|
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
|
|
1696
|
-
if (normalized[
|
|
1697
|
-
delete normalized[
|
|
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((
|
|
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((
|
|
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((
|
|
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
|
|
1787
|
-
import
|
|
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
|
-
|
|
1798
|
-
this.directory =
|
|
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 =
|
|
2059
|
+
const directory = fs7.mkdtempSync(path8.join(this.directory, "upload-"));
|
|
1807
2060
|
try {
|
|
1808
2061
|
const staged = metadata2.map((file, index) => {
|
|
1809
|
-
const parent =
|
|
1810
|
-
|
|
1811
|
-
const filePath =
|
|
1812
|
-
|
|
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
|
|
1816
|
-
|
|
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
|
-
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
1905
|
-
const ref = /\[ref=((?:f\d+)?e\d+)\](?: \[cursor=pointer\])?(?: \[box=[-\d,.]+\])?$/.exec(
|
|
1906
|
-
return { key, ref, role:
|
|
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
|
|
1960
|
-
if (node[
|
|
1961
|
-
line += ` [${
|
|
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
|
|
2327
|
+
let timer2;
|
|
2075
2328
|
try {
|
|
2076
2329
|
return await Promise.race([
|
|
2077
2330
|
operation,
|
|
2078
2331
|
new Promise((_, reject) => {
|
|
2079
|
-
|
|
2332
|
+
timer2 = setTimeout(() => reject(timeoutError()), Math.max(0, deadline - Date.now()));
|
|
2080
2333
|
})
|
|
2081
2334
|
]);
|
|
2082
2335
|
} finally {
|
|
2083
|
-
clearTimeout(
|
|
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
|
|
2550
|
+
let timer2;
|
|
2298
2551
|
try {
|
|
2299
2552
|
return await Promise.race([
|
|
2300
2553
|
operation,
|
|
2301
2554
|
new Promise((_, reject) => {
|
|
2302
|
-
|
|
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(
|
|
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
|
|
2710
|
+
let timer2;
|
|
2458
2711
|
try {
|
|
2459
2712
|
return await Promise.race([
|
|
2460
2713
|
promise,
|
|
2461
2714
|
new Promise((_, reject) => {
|
|
2462
|
-
|
|
2715
|
+
timer2 = setTimeout(() => reject(new Error("Wait deadline exceeded")), Math.max(0, deadline - Date.now()));
|
|
2463
2716
|
})
|
|
2464
2717
|
]);
|
|
2465
2718
|
} finally {
|
|
2466
|
-
clearTimeout(
|
|
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(
|
|
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
|
|
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
|
|
2628
|
-
u.searchParams.set(
|
|
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
|
|
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
|
-
|
|
3077
|
+
timer2 = setTimeout(() => resolve2(this.query(input, false)), Number(input.timeoutMs));
|
|
2825
3078
|
changed();
|
|
2826
3079
|
});
|
|
2827
3080
|
} finally {
|
|
2828
|
-
clearTimeout(
|
|
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
|
|
3113
|
+
let timer2;
|
|
2861
3114
|
try {
|
|
2862
3115
|
return await Promise.race([
|
|
2863
3116
|
pending.result,
|
|
2864
3117
|
new Promise((resolve2) => {
|
|
2865
|
-
|
|
3118
|
+
timer2 = setTimeout(() => resolve2(undefined), ms);
|
|
2866
3119
|
})
|
|
2867
3120
|
]);
|
|
2868
3121
|
} finally {
|
|
2869
|
-
clearTimeout(
|
|
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
|
|
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
|
-
|
|
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(
|
|
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
|
|
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 (
|
|
3377
|
-
const value = JSON.parse(
|
|
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
|
-
|
|
3386
|
-
|
|
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);
|
|
@@ -3545,7 +3798,7 @@ class BrowserRuntime {
|
|
|
3545
3798
|
return;
|
|
3546
3799
|
});
|
|
3547
3800
|
});
|
|
3548
|
-
|
|
3801
|
+
fs9.mkdirSync(downloadsPath, { recursive: true });
|
|
3549
3802
|
this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
|
|
3550
3803
|
for (const page of context.pages())
|
|
3551
3804
|
this.track(page);
|
|
@@ -3604,23 +3857,23 @@ class BrowserRuntime {
|
|
|
3604
3857
|
return id;
|
|
3605
3858
|
}
|
|
3606
3859
|
safeDownloadFilename(suggestedFilename) {
|
|
3607
|
-
const basename =
|
|
3860
|
+
const basename = path9.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
3608
3861
|
if (!basename || basename === "." || basename === "..")
|
|
3609
3862
|
return "download";
|
|
3610
|
-
const extension =
|
|
3611
|
-
let stem = basename.slice(0, basename.length -
|
|
3863
|
+
const extension = path9.extname(basename).slice(0, 30);
|
|
3864
|
+
let stem = basename.slice(0, basename.length - path9.extname(basename).length) || "download";
|
|
3612
3865
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
3613
3866
|
stem = stem.slice(0, -1);
|
|
3614
3867
|
return `${stem || "download"}${extension}`;
|
|
3615
3868
|
}
|
|
3616
3869
|
availableDownloadPath(suggestedFilename) {
|
|
3617
3870
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
3618
|
-
const extension =
|
|
3871
|
+
const extension = path9.extname(filename);
|
|
3619
3872
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
3620
3873
|
for (let suffix = 1;; suffix += 1) {
|
|
3621
3874
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
3622
|
-
const candidatePath =
|
|
3623
|
-
if (!
|
|
3875
|
+
const candidatePath = path9.join(this.downloadsPath, candidate);
|
|
3876
|
+
if (!fs9.existsSync(candidatePath))
|
|
3624
3877
|
return candidatePath;
|
|
3625
3878
|
}
|
|
3626
3879
|
}
|
|
@@ -3628,18 +3881,18 @@ class BrowserRuntime {
|
|
|
3628
3881
|
const failure = await download.failure();
|
|
3629
3882
|
if (failure)
|
|
3630
3883
|
throw new Error(failure);
|
|
3631
|
-
const temporary =
|
|
3884
|
+
const temporary = path9.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
3632
3885
|
let targetPath;
|
|
3633
3886
|
try {
|
|
3634
3887
|
await download.saveAs(temporary);
|
|
3635
3888
|
targetPath = this.availableDownloadPath(download.suggestedFilename());
|
|
3636
|
-
|
|
3889
|
+
fs9.renameSync(temporary, targetPath);
|
|
3637
3890
|
} finally {
|
|
3638
|
-
|
|
3891
|
+
fs9.rmSync(temporary, { force: true });
|
|
3639
3892
|
}
|
|
3640
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3893
|
+
process.stdout.write(`[r5d-browser] downloaded ${path9.basename(targetPath)}
|
|
3641
3894
|
`);
|
|
3642
|
-
return { downloadId: this.downloadId(
|
|
3895
|
+
return { downloadId: this.downloadId(path9.basename(targetPath)) };
|
|
3643
3896
|
}
|
|
3644
3897
|
downloadId(filename) {
|
|
3645
3898
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -3648,13 +3901,13 @@ class BrowserRuntime {
|
|
|
3648
3901
|
if (typeof downloadId !== "string" || !downloadId)
|
|
3649
3902
|
throw new Error("downloadId is required.");
|
|
3650
3903
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
3651
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3904
|
+
if (this.downloadId(filename) !== downloadId || filename !== path9.basename(filename) || filename.includes("\x00")) {
|
|
3652
3905
|
throw new Error("Invalid downloadId.");
|
|
3653
3906
|
}
|
|
3654
|
-
const filePath =
|
|
3907
|
+
const filePath = path9.join(this.downloadsPath, filename);
|
|
3655
3908
|
let stats;
|
|
3656
3909
|
try {
|
|
3657
|
-
stats =
|
|
3910
|
+
stats = fs9.lstatSync(filePath);
|
|
3658
3911
|
} catch {
|
|
3659
3912
|
throw new Error(`Browser download ${downloadId} no longer exists.`);
|
|
3660
3913
|
}
|
|
@@ -3663,7 +3916,7 @@ class BrowserRuntime {
|
|
|
3663
3916
|
return { filename, filePath, stats };
|
|
3664
3917
|
}
|
|
3665
3918
|
async listDownloads() {
|
|
3666
|
-
return
|
|
3919
|
+
return fs9.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
|
|
3667
3920
|
if (!entry.isFile() || entry.name.startsWith("."))
|
|
3668
3921
|
return [];
|
|
3669
3922
|
const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
|
|
@@ -3687,20 +3940,20 @@ class BrowserRuntime {
|
|
|
3687
3940
|
throw new Error("Invalid download chunk size.");
|
|
3688
3941
|
const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
|
|
3689
3942
|
const bytes = Buffer.alloc(chunkSize);
|
|
3690
|
-
const handle =
|
|
3943
|
+
const handle = fs9.openSync(filePath, fs9.constants.O_RDONLY | fs9.constants.O_NOFOLLOW);
|
|
3691
3944
|
let bytesRead = 0;
|
|
3692
3945
|
try {
|
|
3693
|
-
const openedStats =
|
|
3946
|
+
const openedStats = fs9.fstatSync(handle);
|
|
3694
3947
|
if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
|
|
3695
3948
|
throw new Error("Browser download changed before it could be read.");
|
|
3696
3949
|
}
|
|
3697
|
-
bytesRead =
|
|
3698
|
-
const completedStats =
|
|
3950
|
+
bytesRead = fs9.readSync(handle, bytes, 0, chunkSize, offset);
|
|
3951
|
+
const completedStats = fs9.fstatSync(handle);
|
|
3699
3952
|
if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
|
|
3700
3953
|
throw new Error("Browser download changed while it was being read.");
|
|
3701
3954
|
}
|
|
3702
3955
|
} finally {
|
|
3703
|
-
|
|
3956
|
+
fs9.closeSync(handle);
|
|
3704
3957
|
}
|
|
3705
3958
|
const nextOffset = offset + bytesRead;
|
|
3706
3959
|
return {
|
|
@@ -3738,12 +3991,15 @@ class BrowserRuntime {
|
|
|
3738
3991
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
|
|
3739
3992
|
} catch (error) {
|
|
3740
3993
|
const message = error instanceof Error ? error.message : String(error);
|
|
3994
|
+
if (/Download is starting/i.test(message))
|
|
3995
|
+
return { downloadStarted: true };
|
|
3741
3996
|
if (!/ERR_ABORTED|interrupted by another navigation/i.test(message))
|
|
3742
3997
|
throw new Error(stripCallLog(message));
|
|
3743
3998
|
await page.waitForLoadState("domcontentloaded", { timeout: 5000 }).catch(() => {
|
|
3744
3999
|
return;
|
|
3745
4000
|
});
|
|
3746
4001
|
}
|
|
4002
|
+
return {};
|
|
3747
4003
|
}
|
|
3748
4004
|
async tabInfo(page) {
|
|
3749
4005
|
this.track(page);
|
|
@@ -3949,14 +4205,15 @@ class BrowserRuntime {
|
|
|
3949
4205
|
ownerSessionId: execution.sessionId,
|
|
3950
4206
|
retention: input.retention === "temporary" ? "temporary" : "retained"
|
|
3951
4207
|
});
|
|
4208
|
+
execution.onTabOpened?.(this.ids.get(page2));
|
|
3952
4209
|
const url = typeof input.url === "string" ? input.url : "about:blank";
|
|
3953
4210
|
if (url !== "about:blank") {
|
|
3954
4211
|
const events = this.events.get(page2);
|
|
3955
4212
|
await events.ready;
|
|
3956
4213
|
const result = await events.run(execution.operationId ?? crypto.randomUUID(), async () => {
|
|
3957
|
-
await this.gotoSettled(page2, url);
|
|
4214
|
+
const settled = await this.gotoSettled(page2, url);
|
|
3958
4215
|
await this.guardPage?.(page2);
|
|
3959
|
-
return { tab: await this.tabInfo(page2) };
|
|
4216
|
+
return { tab: await this.tabInfo(page2), ...settled };
|
|
3960
4217
|
});
|
|
3961
4218
|
return { tab: await this.tabInfo(page2), ...result };
|
|
3962
4219
|
}
|
|
@@ -4131,9 +4388,9 @@ class BrowserRuntime {
|
|
|
4131
4388
|
return { tabId, exported: false, code: "export_too_large" };
|
|
4132
4389
|
const exports = files.map((file) => {
|
|
4133
4390
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
4134
|
-
|
|
4391
|
+
fs9.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
4135
4392
|
return {
|
|
4136
|
-
downloadId: this.downloadId(
|
|
4393
|
+
downloadId: this.downloadId(path9.basename(target2)),
|
|
4137
4394
|
filename: file.filename,
|
|
4138
4395
|
size: file.bytes.length,
|
|
4139
4396
|
mimeType: file.mimeType
|
|
@@ -4156,9 +4413,10 @@ class BrowserRuntime {
|
|
|
4156
4413
|
case "close_tab":
|
|
4157
4414
|
await page.close();
|
|
4158
4415
|
return { closed: true, tabId };
|
|
4159
|
-
case "navigate":
|
|
4160
|
-
await this.gotoSettled(page, String(input.url));
|
|
4161
|
-
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
|
+
}
|
|
4162
4420
|
case "set_viewport": {
|
|
4163
4421
|
const viewport = parseViewportInput(input);
|
|
4164
4422
|
const result = await this.setViewport(page, tabId, viewport);
|
|
@@ -4313,7 +4571,7 @@ class BrowserRuntime {
|
|
|
4313
4571
|
}
|
|
4314
4572
|
case "scroll": {
|
|
4315
4573
|
if (input.ref !== undefined) {
|
|
4316
|
-
if (["direction", "amount", "x", "y"].some((
|
|
4574
|
+
if (["direction", "amount", "x", "y"].some((key2) => input[key2] !== undefined))
|
|
4317
4575
|
throw new Error("scroll accepts ref or wheel/pointer parameters, not both.");
|
|
4318
4576
|
const ref = requireRef(input.ref);
|
|
4319
4577
|
const locator = this.refLocator(page, ref);
|
|
@@ -4389,7 +4647,7 @@ class BrowserRuntime {
|
|
|
4389
4647
|
}
|
|
4390
4648
|
case "form_input": {
|
|
4391
4649
|
const ref = requireRef(input.ref);
|
|
4392
|
-
const provided = ["value", "values", "checked"].filter((
|
|
4650
|
+
const provided = ["value", "values", "checked"].filter((key2) => input[key2] !== undefined);
|
|
4393
4651
|
if (provided.length !== 1)
|
|
4394
4652
|
throw new Error("form_input requires exactly one of value, values, or checked.");
|
|
4395
4653
|
const locator = this.refLocator(page, ref);
|
|
@@ -4469,10 +4727,10 @@ class BrowserRuntime {
|
|
|
4469
4727
|
for (const modifier of modifiers)
|
|
4470
4728
|
await page.keyboard.down(modifier);
|
|
4471
4729
|
try {
|
|
4472
|
-
for (const
|
|
4473
|
-
if (typeof
|
|
4730
|
+
for (const key2 of keys) {
|
|
4731
|
+
if (typeof key2 !== "string")
|
|
4474
4732
|
throw new Error("keyboard keys must all be strings.");
|
|
4475
|
-
await page.keyboard.press(
|
|
4733
|
+
await page.keyboard.press(key2);
|
|
4476
4734
|
}
|
|
4477
4735
|
} finally {
|
|
4478
4736
|
for (const modifier of modifiers.toReversed())
|
|
@@ -4616,6 +4874,7 @@ class NativeRuntime {
|
|
|
4616
4874
|
engine;
|
|
4617
4875
|
plugins = [];
|
|
4618
4876
|
owners = new Map;
|
|
4877
|
+
closedOwners = new Map;
|
|
4619
4878
|
generations = new Map;
|
|
4620
4879
|
tracking = new WeakMap;
|
|
4621
4880
|
ended = new Set;
|
|
@@ -4623,7 +4882,8 @@ class NativeRuntime {
|
|
|
4623
4882
|
controllers = new Map;
|
|
4624
4883
|
disconnected = false;
|
|
4625
4884
|
connectionEpoch = 0;
|
|
4626
|
-
|
|
4885
|
+
pageEpochs = new WeakMap;
|
|
4886
|
+
revocationEpoch = 0;
|
|
4627
4887
|
operations = new Map;
|
|
4628
4888
|
hooks = Promise.resolve();
|
|
4629
4889
|
browserId;
|
|
@@ -4671,7 +4931,11 @@ class NativeRuntime {
|
|
|
4671
4931
|
});
|
|
4672
4932
|
});
|
|
4673
4933
|
page.on("close", () => {
|
|
4674
|
-
this.
|
|
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
|
+
}
|
|
4675
4939
|
this.generations.delete(id);
|
|
4676
4940
|
this.owners.delete(id);
|
|
4677
4941
|
this.enqueue(async () => {
|
|
@@ -4680,24 +4944,51 @@ class NativeRuntime {
|
|
|
4680
4944
|
});
|
|
4681
4945
|
});
|
|
4682
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
|
+
}
|
|
4683
4957
|
async download(download, page, downloadId) {
|
|
4684
|
-
const
|
|
4685
|
-
|
|
4686
|
-
const
|
|
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;
|
|
4687
4962
|
try {
|
|
4688
|
-
|
|
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
|
|
4689
4974
|
throw new Error("Download ownership changed");
|
|
4690
|
-
this.validateScope(scope);
|
|
4691
4975
|
} catch {
|
|
4692
|
-
await
|
|
4976
|
+
await this.discardDownload(download);
|
|
4693
4977
|
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4694
4978
|
}
|
|
4695
4979
|
const handler = this.plugins.find((p) => p.onDownload);
|
|
4696
4980
|
if (!handler) {
|
|
4697
|
-
await
|
|
4981
|
+
await this.discardDownload(download);
|
|
4698
4982
|
return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
|
|
4699
4983
|
}
|
|
4700
|
-
return handler.onDownload(download, id,
|
|
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(() => {});
|
|
4701
4992
|
}
|
|
4702
4993
|
scopeEpoch(scope) {
|
|
4703
4994
|
this.validateScope(scope);
|
|
@@ -4866,11 +5157,11 @@ class NativeRuntime {
|
|
|
4866
5157
|
await this.endSession(scope);
|
|
4867
5158
|
return { ended: true };
|
|
4868
5159
|
}
|
|
4869
|
-
const controller = new AbortController,
|
|
4870
|
-
let set = this.controllers.get(
|
|
5160
|
+
const controller = new AbortController, key2 = scopeKey(scope);
|
|
5161
|
+
let set = this.controllers.get(key2);
|
|
4871
5162
|
if (!set) {
|
|
4872
5163
|
set = new Set;
|
|
4873
|
-
this.controllers.set(
|
|
5164
|
+
this.controllers.set(key2, set);
|
|
4874
5165
|
}
|
|
4875
5166
|
set.add(controller);
|
|
4876
5167
|
this.operations.set(operationId, controller);
|
|
@@ -4880,7 +5171,7 @@ class NativeRuntime {
|
|
|
4880
5171
|
this.operations.delete(operationId);
|
|
4881
5172
|
set.delete(controller);
|
|
4882
5173
|
if (!set.size)
|
|
4883
|
-
this.controllers.delete(
|
|
5174
|
+
this.controllers.delete(key2);
|
|
4884
5175
|
}
|
|
4885
5176
|
}
|
|
4886
5177
|
async executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage) {
|
|
@@ -4904,8 +5195,8 @@ class NativeRuntime {
|
|
|
4904
5195
|
if (op === "release_tab") {
|
|
4905
5196
|
const tabId = String(args.tabId);
|
|
4906
5197
|
begin();
|
|
4907
|
-
this.
|
|
4908
|
-
this.
|
|
5198
|
+
this.revocationEpoch++;
|
|
5199
|
+
this.revokeOwnership(tabId);
|
|
4909
5200
|
this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
|
|
4910
5201
|
for (const p of this.plugins)
|
|
4911
5202
|
await p.onHandoff?.(tabId, scope);
|
|
@@ -4929,7 +5220,11 @@ class NativeRuntime {
|
|
|
4929
5220
|
return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
|
|
4930
5221
|
}
|
|
4931
5222
|
try {
|
|
4932
|
-
const
|
|
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 });
|
|
4933
5228
|
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4934
5229
|
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4935
5230
|
const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
|
|
@@ -4945,18 +5240,21 @@ class NativeRuntime {
|
|
|
4945
5240
|
}
|
|
4946
5241
|
}
|
|
4947
5242
|
async endSession(scope) {
|
|
4948
|
-
const
|
|
4949
|
-
this.ended.add(
|
|
4950
|
-
this.epochs.set(
|
|
4951
|
-
for (const controller of this.controllers.get(
|
|
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) ?? [])
|
|
4952
5247
|
controller.abort(new Error("Runtime scope revoked"));
|
|
4953
|
-
this.
|
|
5248
|
+
this.revocationEpoch++;
|
|
4954
5249
|
for (const [id, owner] of this.owners)
|
|
4955
|
-
if (scopeKey(owner) ===
|
|
4956
|
-
this.
|
|
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);
|
|
4957
5255
|
for (const p of this.plugins)
|
|
4958
5256
|
await p.onSessionEnd?.(scope);
|
|
4959
|
-
this.ended.delete(
|
|
5257
|
+
this.ended.delete(key2);
|
|
4960
5258
|
}
|
|
4961
5259
|
async shutdown() {
|
|
4962
5260
|
await this.disconnect();
|
|
@@ -4987,8 +5285,8 @@ class NativeRuntime {
|
|
|
4987
5285
|
// cli/src/runtime/relay.ts
|
|
4988
5286
|
import WebSocket2 from "ws";
|
|
4989
5287
|
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4990
|
-
import
|
|
4991
|
-
import
|
|
5288
|
+
import fs10 from "node:fs/promises";
|
|
5289
|
+
import path10 from "node:path";
|
|
4992
5290
|
|
|
4993
5291
|
// cli/src/live/producer.ts
|
|
4994
5292
|
import WebSocket from "ws";
|
|
@@ -5089,13 +5387,13 @@ class CaptureTimeout extends Error {
|
|
|
5089
5387
|
}
|
|
5090
5388
|
}
|
|
5091
5389
|
async function bounded2(stage, operation) {
|
|
5092
|
-
let
|
|
5390
|
+
let timer2;
|
|
5093
5391
|
try {
|
|
5094
5392
|
return await Promise.race([operation, new Promise((_, reject) => {
|
|
5095
|
-
|
|
5393
|
+
timer2 = setTimeout(() => reject(new CaptureTimeout(stage)), STAGE_TIMEOUT_MS);
|
|
5096
5394
|
})]);
|
|
5097
5395
|
} finally {
|
|
5098
|
-
clearTimeout(
|
|
5396
|
+
clearTimeout(timer2);
|
|
5099
5397
|
}
|
|
5100
5398
|
}
|
|
5101
5399
|
|
|
@@ -5245,12 +5543,12 @@ class NativeLiveProducer {
|
|
|
5245
5543
|
this.socket = ws;
|
|
5246
5544
|
try {
|
|
5247
5545
|
await new Promise((resolve2, reject) => {
|
|
5248
|
-
const
|
|
5546
|
+
const timer2 = setTimeout(() => {
|
|
5249
5547
|
ws.terminate();
|
|
5250
5548
|
reject(new Error("Media timeout"));
|
|
5251
5549
|
}, 5000);
|
|
5252
5550
|
const done = (error) => {
|
|
5253
|
-
clearTimeout(
|
|
5551
|
+
clearTimeout(timer2);
|
|
5254
5552
|
error ? reject(error) : resolve2();
|
|
5255
5553
|
};
|
|
5256
5554
|
ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
|
|
@@ -5376,10 +5674,10 @@ function wireResult(op, value) {
|
|
|
5376
5674
|
const opaque = ["output", "inputSchema", "annotations", "originalAction"];
|
|
5377
5675
|
if (op === "run_js")
|
|
5378
5676
|
opaque.push("result");
|
|
5379
|
-
for (const
|
|
5380
|
-
if (output[
|
|
5381
|
-
output[`${
|
|
5382
|
-
delete output[
|
|
5677
|
+
for (const key2 of opaque)
|
|
5678
|
+
if (output[key2] !== undefined) {
|
|
5679
|
+
output[`${key2}Json`] = JSON.stringify(output[key2]);
|
|
5680
|
+
delete output[key2];
|
|
5383
5681
|
}
|
|
5384
5682
|
if (op === "webmcp_list" && Array.isArray(output.tools))
|
|
5385
5683
|
output.tools = output.tools.map((tool) => wireResult("tool-description", tool));
|
|
@@ -5391,9 +5689,9 @@ function wireResult(op, value) {
|
|
|
5391
5689
|
output.newRuntimeTabIds = output.newTabIds;
|
|
5392
5690
|
delete output.newTabIds;
|
|
5393
5691
|
}
|
|
5394
|
-
for (const
|
|
5395
|
-
if (output[
|
|
5396
|
-
output[
|
|
5692
|
+
for (const key2 of ["tab", "observation"])
|
|
5693
|
+
if (output[key2])
|
|
5694
|
+
output[key2] = wireResult("metadata", output[key2]);
|
|
5397
5695
|
if (Array.isArray(output.tabs))
|
|
5398
5696
|
output.tabs = output.tabs.map((tab) => wireResult("metadata", tab));
|
|
5399
5697
|
if (op === "batch" && Array.isArray(output.results))
|
|
@@ -5559,7 +5857,7 @@ class Relay {
|
|
|
5559
5857
|
if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5560
5858
|
return;
|
|
5561
5859
|
this.state = "authenticating";
|
|
5562
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
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 } } }));
|
|
5563
5861
|
});
|
|
5564
5862
|
socket.on("message", (bytes, binary) => {
|
|
5565
5863
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5721,7 +6019,7 @@ class Relay {
|
|
|
5721
6019
|
finish = resolve2;
|
|
5722
6020
|
}), interrupt: () => interrupt(), expire: () => expire() };
|
|
5723
6021
|
this.active = active;
|
|
5724
|
-
let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(),
|
|
6022
|
+
let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(), timer2;
|
|
5725
6023
|
const screenshotStage = message.op === "screenshot" ? (next) => {
|
|
5726
6024
|
stage = next;
|
|
5727
6025
|
stageStartedAt = Date.now();
|
|
@@ -5745,7 +6043,7 @@ class Relay {
|
|
|
5745
6043
|
active.interrupted = true;
|
|
5746
6044
|
else
|
|
5747
6045
|
active.timedOut = true;
|
|
5748
|
-
clearTimeout(
|
|
6046
|
+
clearTimeout(timer2);
|
|
5749
6047
|
screenshotUpload.abort();
|
|
5750
6048
|
if (message.op === "screenshot")
|
|
5751
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() }));
|
|
@@ -5757,7 +6055,7 @@ class Relay {
|
|
|
5757
6055
|
};
|
|
5758
6056
|
interrupt = () => terminal(true);
|
|
5759
6057
|
expire = () => terminal(false);
|
|
5760
|
-
|
|
6058
|
+
timer2 = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
|
|
5761
6059
|
});
|
|
5762
6060
|
const task = (async () => {
|
|
5763
6061
|
let response;
|
|
@@ -5792,20 +6090,20 @@ class Relay {
|
|
|
5792
6090
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5793
6091
|
for (const item of result.exports) {
|
|
5794
6092
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5795
|
-
if (
|
|
6093
|
+
if (path10.basename(filename) !== filename)
|
|
5796
6094
|
throw new Error("Invalid export file");
|
|
5797
|
-
const filenamePath =
|
|
5798
|
-
const stat = await
|
|
6095
|
+
const filenamePath = path10.join(this.previewDirectory, filename);
|
|
6096
|
+
const stat = await fs10.lstat(filenamePath);
|
|
5799
6097
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5800
6098
|
throw new Error("Invalid export file");
|
|
5801
|
-
blobs.push(await this.upload(await
|
|
5802
|
-
await
|
|
6099
|
+
blobs.push(await this.upload(await fs10.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
6100
|
+
await fs10.unlink(filenamePath);
|
|
5803
6101
|
delete item.downloadId;
|
|
5804
6102
|
}
|
|
5805
6103
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5806
6104
|
for (const artifact2 of result.artifacts)
|
|
5807
|
-
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact",
|
|
5808
|
-
result.artifacts = result.artifacts.map((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) }));
|
|
5809
6107
|
}
|
|
5810
6108
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5811
6109
|
throw new Error("Result budget exceeded");
|
|
@@ -5825,7 +6123,7 @@ class Relay {
|
|
|
5825
6123
|
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5826
6124
|
}
|
|
5827
6125
|
} finally {
|
|
5828
|
-
clearTimeout(
|
|
6126
|
+
clearTimeout(timer2);
|
|
5829
6127
|
active.settled = true;
|
|
5830
6128
|
finish();
|
|
5831
6129
|
if (active.timedOut || active.interrupted)
|
|
@@ -5858,16 +6156,16 @@ class Relay {
|
|
|
5858
6156
|
this.active = undefined;
|
|
5859
6157
|
return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
|
|
5860
6158
|
})();
|
|
5861
|
-
let
|
|
6159
|
+
let timer2;
|
|
5862
6160
|
try {
|
|
5863
6161
|
const result = await Promise.race([work, new Promise((_, reject2) => {
|
|
5864
|
-
|
|
6162
|
+
timer2 = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
|
|
5865
6163
|
})]);
|
|
5866
6164
|
send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
|
|
5867
6165
|
} catch {
|
|
5868
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 } });
|
|
5869
6167
|
} finally {
|
|
5870
|
-
clearTimeout(
|
|
6168
|
+
clearTimeout(timer2);
|
|
5871
6169
|
}
|
|
5872
6170
|
}
|
|
5873
6171
|
async upload(bytes, role, name, mimeType, signal = AbortSignal.timeout(30000)) {
|
|
@@ -5906,7 +6204,7 @@ class Relay {
|
|
|
5906
6204
|
import { mkdir as mkdir2, open as open3, rename, unlink as unlink3, rmdir as rmdir2, lstat as lstat3 } from "node:fs/promises";
|
|
5907
6205
|
import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
|
|
5908
6206
|
import { randomUUID as randomUUID8, createHash as createHash7 } from "node:crypto";
|
|
5909
|
-
import { join as join2, basename } from "node:path";
|
|
6207
|
+
import { join as join2, basename as basename2 } from "node:path";
|
|
5910
6208
|
import { Readable, Transform as Transform2 } from "node:stream";
|
|
5911
6209
|
import { pipeline as pipeline2 } from "node:stream/promises";
|
|
5912
6210
|
|
|
@@ -5932,7 +6230,7 @@ class SecretVault {
|
|
|
5932
6230
|
throw new Error("Capture rejected");
|
|
5933
6231
|
const epoch = this.epoch, target2 = await this.access.resolveTarget(tabId, scope, frames);
|
|
5934
6232
|
try {
|
|
5935
|
-
let
|
|
6233
|
+
let timer2;
|
|
5936
6234
|
const values = await Promise.race([this.access.suppressDiagnostics(tabId, () => target2.frame.evaluate(async ({ code: code3, limits }) => {
|
|
5937
6235
|
const values2 = Object.create(null);
|
|
5938
6236
|
let bytes = 0;
|
|
@@ -5952,11 +6250,11 @@ class SecretVault {
|
|
|
5952
6250
|
throw new Error("Capture failed");
|
|
5953
6251
|
}
|
|
5954
6252
|
}, { code: code2, limits: LIMITS })), new Promise((_resolve, reject) => {
|
|
5955
|
-
|
|
5956
|
-
|
|
6253
|
+
timer2 = setTimeout(() => reject(new Error("Capture timeout")), 15000);
|
|
6254
|
+
timer2.unref?.();
|
|
5957
6255
|
})]).finally(() => {
|
|
5958
|
-
if (
|
|
5959
|
-
clearTimeout(
|
|
6256
|
+
if (timer2)
|
|
6257
|
+
clearTimeout(timer2);
|
|
5960
6258
|
});
|
|
5961
6259
|
target2.assertCurrent();
|
|
5962
6260
|
if (epoch !== this.epoch)
|
|
@@ -6033,10 +6331,26 @@ class SecretVault {
|
|
|
6033
6331
|
import { constants as constants3, createWriteStream } from "node:fs";
|
|
6034
6332
|
import { lstat as lstat2, open as open2, unlink as unlink2 } from "node:fs/promises";
|
|
6035
6333
|
import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
|
|
6036
|
-
import { dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
6334
|
+
import { basename, dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
6037
6335
|
import { Transform } from "node:stream";
|
|
6038
6336
|
import { pipeline } from "node:stream/promises";
|
|
6039
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
|
+
}
|
|
6040
6354
|
function captureEvidence() {
|
|
6041
6355
|
return { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
|
|
6042
6356
|
}
|
|
@@ -6056,6 +6370,7 @@ async function sourceAvailability(source) {
|
|
|
6056
6370
|
if (source.identity && (source.identity.dev !== stat.dev || source.identity.ino !== stat.ino))
|
|
6057
6371
|
return "unsafe";
|
|
6058
6372
|
source.identity ??= { dev: stat.dev, ino: stat.ino };
|
|
6373
|
+
source.size ??= stat.size;
|
|
6059
6374
|
return "present";
|
|
6060
6375
|
} catch (error) {
|
|
6061
6376
|
return ["ENOENT", "ENOTDIR"].includes(reasonFor(error)) ? "unavailable" : "unconfirmed";
|
|
@@ -6102,6 +6417,7 @@ function contentValidation(name, size) {
|
|
|
6102
6417
|
}
|
|
6103
6418
|
async function captureDownload(browserSource, destination, signal, evidence) {
|
|
6104
6419
|
const { download } = browserSource;
|
|
6420
|
+
const hooks = browserSource.hooks ?? {};
|
|
6105
6421
|
let operation = "completion";
|
|
6106
6422
|
let source;
|
|
6107
6423
|
let retained2;
|
|
@@ -6110,15 +6426,22 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6110
6426
|
evidence.browserCompletion = failure === null ? "completed" : "failed";
|
|
6111
6427
|
if (failure !== null)
|
|
6112
6428
|
throw new CaptureError("download_capture_browser_failed", "browser-failed");
|
|
6429
|
+
hooks.completed?.();
|
|
6113
6430
|
operation = "path";
|
|
6114
|
-
const
|
|
6431
|
+
const path11 = await duringCapture(download.path(), signal);
|
|
6115
6432
|
signal.throwIfAborted();
|
|
6116
6433
|
evidence.stage = "browser-file";
|
|
6117
|
-
if (dirname2(resolve2(
|
|
6434
|
+
if (dirname2(resolve2(path11)) !== resolve2(browserSource.directory) || browserSource.path && path11 !== browserSource.path)
|
|
6118
6435
|
throw new CaptureError("download_capture_source_unavailable", "unsafe-path");
|
|
6119
|
-
browserSource.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");
|
|
6120
6443
|
operation = "open";
|
|
6121
|
-
source = await open2(
|
|
6444
|
+
source = await open2(path11, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
6122
6445
|
operation = "stat";
|
|
6123
6446
|
const before = await source.stat();
|
|
6124
6447
|
if (!before.isFile())
|
|
@@ -6126,10 +6449,12 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6126
6449
|
if (browserSource.identity && (before.dev !== browserSource.identity.dev || before.ino !== browserSource.identity.ino))
|
|
6127
6450
|
throw new CaptureError("download_capture_source_unavailable", "source-changed");
|
|
6128
6451
|
browserSource.identity = { dev: before.dev, ino: before.ino };
|
|
6452
|
+
browserSource.size = before.size;
|
|
6129
6453
|
evidence.sourceAvailability = "present";
|
|
6130
6454
|
evidence.browser = { size: before.size };
|
|
6131
6455
|
if (before.size > LIMITS.file)
|
|
6132
6456
|
throw new CaptureError("download_quota_exceeded", "quota-exceeded");
|
|
6457
|
+
hooks.reserve?.(before.size);
|
|
6133
6458
|
signal.throwIfAborted();
|
|
6134
6459
|
evidence.stage = "copy";
|
|
6135
6460
|
operation = "copy";
|
|
@@ -6181,20 +6506,29 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6181
6506
|
}
|
|
6182
6507
|
}
|
|
6183
6508
|
async function cleanupDownload(source, evidence) {
|
|
6184
|
-
|
|
6509
|
+
const hooks = source.hooks ?? {};
|
|
6510
|
+
let timer2;
|
|
6185
6511
|
try {
|
|
6186
|
-
const
|
|
6512
|
+
const outcome = await Promise.race([
|
|
6187
6513
|
(async () => {
|
|
6514
|
+
let failed = false;
|
|
6188
6515
|
if (!source.path) {
|
|
6189
|
-
const
|
|
6516
|
+
const path11 = await source.download.path().catch(() => {
|
|
6517
|
+
failed = true;
|
|
6190
6518
|
return;
|
|
6191
6519
|
});
|
|
6192
|
-
if (
|
|
6193
|
-
source.path =
|
|
6520
|
+
if (path11 && dirname2(resolve2(path11)) === resolve2(source.directory))
|
|
6521
|
+
source.path = path11;
|
|
6194
6522
|
}
|
|
6523
|
+
if (source.path && hooks.claim && !hooks.claim(basename(source.path)))
|
|
6524
|
+
return true;
|
|
6195
6525
|
await source.download.delete().catch(() => {});
|
|
6196
|
-
if (!source.path)
|
|
6197
|
-
|
|
6526
|
+
if (!source.path) {
|
|
6527
|
+
if (!failed || !hooks.release)
|
|
6528
|
+
return false;
|
|
6529
|
+
hooks.release();
|
|
6530
|
+
return true;
|
|
6531
|
+
}
|
|
6198
6532
|
await unlink2(source.path).catch(() => {});
|
|
6199
6533
|
try {
|
|
6200
6534
|
await lstat2(source.path);
|
|
@@ -6204,26 +6538,33 @@ async function cleanupDownload(source, evidence) {
|
|
|
6204
6538
|
}
|
|
6205
6539
|
})(),
|
|
6206
6540
|
new Promise((resolve3) => {
|
|
6207
|
-
|
|
6208
|
-
|
|
6541
|
+
timer2 = setTimeout(() => resolve3("timeout"), 2000);
|
|
6542
|
+
timer2.unref?.();
|
|
6209
6543
|
})
|
|
6210
6544
|
]);
|
|
6545
|
+
const deleted = outcome === "timeout" ? !source.path && !!hooks.release : outcome;
|
|
6211
6546
|
if (evidence)
|
|
6212
6547
|
evidence.cleanup = deleted ? "deleted" : "browser-context";
|
|
6213
6548
|
return deleted;
|
|
6214
6549
|
} finally {
|
|
6215
|
-
clearTimeout(
|
|
6550
|
+
clearTimeout(timer2);
|
|
6216
6551
|
}
|
|
6217
6552
|
}
|
|
6218
6553
|
|
|
6219
6554
|
// cli/src/data/index.ts
|
|
6220
6555
|
var safeName = (s) => {
|
|
6221
|
-
const name =
|
|
6556
|
+
const name = basename2(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
|
|
6222
6557
|
return !name || name === "." || name === ".." ? "file" : name;
|
|
6223
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.";
|
|
6224
6562
|
async function createDataPlugin(access, options) {
|
|
6225
6563
|
if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
|
|
6226
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");
|
|
6227
6568
|
await mkdir2(options.directory, { mode: 448 });
|
|
6228
6569
|
const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
|
|
6229
6570
|
let stopped = false;
|
|
@@ -6231,7 +6572,8 @@ async function createDataPlugin(access, options) {
|
|
|
6231
6572
|
function remember(r) {
|
|
6232
6573
|
if (r.purpose !== "download")
|
|
6233
6574
|
return;
|
|
6234
|
-
|
|
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 });
|
|
6235
6577
|
while (terminal.size > 128)
|
|
6236
6578
|
terminal.delete(terminal.keys().next().value);
|
|
6237
6579
|
}
|
|
@@ -6241,39 +6583,55 @@ async function createDataPlugin(access, options) {
|
|
|
6241
6583
|
}
|
|
6242
6584
|
function status(scope, id) {
|
|
6243
6585
|
const t = terminal.get(String(id));
|
|
6244
|
-
if (t && t.until >= Date.now() &&
|
|
6586
|
+
if (t && t.until >= Date.now() && visible(t, scope))
|
|
6245
6587
|
return t.meta;
|
|
6246
6588
|
return meta(get(scope, id));
|
|
6247
6589
|
}
|
|
6248
6590
|
function meta(r) {
|
|
6249
|
-
const failed = r.state === "capture-failed";
|
|
6591
|
+
const failed = r.state === "capture-failed", outside = r.capture?.diagnostic?.reason === "outside-spool";
|
|
6250
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" ? {
|
|
6251
6593
|
downloadId: r.id,
|
|
6252
6594
|
mimeType: "application/octet-stream",
|
|
6253
6595
|
sourceKind: "download",
|
|
6596
|
+
owner: r.shared ? "user" : "this_session",
|
|
6254
6597
|
readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : failed ? "unavailable" : "pending",
|
|
6255
6598
|
capture: r.capture,
|
|
6256
6599
|
contentValidation: r.contentValidation,
|
|
6257
6600
|
...r.state === "ready" ? { retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {},
|
|
6258
|
-
...failed ? { code: r.terminalCode, retry: { tool: "browser_retry_download_capture", arguments: { downloadId: r.id } }, 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." } : {}
|
|
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." } : {}
|
|
6259
6602
|
} : {} };
|
|
6260
6603
|
}
|
|
6261
6604
|
function get(scope, id) {
|
|
6262
6605
|
const r = resources.get(String(id));
|
|
6263
|
-
if (!r || !
|
|
6606
|
+
if (!r || !visible(r, scope) || r.expiresAt < Date.now())
|
|
6264
6607
|
throw new Error("Unknown resource");
|
|
6265
6608
|
return r;
|
|
6266
6609
|
}
|
|
6267
|
-
const reserved = (r) =>
|
|
6268
|
-
|
|
6269
|
-
|
|
6270
|
-
|
|
6271
|
-
|
|
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)
|
|
6272
6625
|
throw new Error("Local data quota exceeded");
|
|
6273
6626
|
}
|
|
6274
|
-
function
|
|
6275
|
-
|
|
6276
|
-
|
|
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 };
|
|
6277
6635
|
resources.set(r.id, r);
|
|
6278
6636
|
return r;
|
|
6279
6637
|
}
|
|
@@ -6328,8 +6686,8 @@ async function createDataPlugin(access, options) {
|
|
|
6328
6686
|
await Promise.all([...resources.values()].filter(predicate).map(remove));
|
|
6329
6687
|
}
|
|
6330
6688
|
async function transfer(r, g) {
|
|
6331
|
-
const
|
|
6332
|
-
|
|
6689
|
+
const timer2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
6690
|
+
timer2.unref?.();
|
|
6333
6691
|
r.state = "transferring";
|
|
6334
6692
|
try {
|
|
6335
6693
|
if (r.purpose === "upload") {
|
|
@@ -6388,7 +6746,7 @@ async function createDataPlugin(access, options) {
|
|
|
6388
6746
|
owned.delete(r.path);
|
|
6389
6747
|
}
|
|
6390
6748
|
} finally {
|
|
6391
|
-
clearTimeout(
|
|
6749
|
+
clearTimeout(timer2);
|
|
6392
6750
|
if (r.purpose === "secret-export") {
|
|
6393
6751
|
r.bytes?.fill(0);
|
|
6394
6752
|
r.bytes = undefined;
|
|
@@ -6426,18 +6784,30 @@ async function createDataPlugin(access, options) {
|
|
|
6426
6784
|
source.download.cancel().catch(() => {});
|
|
6427
6785
|
};
|
|
6428
6786
|
r.abort.signal.addEventListener("abort", cancel, { once: true });
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
6432
|
-
|
|
6433
|
-
|
|
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
|
+
} };
|
|
6434
6804
|
const task = (async () => {
|
|
6435
6805
|
try {
|
|
6436
6806
|
await discardCopy(r);
|
|
6437
|
-
const
|
|
6438
|
-
r.path =
|
|
6439
|
-
owned.add(
|
|
6440
|
-
const verified = await captureDownload(source,
|
|
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);
|
|
6441
6811
|
if (!valid())
|
|
6442
6812
|
throw new CaptureError("download_capture_cancelled", "cancelled");
|
|
6443
6813
|
r.size = verified.size;
|
|
@@ -6460,6 +6830,8 @@ async function createDataPlugin(access, options) {
|
|
|
6460
6830
|
discarded = false;
|
|
6461
6831
|
}
|
|
6462
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;
|
|
6463
6835
|
r.capture.cleanup = "retained";
|
|
6464
6836
|
r.state = "capture-failed";
|
|
6465
6837
|
} else
|
|
@@ -6475,6 +6847,77 @@ async function createDataPlugin(access, options) {
|
|
|
6475
6847
|
await remove(r);
|
|
6476
6848
|
});
|
|
6477
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
|
+
});
|
|
6478
6921
|
let sweep = setInterval(() => {
|
|
6479
6922
|
sweepExpired();
|
|
6480
6923
|
}, 1e4);
|
|
@@ -6497,13 +6940,13 @@ async function createDataPlugin(access, options) {
|
|
|
6497
6940
|
}
|
|
6498
6941
|
if (op === "create_download") {
|
|
6499
6942
|
const r = resources.get(String(args.downloadId ?? args.fileId ?? args.resourceId));
|
|
6500
|
-
if (!r || !
|
|
6943
|
+
if (!r || !visible(r, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
|
|
6501
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);
|
|
6502
6945
|
return meta(r);
|
|
6503
6946
|
}
|
|
6504
6947
|
if (op === "retry_download_capture") {
|
|
6505
6948
|
const r = resources.get(String(args.downloadId));
|
|
6506
|
-
if (!r || !
|
|
6949
|
+
if (!r || !visible(r, scope) || r.expiresAt <= Date.now() || r.purpose !== "download" || r.state !== "capture-failed" || !r.source)
|
|
6507
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);
|
|
6508
6951
|
startCapture(r).catch(() => {});
|
|
6509
6952
|
return meta(r);
|
|
@@ -6532,7 +6975,7 @@ async function createDataPlugin(access, options) {
|
|
|
6532
6975
|
}
|
|
6533
6976
|
if (op === "list_downloads") {
|
|
6534
6977
|
await sweepExpired();
|
|
6535
|
-
return { files: [...resources.values()].filter((r) =>
|
|
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) };
|
|
6536
6979
|
}
|
|
6537
6980
|
if (op === "upload_files") {
|
|
6538
6981
|
const ids = args.fileIds;
|
|
@@ -6587,51 +7030,29 @@ async function createDataPlugin(access, options) {
|
|
|
6587
7030
|
}
|
|
6588
7031
|
throw new Error("Unsupported data operation");
|
|
6589
7032
|
},
|
|
6590
|
-
async onDownload(download, tabId,
|
|
6591
|
-
|
|
6592
|
-
|
|
6593
|
-
|
|
6594
|
-
|
|
6595
|
-
|
|
6596
|
-
|
|
6597
|
-
|
|
6598
|
-
|
|
6599
|
-
r.source = { download, directory: options.downloadDirectory };
|
|
6600
|
-
await startCapture(r);
|
|
6601
|
-
if (r.state === "ready")
|
|
6602
|
-
return { ...meta(r), state: "completed" };
|
|
6603
|
-
if (r.state === "capture-failed")
|
|
6604
|
-
return { ...meta(r), state: "failed" };
|
|
6605
|
-
return status(scope, downloadId);
|
|
6606
|
-
} catch (error) {
|
|
6607
|
-
download.cancel().catch(() => {});
|
|
6608
|
-
if (r) {
|
|
6609
|
-
r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
|
|
6610
|
-
await remove(r);
|
|
6611
|
-
return status(scope, downloadId);
|
|
6612
|
-
}
|
|
6613
|
-
if (!await cleanupDownload({ download, directory: options.downloadDirectory }))
|
|
6614
|
-
failClosed();
|
|
6615
|
-
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." };
|
|
6616
|
-
terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6617
|
-
while (terminal.size > 128)
|
|
6618
|
-
terminal.delete(terminal.keys().next().value);
|
|
6619
|
-
return failed;
|
|
6620
|
-
}
|
|
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) });
|
|
6621
7042
|
},
|
|
6622
7043
|
async onNavigation(tabId, generation) {
|
|
6623
7044
|
await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
|
|
6624
7045
|
},
|
|
6625
7046
|
async onTabClose(tabId) {
|
|
6626
|
-
await revoke((r) => r.tabId === tabId);
|
|
7047
|
+
await revoke((r) => r.purpose !== "download" && r.tabId === tabId);
|
|
6627
7048
|
},
|
|
6628
7049
|
async onSessionEnd(scope) {
|
|
6629
7050
|
vault.revoke((r) => sameScope(r.scope, scope));
|
|
6630
|
-
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));
|
|
6631
7052
|
},
|
|
6632
7053
|
async onHandoff(tabId, scope) {
|
|
6633
7054
|
vault.revoke((r) => r.tabId === tabId && sameScope(r.scope, scope));
|
|
6634
|
-
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));
|
|
6635
7056
|
},
|
|
6636
7057
|
async onDisconnect() {
|
|
6637
7058
|
stopped = true;
|
|
@@ -6721,21 +7142,21 @@ function createForwardPlugin(options) {
|
|
|
6721
7142
|
function parse2(args) {
|
|
6722
7143
|
const options = { profiles: [] };
|
|
6723
7144
|
for (let i = 0;i < args.length; i++) {
|
|
6724
|
-
const
|
|
6725
|
-
if (
|
|
7145
|
+
const key2 = args[i];
|
|
7146
|
+
if (key2 === "--ephemeral")
|
|
6726
7147
|
options.ephemeral = true;
|
|
6727
|
-
else if (
|
|
7148
|
+
else if (key2 === "--live-view")
|
|
6728
7149
|
options.liveView = true;
|
|
6729
|
-
else if (
|
|
7150
|
+
else if (key2 === "--profile" || key2 === "--server" || key2 === "--chrome-path") {
|
|
6730
7151
|
if (!args[i + 1] || args[i + 1].startsWith("--"))
|
|
6731
|
-
throw new Error(`Missing ${
|
|
7152
|
+
throw new Error(`Missing ${key2} value`);
|
|
6732
7153
|
const value = args[++i];
|
|
6733
|
-
if (
|
|
7154
|
+
if (key2 === "--profile")
|
|
6734
7155
|
options.profiles.push(value);
|
|
6735
7156
|
else
|
|
6736
|
-
options[
|
|
7157
|
+
options[key2 === "--server" ? "server" : "chrome-path"] = value;
|
|
6737
7158
|
} else
|
|
6738
|
-
throw new Error(`Unknown browser option ${
|
|
7159
|
+
throw new Error(`Unknown browser option ${key2}`);
|
|
6739
7160
|
}
|
|
6740
7161
|
return options;
|
|
6741
7162
|
}
|
|
@@ -6767,7 +7188,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6767
7188
|
for (const signal of signals)
|
|
6768
7189
|
process.on(signal, signalStop);
|
|
6769
7190
|
try {
|
|
6770
|
-
const requestedRoot =
|
|
7191
|
+
const requestedRoot = path11.resolve(installationRoot());
|
|
6771
7192
|
for (const profile of profiles)
|
|
6772
7193
|
assertControlPaths(requestedRoot, controlSocketPath(requestedRoot, profile));
|
|
6773
7194
|
const root = await privateDirectory2(requestedRoot);
|
|
@@ -6796,7 +7217,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6796
7217
|
const server = serverURL(options.server ?? "https://browser-mcp.click");
|
|
6797
7218
|
for (const profile of profiles) {
|
|
6798
7219
|
const controlPath = controlSocketPath(root, profile);
|
|
6799
|
-
const previousSocket = await
|
|
7220
|
+
const previousSocket = await fs11.lstat(controlPath).catch((error) => {
|
|
6800
7221
|
if (error.code !== "ENOENT")
|
|
6801
7222
|
throw controlFailure("local-control", error);
|
|
6802
7223
|
});
|
|
@@ -6830,7 +7251,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6830
7251
|
let starting = true;
|
|
6831
7252
|
let session;
|
|
6832
7253
|
let runtime, relay, local;
|
|
6833
|
-
let stopQuota;
|
|
6834
7254
|
const controlPath = controlSocketPath(root, profile);
|
|
6835
7255
|
let stopControl;
|
|
6836
7256
|
const clients = new Set;
|
|
@@ -6845,7 +7265,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6845
7265
|
session?.lifecycle.requestShutdown("owner-close");
|
|
6846
7266
|
await cleanupSteps([
|
|
6847
7267
|
["Relay", () => runtimeCleanup(() => relay?.stop())],
|
|
6848
|
-
["Download quota", () => runtimeCleanup(() => stopQuota?.())],
|
|
6849
7268
|
["Runtime", () => runtimeCleanup(() => runtime?.shutdown())],
|
|
6850
7269
|
["Local control", async () => {
|
|
6851
7270
|
for (const client of clients)
|
|
@@ -6875,21 +7294,19 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6875
7294
|
if (groupSignal.aborted)
|
|
6876
7295
|
groupStop();
|
|
6877
7296
|
let failure, cleanupFailure;
|
|
6878
|
-
let runtimeStage = "
|
|
7297
|
+
let runtimeStage = "pairing";
|
|
6879
7298
|
try {
|
|
6880
7299
|
abort.signal.throwIfAborted();
|
|
6881
7300
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
6882
7301
|
session.lifecycle.ended.then(endSession);
|
|
6883
7302
|
abort.signal.throwIfAborted();
|
|
6884
|
-
stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
|
|
6885
|
-
abort.signal.throwIfAborted();
|
|
6886
7303
|
runtimeStage = "pairing";
|
|
6887
7304
|
const token = await credential(root, server, profile, abort.signal);
|
|
6888
7305
|
abort.signal.throwIfAborted();
|
|
6889
7306
|
runtimeStage = "runtime-setup";
|
|
6890
|
-
const previews =
|
|
7307
|
+
const previews = path11.join(session.runPath, "previews");
|
|
6891
7308
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
6892
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
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: () => {
|
|
6893
7310
|
console.error("Download cleanup could not be verified; closing the owned browser to bound private spool retention. No website action was replayed.");
|
|
6894
7311
|
requestStop("owner-close");
|
|
6895
7312
|
} }));
|
|
@@ -6928,7 +7345,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6928
7345
|
return;
|
|
6929
7346
|
} else if (cmd !== "status")
|
|
6930
7347
|
throw new Error("Invalid command");
|
|
6931
|
-
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.
|
|
7348
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.18", protocol: 3 }) + `
|
|
6932
7349
|
`);
|
|
6933
7350
|
})().catch(() => socket.destroy());
|
|
6934
7351
|
});
|