@ricsam/browser-mcp 0.3.17 → 0.3.19
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-8d06b7q4.js} +831 -404
- 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.19";
|
|
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);
|
|
@@ -3455,6 +3708,8 @@ var messages = {
|
|
|
3455
3708
|
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3456
3709
|
transfer_failed: "The file transfer failed or its completion could not be confirmed.",
|
|
3457
3710
|
resource_unavailable: "The requested resource is unavailable. No download link was created.",
|
|
3711
|
+
resource_not_found: "No resource with this ID is visible to this session.",
|
|
3712
|
+
upload_not_ready: "A staged upload is not ready to attach.",
|
|
3458
3713
|
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3459
3714
|
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3460
3715
|
};
|
|
@@ -3545,7 +3800,7 @@ class BrowserRuntime {
|
|
|
3545
3800
|
return;
|
|
3546
3801
|
});
|
|
3547
3802
|
});
|
|
3548
|
-
|
|
3803
|
+
fs9.mkdirSync(downloadsPath, { recursive: true });
|
|
3549
3804
|
this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
|
|
3550
3805
|
for (const page of context.pages())
|
|
3551
3806
|
this.track(page);
|
|
@@ -3604,23 +3859,23 @@ class BrowserRuntime {
|
|
|
3604
3859
|
return id;
|
|
3605
3860
|
}
|
|
3606
3861
|
safeDownloadFilename(suggestedFilename) {
|
|
3607
|
-
const basename =
|
|
3862
|
+
const basename = path9.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
3608
3863
|
if (!basename || basename === "." || basename === "..")
|
|
3609
3864
|
return "download";
|
|
3610
|
-
const extension =
|
|
3611
|
-
let stem = basename.slice(0, basename.length -
|
|
3865
|
+
const extension = path9.extname(basename).slice(0, 30);
|
|
3866
|
+
let stem = basename.slice(0, basename.length - path9.extname(basename).length) || "download";
|
|
3612
3867
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
3613
3868
|
stem = stem.slice(0, -1);
|
|
3614
3869
|
return `${stem || "download"}${extension}`;
|
|
3615
3870
|
}
|
|
3616
3871
|
availableDownloadPath(suggestedFilename) {
|
|
3617
3872
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
3618
|
-
const extension =
|
|
3873
|
+
const extension = path9.extname(filename);
|
|
3619
3874
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
3620
3875
|
for (let suffix = 1;; suffix += 1) {
|
|
3621
3876
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
3622
|
-
const candidatePath =
|
|
3623
|
-
if (!
|
|
3877
|
+
const candidatePath = path9.join(this.downloadsPath, candidate);
|
|
3878
|
+
if (!fs9.existsSync(candidatePath))
|
|
3624
3879
|
return candidatePath;
|
|
3625
3880
|
}
|
|
3626
3881
|
}
|
|
@@ -3628,18 +3883,18 @@ class BrowserRuntime {
|
|
|
3628
3883
|
const failure = await download.failure();
|
|
3629
3884
|
if (failure)
|
|
3630
3885
|
throw new Error(failure);
|
|
3631
|
-
const temporary =
|
|
3886
|
+
const temporary = path9.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
3632
3887
|
let targetPath;
|
|
3633
3888
|
try {
|
|
3634
3889
|
await download.saveAs(temporary);
|
|
3635
3890
|
targetPath = this.availableDownloadPath(download.suggestedFilename());
|
|
3636
|
-
|
|
3891
|
+
fs9.renameSync(temporary, targetPath);
|
|
3637
3892
|
} finally {
|
|
3638
|
-
|
|
3893
|
+
fs9.rmSync(temporary, { force: true });
|
|
3639
3894
|
}
|
|
3640
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3895
|
+
process.stdout.write(`[r5d-browser] downloaded ${path9.basename(targetPath)}
|
|
3641
3896
|
`);
|
|
3642
|
-
return { downloadId: this.downloadId(
|
|
3897
|
+
return { downloadId: this.downloadId(path9.basename(targetPath)) };
|
|
3643
3898
|
}
|
|
3644
3899
|
downloadId(filename) {
|
|
3645
3900
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -3648,13 +3903,13 @@ class BrowserRuntime {
|
|
|
3648
3903
|
if (typeof downloadId !== "string" || !downloadId)
|
|
3649
3904
|
throw new Error("downloadId is required.");
|
|
3650
3905
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
3651
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3906
|
+
if (this.downloadId(filename) !== downloadId || filename !== path9.basename(filename) || filename.includes("\x00")) {
|
|
3652
3907
|
throw new Error("Invalid downloadId.");
|
|
3653
3908
|
}
|
|
3654
|
-
const filePath =
|
|
3909
|
+
const filePath = path9.join(this.downloadsPath, filename);
|
|
3655
3910
|
let stats;
|
|
3656
3911
|
try {
|
|
3657
|
-
stats =
|
|
3912
|
+
stats = fs9.lstatSync(filePath);
|
|
3658
3913
|
} catch {
|
|
3659
3914
|
throw new Error(`Browser download ${downloadId} no longer exists.`);
|
|
3660
3915
|
}
|
|
@@ -3663,7 +3918,7 @@ class BrowserRuntime {
|
|
|
3663
3918
|
return { filename, filePath, stats };
|
|
3664
3919
|
}
|
|
3665
3920
|
async listDownloads() {
|
|
3666
|
-
return
|
|
3921
|
+
return fs9.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
|
|
3667
3922
|
if (!entry.isFile() || entry.name.startsWith("."))
|
|
3668
3923
|
return [];
|
|
3669
3924
|
const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
|
|
@@ -3687,20 +3942,20 @@ class BrowserRuntime {
|
|
|
3687
3942
|
throw new Error("Invalid download chunk size.");
|
|
3688
3943
|
const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
|
|
3689
3944
|
const bytes = Buffer.alloc(chunkSize);
|
|
3690
|
-
const handle =
|
|
3945
|
+
const handle = fs9.openSync(filePath, fs9.constants.O_RDONLY | fs9.constants.O_NOFOLLOW);
|
|
3691
3946
|
let bytesRead = 0;
|
|
3692
3947
|
try {
|
|
3693
|
-
const openedStats =
|
|
3948
|
+
const openedStats = fs9.fstatSync(handle);
|
|
3694
3949
|
if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
|
|
3695
3950
|
throw new Error("Browser download changed before it could be read.");
|
|
3696
3951
|
}
|
|
3697
|
-
bytesRead =
|
|
3698
|
-
const completedStats =
|
|
3952
|
+
bytesRead = fs9.readSync(handle, bytes, 0, chunkSize, offset);
|
|
3953
|
+
const completedStats = fs9.fstatSync(handle);
|
|
3699
3954
|
if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
|
|
3700
3955
|
throw new Error("Browser download changed while it was being read.");
|
|
3701
3956
|
}
|
|
3702
3957
|
} finally {
|
|
3703
|
-
|
|
3958
|
+
fs9.closeSync(handle);
|
|
3704
3959
|
}
|
|
3705
3960
|
const nextOffset = offset + bytesRead;
|
|
3706
3961
|
return {
|
|
@@ -3738,12 +3993,15 @@ class BrowserRuntime {
|
|
|
3738
3993
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
|
|
3739
3994
|
} catch (error) {
|
|
3740
3995
|
const message = error instanceof Error ? error.message : String(error);
|
|
3996
|
+
if (/Download is starting/i.test(message))
|
|
3997
|
+
return { downloadStarted: true };
|
|
3741
3998
|
if (!/ERR_ABORTED|interrupted by another navigation/i.test(message))
|
|
3742
3999
|
throw new Error(stripCallLog(message));
|
|
3743
4000
|
await page.waitForLoadState("domcontentloaded", { timeout: 5000 }).catch(() => {
|
|
3744
4001
|
return;
|
|
3745
4002
|
});
|
|
3746
4003
|
}
|
|
4004
|
+
return {};
|
|
3747
4005
|
}
|
|
3748
4006
|
async tabInfo(page) {
|
|
3749
4007
|
this.track(page);
|
|
@@ -3949,14 +4207,15 @@ class BrowserRuntime {
|
|
|
3949
4207
|
ownerSessionId: execution.sessionId,
|
|
3950
4208
|
retention: input.retention === "temporary" ? "temporary" : "retained"
|
|
3951
4209
|
});
|
|
4210
|
+
execution.onTabOpened?.(this.ids.get(page2));
|
|
3952
4211
|
const url = typeof input.url === "string" ? input.url : "about:blank";
|
|
3953
4212
|
if (url !== "about:blank") {
|
|
3954
4213
|
const events = this.events.get(page2);
|
|
3955
4214
|
await events.ready;
|
|
3956
4215
|
const result = await events.run(execution.operationId ?? crypto.randomUUID(), async () => {
|
|
3957
|
-
await this.gotoSettled(page2, url);
|
|
4216
|
+
const settled = await this.gotoSettled(page2, url);
|
|
3958
4217
|
await this.guardPage?.(page2);
|
|
3959
|
-
return { tab: await this.tabInfo(page2) };
|
|
4218
|
+
return { tab: await this.tabInfo(page2), ...settled };
|
|
3960
4219
|
});
|
|
3961
4220
|
return { tab: await this.tabInfo(page2), ...result };
|
|
3962
4221
|
}
|
|
@@ -4131,9 +4390,9 @@ class BrowserRuntime {
|
|
|
4131
4390
|
return { tabId, exported: false, code: "export_too_large" };
|
|
4132
4391
|
const exports = files.map((file) => {
|
|
4133
4392
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
4134
|
-
|
|
4393
|
+
fs9.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
4135
4394
|
return {
|
|
4136
|
-
downloadId: this.downloadId(
|
|
4395
|
+
downloadId: this.downloadId(path9.basename(target2)),
|
|
4137
4396
|
filename: file.filename,
|
|
4138
4397
|
size: file.bytes.length,
|
|
4139
4398
|
mimeType: file.mimeType
|
|
@@ -4156,9 +4415,10 @@ class BrowserRuntime {
|
|
|
4156
4415
|
case "close_tab":
|
|
4157
4416
|
await page.close();
|
|
4158
4417
|
return { closed: true, tabId };
|
|
4159
|
-
case "navigate":
|
|
4160
|
-
await this.gotoSettled(page, String(input.url));
|
|
4161
|
-
return { tab: await this.tabInfo(page) };
|
|
4418
|
+
case "navigate": {
|
|
4419
|
+
const settled = await this.gotoSettled(page, String(input.url));
|
|
4420
|
+
return { tab: await this.tabInfo(page), ...settled };
|
|
4421
|
+
}
|
|
4162
4422
|
case "set_viewport": {
|
|
4163
4423
|
const viewport = parseViewportInput(input);
|
|
4164
4424
|
const result = await this.setViewport(page, tabId, viewport);
|
|
@@ -4313,7 +4573,7 @@ class BrowserRuntime {
|
|
|
4313
4573
|
}
|
|
4314
4574
|
case "scroll": {
|
|
4315
4575
|
if (input.ref !== undefined) {
|
|
4316
|
-
if (["direction", "amount", "x", "y"].some((
|
|
4576
|
+
if (["direction", "amount", "x", "y"].some((key2) => input[key2] !== undefined))
|
|
4317
4577
|
throw new Error("scroll accepts ref or wheel/pointer parameters, not both.");
|
|
4318
4578
|
const ref = requireRef(input.ref);
|
|
4319
4579
|
const locator = this.refLocator(page, ref);
|
|
@@ -4389,7 +4649,7 @@ class BrowserRuntime {
|
|
|
4389
4649
|
}
|
|
4390
4650
|
case "form_input": {
|
|
4391
4651
|
const ref = requireRef(input.ref);
|
|
4392
|
-
const provided = ["value", "values", "checked"].filter((
|
|
4652
|
+
const provided = ["value", "values", "checked"].filter((key2) => input[key2] !== undefined);
|
|
4393
4653
|
if (provided.length !== 1)
|
|
4394
4654
|
throw new Error("form_input requires exactly one of value, values, or checked.");
|
|
4395
4655
|
const locator = this.refLocator(page, ref);
|
|
@@ -4469,10 +4729,10 @@ class BrowserRuntime {
|
|
|
4469
4729
|
for (const modifier of modifiers)
|
|
4470
4730
|
await page.keyboard.down(modifier);
|
|
4471
4731
|
try {
|
|
4472
|
-
for (const
|
|
4473
|
-
if (typeof
|
|
4732
|
+
for (const key2 of keys) {
|
|
4733
|
+
if (typeof key2 !== "string")
|
|
4474
4734
|
throw new Error("keyboard keys must all be strings.");
|
|
4475
|
-
await page.keyboard.press(
|
|
4735
|
+
await page.keyboard.press(key2);
|
|
4476
4736
|
}
|
|
4477
4737
|
} finally {
|
|
4478
4738
|
for (const modifier of modifiers.toReversed())
|
|
@@ -4616,6 +4876,7 @@ class NativeRuntime {
|
|
|
4616
4876
|
engine;
|
|
4617
4877
|
plugins = [];
|
|
4618
4878
|
owners = new Map;
|
|
4879
|
+
closedOwners = new Map;
|
|
4619
4880
|
generations = new Map;
|
|
4620
4881
|
tracking = new WeakMap;
|
|
4621
4882
|
ended = new Set;
|
|
@@ -4623,7 +4884,8 @@ class NativeRuntime {
|
|
|
4623
4884
|
controllers = new Map;
|
|
4624
4885
|
disconnected = false;
|
|
4625
4886
|
connectionEpoch = 0;
|
|
4626
|
-
|
|
4887
|
+
pageEpochs = new WeakMap;
|
|
4888
|
+
revocationEpoch = 0;
|
|
4627
4889
|
operations = new Map;
|
|
4628
4890
|
hooks = Promise.resolve();
|
|
4629
4891
|
browserId;
|
|
@@ -4671,7 +4933,11 @@ class NativeRuntime {
|
|
|
4671
4933
|
});
|
|
4672
4934
|
});
|
|
4673
4935
|
page.on("close", () => {
|
|
4674
|
-
this.
|
|
4936
|
+
const owner = this.owners.get(id);
|
|
4937
|
+
if (owner) {
|
|
4938
|
+
this.closedOwners.set(page, owner);
|
|
4939
|
+
setTimeout(() => this.closedOwners.delete(page), 60000).unref?.();
|
|
4940
|
+
}
|
|
4675
4941
|
this.generations.delete(id);
|
|
4676
4942
|
this.owners.delete(id);
|
|
4677
4943
|
this.enqueue(async () => {
|
|
@@ -4680,24 +4946,51 @@ class NativeRuntime {
|
|
|
4680
4946
|
});
|
|
4681
4947
|
});
|
|
4682
4948
|
}
|
|
4949
|
+
revokeOwnership(tabId) {
|
|
4950
|
+
this.owners.delete(tabId);
|
|
4951
|
+
let page;
|
|
4952
|
+
try {
|
|
4953
|
+
page = this.engine.page(tabId);
|
|
4954
|
+
} catch {
|
|
4955
|
+
return;
|
|
4956
|
+
}
|
|
4957
|
+
this.pageEpochs.set(page, (this.pageEpochs.get(page) ?? 0) + 1);
|
|
4958
|
+
}
|
|
4683
4959
|
async download(download, page, downloadId) {
|
|
4684
|
-
const
|
|
4685
|
-
|
|
4686
|
-
const
|
|
4960
|
+
for (const plugin of this.plugins)
|
|
4961
|
+
plugin.observeDownload?.(download);
|
|
4962
|
+
const pageEpoch = this.pageEpochs.get(page) ?? 0, revocationEpoch = this.revocationEpoch, connectionEpoch = this.connectionEpoch;
|
|
4963
|
+
let id, owner;
|
|
4687
4964
|
try {
|
|
4688
|
-
|
|
4965
|
+
await this.track(page);
|
|
4966
|
+
id = await this.engine.idFor(page);
|
|
4967
|
+
const scope = this.owners.get(id) ?? this.closedOwners.get(page);
|
|
4968
|
+
if (connectionEpoch !== this.connectionEpoch || (this.pageEpochs.get(page) ?? 0) !== pageEpoch)
|
|
4969
|
+
throw new Error("Download ownership changed");
|
|
4970
|
+
if (scope) {
|
|
4971
|
+
this.validateScope(scope);
|
|
4972
|
+
owner = { kind: "session", scope: { ...scope } };
|
|
4973
|
+
} else if (!page.isClosed() && revocationEpoch === this.revocationEpoch && !this.disconnected)
|
|
4974
|
+
owner = { kind: "user" };
|
|
4975
|
+
else
|
|
4689
4976
|
throw new Error("Download ownership changed");
|
|
4690
|
-
this.validateScope(scope);
|
|
4691
4977
|
} catch {
|
|
4692
|
-
await
|
|
4978
|
+
await this.discardDownload(download);
|
|
4693
4979
|
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4694
4980
|
}
|
|
4695
4981
|
const handler = this.plugins.find((p) => p.onDownload);
|
|
4696
4982
|
if (!handler) {
|
|
4697
|
-
await
|
|
4983
|
+
await this.discardDownload(download);
|
|
4698
4984
|
return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
|
|
4699
4985
|
}
|
|
4700
|
-
return handler.onDownload(download, id,
|
|
4986
|
+
return handler.onDownload(download, id, owner, this.generations.get(id) ?? 0, downloadId);
|
|
4987
|
+
}
|
|
4988
|
+
async discardDownload(download) {
|
|
4989
|
+
const plugin = this.plugins.find((p) => p.discardDownload);
|
|
4990
|
+
if (plugin)
|
|
4991
|
+
await plugin.discardDownload(download).catch(() => {});
|
|
4992
|
+
else
|
|
4993
|
+
await download.cancel().catch(() => {});
|
|
4701
4994
|
}
|
|
4702
4995
|
scopeEpoch(scope) {
|
|
4703
4996
|
this.validateScope(scope);
|
|
@@ -4866,11 +5159,11 @@ class NativeRuntime {
|
|
|
4866
5159
|
await this.endSession(scope);
|
|
4867
5160
|
return { ended: true };
|
|
4868
5161
|
}
|
|
4869
|
-
const controller = new AbortController,
|
|
4870
|
-
let set = this.controllers.get(
|
|
5162
|
+
const controller = new AbortController, key2 = scopeKey(scope);
|
|
5163
|
+
let set = this.controllers.get(key2);
|
|
4871
5164
|
if (!set) {
|
|
4872
5165
|
set = new Set;
|
|
4873
|
-
this.controllers.set(
|
|
5166
|
+
this.controllers.set(key2, set);
|
|
4874
5167
|
}
|
|
4875
5168
|
set.add(controller);
|
|
4876
5169
|
this.operations.set(operationId, controller);
|
|
@@ -4880,7 +5173,7 @@ class NativeRuntime {
|
|
|
4880
5173
|
this.operations.delete(operationId);
|
|
4881
5174
|
set.delete(controller);
|
|
4882
5175
|
if (!set.size)
|
|
4883
|
-
this.controllers.delete(
|
|
5176
|
+
this.controllers.delete(key2);
|
|
4884
5177
|
}
|
|
4885
5178
|
}
|
|
4886
5179
|
async executeInner(op, args, scope, operationId, beforeDispatch, screenshotStage) {
|
|
@@ -4904,8 +5197,8 @@ class NativeRuntime {
|
|
|
4904
5197
|
if (op === "release_tab") {
|
|
4905
5198
|
const tabId = String(args.tabId);
|
|
4906
5199
|
begin();
|
|
4907
|
-
this.
|
|
4908
|
-
this.
|
|
5200
|
+
this.revocationEpoch++;
|
|
5201
|
+
this.revokeOwnership(tabId);
|
|
4909
5202
|
this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
|
|
4910
5203
|
for (const p of this.plugins)
|
|
4911
5204
|
await p.onHandoff?.(tabId, scope);
|
|
@@ -4929,7 +5222,11 @@ class NativeRuntime {
|
|
|
4929
5222
|
return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
|
|
4930
5223
|
}
|
|
4931
5224
|
try {
|
|
4932
|
-
const
|
|
5225
|
+
const onTabOpened = (tabId) => {
|
|
5226
|
+
if (!this.disconnected && (this.epochs.get(scopeKey(scope)) ?? 0) === operationEpoch)
|
|
5227
|
+
this.owners.set(tabId, { ...scope });
|
|
5228
|
+
};
|
|
5229
|
+
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin, screenshotStage, onTabOpened });
|
|
4933
5230
|
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4934
5231
|
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4935
5232
|
const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
|
|
@@ -4945,18 +5242,21 @@ class NativeRuntime {
|
|
|
4945
5242
|
}
|
|
4946
5243
|
}
|
|
4947
5244
|
async endSession(scope) {
|
|
4948
|
-
const
|
|
4949
|
-
this.ended.add(
|
|
4950
|
-
this.epochs.set(
|
|
4951
|
-
for (const controller of this.controllers.get(
|
|
5245
|
+
const key2 = scopeKey(scope);
|
|
5246
|
+
this.ended.add(key2);
|
|
5247
|
+
this.epochs.set(key2, (this.epochs.get(key2) ?? 0) + 1);
|
|
5248
|
+
for (const controller of this.controllers.get(key2) ?? [])
|
|
4952
5249
|
controller.abort(new Error("Runtime scope revoked"));
|
|
4953
|
-
this.
|
|
5250
|
+
this.revocationEpoch++;
|
|
4954
5251
|
for (const [id, owner] of this.owners)
|
|
4955
|
-
if (scopeKey(owner) ===
|
|
4956
|
-
this.
|
|
5252
|
+
if (scopeKey(owner) === key2)
|
|
5253
|
+
this.revokeOwnership(id);
|
|
5254
|
+
for (const [page, owner] of this.closedOwners)
|
|
5255
|
+
if (scopeKey(owner) === key2)
|
|
5256
|
+
this.closedOwners.delete(page);
|
|
4957
5257
|
for (const p of this.plugins)
|
|
4958
5258
|
await p.onSessionEnd?.(scope);
|
|
4959
|
-
this.ended.delete(
|
|
5259
|
+
this.ended.delete(key2);
|
|
4960
5260
|
}
|
|
4961
5261
|
async shutdown() {
|
|
4962
5262
|
await this.disconnect();
|
|
@@ -4987,8 +5287,8 @@ class NativeRuntime {
|
|
|
4987
5287
|
// cli/src/runtime/relay.ts
|
|
4988
5288
|
import WebSocket2 from "ws";
|
|
4989
5289
|
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4990
|
-
import
|
|
4991
|
-
import
|
|
5290
|
+
import fs10 from "node:fs/promises";
|
|
5291
|
+
import path10 from "node:path";
|
|
4992
5292
|
|
|
4993
5293
|
// cli/src/live/producer.ts
|
|
4994
5294
|
import WebSocket from "ws";
|
|
@@ -5089,13 +5389,13 @@ class CaptureTimeout extends Error {
|
|
|
5089
5389
|
}
|
|
5090
5390
|
}
|
|
5091
5391
|
async function bounded2(stage, operation) {
|
|
5092
|
-
let
|
|
5392
|
+
let timer2;
|
|
5093
5393
|
try {
|
|
5094
5394
|
return await Promise.race([operation, new Promise((_, reject) => {
|
|
5095
|
-
|
|
5395
|
+
timer2 = setTimeout(() => reject(new CaptureTimeout(stage)), STAGE_TIMEOUT_MS);
|
|
5096
5396
|
})]);
|
|
5097
5397
|
} finally {
|
|
5098
|
-
clearTimeout(
|
|
5398
|
+
clearTimeout(timer2);
|
|
5099
5399
|
}
|
|
5100
5400
|
}
|
|
5101
5401
|
|
|
@@ -5245,12 +5545,12 @@ class NativeLiveProducer {
|
|
|
5245
5545
|
this.socket = ws;
|
|
5246
5546
|
try {
|
|
5247
5547
|
await new Promise((resolve2, reject) => {
|
|
5248
|
-
const
|
|
5548
|
+
const timer2 = setTimeout(() => {
|
|
5249
5549
|
ws.terminate();
|
|
5250
5550
|
reject(new Error("Media timeout"));
|
|
5251
5551
|
}, 5000);
|
|
5252
5552
|
const done = (error) => {
|
|
5253
|
-
clearTimeout(
|
|
5553
|
+
clearTimeout(timer2);
|
|
5254
5554
|
error ? reject(error) : resolve2();
|
|
5255
5555
|
};
|
|
5256
5556
|
ws.once("open", () => ws.send(JSON.stringify({ type: "auth", token: this.options.token, instanceId: this.options.instanceId, credentialEpoch: this.options.credentialEpoch })));
|
|
@@ -5376,10 +5676,10 @@ function wireResult(op, value) {
|
|
|
5376
5676
|
const opaque = ["output", "inputSchema", "annotations", "originalAction"];
|
|
5377
5677
|
if (op === "run_js")
|
|
5378
5678
|
opaque.push("result");
|
|
5379
|
-
for (const
|
|
5380
|
-
if (output[
|
|
5381
|
-
output[`${
|
|
5382
|
-
delete output[
|
|
5679
|
+
for (const key2 of opaque)
|
|
5680
|
+
if (output[key2] !== undefined) {
|
|
5681
|
+
output[`${key2}Json`] = JSON.stringify(output[key2]);
|
|
5682
|
+
delete output[key2];
|
|
5383
5683
|
}
|
|
5384
5684
|
if (op === "webmcp_list" && Array.isArray(output.tools))
|
|
5385
5685
|
output.tools = output.tools.map((tool) => wireResult("tool-description", tool));
|
|
@@ -5391,9 +5691,9 @@ function wireResult(op, value) {
|
|
|
5391
5691
|
output.newRuntimeTabIds = output.newTabIds;
|
|
5392
5692
|
delete output.newTabIds;
|
|
5393
5693
|
}
|
|
5394
|
-
for (const
|
|
5395
|
-
if (output[
|
|
5396
|
-
output[
|
|
5694
|
+
for (const key2 of ["tab", "observation"])
|
|
5695
|
+
if (output[key2])
|
|
5696
|
+
output[key2] = wireResult("metadata", output[key2]);
|
|
5397
5697
|
if (Array.isArray(output.tabs))
|
|
5398
5698
|
output.tabs = output.tabs.map((tab) => wireResult("metadata", tab));
|
|
5399
5699
|
if (op === "batch" && Array.isArray(output.results))
|
|
@@ -5559,7 +5859,7 @@ class Relay {
|
|
|
5559
5859
|
if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5560
5860
|
return;
|
|
5561
5861
|
this.state = "authenticating";
|
|
5562
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
5862
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.19", 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
5863
|
});
|
|
5564
5864
|
socket.on("message", (bytes, binary) => {
|
|
5565
5865
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5721,7 +6021,7 @@ class Relay {
|
|
|
5721
6021
|
finish = resolve2;
|
|
5722
6022
|
}), interrupt: () => interrupt(), expire: () => expire() };
|
|
5723
6023
|
this.active = active;
|
|
5724
|
-
let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(),
|
|
6024
|
+
let stage = message.op === "screenshot" ? "screenshot_prepare" : "execute", stageStartedAt = Date.now(), timer2;
|
|
5725
6025
|
const screenshotStage = message.op === "screenshot" ? (next) => {
|
|
5726
6026
|
stage = next;
|
|
5727
6027
|
stageStartedAt = Date.now();
|
|
@@ -5745,7 +6045,7 @@ class Relay {
|
|
|
5745
6045
|
active.interrupted = true;
|
|
5746
6046
|
else
|
|
5747
6047
|
active.timedOut = true;
|
|
5748
|
-
clearTimeout(
|
|
6048
|
+
clearTimeout(timer2);
|
|
5749
6049
|
screenshotUpload.abort();
|
|
5750
6050
|
if (message.op === "screenshot")
|
|
5751
6051
|
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 +6057,7 @@ class Relay {
|
|
|
5757
6057
|
};
|
|
5758
6058
|
interrupt = () => terminal(true);
|
|
5759
6059
|
expire = () => terminal(false);
|
|
5760
|
-
|
|
6060
|
+
timer2 = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
|
|
5761
6061
|
});
|
|
5762
6062
|
const task = (async () => {
|
|
5763
6063
|
let response;
|
|
@@ -5792,20 +6092,20 @@ class Relay {
|
|
|
5792
6092
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5793
6093
|
for (const item of result.exports) {
|
|
5794
6094
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5795
|
-
if (
|
|
6095
|
+
if (path10.basename(filename) !== filename)
|
|
5796
6096
|
throw new Error("Invalid export file");
|
|
5797
|
-
const filenamePath =
|
|
5798
|
-
const stat = await
|
|
6097
|
+
const filenamePath = path10.join(this.previewDirectory, filename);
|
|
6098
|
+
const stat = await fs10.lstat(filenamePath);
|
|
5799
6099
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5800
6100
|
throw new Error("Invalid export file");
|
|
5801
|
-
blobs.push(await this.upload(await
|
|
5802
|
-
await
|
|
6101
|
+
blobs.push(await this.upload(await fs10.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
6102
|
+
await fs10.unlink(filenamePath);
|
|
5803
6103
|
delete item.downloadId;
|
|
5804
6104
|
}
|
|
5805
6105
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5806
6106
|
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:
|
|
6107
|
+
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"));
|
|
6108
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path10.basename(a.filename) }));
|
|
5809
6109
|
}
|
|
5810
6110
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5811
6111
|
throw new Error("Result budget exceeded");
|
|
@@ -5825,7 +6125,7 @@ class Relay {
|
|
|
5825
6125
|
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5826
6126
|
}
|
|
5827
6127
|
} finally {
|
|
5828
|
-
clearTimeout(
|
|
6128
|
+
clearTimeout(timer2);
|
|
5829
6129
|
active.settled = true;
|
|
5830
6130
|
finish();
|
|
5831
6131
|
if (active.timedOut || active.interrupted)
|
|
@@ -5858,16 +6158,16 @@ class Relay {
|
|
|
5858
6158
|
this.active = undefined;
|
|
5859
6159
|
return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
|
|
5860
6160
|
})();
|
|
5861
|
-
let
|
|
6161
|
+
let timer2;
|
|
5862
6162
|
try {
|
|
5863
6163
|
const result = await Promise.race([work, new Promise((_, reject2) => {
|
|
5864
|
-
|
|
6164
|
+
timer2 = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
|
|
5865
6165
|
})]);
|
|
5866
6166
|
send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
|
|
5867
6167
|
} catch {
|
|
5868
6168
|
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
6169
|
} finally {
|
|
5870
|
-
clearTimeout(
|
|
6170
|
+
clearTimeout(timer2);
|
|
5871
6171
|
}
|
|
5872
6172
|
}
|
|
5873
6173
|
async upload(bytes, role, name, mimeType, signal = AbortSignal.timeout(30000)) {
|
|
@@ -5906,7 +6206,7 @@ class Relay {
|
|
|
5906
6206
|
import { mkdir as mkdir2, open as open3, rename, unlink as unlink3, rmdir as rmdir2, lstat as lstat3 } from "node:fs/promises";
|
|
5907
6207
|
import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
|
|
5908
6208
|
import { randomUUID as randomUUID8, createHash as createHash7 } from "node:crypto";
|
|
5909
|
-
import { join as join2, basename } from "node:path";
|
|
6209
|
+
import { join as join2, basename as basename2 } from "node:path";
|
|
5910
6210
|
import { Readable, Transform as Transform2 } from "node:stream";
|
|
5911
6211
|
import { pipeline as pipeline2 } from "node:stream/promises";
|
|
5912
6212
|
|
|
@@ -5932,7 +6232,7 @@ class SecretVault {
|
|
|
5932
6232
|
throw new Error("Capture rejected");
|
|
5933
6233
|
const epoch = this.epoch, target2 = await this.access.resolveTarget(tabId, scope, frames);
|
|
5934
6234
|
try {
|
|
5935
|
-
let
|
|
6235
|
+
let timer2;
|
|
5936
6236
|
const values = await Promise.race([this.access.suppressDiagnostics(tabId, () => target2.frame.evaluate(async ({ code: code3, limits }) => {
|
|
5937
6237
|
const values2 = Object.create(null);
|
|
5938
6238
|
let bytes = 0;
|
|
@@ -5952,11 +6252,11 @@ class SecretVault {
|
|
|
5952
6252
|
throw new Error("Capture failed");
|
|
5953
6253
|
}
|
|
5954
6254
|
}, { code: code2, limits: LIMITS })), new Promise((_resolve, reject) => {
|
|
5955
|
-
|
|
5956
|
-
|
|
6255
|
+
timer2 = setTimeout(() => reject(new Error("Capture timeout")), 15000);
|
|
6256
|
+
timer2.unref?.();
|
|
5957
6257
|
})]).finally(() => {
|
|
5958
|
-
if (
|
|
5959
|
-
clearTimeout(
|
|
6258
|
+
if (timer2)
|
|
6259
|
+
clearTimeout(timer2);
|
|
5960
6260
|
});
|
|
5961
6261
|
target2.assertCurrent();
|
|
5962
6262
|
if (epoch !== this.epoch)
|
|
@@ -6033,10 +6333,26 @@ class SecretVault {
|
|
|
6033
6333
|
import { constants as constants3, createWriteStream } from "node:fs";
|
|
6034
6334
|
import { lstat as lstat2, open as open2, unlink as unlink2 } from "node:fs/promises";
|
|
6035
6335
|
import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
|
|
6036
|
-
import { dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
6336
|
+
import { basename, dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
6037
6337
|
import { Transform } from "node:stream";
|
|
6038
6338
|
import { pipeline } from "node:stream/promises";
|
|
6039
6339
|
var filesystemReasons = new Set(["ENOENT", "EACCES", "EPERM", "ELOOP", "ENOTDIR", "EMFILE", "ENFILE", "EIO", "ENOSPC"]);
|
|
6340
|
+
var SETTLEMENT_WAIT_MS = 5000;
|
|
6341
|
+
function within(promise, ms) {
|
|
6342
|
+
if (!promise)
|
|
6343
|
+
return Promise.resolve(undefined);
|
|
6344
|
+
return new Promise((resolve3) => {
|
|
6345
|
+
const timer2 = setTimeout(() => resolve3(undefined), ms);
|
|
6346
|
+
timer2.unref?.();
|
|
6347
|
+
promise.then((value) => {
|
|
6348
|
+
clearTimeout(timer2);
|
|
6349
|
+
resolve3(value);
|
|
6350
|
+
}, () => {
|
|
6351
|
+
clearTimeout(timer2);
|
|
6352
|
+
resolve3(undefined);
|
|
6353
|
+
});
|
|
6354
|
+
});
|
|
6355
|
+
}
|
|
6040
6356
|
function captureEvidence() {
|
|
6041
6357
|
return { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
|
|
6042
6358
|
}
|
|
@@ -6056,6 +6372,7 @@ async function sourceAvailability(source) {
|
|
|
6056
6372
|
if (source.identity && (source.identity.dev !== stat.dev || source.identity.ino !== stat.ino))
|
|
6057
6373
|
return "unsafe";
|
|
6058
6374
|
source.identity ??= { dev: stat.dev, ino: stat.ino };
|
|
6375
|
+
source.size ??= stat.size;
|
|
6059
6376
|
return "present";
|
|
6060
6377
|
} catch (error) {
|
|
6061
6378
|
return ["ENOENT", "ENOTDIR"].includes(reasonFor(error)) ? "unavailable" : "unconfirmed";
|
|
@@ -6102,6 +6419,7 @@ function contentValidation(name, size) {
|
|
|
6102
6419
|
}
|
|
6103
6420
|
async function captureDownload(browserSource, destination, signal, evidence) {
|
|
6104
6421
|
const { download } = browserSource;
|
|
6422
|
+
const hooks = browserSource.hooks ?? {};
|
|
6105
6423
|
let operation = "completion";
|
|
6106
6424
|
let source;
|
|
6107
6425
|
let retained2;
|
|
@@ -6110,15 +6428,22 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6110
6428
|
evidence.browserCompletion = failure === null ? "completed" : "failed";
|
|
6111
6429
|
if (failure !== null)
|
|
6112
6430
|
throw new CaptureError("download_capture_browser_failed", "browser-failed");
|
|
6431
|
+
hooks.completed?.();
|
|
6113
6432
|
operation = "path";
|
|
6114
|
-
const
|
|
6433
|
+
const path11 = await duringCapture(download.path(), signal);
|
|
6115
6434
|
signal.throwIfAborted();
|
|
6116
6435
|
evidence.stage = "browser-file";
|
|
6117
|
-
if (dirname2(resolve2(
|
|
6436
|
+
if (dirname2(resolve2(path11)) !== resolve2(browserSource.directory) || browserSource.path && path11 !== browserSource.path)
|
|
6118
6437
|
throw new CaptureError("download_capture_source_unavailable", "unsafe-path");
|
|
6119
|
-
browserSource.path =
|
|
6438
|
+
browserSource.path = path11;
|
|
6439
|
+
const guid = basename(path11);
|
|
6440
|
+
if (hooks.claim && !hooks.claim(guid))
|
|
6441
|
+
throw new CaptureError("download_capture_source_unavailable", "source-changed");
|
|
6442
|
+
const settled = await duringCapture(within(hooks.settlement?.(guid), SETTLEMENT_WAIT_MS), signal);
|
|
6443
|
+
if (settled?.state === "completed" && settled.filePath && hooks.isSpoolPath && !hooks.isSpoolPath(settled.filePath, guid))
|
|
6444
|
+
throw new CaptureError("download_capture_source_unavailable", "outside-spool");
|
|
6120
6445
|
operation = "open";
|
|
6121
|
-
source = await open2(
|
|
6446
|
+
source = await open2(path11, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
6122
6447
|
operation = "stat";
|
|
6123
6448
|
const before = await source.stat();
|
|
6124
6449
|
if (!before.isFile())
|
|
@@ -6126,10 +6451,12 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6126
6451
|
if (browserSource.identity && (before.dev !== browserSource.identity.dev || before.ino !== browserSource.identity.ino))
|
|
6127
6452
|
throw new CaptureError("download_capture_source_unavailable", "source-changed");
|
|
6128
6453
|
browserSource.identity = { dev: before.dev, ino: before.ino };
|
|
6454
|
+
browserSource.size = before.size;
|
|
6129
6455
|
evidence.sourceAvailability = "present";
|
|
6130
6456
|
evidence.browser = { size: before.size };
|
|
6131
6457
|
if (before.size > LIMITS.file)
|
|
6132
6458
|
throw new CaptureError("download_quota_exceeded", "quota-exceeded");
|
|
6459
|
+
hooks.reserve?.(before.size);
|
|
6133
6460
|
signal.throwIfAborted();
|
|
6134
6461
|
evidence.stage = "copy";
|
|
6135
6462
|
operation = "copy";
|
|
@@ -6181,20 +6508,29 @@ async function captureDownload(browserSource, destination, signal, evidence) {
|
|
|
6181
6508
|
}
|
|
6182
6509
|
}
|
|
6183
6510
|
async function cleanupDownload(source, evidence) {
|
|
6184
|
-
|
|
6511
|
+
const hooks = source.hooks ?? {};
|
|
6512
|
+
let timer2;
|
|
6185
6513
|
try {
|
|
6186
|
-
const
|
|
6514
|
+
const outcome = await Promise.race([
|
|
6187
6515
|
(async () => {
|
|
6516
|
+
let failed = false;
|
|
6188
6517
|
if (!source.path) {
|
|
6189
|
-
const
|
|
6518
|
+
const path11 = await source.download.path().catch(() => {
|
|
6519
|
+
failed = true;
|
|
6190
6520
|
return;
|
|
6191
6521
|
});
|
|
6192
|
-
if (
|
|
6193
|
-
source.path =
|
|
6522
|
+
if (path11 && dirname2(resolve2(path11)) === resolve2(source.directory))
|
|
6523
|
+
source.path = path11;
|
|
6194
6524
|
}
|
|
6525
|
+
if (source.path && hooks.claim && !hooks.claim(basename(source.path)))
|
|
6526
|
+
return true;
|
|
6195
6527
|
await source.download.delete().catch(() => {});
|
|
6196
|
-
if (!source.path)
|
|
6197
|
-
|
|
6528
|
+
if (!source.path) {
|
|
6529
|
+
if (!failed || !hooks.release)
|
|
6530
|
+
return false;
|
|
6531
|
+
hooks.release();
|
|
6532
|
+
return true;
|
|
6533
|
+
}
|
|
6198
6534
|
await unlink2(source.path).catch(() => {});
|
|
6199
6535
|
try {
|
|
6200
6536
|
await lstat2(source.path);
|
|
@@ -6204,26 +6540,34 @@ async function cleanupDownload(source, evidence) {
|
|
|
6204
6540
|
}
|
|
6205
6541
|
})(),
|
|
6206
6542
|
new Promise((resolve3) => {
|
|
6207
|
-
|
|
6208
|
-
|
|
6543
|
+
timer2 = setTimeout(() => resolve3("timeout"), 2000);
|
|
6544
|
+
timer2.unref?.();
|
|
6209
6545
|
})
|
|
6210
6546
|
]);
|
|
6547
|
+
const deleted = outcome === "timeout" ? !source.path && !!hooks.release : outcome;
|
|
6211
6548
|
if (evidence)
|
|
6212
6549
|
evidence.cleanup = deleted ? "deleted" : "browser-context";
|
|
6213
6550
|
return deleted;
|
|
6214
6551
|
} finally {
|
|
6215
|
-
clearTimeout(
|
|
6552
|
+
clearTimeout(timer2);
|
|
6216
6553
|
}
|
|
6217
6554
|
}
|
|
6218
6555
|
|
|
6219
6556
|
// cli/src/data/index.ts
|
|
6220
6557
|
var safeName = (s) => {
|
|
6221
|
-
const name =
|
|
6558
|
+
const name = basename2(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
|
|
6222
6559
|
return !name || name === "." || name === ".." ? "file" : name;
|
|
6223
6560
|
};
|
|
6561
|
+
var USER_SCOPE = { browserId: "", tokenId: "", sessionKey: "", instanceId: "" };
|
|
6562
|
+
var visible = (r, scope) => !!r.shared || sameScope(r.scope, scope);
|
|
6563
|
+
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.";
|
|
6564
|
+
var NOT_FOUND_RECOVERY = "Nothing was changed. Use the resourceId from the result that created the resource, or a downloadId from browser_list_downloads; file names are not IDs. Resources expire, and cancellation or session end removes them.";
|
|
6224
6565
|
async function createDataPlugin(access, options) {
|
|
6225
6566
|
if (!secureDataUrl(new URL(options.serverOrigin), options.allowInsecureLoopback))
|
|
6226
6567
|
throw new Error("HTTPS data server required");
|
|
6568
|
+
const guard = options.downloads, downloadDirectory = guard?.directory ?? options.downloadDirectory;
|
|
6569
|
+
if (!downloadDirectory)
|
|
6570
|
+
throw new Error("Download spool required");
|
|
6227
6571
|
await mkdir2(options.directory, { mode: 448 });
|
|
6228
6572
|
const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
|
|
6229
6573
|
let stopped = false;
|
|
@@ -6231,7 +6575,8 @@ async function createDataPlugin(access, options) {
|
|
|
6231
6575
|
function remember(r) {
|
|
6232
6576
|
if (r.purpose !== "download")
|
|
6233
6577
|
return;
|
|
6234
|
-
|
|
6578
|
+
const outside = r.capture?.diagnostic?.reason === "outside-spool";
|
|
6579
|
+
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
6580
|
while (terminal.size > 128)
|
|
6236
6581
|
terminal.delete(terminal.keys().next().value);
|
|
6237
6582
|
}
|
|
@@ -6241,39 +6586,62 @@ async function createDataPlugin(access, options) {
|
|
|
6241
6586
|
}
|
|
6242
6587
|
function status(scope, id) {
|
|
6243
6588
|
const t = terminal.get(String(id));
|
|
6244
|
-
if (t && t.until >= Date.now() &&
|
|
6589
|
+
if (t && t.until >= Date.now() && visible(t, scope))
|
|
6245
6590
|
return t.meta;
|
|
6246
|
-
return meta(
|
|
6591
|
+
return meta(lookup(scope, id));
|
|
6247
6592
|
}
|
|
6248
6593
|
function meta(r) {
|
|
6249
|
-
const failed = r.state === "capture-failed";
|
|
6594
|
+
const failed = r.state === "capture-failed", outside = r.capture?.diagnostic?.reason === "outside-spool";
|
|
6250
6595
|
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
6596
|
downloadId: r.id,
|
|
6252
6597
|
mimeType: "application/octet-stream",
|
|
6253
6598
|
sourceKind: "download",
|
|
6599
|
+
owner: r.shared ? "user" : "this_session",
|
|
6254
6600
|
readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : failed ? "unavailable" : "pending",
|
|
6255
6601
|
capture: r.capture,
|
|
6256
6602
|
contentValidation: r.contentValidation,
|
|
6257
6603
|
...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." } : {}
|
|
6604
|
+
...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
6605
|
} : {} };
|
|
6260
6606
|
}
|
|
6261
6607
|
function get(scope, id) {
|
|
6262
6608
|
const r = resources.get(String(id));
|
|
6263
|
-
if (!r || !
|
|
6609
|
+
if (!r || !visible(r, scope) || r.expiresAt < Date.now())
|
|
6264
6610
|
throw new Error("Unknown resource");
|
|
6265
6611
|
return r;
|
|
6266
6612
|
}
|
|
6267
|
-
|
|
6268
|
-
|
|
6269
|
-
|
|
6270
|
-
|
|
6271
|
-
|
|
6613
|
+
function lookup(scope, id) {
|
|
6614
|
+
try {
|
|
6615
|
+
return get(scope, id);
|
|
6616
|
+
} catch {
|
|
6617
|
+
throw new RuntimeFault("resource_not_found", NOT_FOUND_RECOVERY, true);
|
|
6618
|
+
}
|
|
6619
|
+
}
|
|
6620
|
+
const reserved = (r) => {
|
|
6621
|
+
if (r.purpose !== "download")
|
|
6622
|
+
return r.size;
|
|
6623
|
+
if (!r.source)
|
|
6624
|
+
return r.hash ? r.size : 0;
|
|
6625
|
+
if (r.sourceBytes !== undefined)
|
|
6626
|
+
return 2 * r.sourceBytes;
|
|
6627
|
+
return r.state === "capture-failed" && r.capture?.sourceAvailability !== "unavailable" ? 2 * LIMITS.file : 0;
|
|
6628
|
+
};
|
|
6629
|
+
const logical = (r) => r.purpose !== "download" ? r.size : r.hash ? r.size : r.sourceBytes ?? 0;
|
|
6630
|
+
const diskBytes = (except) => [...resources.values()].reduce((n, r) => r === except ? n : n + reserved(r), 0);
|
|
6631
|
+
const sessionBytes = (scope, except) => [...resources.values()].reduce((n, r) => r === except || r.shared || !sameScope(r.scope, scope) ? n : n + logical(r), 0);
|
|
6632
|
+
function reserve(scope, size, purpose, shared = false) {
|
|
6633
|
+
const cost = purpose === "download" ? 0 : size;
|
|
6634
|
+
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
6635
|
throw new Error("Local data quota exceeded");
|
|
6273
6636
|
}
|
|
6274
|
-
function
|
|
6275
|
-
|
|
6276
|
-
|
|
6637
|
+
function reserveSource(r, size) {
|
|
6638
|
+
if (size > LIMITS.file || diskBytes(r) + 2 * size > LIMITS.browser || !r.shared && sessionBytes(r.scope, r) + size > LIMITS.session)
|
|
6639
|
+
throw new CaptureError("download_quota_exceeded", "quota-exceeded");
|
|
6640
|
+
r.sourceBytes = size;
|
|
6641
|
+
}
|
|
6642
|
+
function create(scope, purpose, size, name, shared = false) {
|
|
6643
|
+
reserve(scope, size, purpose, shared);
|
|
6644
|
+
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
6645
|
resources.set(r.id, r);
|
|
6278
6646
|
return r;
|
|
6279
6647
|
}
|
|
@@ -6328,8 +6696,8 @@ async function createDataPlugin(access, options) {
|
|
|
6328
6696
|
await Promise.all([...resources.values()].filter(predicate).map(remove));
|
|
6329
6697
|
}
|
|
6330
6698
|
async function transfer(r, g) {
|
|
6331
|
-
const
|
|
6332
|
-
|
|
6699
|
+
const timer2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
6700
|
+
timer2.unref?.();
|
|
6333
6701
|
r.state = "transferring";
|
|
6334
6702
|
try {
|
|
6335
6703
|
if (r.purpose === "upload") {
|
|
@@ -6388,7 +6756,7 @@ async function createDataPlugin(access, options) {
|
|
|
6388
6756
|
owned.delete(r.path);
|
|
6389
6757
|
}
|
|
6390
6758
|
} finally {
|
|
6391
|
-
clearTimeout(
|
|
6759
|
+
clearTimeout(timer2);
|
|
6392
6760
|
if (r.purpose === "secret-export") {
|
|
6393
6761
|
r.bytes?.fill(0);
|
|
6394
6762
|
r.bytes = undefined;
|
|
@@ -6426,18 +6794,30 @@ async function createDataPlugin(access, options) {
|
|
|
6426
6794
|
source.download.cancel().catch(() => {});
|
|
6427
6795
|
};
|
|
6428
6796
|
r.abort.signal.addEventListener("abort", cancel, { once: true });
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
6432
|
-
|
|
6433
|
-
|
|
6797
|
+
let timeout2;
|
|
6798
|
+
const arm = (ms) => {
|
|
6799
|
+
clearTimeout(timeout2);
|
|
6800
|
+
timeout2 = setTimeout(() => {
|
|
6801
|
+
r.terminalCode ??= "download_capture_timeout";
|
|
6802
|
+
r.abort.abort();
|
|
6803
|
+
}, Math.max(1, ms));
|
|
6804
|
+
timeout2.unref?.();
|
|
6805
|
+
};
|
|
6806
|
+
arm(r.completedAt === undefined ? r.expiresAt - Date.now() : Math.min(LIMITS.duration, r.expiresAt - Date.now()));
|
|
6807
|
+
source.hooks = { ...source.hooks, completed: () => {
|
|
6808
|
+
if (r.completedAt === undefined) {
|
|
6809
|
+
r.completedAt = Date.now();
|
|
6810
|
+
r.expiresAt = r.completedAt + LIMITS.ttl;
|
|
6811
|
+
}
|
|
6812
|
+
arm(Math.min(LIMITS.duration, r.expiresAt - Date.now()));
|
|
6813
|
+
} };
|
|
6434
6814
|
const task = (async () => {
|
|
6435
6815
|
try {
|
|
6436
6816
|
await discardCopy(r);
|
|
6437
|
-
const
|
|
6438
|
-
r.path =
|
|
6439
|
-
owned.add(
|
|
6440
|
-
const verified = await captureDownload(source,
|
|
6817
|
+
const path11 = join2(options.directory, r.id);
|
|
6818
|
+
r.path = path11;
|
|
6819
|
+
owned.add(path11);
|
|
6820
|
+
const verified = await captureDownload(source, path11, r.abort.signal, r.capture);
|
|
6441
6821
|
if (!valid())
|
|
6442
6822
|
throw new CaptureError("download_capture_cancelled", "cancelled");
|
|
6443
6823
|
r.size = verified.size;
|
|
@@ -6460,6 +6840,8 @@ async function createDataPlugin(access, options) {
|
|
|
6460
6840
|
discarded = false;
|
|
6461
6841
|
}
|
|
6462
6842
|
if (valid() && discarded && r.capture?.browserCompletion === "completed" && r.capture.sourceAvailability !== "unsafe" && r.terminalCode !== "download_quota_exceeded") {
|
|
6843
|
+
if (r.capture.sourceAvailability === "present")
|
|
6844
|
+
r.sourceBytes ??= source.size;
|
|
6463
6845
|
r.capture.cleanup = "retained";
|
|
6464
6846
|
r.state = "capture-failed";
|
|
6465
6847
|
} else
|
|
@@ -6475,6 +6857,77 @@ async function createDataPlugin(access, options) {
|
|
|
6475
6857
|
await remove(r);
|
|
6476
6858
|
});
|
|
6477
6859
|
}
|
|
6860
|
+
function spoolHooks(download) {
|
|
6861
|
+
if (!guard)
|
|
6862
|
+
return {};
|
|
6863
|
+
return { claim: (guid) => guard.claim(guid, download), release: () => guard.release(download), settlement: (guid) => guard.settlement(guid), isSpoolPath: (path11, guid) => guard.isSpoolPath(path11, guid) };
|
|
6864
|
+
}
|
|
6865
|
+
async function admit(download, name, scope, tabId, generation, downloadId, hooks) {
|
|
6866
|
+
const shared = !scope, owner = scope ?? USER_SCOPE;
|
|
6867
|
+
let r;
|
|
6868
|
+
try {
|
|
6869
|
+
r = create(owner, "download", LIMITS.file, name, shared);
|
|
6870
|
+
resources.delete(r.id);
|
|
6871
|
+
r.id = downloadId;
|
|
6872
|
+
resources.set(r.id, r);
|
|
6873
|
+
r.expiresAt = Date.now() + DOWNLOAD_DEADLINE_MS;
|
|
6874
|
+
r.tabId = tabId;
|
|
6875
|
+
r.generation = generation;
|
|
6876
|
+
const resource = r;
|
|
6877
|
+
r.source = { download, directory: downloadDirectory, hooks: { ...hooks, reserve: (size) => reserveSource(resource, size) } };
|
|
6878
|
+
await startCapture(r);
|
|
6879
|
+
if (r.state === "ready")
|
|
6880
|
+
return { ...meta(r), state: "completed" };
|
|
6881
|
+
if (r.state === "capture-failed")
|
|
6882
|
+
return { ...meta(r), state: "failed" };
|
|
6883
|
+
return status(owner, downloadId);
|
|
6884
|
+
} catch (error) {
|
|
6885
|
+
download.cancel().catch(() => {});
|
|
6886
|
+
if (r) {
|
|
6887
|
+
r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
|
|
6888
|
+
await remove(r);
|
|
6889
|
+
return status(owner, downloadId);
|
|
6890
|
+
}
|
|
6891
|
+
if (!await cleanupDownload({ download, directory: downloadDirectory, hooks }))
|
|
6892
|
+
failClosed();
|
|
6893
|
+
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." };
|
|
6894
|
+
terminal.set(downloadId, { scope: { ...owner }, shared: shared || undefined, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6895
|
+
while (terminal.size > 128)
|
|
6896
|
+
terminal.delete(terminal.keys().next().value);
|
|
6897
|
+
return failed;
|
|
6898
|
+
}
|
|
6899
|
+
}
|
|
6900
|
+
async function adopt(entry) {
|
|
6901
|
+
if (stopped || !guard)
|
|
6902
|
+
return;
|
|
6903
|
+
const file = guard.leaf(entry.guid);
|
|
6904
|
+
const settled = async () => (await guard.settlement(entry.guid))?.state;
|
|
6905
|
+
const handle = {
|
|
6906
|
+
failure: async () => await settled() === "completed" ? null : "canceled",
|
|
6907
|
+
path: async () => {
|
|
6908
|
+
if (await settled() !== "completed")
|
|
6909
|
+
throw new Error("Download canceled");
|
|
6910
|
+
return file;
|
|
6911
|
+
},
|
|
6912
|
+
cancel: async () => {
|
|
6913
|
+
await guard.cancel(entry.guid);
|
|
6914
|
+
},
|
|
6915
|
+
delete: async () => {
|
|
6916
|
+
await unlink3(file).catch(() => {});
|
|
6917
|
+
}
|
|
6918
|
+
};
|
|
6919
|
+
await admit(handle, entry.suggestedFilename, undefined, undefined, 0, randomUUID8(), {
|
|
6920
|
+
claim: () => true,
|
|
6921
|
+
settlement: (guid) => guard.settlement(guid),
|
|
6922
|
+
isSpoolPath: (path11, guid) => guard.isSpoolPath(path11, guid)
|
|
6923
|
+
}).catch(() => {});
|
|
6924
|
+
}
|
|
6925
|
+
guard?.onUnattributed((entry) => {
|
|
6926
|
+
if (stopped)
|
|
6927
|
+
return false;
|
|
6928
|
+
adopt(entry);
|
|
6929
|
+
return true;
|
|
6930
|
+
});
|
|
6478
6931
|
let sweep = setInterval(() => {
|
|
6479
6932
|
sweepExpired();
|
|
6480
6933
|
}, 1e4);
|
|
@@ -6497,13 +6950,13 @@ async function createDataPlugin(access, options) {
|
|
|
6497
6950
|
}
|
|
6498
6951
|
if (op === "create_download") {
|
|
6499
6952
|
const r = resources.get(String(args.downloadId ?? args.fileId ?? args.resourceId));
|
|
6500
|
-
if (!r || !
|
|
6953
|
+
if (!r || !visible(r, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
|
|
6501
6954
|
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
6955
|
return meta(r);
|
|
6503
6956
|
}
|
|
6504
6957
|
if (op === "retry_download_capture") {
|
|
6505
6958
|
const r = resources.get(String(args.downloadId));
|
|
6506
|
-
if (!r || !
|
|
6959
|
+
if (!r || !visible(r, scope) || r.expiresAt <= Date.now() || r.purpose !== "download" || r.state !== "capture-failed" || !r.source)
|
|
6507
6960
|
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
6961
|
startCapture(r).catch(() => {});
|
|
6509
6962
|
return meta(r);
|
|
@@ -6513,7 +6966,7 @@ async function createDataPlugin(access, options) {
|
|
|
6513
6966
|
return status(scope, args.resourceId ?? args.transferId);
|
|
6514
6967
|
}
|
|
6515
6968
|
if (op === "cancel_transfer") {
|
|
6516
|
-
const r =
|
|
6969
|
+
const r = lookup(scope, args.resourceId ?? args.transferId);
|
|
6517
6970
|
if (r.state === "attached")
|
|
6518
6971
|
throw new Error("Attached files retained until document ends");
|
|
6519
6972
|
r.terminalCode = "download_cancelled";
|
|
@@ -6532,15 +6985,15 @@ async function createDataPlugin(access, options) {
|
|
|
6532
6985
|
}
|
|
6533
6986
|
if (op === "list_downloads") {
|
|
6534
6987
|
await sweepExpired();
|
|
6535
|
-
return { files: [...resources.values()].filter((r) =>
|
|
6988
|
+
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
6989
|
}
|
|
6537
6990
|
if (op === "upload_files") {
|
|
6538
6991
|
const ids = args.fileIds;
|
|
6539
6992
|
if (!Array.isArray(ids) || !ids.length || ids.length > 100 || new Set(ids).size !== ids.length)
|
|
6540
6993
|
throw new Error("Invalid staged files");
|
|
6541
|
-
const files = ids.map((id) =>
|
|
6994
|
+
const files = ids.map((id) => lookup(scope, id));
|
|
6542
6995
|
if (files.some((r) => r.purpose !== "upload" || r.state !== "ready" || !r.path))
|
|
6543
|
-
throw new
|
|
6996
|
+
throw new RuntimeFault("upload_not_ready", "Nothing was attached. Wait until browser_transfer_status reports state ready for every fileId (a staged upload whose bytes were sent), then attach again.", true);
|
|
6544
6997
|
const target2 = await access.resolveUploadTarget(String(args.tabId), args, scope);
|
|
6545
6998
|
try {
|
|
6546
6999
|
target2.assertCurrent();
|
|
@@ -6587,51 +7040,29 @@ async function createDataPlugin(access, options) {
|
|
|
6587
7040
|
}
|
|
6588
7041
|
throw new Error("Unsupported data operation");
|
|
6589
7042
|
},
|
|
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
|
-
}
|
|
7043
|
+
async onDownload(download, tabId, owner, generation, downloadId = randomUUID8()) {
|
|
7044
|
+
return admit(download, download.suggestedFilename(), owner.kind === "session" ? owner.scope : undefined, tabId, generation, downloadId, spoolHooks(download));
|
|
7045
|
+
},
|
|
7046
|
+
observeDownload(download) {
|
|
7047
|
+
guard?.observe(download);
|
|
7048
|
+
},
|
|
7049
|
+
async discardDownload(download) {
|
|
7050
|
+
download.cancel().catch(() => {});
|
|
7051
|
+
await cleanupDownload({ download, directory: downloadDirectory, hooks: spoolHooks(download) });
|
|
6621
7052
|
},
|
|
6622
7053
|
async onNavigation(tabId, generation) {
|
|
6623
7054
|
await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
|
|
6624
7055
|
},
|
|
6625
7056
|
async onTabClose(tabId) {
|
|
6626
|
-
await revoke((r) => r.tabId === tabId);
|
|
7057
|
+
await revoke((r) => r.purpose !== "download" && r.tabId === tabId);
|
|
6627
7058
|
},
|
|
6628
7059
|
async onSessionEnd(scope) {
|
|
6629
7060
|
vault.revoke((r) => sameScope(r.scope, scope));
|
|
6630
|
-
await Promise.all([...resources.values()].filter((r) => sameScope(r.scope, scope) && r.state !== "attached").map(remove));
|
|
7061
|
+
await Promise.all([...resources.values()].filter((r) => !r.shared && sameScope(r.scope, scope) && r.state !== "attached").map(remove));
|
|
6631
7062
|
},
|
|
6632
7063
|
async onHandoff(tabId, scope) {
|
|
6633
7064
|
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));
|
|
7065
|
+
await Promise.all([...resources.values()].filter((r) => r.purpose !== "download" && r.tabId === tabId && sameScope(r.scope, scope) && r.state !== "attached").map(remove));
|
|
6635
7066
|
},
|
|
6636
7067
|
async onDisconnect() {
|
|
6637
7068
|
stopped = true;
|
|
@@ -6721,21 +7152,21 @@ function createForwardPlugin(options) {
|
|
|
6721
7152
|
function parse2(args) {
|
|
6722
7153
|
const options = { profiles: [] };
|
|
6723
7154
|
for (let i = 0;i < args.length; i++) {
|
|
6724
|
-
const
|
|
6725
|
-
if (
|
|
7155
|
+
const key2 = args[i];
|
|
7156
|
+
if (key2 === "--ephemeral")
|
|
6726
7157
|
options.ephemeral = true;
|
|
6727
|
-
else if (
|
|
7158
|
+
else if (key2 === "--live-view")
|
|
6728
7159
|
options.liveView = true;
|
|
6729
|
-
else if (
|
|
7160
|
+
else if (key2 === "--profile" || key2 === "--server" || key2 === "--chrome-path") {
|
|
6730
7161
|
if (!args[i + 1] || args[i + 1].startsWith("--"))
|
|
6731
|
-
throw new Error(`Missing ${
|
|
7162
|
+
throw new Error(`Missing ${key2} value`);
|
|
6732
7163
|
const value = args[++i];
|
|
6733
|
-
if (
|
|
7164
|
+
if (key2 === "--profile")
|
|
6734
7165
|
options.profiles.push(value);
|
|
6735
7166
|
else
|
|
6736
|
-
options[
|
|
7167
|
+
options[key2 === "--server" ? "server" : "chrome-path"] = value;
|
|
6737
7168
|
} else
|
|
6738
|
-
throw new Error(`Unknown browser option ${
|
|
7169
|
+
throw new Error(`Unknown browser option ${key2}`);
|
|
6739
7170
|
}
|
|
6740
7171
|
return options;
|
|
6741
7172
|
}
|
|
@@ -6767,7 +7198,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6767
7198
|
for (const signal of signals)
|
|
6768
7199
|
process.on(signal, signalStop);
|
|
6769
7200
|
try {
|
|
6770
|
-
const requestedRoot =
|
|
7201
|
+
const requestedRoot = path11.resolve(installationRoot());
|
|
6771
7202
|
for (const profile of profiles)
|
|
6772
7203
|
assertControlPaths(requestedRoot, controlSocketPath(requestedRoot, profile));
|
|
6773
7204
|
const root = await privateDirectory2(requestedRoot);
|
|
@@ -6796,7 +7227,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6796
7227
|
const server = serverURL(options.server ?? "https://browser-mcp.click");
|
|
6797
7228
|
for (const profile of profiles) {
|
|
6798
7229
|
const controlPath = controlSocketPath(root, profile);
|
|
6799
|
-
const previousSocket = await
|
|
7230
|
+
const previousSocket = await fs11.lstat(controlPath).catch((error) => {
|
|
6800
7231
|
if (error.code !== "ENOENT")
|
|
6801
7232
|
throw controlFailure("local-control", error);
|
|
6802
7233
|
});
|
|
@@ -6830,7 +7261,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6830
7261
|
let starting = true;
|
|
6831
7262
|
let session;
|
|
6832
7263
|
let runtime, relay, local;
|
|
6833
|
-
let stopQuota;
|
|
6834
7264
|
const controlPath = controlSocketPath(root, profile);
|
|
6835
7265
|
let stopControl;
|
|
6836
7266
|
const clients = new Set;
|
|
@@ -6845,7 +7275,6 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6845
7275
|
session?.lifecycle.requestShutdown("owner-close");
|
|
6846
7276
|
await cleanupSteps([
|
|
6847
7277
|
["Relay", () => runtimeCleanup(() => relay?.stop())],
|
|
6848
|
-
["Download quota", () => runtimeCleanup(() => stopQuota?.())],
|
|
6849
7278
|
["Runtime", () => runtimeCleanup(() => runtime?.shutdown())],
|
|
6850
7279
|
["Local control", async () => {
|
|
6851
7280
|
for (const client of clients)
|
|
@@ -6875,21 +7304,19 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6875
7304
|
if (groupSignal.aborted)
|
|
6876
7305
|
groupStop();
|
|
6877
7306
|
let failure, cleanupFailure;
|
|
6878
|
-
let runtimeStage = "
|
|
7307
|
+
let runtimeStage = "pairing";
|
|
6879
7308
|
try {
|
|
6880
7309
|
abort.signal.throwIfAborted();
|
|
6881
7310
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
6882
7311
|
session.lifecycle.ended.then(endSession);
|
|
6883
7312
|
abort.signal.throwIfAborted();
|
|
6884
|
-
stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
|
|
6885
|
-
abort.signal.throwIfAborted();
|
|
6886
7313
|
runtimeStage = "pairing";
|
|
6887
7314
|
const token = await credential(root, server, profile, abort.signal);
|
|
6888
7315
|
abort.signal.throwIfAborted();
|
|
6889
7316
|
runtimeStage = "runtime-setup";
|
|
6890
|
-
const previews =
|
|
7317
|
+
const previews = path11.join(session.runPath, "previews");
|
|
6891
7318
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
6892
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
7319
|
+
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
7320
|
console.error("Download cleanup could not be verified; closing the owned browser to bound private spool retention. No website action was replayed.");
|
|
6894
7321
|
requestStop("owner-close");
|
|
6895
7322
|
} }));
|
|
@@ -6928,7 +7355,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6928
7355
|
return;
|
|
6929
7356
|
} else if (cmd !== "status")
|
|
6930
7357
|
throw new Error("Invalid command");
|
|
6931
|
-
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.
|
|
7358
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.19", protocol: 3 }) + `
|
|
6932
7359
|
`);
|
|
6933
7360
|
})().catch(() => socket.destroy());
|
|
6934
7361
|
});
|