@ricsam/browser-mcp 0.3.14 → 0.3.15
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 +16 -4
- package/dist/{chunk-y9x8c0rq.js → chunk-ts4nynm9.js} +613 -245
- package/dist/main.js +3 -3
- package/package.json +1 -1
|
@@ -15,13 +15,13 @@ import"./chunk-1sjcwr28.js";
|
|
|
15
15
|
|
|
16
16
|
// cli/src/browser/main.ts
|
|
17
17
|
import fs10 from "node:fs/promises";
|
|
18
|
-
import
|
|
18
|
+
import path10 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
23
|
import fs3 from "node:fs/promises";
|
|
24
|
-
import
|
|
24
|
+
import path4 from "node:path";
|
|
25
25
|
import os2 from "node:os";
|
|
26
26
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
27
27
|
|
|
@@ -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.15";
|
|
58
58
|
|
|
59
59
|
// cli/src/browser/chrome-diagnostics.ts
|
|
60
60
|
import { constants } from "node:fs";
|
|
@@ -725,23 +725,48 @@ async function launchOwnedChrome(options) {
|
|
|
725
725
|
// cli/src/browser/recovery.ts
|
|
726
726
|
import fs2 from "node:fs/promises";
|
|
727
727
|
import { constants as constants2 } from "node:fs";
|
|
728
|
-
import
|
|
728
|
+
import path3 from "node:path";
|
|
729
729
|
import os from "node:os";
|
|
730
730
|
import net2 from "node:net";
|
|
731
731
|
import { createHash } from "node:crypto";
|
|
732
732
|
import { execFile } from "node:child_process";
|
|
733
733
|
import { promisify } from "node:util";
|
|
734
|
+
|
|
735
|
+
// cli/src/browser/control-path.ts
|
|
736
|
+
import path2 from "node:path";
|
|
737
|
+
var privateControlPrefix = "c-";
|
|
738
|
+
function assertControlSocketPath(socketPath) {
|
|
739
|
+
const limit = process.platform === "linux" ? 107 : process.platform === "darwin" ? 103 : undefined;
|
|
740
|
+
if (limit === undefined)
|
|
741
|
+
throw new Error("Local browser control is supported only on Linux and macOS");
|
|
742
|
+
if (socketPath.includes("\x00"))
|
|
743
|
+
throw new Error("Local control unavailable; stage=control-path reason=invalid-path. Use a real, private HOME directory without NUL characters.");
|
|
744
|
+
const bytes = Buffer.byteLength(socketPath, "utf8");
|
|
745
|
+
if (bytes > limit)
|
|
746
|
+
throw new Error(`Local control unavailable; stage=control-path reason=path-too-long bytes=${bytes} limit=${limit}. Use a shorter real, private HOME directory for all browser commands; symlink shortcuts are not supported. Before relocating existing data, stop its CLI and Chrome and verify ownership. No lock or socket was removed; do not delete artifacts to bypass this check.`);
|
|
747
|
+
}
|
|
748
|
+
function assertControlPaths(root, publicPath) {
|
|
749
|
+
assertControlSocketPath(publicPath);
|
|
750
|
+
assertControlSocketPath(path2.join(root, `${privateControlPrefix}XXXXXX`, "s"));
|
|
751
|
+
}
|
|
752
|
+
function controlFailure(stage, error) {
|
|
753
|
+
const code = error?.code;
|
|
754
|
+
const reason = typeof code === "string" && ["EACCES", "EPERM", "EADDRINUSE", "EEXIST", "ENOENT", "ECONNREFUSED", "ENAMETOOLONG", "EINVAL", "ENOSPC", "EMFILE", "ENFILE", "ETIMEDOUT"].includes(code) ? code : "operation-failed";
|
|
755
|
+
return new Error(`Local control failed; stage=${stage} reason=${reason}. Check that all browser commands use the same private HOME and profile. If the prior CLI and Chrome have stopped, use browser recover with that profile to verify stale artifacts; never blindly delete locks or sockets. Private error details suppressed.`);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// cli/src/browser/recovery.ts
|
|
734
759
|
function controlSocketPath(root, profile) {
|
|
735
|
-
return
|
|
760
|
+
return path3.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
|
|
736
761
|
}
|
|
737
762
|
var code = (e) => e.code;
|
|
738
763
|
var fail2 = (file, reason) => {
|
|
739
764
|
throw new Error(`Recovery refused: ${reason}: ${file}. Stop the prior host and Chrome, verify ownership and retry browser recover; do not blindly delete artifacts.`);
|
|
740
765
|
};
|
|
741
766
|
async function directories(directory) {
|
|
742
|
-
let cursor =
|
|
743
|
-
for (const part of directory.slice(cursor.length).split(
|
|
744
|
-
cursor =
|
|
767
|
+
let cursor = path3.parse(directory).root;
|
|
768
|
+
for (const part of directory.slice(cursor.length).split(path3.sep).filter(Boolean)) {
|
|
769
|
+
cursor = path3.join(cursor, part);
|
|
745
770
|
const s = await fs2.lstat(cursor);
|
|
746
771
|
if (!s.isDirectory() || s.isSymbolicLink())
|
|
747
772
|
fail2(cursor, "unsafe directory ancestor");
|
|
@@ -793,7 +818,7 @@ async function assertProfileStopped(profile) {
|
|
|
793
818
|
fail2(profile, `possible surviving profile process: PID ${pid}`);
|
|
794
819
|
}
|
|
795
820
|
}
|
|
796
|
-
const singleton =
|
|
821
|
+
const singleton = path3.join(profile, "SingletonLock");
|
|
797
822
|
let s;
|
|
798
823
|
try {
|
|
799
824
|
s = await fs2.lstat(singleton);
|
|
@@ -810,6 +835,7 @@ async function assertProfileStopped(profile) {
|
|
|
810
835
|
dead(Number(match[2]), singleton);
|
|
811
836
|
}
|
|
812
837
|
async function refusedSocket(file) {
|
|
838
|
+
assertControlSocketPath(file);
|
|
813
839
|
await new Promise((resolve2, reject) => {
|
|
814
840
|
const socket = net2.createConnection(file);
|
|
815
841
|
const finish = (error) => {
|
|
@@ -829,11 +855,12 @@ async function recoverProfile(root, name) {
|
|
|
829
855
|
throw new Error("Recovery is supported only on Linux and macOS");
|
|
830
856
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
831
857
|
throw new Error("Profile must be a simple name, not a path");
|
|
832
|
-
root =
|
|
833
|
-
const profile =
|
|
858
|
+
root = path3.resolve(root);
|
|
859
|
+
const profile = path3.join(root, "profiles", name), lock = path3.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
|
|
860
|
+
assertControlSocketPath(socket);
|
|
834
861
|
try {
|
|
835
862
|
await privateDir(root);
|
|
836
|
-
await privateDir(
|
|
863
|
+
await privateDir(path3.join(root, "profiles"));
|
|
837
864
|
await privateDir(profile);
|
|
838
865
|
const original = await artifact(lock), originalSocket = await artifact(socket, true);
|
|
839
866
|
if (!original) {
|
|
@@ -858,7 +885,7 @@ async function recoverProfile(root, name) {
|
|
|
858
885
|
fail2(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
|
|
859
886
|
const validate = async () => {
|
|
860
887
|
await privateDir(root);
|
|
861
|
-
await privateDir(
|
|
888
|
+
await privateDir(path3.join(root, "profiles"));
|
|
862
889
|
await privateDir(profile);
|
|
863
890
|
dead(owner.pid, lock);
|
|
864
891
|
await assertProfileStopped(profile);
|
|
@@ -887,13 +914,13 @@ async function recoverProfile(root, name) {
|
|
|
887
914
|
|
|
888
915
|
// cli/src/browser/lifecycle.ts
|
|
889
916
|
function installationRoot() {
|
|
890
|
-
return
|
|
917
|
+
return path4.join(os2.homedir(), ".browser-mcp");
|
|
891
918
|
}
|
|
892
919
|
async function privateDirectory2(directory) {
|
|
893
|
-
const absolute =
|
|
894
|
-
let cursor =
|
|
895
|
-
for (const piece of absolute.slice(cursor.length).split(
|
|
896
|
-
cursor =
|
|
920
|
+
const absolute = path4.resolve(directory);
|
|
921
|
+
let cursor = path4.parse(absolute).root;
|
|
922
|
+
for (const piece of absolute.slice(cursor.length).split(path4.sep)) {
|
|
923
|
+
cursor = path4.join(cursor, piece);
|
|
897
924
|
try {
|
|
898
925
|
await fs3.mkdir(cursor, { mode: 448 });
|
|
899
926
|
} catch (e) {
|
|
@@ -910,9 +937,9 @@ async function privateDirectory2(directory) {
|
|
|
910
937
|
return absolute;
|
|
911
938
|
}
|
|
912
939
|
async function discoverChrome(override) {
|
|
913
|
-
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
940
|
+
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path4.join(os2.homedir(), "Applications/Google Chrome.app/Contents/MacOS/Google Chrome")] : process.platform === "win32" ? [process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter(Boolean).map((p) => path4.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
|
|
914
941
|
for (const candidate of candidates) {
|
|
915
|
-
if (!
|
|
942
|
+
if (!path4.isAbsolute(candidate))
|
|
916
943
|
throw new Error("Chrome override must be an absolute executable path");
|
|
917
944
|
try {
|
|
918
945
|
const real = await fs3.realpath(candidate), stat = await fs3.stat(real);
|
|
@@ -931,12 +958,12 @@ async function launchDedicated(options = {}) {
|
|
|
931
958
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
932
959
|
throw new Error("Profile must be a simple name, not a path");
|
|
933
960
|
const root = await privateDirectory2(options.root ?? installationRoot());
|
|
934
|
-
const profiles = await privateDirectory2(
|
|
935
|
-
const profile =
|
|
961
|
+
const profiles = await privateDirectory2(path4.join(root, "profiles"));
|
|
962
|
+
const profile = path4.join(profiles, options.ephemeral ? `ephemeral-${randomUUID3()}` : name);
|
|
936
963
|
await privateDirectory2(profile);
|
|
937
964
|
const profileStat = await fs3.lstat(profile);
|
|
938
965
|
options.signal?.throwIfAborted();
|
|
939
|
-
const lockPath =
|
|
966
|
+
const lockPath = path4.join(profile, "runtime.lock"), nonce = randomUUID3(), instanceId = randomUUID3();
|
|
940
967
|
let lock;
|
|
941
968
|
try {
|
|
942
969
|
lock = await fs3.open(lockPath, "wx", 384);
|
|
@@ -954,7 +981,7 @@ async function launchDedicated(options = {}) {
|
|
|
954
981
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
955
982
|
if (options.signal?.aborted)
|
|
956
983
|
onAbort();
|
|
957
|
-
const runPath =
|
|
984
|
+
const runPath = path4.join(profile, `run-${instanceId}`);
|
|
958
985
|
const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
|
|
959
986
|
let context, launched = false, lockWritten = false;
|
|
960
987
|
let chrome;
|
|
@@ -1020,7 +1047,7 @@ async function launchDedicated(options = {}) {
|
|
|
1020
1047
|
lockWritten = true;
|
|
1021
1048
|
await fs3.mkdir(runPath, { mode: 448 });
|
|
1022
1049
|
runStat = await fs3.lstat(runPath);
|
|
1023
|
-
await fs3.writeFile(
|
|
1050
|
+
await fs3.writeFile(path4.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
|
|
1024
1051
|
options.signal?.throwIfAborted();
|
|
1025
1052
|
lifecycle.setStage("discovery");
|
|
1026
1053
|
let executablePath;
|
|
@@ -1058,11 +1085,12 @@ ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
|
|
|
1058
1085
|
|
|
1059
1086
|
// cli/src/browser/control.ts
|
|
1060
1087
|
import fs4 from "node:fs/promises";
|
|
1061
|
-
import
|
|
1088
|
+
import path5 from "node:path";
|
|
1062
1089
|
async function listenControl(server, root, controlPath) {
|
|
1090
|
+
assertControlPaths(root, controlPath);
|
|
1063
1091
|
const rootStat = await fs4.lstat(root);
|
|
1064
|
-
const directory = await fs4.mkdtemp(
|
|
1065
|
-
const dirStat = await fs4.lstat(directory), boundPath =
|
|
1092
|
+
const directory = await fs4.mkdtemp(path5.join(root, privateControlPrefix));
|
|
1093
|
+
const dirStat = await fs4.lstat(directory), boundPath = path5.join(directory, "s");
|
|
1066
1094
|
let socketStat, published = false;
|
|
1067
1095
|
const close = onceAsync(() => cleanupSteps([
|
|
1068
1096
|
["Control listener", async () => {
|
|
@@ -1089,12 +1117,13 @@ async function listenControl(server, root, controlPath) {
|
|
|
1089
1117
|
const stat = await fs4.lstat(directory);
|
|
1090
1118
|
if (await fs4.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
|
|
1091
1119
|
throw new Error(`Control directory ownership changed; retained ${directory}`);
|
|
1092
|
-
await fs4.unlink(
|
|
1120
|
+
await fs4.unlink(path5.join(directory, "ownership.json"));
|
|
1093
1121
|
await fs4.rmdir(directory);
|
|
1094
1122
|
}]
|
|
1095
1123
|
]));
|
|
1096
1124
|
try {
|
|
1097
|
-
await fs4.writeFile(
|
|
1125
|
+
await fs4.writeFile(path5.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
|
|
1126
|
+
assertControlSocketPath(boundPath);
|
|
1098
1127
|
await new Promise((resolve2, reject) => {
|
|
1099
1128
|
server.once("error", reject);
|
|
1100
1129
|
server.listen(boundPath, resolve2);
|
|
@@ -1119,7 +1148,7 @@ ${cleanupError}`);
|
|
|
1119
1148
|
|
|
1120
1149
|
// cli/src/browser/pairing.ts
|
|
1121
1150
|
import fs5 from "node:fs/promises";
|
|
1122
|
-
import
|
|
1151
|
+
import path6 from "node:path";
|
|
1123
1152
|
import { randomBytes, createHash as createHash2 } from "node:crypto";
|
|
1124
1153
|
import { setTimeout as delay } from "node:timers/promises";
|
|
1125
1154
|
function serverURL(raw) {
|
|
@@ -1132,7 +1161,7 @@ function serverURL(raw) {
|
|
|
1132
1161
|
}
|
|
1133
1162
|
async function credential(root, server, profile, signal) {
|
|
1134
1163
|
signal?.throwIfAborted();
|
|
1135
|
-
const filename =
|
|
1164
|
+
const filename = path6.join(root, `credential-${createHash2("sha256").update(`${server}
|
|
1136
1165
|
${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
1137
1166
|
try {
|
|
1138
1167
|
const stat = await fs5.lstat(filename);
|
|
@@ -1234,7 +1263,23 @@ function screenshotPoint(transform, current, delivered, point) {
|
|
|
1234
1263
|
|
|
1235
1264
|
// cli/src/browser/browser-runtime.ts
|
|
1236
1265
|
import fs8 from "node:fs";
|
|
1237
|
-
import
|
|
1266
|
+
import path8 from "node:path";
|
|
1267
|
+
|
|
1268
|
+
// shared/document-url.ts
|
|
1269
|
+
function validateDocumentURL(value) {
|
|
1270
|
+
if (typeof value !== "string" || !value || value.length > 8192 || /[\u0000-\u0020\u007f]/.test(value))
|
|
1271
|
+
throw new Error("url must be an absolute URL of at most 8192 characters; encode whitespace.");
|
|
1272
|
+
let url;
|
|
1273
|
+
try {
|
|
1274
|
+
url = new URL(value);
|
|
1275
|
+
} catch {
|
|
1276
|
+
throw new Error("url must be an absolute URL.");
|
|
1277
|
+
}
|
|
1278
|
+
if (url.username || url.password)
|
|
1279
|
+
throw new Error("url must not contain inline credentials.");
|
|
1280
|
+
if (url.protocol === "javascript:")
|
|
1281
|
+
throw new Error("javascript: is script execution, not document navigation; use browser_run_js with explicit intent.");
|
|
1282
|
+
}
|
|
1238
1283
|
|
|
1239
1284
|
// cli/src/browser/upload-input.ts
|
|
1240
1285
|
var BROWSER_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
@@ -1692,6 +1737,8 @@ function preflightBrowserInput(action, raw) {
|
|
|
1692
1737
|
}
|
|
1693
1738
|
if (action === "stop_port_forward" && (typeof input.forwardId !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,199}$/.test(input.forwardId)))
|
|
1694
1739
|
throw new Error("stop_port_forward requires a valid forwardId.");
|
|
1740
|
+
if ((action === "open_tab" || action === "navigate") && input.url !== undefined)
|
|
1741
|
+
validateDocumentURL(input.url);
|
|
1695
1742
|
if (action === "set_viewport")
|
|
1696
1743
|
parseViewportInput(input);
|
|
1697
1744
|
if (action === "read_page")
|
|
@@ -1737,7 +1784,7 @@ function preflightBrowserInput(action, raw) {
|
|
|
1737
1784
|
|
|
1738
1785
|
// cli/src/browser/upload-store.ts
|
|
1739
1786
|
import fs6 from "node:fs";
|
|
1740
|
-
import
|
|
1787
|
+
import path7 from "node:path";
|
|
1741
1788
|
import { createHash as createHash3 } from "node:crypto";
|
|
1742
1789
|
class BrowserUploadStore {
|
|
1743
1790
|
releaseTarget;
|
|
@@ -1748,7 +1795,7 @@ class BrowserUploadStore {
|
|
|
1748
1795
|
}) {
|
|
1749
1796
|
this.releaseTarget = releaseTarget;
|
|
1750
1797
|
fs6.mkdirSync(root, { recursive: true, mode: 448 });
|
|
1751
|
-
this.directory = fs6.mkdtempSync(
|
|
1798
|
+
this.directory = fs6.mkdtempSync(path7.join(root, "run-"));
|
|
1752
1799
|
}
|
|
1753
1800
|
begin(id, tabId, files, target2) {
|
|
1754
1801
|
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
|
|
@@ -1756,12 +1803,12 @@ class BrowserUploadStore {
|
|
|
1756
1803
|
if (!Array.isArray(files) || files.length === 0 || files.length > 100)
|
|
1757
1804
|
throw new Error("Upload requires between 1 and 100 files.");
|
|
1758
1805
|
const metadata2 = files.map(validateUploadFile);
|
|
1759
|
-
const directory = fs6.mkdtempSync(
|
|
1806
|
+
const directory = fs6.mkdtempSync(path7.join(this.directory, "upload-"));
|
|
1760
1807
|
try {
|
|
1761
1808
|
const staged = metadata2.map((file, index) => {
|
|
1762
|
-
const parent =
|
|
1809
|
+
const parent = path7.join(directory, String(index));
|
|
1763
1810
|
fs6.mkdirSync(parent, { mode: 448 });
|
|
1764
|
-
const filePath =
|
|
1811
|
+
const filePath = path7.join(parent, file.filename);
|
|
1765
1812
|
fs6.closeSync(fs6.openSync(filePath, "wx", 384));
|
|
1766
1813
|
return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
|
|
1767
1814
|
});
|
|
@@ -1916,8 +1963,8 @@ function captureInUtilityWorld({ elements, injected }, options) {
|
|
|
1916
1963
|
line += ` [ref=${node.ref}]`;
|
|
1917
1964
|
if (node.box)
|
|
1918
1965
|
line += ` [box=${[node.box.x, node.box.y, node.box.width, node.box.height].join(",")}]`;
|
|
1919
|
-
if (node.
|
|
1920
|
-
line += `: ${JSON.stringify(node.
|
|
1966
|
+
if (node.text !== undefined)
|
|
1967
|
+
line += `: ${JSON.stringify(node.text)}`;
|
|
1921
1968
|
lines.push(line);
|
|
1922
1969
|
for (const child of node.children || [])
|
|
1923
1970
|
visit(child, depth + 1);
|
|
@@ -2140,7 +2187,7 @@ function renderSnapshot(document2, input) {
|
|
|
2140
2187
|
error: `Scope matched ${document2.scopeMatchCount} elements. Use query to inspect matches, then choose a unique scope/ref.`,
|
|
2141
2188
|
scopeMatchCount: document2.scopeMatchCount
|
|
2142
2189
|
} : input.snapshotId && input.snapshotId !== snapshotId ? { code: "snapshot_changed", error: "The observation changed. Restart the search at offset 0; old offsets are not reused." } : undefined;
|
|
2143
|
-
const context = { frameContext: input.frames, scope: input.scope ?? null };
|
|
2190
|
+
const context = { frameContext: input.frames, scope: input.scope ?? null, query: input.query ?? null };
|
|
2144
2191
|
if (failure)
|
|
2145
2192
|
return { ...failure, ...context, text: "", complete: false, truncated: false, snapshotId };
|
|
2146
2193
|
const queryRefs = new Set(document2.matchRefs);
|
|
@@ -2207,6 +2254,8 @@ function renderSnapshot(document2, input) {
|
|
|
2207
2254
|
const nextOffset = input.query && input.offset + returnedMatches < allMatches.length ? input.offset + returnedMatches : null;
|
|
2208
2255
|
const complete = !depthOmitted && !characterLimited && !document2.unavailableFrames.length && (!input.query || !unrepresentedMatches && nextOffset === null && input.offset === 0);
|
|
2209
2256
|
const notes = [];
|
|
2257
|
+
if (input.query && document2.matchCount === 0)
|
|
2258
|
+
notes.push("No visible elements matched the supplied query. This is a search result, not a document outline; omit query to read the outline, or correct the intended locator.");
|
|
2210
2259
|
if (depthOmitted)
|
|
2211
2260
|
notes.push(`${depthOmitted} outline lines omitted by depth ${input.depth}. Read a scope/ref, search with query, or omit depth.`);
|
|
2212
2261
|
if (characterLimited)
|
|
@@ -3393,25 +3442,27 @@ class RuntimeFault extends Error {
|
|
|
3393
3442
|
}
|
|
3394
3443
|
var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
|
|
3395
3444
|
var messages = {
|
|
3396
|
-
unsupported_target: "
|
|
3445
|
+
unsupported_target: "Chrome does not expose the interface required by this operation on this target.",
|
|
3446
|
+
browser_operation_unsupported: "Chrome reported that this operation or protocol method is not supported on this target.",
|
|
3397
3447
|
tab_closed: "The tab is closed or detached.",
|
|
3398
3448
|
runtime_disconnected: "The runtime or browser connection ended.",
|
|
3399
3449
|
context_destroyed: "The document execution context changed during the operation.",
|
|
3400
3450
|
execution_timeout: "The browser operation exceeded its internal wait budget.",
|
|
3401
3451
|
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3402
3452
|
transfer_failed: "The file transfer failed or its completion could not be confirmed.",
|
|
3453
|
+
resource_unavailable: "The requested resource is unavailable. No download link was created.",
|
|
3403
3454
|
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3404
3455
|
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3405
3456
|
};
|
|
3406
3457
|
function failureFor(error, op, operationId, stage) {
|
|
3407
3458
|
const text = error instanceof Error ? error.message : "";
|
|
3408
|
-
let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
|
|
3459
|
+
let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : /Protocol error.*(?:not supported|not allowed|wasn't found|Method not found)|Printing is not available|not available in an isolated browser context/i.test(text) ? "browser_operation_unsupported" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
|
|
3409
3460
|
const observation = OBSERVATION_OPERATIONS.has(op);
|
|
3410
3461
|
const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
|
|
3411
|
-
const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
|
|
3462
|
+
const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
|
|
3412
3463
|
const diagnosticId = randomUUID4();
|
|
3413
3464
|
console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
|
|
3414
|
-
return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: "settled", cancellationConfirmed: false } };
|
|
3465
|
+
return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
|
|
3415
3466
|
}
|
|
3416
3467
|
|
|
3417
3468
|
// cli/src/browser/browser-runtime.ts
|
|
@@ -3540,22 +3591,22 @@ class BrowserRuntime {
|
|
|
3540
3591
|
return id;
|
|
3541
3592
|
}
|
|
3542
3593
|
safeDownloadFilename(suggestedFilename) {
|
|
3543
|
-
const basename =
|
|
3594
|
+
const basename = path8.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
3544
3595
|
if (!basename || basename === "." || basename === "..")
|
|
3545
3596
|
return "download";
|
|
3546
|
-
const extension =
|
|
3547
|
-
let stem = basename.slice(0, basename.length -
|
|
3597
|
+
const extension = path8.extname(basename).slice(0, 30);
|
|
3598
|
+
let stem = basename.slice(0, basename.length - path8.extname(basename).length) || "download";
|
|
3548
3599
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
3549
3600
|
stem = stem.slice(0, -1);
|
|
3550
3601
|
return `${stem || "download"}${extension}`;
|
|
3551
3602
|
}
|
|
3552
3603
|
availableDownloadPath(suggestedFilename) {
|
|
3553
3604
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
3554
|
-
const extension =
|
|
3605
|
+
const extension = path8.extname(filename);
|
|
3555
3606
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
3556
3607
|
for (let suffix = 1;; suffix += 1) {
|
|
3557
3608
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
3558
|
-
const candidatePath =
|
|
3609
|
+
const candidatePath = path8.join(this.downloadsPath, candidate);
|
|
3559
3610
|
if (!fs8.existsSync(candidatePath))
|
|
3560
3611
|
return candidatePath;
|
|
3561
3612
|
}
|
|
@@ -3564,7 +3615,7 @@ class BrowserRuntime {
|
|
|
3564
3615
|
const failure = await download.failure();
|
|
3565
3616
|
if (failure)
|
|
3566
3617
|
throw new Error(failure);
|
|
3567
|
-
const temporary =
|
|
3618
|
+
const temporary = path8.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
3568
3619
|
let targetPath;
|
|
3569
3620
|
try {
|
|
3570
3621
|
await download.saveAs(temporary);
|
|
@@ -3573,9 +3624,9 @@ class BrowserRuntime {
|
|
|
3573
3624
|
} finally {
|
|
3574
3625
|
fs8.rmSync(temporary, { force: true });
|
|
3575
3626
|
}
|
|
3576
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3627
|
+
process.stdout.write(`[r5d-browser] downloaded ${path8.basename(targetPath)}
|
|
3577
3628
|
`);
|
|
3578
|
-
return { downloadId: this.downloadId(
|
|
3629
|
+
return { downloadId: this.downloadId(path8.basename(targetPath)) };
|
|
3579
3630
|
}
|
|
3580
3631
|
downloadId(filename) {
|
|
3581
3632
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -3584,10 +3635,10 @@ class BrowserRuntime {
|
|
|
3584
3635
|
if (typeof downloadId !== "string" || !downloadId)
|
|
3585
3636
|
throw new Error("downloadId is required.");
|
|
3586
3637
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
3587
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3638
|
+
if (this.downloadId(filename) !== downloadId || filename !== path8.basename(filename) || filename.includes("\x00")) {
|
|
3588
3639
|
throw new Error("Invalid downloadId.");
|
|
3589
3640
|
}
|
|
3590
|
-
const filePath =
|
|
3641
|
+
const filePath = path8.join(this.downloadsPath, filename);
|
|
3591
3642
|
let stats;
|
|
3592
3643
|
try {
|
|
3593
3644
|
stats = fs8.lstatSync(filePath);
|
|
@@ -3865,6 +3916,8 @@ class BrowserRuntime {
|
|
|
3865
3916
|
async dispatch(action, input, execution) {
|
|
3866
3917
|
if (typeof input.tabId === "string" && action !== "close_tab")
|
|
3867
3918
|
await this.guardPage?.(this.page(input.tabId));
|
|
3919
|
+
if (typeof input.tabId !== "string")
|
|
3920
|
+
execution.beforeDispatch?.();
|
|
3868
3921
|
if (action === "upload_abort") {
|
|
3869
3922
|
this.uploads.abort(input.uploadId, input.tabId);
|
|
3870
3923
|
return { aborted: true };
|
|
@@ -3915,6 +3968,7 @@ class BrowserRuntime {
|
|
|
3915
3968
|
input = { ...input, ...input.from ? { from: map(input.from), to: map(input.to) } : map({ x: Number(input.x), y: Number(input.y) }) };
|
|
3916
3969
|
delete input.screenshot;
|
|
3917
3970
|
}
|
|
3971
|
+
execution.beforeDispatch?.();
|
|
3918
3972
|
if (!["screenshot", "read_page", "inspect", "events", "diagnostics", "capabilities"].includes(action))
|
|
3919
3973
|
this.screenshots.delete(tabId);
|
|
3920
3974
|
if (action === "mouse_click" || action === "keyboard") {
|
|
@@ -3935,7 +3989,9 @@ class BrowserRuntime {
|
|
|
3935
3989
|
const webmcp = await this.webmcp.get(page).list();
|
|
3936
3990
|
return {
|
|
3937
3991
|
tabId,
|
|
3938
|
-
observation:
|
|
3992
|
+
observation: null,
|
|
3993
|
+
screenshot: { supported: null, requires: "Chrome screenshot and document geometry APIs" },
|
|
3994
|
+
runJs: { supported: null, requires: "An execution context exposed by Chrome" },
|
|
3939
3995
|
batch: { maxSteps: 8, maxBudgetMs: 30000, adaptive: false },
|
|
3940
3996
|
diagnostics: true,
|
|
3941
3997
|
dialogs: true,
|
|
@@ -3952,6 +4008,7 @@ class BrowserRuntime {
|
|
|
3952
4008
|
requires: "Origin permission and browser focus; permissions are never auto-granted"
|
|
3953
4009
|
},
|
|
3954
4010
|
export: {
|
|
4011
|
+
supported: null,
|
|
3955
4012
|
formats: ["text", "html", "pdf", "assets"],
|
|
3956
4013
|
pdf: "Requires Chrome printToPDF",
|
|
3957
4014
|
assets: "Only already observed, uncompressed image/font/CSS responses with a bounded Content-Length"
|
|
@@ -4063,7 +4120,7 @@ class BrowserRuntime {
|
|
|
4063
4120
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
4064
4121
|
fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
4065
4122
|
return {
|
|
4066
|
-
downloadId: this.downloadId(
|
|
4123
|
+
downloadId: this.downloadId(path8.basename(target2)),
|
|
4067
4124
|
filename: file.filename,
|
|
4068
4125
|
size: file.bytes.length,
|
|
4069
4126
|
mimeType: file.mimeType
|
|
@@ -4540,11 +4597,13 @@ class NativeRuntime {
|
|
|
4540
4597
|
plugins = [];
|
|
4541
4598
|
owners = new Map;
|
|
4542
4599
|
generations = new Map;
|
|
4543
|
-
|
|
4600
|
+
tracking = new WeakMap;
|
|
4544
4601
|
ended = new Set;
|
|
4545
4602
|
epochs = new Map;
|
|
4546
4603
|
controllers = new Map;
|
|
4547
4604
|
disconnected = false;
|
|
4605
|
+
connectionEpoch = 0;
|
|
4606
|
+
downloadAdmissionEpoch = 0;
|
|
4548
4607
|
operations = new Map;
|
|
4549
4608
|
hooks = Promise.resolve();
|
|
4550
4609
|
browserId;
|
|
@@ -4553,7 +4612,7 @@ class NativeRuntime {
|
|
|
4553
4612
|
this.instanceId = instanceId;
|
|
4554
4613
|
this.serverOrigin = serverOrigin;
|
|
4555
4614
|
installCancellation(context);
|
|
4556
|
-
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), (page) => this.
|
|
4615
|
+
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page));
|
|
4557
4616
|
context.on("page", (page) => {
|
|
4558
4617
|
this.track(page);
|
|
4559
4618
|
});
|
|
@@ -4565,14 +4624,20 @@ class NativeRuntime {
|
|
|
4565
4624
|
this.disconnected = true;
|
|
4566
4625
|
});
|
|
4567
4626
|
}
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4627
|
+
track(page) {
|
|
4628
|
+
let pending = this.tracking.get(page);
|
|
4629
|
+
if (!pending) {
|
|
4630
|
+
pending = this.trackPage(page);
|
|
4631
|
+
this.tracking.set(page, pending);
|
|
4632
|
+
}
|
|
4633
|
+
return pending;
|
|
4634
|
+
}
|
|
4635
|
+
async trackPage(page) {
|
|
4572
4636
|
const id = await this.engine.idFor(page);
|
|
4573
4637
|
this.generations.set(id, 0);
|
|
4574
4638
|
const opener = await page.opener();
|
|
4575
4639
|
if (opener) {
|
|
4640
|
+
await this.track(opener);
|
|
4576
4641
|
const openerId = await this.engine.idFor(opener), owner = this.owners.get(openerId);
|
|
4577
4642
|
if (owner)
|
|
4578
4643
|
this.owners.set(id, { ...owner });
|
|
@@ -4586,6 +4651,7 @@ class NativeRuntime {
|
|
|
4586
4651
|
});
|
|
4587
4652
|
});
|
|
4588
4653
|
page.on("close", () => {
|
|
4654
|
+
this.downloadAdmissionEpoch++;
|
|
4589
4655
|
this.generations.delete(id);
|
|
4590
4656
|
this.owners.delete(id);
|
|
4591
4657
|
this.enqueue(async () => {
|
|
@@ -4595,9 +4661,15 @@ class NativeRuntime {
|
|
|
4595
4661
|
});
|
|
4596
4662
|
}
|
|
4597
4663
|
async download(download, page, downloadId) {
|
|
4664
|
+
const admissionEpoch = this.downloadAdmissionEpoch, connectionEpoch = this.connectionEpoch;
|
|
4665
|
+
await this.track(page);
|
|
4598
4666
|
const id = await this.engine.idFor(page), scope = this.owners.get(id);
|
|
4599
|
-
|
|
4600
|
-
|
|
4667
|
+
try {
|
|
4668
|
+
if (!scope || page.isClosed() || admissionEpoch !== this.downloadAdmissionEpoch || connectionEpoch !== this.connectionEpoch)
|
|
4669
|
+
throw new Error("Download ownership changed");
|
|
4670
|
+
this.validateScope(scope);
|
|
4671
|
+
} catch {
|
|
4672
|
+
await download.cancel().catch(() => {});
|
|
4601
4673
|
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4602
4674
|
}
|
|
4603
4675
|
const handler = this.plugins.find((p) => p.onDownload);
|
|
@@ -4615,51 +4687,15 @@ class NativeRuntime {
|
|
|
4615
4687
|
if (!scope || Object.values(scope).some((v) => typeof v !== "string" || !v) || !scope.browserId || !scope.tokenId || !scope.sessionKey || scope.instanceId !== this.instanceId || this.browserId && scope.browserId !== this.browserId || this.ended.has(scopeKey(scope)) || this.disconnected)
|
|
4616
4688
|
throw new Error("Invalid or revoked runtime scope");
|
|
4617
4689
|
}
|
|
4618
|
-
|
|
4619
|
-
if (value === "about:blank" || value === "about:srcdoc")
|
|
4620
|
-
return true;
|
|
4621
|
-
try {
|
|
4622
|
-
const u = new URL(value);
|
|
4623
|
-
return ["https:", "http:"].includes(u.protocol) && u.origin !== this.serverOrigin && !u.username && !u.password;
|
|
4624
|
-
} catch {
|
|
4625
|
-
return false;
|
|
4626
|
-
}
|
|
4627
|
-
}
|
|
4628
|
-
assertPage(page) {
|
|
4690
|
+
assertPageAvailable(page) {
|
|
4629
4691
|
if (page.isClosed())
|
|
4630
4692
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4631
|
-
if (page.frames().some((f) => !this.allowURL(f.url())))
|
|
4632
|
-
throw new RuntimeFault("unsupported_target", "Call browser_capabilities. For documents use the website download, browser_list_downloads, then browser_create_download; do not screenshot or evaluate an internal viewer.", true);
|
|
4633
|
-
}
|
|
4634
|
-
async assertPageDeep(page) {
|
|
4635
|
-
this.assertPage(page);
|
|
4636
|
-
const visited = new Set;
|
|
4637
|
-
let opener = await page.opener();
|
|
4638
|
-
while (opener && !visited.has(opener)) {
|
|
4639
|
-
visited.add(opener);
|
|
4640
|
-
this.assertPage(opener);
|
|
4641
|
-
opener = await opener.opener();
|
|
4642
|
-
}
|
|
4643
|
-
const cdp = await this.context.newCDPSession(page);
|
|
4644
|
-
try {
|
|
4645
|
-
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
4646
|
-
const check = (tree) => {
|
|
4647
|
-
const origin = tree.frame.securityOrigin;
|
|
4648
|
-
if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
|
|
4649
|
-
throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
|
|
4650
|
-
for (const child of tree.childFrames ?? [])
|
|
4651
|
-
check(child);
|
|
4652
|
-
};
|
|
4653
|
-
check(frameTree);
|
|
4654
|
-
} finally {
|
|
4655
|
-
await cdp.detach();
|
|
4656
|
-
}
|
|
4657
4693
|
}
|
|
4658
4694
|
async resolveTarget(tabId, scope, frames = []) {
|
|
4659
4695
|
this.validateScope(scope);
|
|
4660
|
-
const page = this.claimPage(tabId, scope);
|
|
4696
|
+
const page = await this.claimPage(tabId, scope);
|
|
4661
4697
|
await this.track(page);
|
|
4662
|
-
|
|
4698
|
+
this.assertPageAvailable(page);
|
|
4663
4699
|
let frame = page.mainFrame();
|
|
4664
4700
|
for (const selector of frames) {
|
|
4665
4701
|
const locator = frame.locator(selector);
|
|
@@ -4676,7 +4712,7 @@ class NativeRuntime {
|
|
|
4676
4712
|
const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4677
4713
|
const assertCurrent = () => {
|
|
4678
4714
|
this.validateScope(scope);
|
|
4679
|
-
this.
|
|
4715
|
+
this.assertPageAvailable(page);
|
|
4680
4716
|
if ((this.epochs.get(scopeKey(scope)) ?? 0) !== scopeEpoch || frame.isDetached() || this.generations.get(tabId) !== generation || scopeKey(this.owners.get(tabId)) !== scopeKey(scope))
|
|
4681
4717
|
throw new Error("Stale document or scope");
|
|
4682
4718
|
};
|
|
@@ -4690,7 +4726,7 @@ class NativeRuntime {
|
|
|
4690
4726
|
throw new Error("File input unavailable");
|
|
4691
4727
|
try {
|
|
4692
4728
|
const frame = await element.ownerFrame();
|
|
4693
|
-
if (!frame ||
|
|
4729
|
+
if (!frame || frame.isDetached())
|
|
4694
4730
|
throw new Error("File input frame unavailable");
|
|
4695
4731
|
const valid = await element.evaluate((el) => el instanceof HTMLInputElement && el.type === "file" && !el.webkitdirectory && el.isConnected);
|
|
4696
4732
|
target2.assertCurrent();
|
|
@@ -4712,7 +4748,7 @@ class NativeRuntime {
|
|
|
4712
4748
|
events.diagnosticsSuppressed = false;
|
|
4713
4749
|
}
|
|
4714
4750
|
}
|
|
4715
|
-
claimPage(tabId, scope) {
|
|
4751
|
+
async claimPage(tabId, scope) {
|
|
4716
4752
|
this.validateScope(scope);
|
|
4717
4753
|
let page;
|
|
4718
4754
|
try {
|
|
@@ -4720,17 +4756,52 @@ class NativeRuntime {
|
|
|
4720
4756
|
} catch {
|
|
4721
4757
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4722
4758
|
}
|
|
4759
|
+
await this.track(page);
|
|
4760
|
+
this.validateScope(scope);
|
|
4723
4761
|
const owner = this.owners.get(tabId);
|
|
4724
4762
|
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4725
4763
|
throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
|
|
4726
4764
|
this.owners.set(tabId, { ...scope });
|
|
4727
4765
|
return page;
|
|
4728
4766
|
}
|
|
4729
|
-
targetCapabilities(tabId, scope) {
|
|
4730
|
-
const page = this.claimPage(tabId, scope);
|
|
4731
|
-
const
|
|
4732
|
-
|
|
4733
|
-
|
|
4767
|
+
async targetCapabilities(tabId, scope) {
|
|
4768
|
+
const page = await this.claimPage(tabId, scope);
|
|
4769
|
+
const urls = page.frames().map((frame) => frame.url());
|
|
4770
|
+
let pdf = urls.some((url) => url.startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/"));
|
|
4771
|
+
let frameMetadataAvailable = false;
|
|
4772
|
+
const cdp = await this.context.newCDPSession(page).catch(() => {
|
|
4773
|
+
return;
|
|
4774
|
+
});
|
|
4775
|
+
try {
|
|
4776
|
+
if (cdp) {
|
|
4777
|
+
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
4778
|
+
const visit = (tree) => {
|
|
4779
|
+
pdf ||= tree.frame.mimeType === "application/pdf";
|
|
4780
|
+
for (const child of tree.childFrames ?? [])
|
|
4781
|
+
visit(child);
|
|
4782
|
+
};
|
|
4783
|
+
visit(frameTree);
|
|
4784
|
+
frameMetadataAvailable = true;
|
|
4785
|
+
}
|
|
4786
|
+
} catch {} finally {
|
|
4787
|
+
await cdp?.detach().catch(() => {
|
|
4788
|
+
return;
|
|
4789
|
+
});
|
|
4790
|
+
}
|
|
4791
|
+
const possiblePdf = pdf || /\.pdf(?:[?#]|$)/i.test(page.url());
|
|
4792
|
+
const internal = urls.some((url) => /^(?:chrome(?:-untrusted|-extension)?|devtools|about):/.test(url) && !/^about:(?:blank|srcdoc)(?:[?#]|$)/.test(url));
|
|
4793
|
+
return {
|
|
4794
|
+
targetKind: pdf ? "pdf_viewer" : possiblePdf ? "possible_pdf" : internal ? "internal" : /^https?:/.test(page.url()) ? "web" : "document",
|
|
4795
|
+
documentAccess: "owner_authorized",
|
|
4796
|
+
targetPolicyRestricted: false,
|
|
4797
|
+
pageToolsSupported: null,
|
|
4798
|
+
capabilityProbe: "metadata_and_webmcp",
|
|
4799
|
+
frameMetadataAvailable,
|
|
4800
|
+
pdfDetected: pdf,
|
|
4801
|
+
requiresDocumentTools: possiblePdf ? true : null,
|
|
4802
|
+
supportNote: "No URL, frame or opener policy denies this target. null means unprobed; each operation depends on the interfaces Chrome exposes, not the document scheme. Tab navigation does not require document inspection.",
|
|
4803
|
+
...possiblePdf ? { retrieval: { tool: "browser_create_download", source: "browser_list_downloads" }, recovery: "PDF viewer DOM may expose only viewer controls, not document text. Use screenshots for rendered content where Chrome supports them. For original bytes use the viewer or website download control, then browser_list_downloads and browser_create_download. Text/HTML export describes the viewer; PDF export prints the page, not the original file. No cookies are forwarded or URLs replayed automatically." } : {}
|
|
4804
|
+
};
|
|
4734
4805
|
}
|
|
4735
4806
|
async closeBlockedTab(tabId, scope, operationId) {
|
|
4736
4807
|
this.validateScope(scope);
|
|
@@ -4744,7 +4815,33 @@ class NativeRuntime {
|
|
|
4744
4815
|
this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
|
|
4745
4816
|
return { closed: true };
|
|
4746
4817
|
}
|
|
4747
|
-
|
|
4818
|
+
admissionGuard(args, scope) {
|
|
4819
|
+
const epoch = this.scopeEpoch(scope), connectionEpoch = this.connectionEpoch;
|
|
4820
|
+
const tabId = typeof args.tabId === "string" ? args.tabId : undefined;
|
|
4821
|
+
const page = tabId ? this.engine.page(tabId) : undefined;
|
|
4822
|
+
const generation = tabId ? this.generations.get(tabId) : undefined;
|
|
4823
|
+
return (checkDocument = true) => {
|
|
4824
|
+
if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
|
|
4825
|
+
throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
|
|
4826
|
+
if (tabId) {
|
|
4827
|
+
let current2;
|
|
4828
|
+
try {
|
|
4829
|
+
current2 = this.engine.page(tabId);
|
|
4830
|
+
} catch {
|
|
4831
|
+
throw new RuntimeFault("tab_closed", "Select an open tab before submitting a new request.", true);
|
|
4832
|
+
}
|
|
4833
|
+
if (current2 !== page || checkDocument && this.generations.get(tabId) !== generation)
|
|
4834
|
+
throw new RuntimeFault("stale_queued_target", "The target document changed while waiting. Observe it again before submitting a new request.", true);
|
|
4835
|
+
const owner = this.owners.get(tabId);
|
|
4836
|
+
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4837
|
+
throw new RuntimeFault("scope_rejected", "The target is no longer owned by this session.", true);
|
|
4838
|
+
}
|
|
4839
|
+
};
|
|
4840
|
+
}
|
|
4841
|
+
cancelOperation(operationId) {
|
|
4842
|
+
this.operations.get(operationId)?.abort(new Error("Runtime operation interrupted; page effects remain uncertain"));
|
|
4843
|
+
}
|
|
4844
|
+
async execute(op, args, scope, operationId, beforeDispatch) {
|
|
4748
4845
|
if (op === "session_end") {
|
|
4749
4846
|
await this.endSession(scope);
|
|
4750
4847
|
return { ended: true };
|
|
@@ -4758,7 +4855,7 @@ class NativeRuntime {
|
|
|
4758
4855
|
set.add(controller);
|
|
4759
4856
|
this.operations.set(operationId, controller);
|
|
4760
4857
|
try {
|
|
4761
|
-
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
|
|
4858
|
+
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch));
|
|
4762
4859
|
} finally {
|
|
4763
4860
|
this.operations.delete(operationId);
|
|
4764
4861
|
set.delete(controller);
|
|
@@ -4766,42 +4863,38 @@ class NativeRuntime {
|
|
|
4766
4863
|
this.controllers.delete(key);
|
|
4767
4864
|
}
|
|
4768
4865
|
}
|
|
4769
|
-
async executeInner(op, args, scope, operationId) {
|
|
4866
|
+
async executeInner(op, args, scope, operationId, beforeDispatch) {
|
|
4867
|
+
let dispatched = false;
|
|
4868
|
+
const begin = () => {
|
|
4869
|
+
this.validateScope(scope);
|
|
4870
|
+
beforeDispatch?.();
|
|
4871
|
+
dispatched = true;
|
|
4872
|
+
};
|
|
4770
4873
|
await this.hooks;
|
|
4771
4874
|
this.validateScope(scope);
|
|
4772
|
-
if (args.url !== undefined && !this.allowURL(String(args.url)))
|
|
4773
|
-
throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
|
|
4774
|
-
if (op === "capabilities" && typeof args.tabId === "string") {
|
|
4775
|
-
const target2 = this.targetCapabilities(args.tabId, scope);
|
|
4776
|
-
if (!target2.pageToolsSupported || target2.pdfDetected)
|
|
4777
|
-
return { tabId: args.tabId, ...target2, observation: target2.pageToolsSupported ? null : false, screenshot: { supported: target2.pageToolsSupported ? null : false }, runJs: { supported: target2.pageToolsSupported ? null : false }, export: { supported: target2.pageToolsSupported ? null : false }, capabilityProbe: "metadata_only" };
|
|
4778
|
-
}
|
|
4779
4875
|
if (typeof args.tabId === "string") {
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4783
|
-
await this.resolveTarget(args.tabId, scope);
|
|
4876
|
+
const page = await this.claimPage(args.tabId, scope);
|
|
4877
|
+
await this.track(page);
|
|
4878
|
+
this.assertPageAvailable(page);
|
|
4784
4879
|
}
|
|
4785
|
-
if (op === "batch" && Array.isArray(args.steps))
|
|
4786
|
-
for (const step of args.steps) {
|
|
4787
|
-
if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
|
|
4788
|
-
throw new Error("Unsupported batch navigation origin");
|
|
4789
|
-
}
|
|
4790
4880
|
if (op === "session_end") {
|
|
4791
4881
|
await this.endSession(scope);
|
|
4792
4882
|
return { ended: true };
|
|
4793
4883
|
}
|
|
4794
4884
|
if (op === "release_tab") {
|
|
4795
4885
|
const tabId = String(args.tabId);
|
|
4796
|
-
|
|
4797
|
-
|
|
4886
|
+
begin();
|
|
4887
|
+
this.downloadAdmissionEpoch++;
|
|
4798
4888
|
this.owners.delete(tabId);
|
|
4799
4889
|
this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
|
|
4890
|
+
for (const p of this.plugins)
|
|
4891
|
+
await p.onHandoff?.(tabId, scope);
|
|
4800
4892
|
return { released: true, tabId };
|
|
4801
4893
|
}
|
|
4802
4894
|
const operationEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4803
4895
|
const plugin = this.plugins.find((p) => p.operations.includes(op));
|
|
4804
4896
|
if (plugin) {
|
|
4897
|
+
begin();
|
|
4805
4898
|
if (op === "cancel_transfer" && args.eventId && args.tabId)
|
|
4806
4899
|
return this.engine.execute("cancel_transfer", args, { operationId });
|
|
4807
4900
|
return plugin.execute(op, args, scope);
|
|
@@ -4809,23 +4902,25 @@ class NativeRuntime {
|
|
|
4809
4902
|
if (!BROWSER_OPERATIONS.includes(op))
|
|
4810
4903
|
throw new Error("Unsupported operation");
|
|
4811
4904
|
if (op === "list_tabs") {
|
|
4905
|
+
begin();
|
|
4812
4906
|
const tabs = await this.engine.listTabs();
|
|
4813
|
-
|
|
4907
|
+
await Promise.all(this.context.pages().map((page) => this.track(page)));
|
|
4908
|
+
this.validateScope(scope);
|
|
4909
|
+
return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
|
|
4814
4910
|
}
|
|
4815
4911
|
try {
|
|
4816
|
-
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
|
|
4912
|
+
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin });
|
|
4913
|
+
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4914
|
+
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4915
|
+
const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
|
|
4817
4916
|
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4818
4917
|
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4819
|
-
if (typeof args.tabId === "string" && op !== "close_tab")
|
|
4820
|
-
await this.assertPageDeep(this.engine.page(args.tabId));
|
|
4821
4918
|
if (op === "open_tab" && typeof result?.tab?.tabId === "string")
|
|
4822
4919
|
this.owners.set(result.tab.tabId, { ...scope });
|
|
4823
|
-
|
|
4824
|
-
return { ...result, ...this.targetCapabilities(args.tabId, scope) };
|
|
4825
|
-
return result;
|
|
4920
|
+
return target2 ? { ...result, ...target2 } : result;
|
|
4826
4921
|
} catch (error) {
|
|
4827
4922
|
if (error instanceof RuntimeFault)
|
|
4828
|
-
throw new RuntimeFault(error.code, error.recovery,
|
|
4923
|
+
throw new RuntimeFault(error.code, error.recovery, !dispatched && error.beforeDispatch);
|
|
4829
4924
|
throw error;
|
|
4830
4925
|
}
|
|
4831
4926
|
}
|
|
@@ -4835,11 +4930,12 @@ class NativeRuntime {
|
|
|
4835
4930
|
this.epochs.set(key, (this.epochs.get(key) ?? 0) + 1);
|
|
4836
4931
|
for (const controller of this.controllers.get(key) ?? [])
|
|
4837
4932
|
controller.abort(new Error("Runtime scope revoked"));
|
|
4838
|
-
|
|
4839
|
-
await p.onSessionEnd?.(scope);
|
|
4933
|
+
this.downloadAdmissionEpoch++;
|
|
4840
4934
|
for (const [id, owner] of this.owners)
|
|
4841
4935
|
if (scopeKey(owner) === key)
|
|
4842
4936
|
this.owners.delete(id);
|
|
4937
|
+
for (const p of this.plugins)
|
|
4938
|
+
await p.onSessionEnd?.(scope);
|
|
4843
4939
|
this.ended.delete(key);
|
|
4844
4940
|
}
|
|
4845
4941
|
async shutdown() {
|
|
@@ -4852,6 +4948,7 @@ class NativeRuntime {
|
|
|
4852
4948
|
}
|
|
4853
4949
|
async disconnect() {
|
|
4854
4950
|
this.disconnected = true;
|
|
4951
|
+
this.connectionEpoch++;
|
|
4855
4952
|
for (const controllers of this.controllers.values())
|
|
4856
4953
|
for (const controller of controllers)
|
|
4857
4954
|
controller.abort(new Error("Runtime disconnected"));
|
|
@@ -4871,7 +4968,7 @@ class NativeRuntime {
|
|
|
4871
4968
|
import WebSocket2 from "ws";
|
|
4872
4969
|
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4873
4970
|
import fs9 from "node:fs/promises";
|
|
4874
|
-
import
|
|
4971
|
+
import path9 from "node:path";
|
|
4875
4972
|
|
|
4876
4973
|
// cli/src/live/producer.ts
|
|
4877
4974
|
import WebSocket from "ws";
|
|
@@ -5250,6 +5347,7 @@ class NativeLiveProducer {
|
|
|
5250
5347
|
|
|
5251
5348
|
// cli/src/runtime/relay.ts
|
|
5252
5349
|
var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
5350
|
+
var QUEUE_LIMITS = Object.freeze({ maxWaiting: 16, maxWaitingPerScope: 8, maxWaitMs: 5000 });
|
|
5253
5351
|
var LIMIT = 2 * 1024 * 1024;
|
|
5254
5352
|
function wireResult(op, value) {
|
|
5255
5353
|
if (!value || typeof value !== "object")
|
|
@@ -5294,6 +5392,7 @@ class Relay {
|
|
|
5294
5392
|
live;
|
|
5295
5393
|
seen = new Set;
|
|
5296
5394
|
active;
|
|
5395
|
+
waiting = [];
|
|
5297
5396
|
recent = [];
|
|
5298
5397
|
blocker(active, scope) {
|
|
5299
5398
|
const quarantined = active.timedOut || active.interrupted;
|
|
@@ -5304,11 +5403,91 @@ class Relay {
|
|
|
5304
5403
|
}
|
|
5305
5404
|
health(scope) {
|
|
5306
5405
|
const active = this.active;
|
|
5307
|
-
|
|
5406
|
+
const quarantined = !!active && (active.timedOut || active.interrupted);
|
|
5407
|
+
return { state: this.state, paused: this.paused, queueDepth: this.waiting.filter((w) => !scope || sameScope3(w.message.scope, scope)).length, queueDepthScope: scope ? "this_scope" : "runtime", queueLimits: QUEUE_LIMITS, admission: quarantined ? "blocked" : active || this.waiting.length ? "queueing" : "ready", quarantined, operation: active ? this.blocker(active, scope) : null, recent: this.recent.filter((r) => !scope || sameScope3(r.scope, scope)).map((r) => r.result) };
|
|
5408
|
+
}
|
|
5409
|
+
interrupt(code2 = "queue_interrupted") {
|
|
5410
|
+
this.active?.interrupt();
|
|
5411
|
+
this.flushWaiting(code2, "The runtime was interrupted. Waiting work was never dispatched; reconnect and re-observe before submitting a fresh request.");
|
|
5412
|
+
}
|
|
5413
|
+
rejectWaiting(entry, code2, message) {
|
|
5414
|
+
const index = this.waiting.indexOf(entry);
|
|
5415
|
+
if (index < 0)
|
|
5416
|
+
return;
|
|
5417
|
+
this.waiting.splice(index, 1);
|
|
5418
|
+
clearTimeout(entry.timer);
|
|
5419
|
+
const result = { operationId: entry.message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, cancellationConfirmed: true, quarantined: !!this.active && (this.active.timedOut || this.active.interrupted), recovery: "This request was never dispatched. Check browser_runtime_health and current target/authority before submitting a fresh request ID; never replay the blocking operation." };
|
|
5420
|
+
entry.send({ type: "result", id: entry.message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message }, result });
|
|
5421
|
+
this.recent.push({ scope: entry.message.scope, result });
|
|
5422
|
+
if (this.recent.length > 32)
|
|
5423
|
+
this.recent.shift();
|
|
5424
|
+
entry.finish();
|
|
5425
|
+
}
|
|
5426
|
+
flushWaiting(code2, message, scope) {
|
|
5427
|
+
for (const entry of [...this.waiting])
|
|
5428
|
+
if (!scope || sameScope3(entry.message.scope, scope))
|
|
5429
|
+
this.rejectWaiting(entry, code2, message);
|
|
5430
|
+
}
|
|
5431
|
+
cancel(id, socket, reason) {
|
|
5432
|
+
const entry = this.waiting.find((w) => w.message.id === id && w.socket === socket);
|
|
5433
|
+
if (entry) {
|
|
5434
|
+
this.rejectWaiting(entry, reason === "deadline" ? "queue_wait_expired" : "queue_cancelled", "Cancelled or expired while waiting; no action was dispatched.");
|
|
5435
|
+
this.drain();
|
|
5436
|
+
return;
|
|
5437
|
+
}
|
|
5438
|
+
if (this.active?.id === id && this.active.socket === socket) {
|
|
5439
|
+
if (reason === "deadline")
|
|
5440
|
+
this.active.expire();
|
|
5441
|
+
else
|
|
5442
|
+
this.interrupt("queue_interrupted");
|
|
5443
|
+
}
|
|
5444
|
+
}
|
|
5445
|
+
dispatchReady(message, socket) {
|
|
5446
|
+
const entry = this.waiting[0];
|
|
5447
|
+
if (!entry || entry.socket !== socket || entry.message.id !== message.id || !entry.checking)
|
|
5448
|
+
return;
|
|
5449
|
+
if (message.allowed !== true) {
|
|
5450
|
+
this.rejectWaiting(entry, "scope_rejected", "Authority expired or was revoked while waiting. No action was dispatched.");
|
|
5451
|
+
this.drain();
|
|
5452
|
+
return;
|
|
5453
|
+
}
|
|
5454
|
+
entry.authorized = true;
|
|
5455
|
+
this.drain();
|
|
5308
5456
|
}
|
|
5309
|
-
|
|
5310
|
-
if (this.active)
|
|
5311
|
-
|
|
5457
|
+
drain() {
|
|
5458
|
+
if (this.active || this.paused || this.stopping)
|
|
5459
|
+
return;
|
|
5460
|
+
const entry = this.waiting[0];
|
|
5461
|
+
if (!entry)
|
|
5462
|
+
return;
|
|
5463
|
+
const { message, socket } = entry;
|
|
5464
|
+
if (socket !== this.socket || socket.readyState !== WebSocket2.OPEN) {
|
|
5465
|
+
this.rejectWaiting(entry, "queue_disconnected", "Connection changed while waiting. No action was dispatched.");
|
|
5466
|
+
this.drain();
|
|
5467
|
+
return;
|
|
5468
|
+
}
|
|
5469
|
+
if (Date.now() >= entry.waitUntil || Date.now() >= entry.deadlineAt) {
|
|
5470
|
+
this.rejectWaiting(entry, "queue_wait_expired", "Queue wait or caller deadline expired. No action was dispatched.");
|
|
5471
|
+
this.drain();
|
|
5472
|
+
return;
|
|
5473
|
+
}
|
|
5474
|
+
try {
|
|
5475
|
+
entry.guard();
|
|
5476
|
+
} catch {
|
|
5477
|
+
this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
|
|
5478
|
+
this.drain();
|
|
5479
|
+
return;
|
|
5480
|
+
}
|
|
5481
|
+
if (message.revalidate === true && !entry.authorized) {
|
|
5482
|
+
if (!entry.checking) {
|
|
5483
|
+
entry.checking = true;
|
|
5484
|
+
entry.send({ type: "dispatch_check", id: message.id });
|
|
5485
|
+
}
|
|
5486
|
+
return;
|
|
5487
|
+
}
|
|
5488
|
+
this.waiting.shift();
|
|
5489
|
+
clearTimeout(entry.timer);
|
|
5490
|
+
this.execute(entry).catch(() => socket.close(1011)).finally(entry.finish);
|
|
5312
5491
|
}
|
|
5313
5492
|
remember(active, result) {
|
|
5314
5493
|
this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
|
|
@@ -5347,7 +5526,7 @@ class Relay {
|
|
|
5347
5526
|
await new Promise((resolve2, reject) => {
|
|
5348
5527
|
socket.once("error", reject);
|
|
5349
5528
|
socket.once("close", () => {
|
|
5350
|
-
this.interrupt();
|
|
5529
|
+
this.interrupt("queue_disconnected");
|
|
5351
5530
|
clearInterval(heartbeat);
|
|
5352
5531
|
resolve2();
|
|
5353
5532
|
});
|
|
@@ -5358,7 +5537,7 @@ class Relay {
|
|
|
5358
5537
|
heartbeat.unref();
|
|
5359
5538
|
socket.once("open", () => {
|
|
5360
5539
|
this.state = "authenticating";
|
|
5361
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
5540
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.15", 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 } } }));
|
|
5362
5541
|
});
|
|
5363
5542
|
socket.on("message", (bytes, binary) => {
|
|
5364
5543
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5383,15 +5562,14 @@ class Relay {
|
|
|
5383
5562
|
this.state = "connected";
|
|
5384
5563
|
this.live = new NativeLiveProducer({ mediaUrl: mediaURL(this.server), token: this.token, instanceId: this.runtime.instanceId, credentialEpoch: message.credentialEpoch, context: this.runtime.context, authorizePage: async (page) => {
|
|
5385
5564
|
try {
|
|
5386
|
-
|
|
5565
|
+
this.runtime.assertPageAvailable(page);
|
|
5387
5566
|
return true;
|
|
5388
5567
|
} catch {
|
|
5389
5568
|
return false;
|
|
5390
5569
|
}
|
|
5391
5570
|
}, getPage: (id) => {
|
|
5392
5571
|
try {
|
|
5393
|
-
|
|
5394
|
-
return page.frames().every((f) => this.runtime.allowURL(f.url())) ? page : undefined;
|
|
5572
|
+
return this.runtime.engine.page(id);
|
|
5395
5573
|
} catch {
|
|
5396
5574
|
return;
|
|
5397
5575
|
}
|
|
@@ -5406,6 +5584,10 @@ class Relay {
|
|
|
5406
5584
|
this.live?.onWatch(message).catch(() => {});
|
|
5407
5585
|
} else if (message.type === "ping")
|
|
5408
5586
|
socket.send(JSON.stringify({ type: "pong" }));
|
|
5587
|
+
else if (message.type === "cancel" && typeof message.id === "string")
|
|
5588
|
+
this.cancel(message.id, socket, message.reason);
|
|
5589
|
+
else if (message.type === "dispatch_ready")
|
|
5590
|
+
this.dispatchReady(message, socket);
|
|
5409
5591
|
else if (message.type === "command") {
|
|
5410
5592
|
if (this.state !== "connected" || this.paused) {
|
|
5411
5593
|
socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: this.paused ? "runtime_paused" : "runtime_initializing", message: "Runtime is paused or initializing; no action was dispatched." }, result: { executionState: "not_started", retrySafe: true, recovery: "Use local browser-mcp browser status for independent health. Resume locally if paused; retry health after the runtime connects." } }));
|
|
@@ -5451,6 +5633,10 @@ class Relay {
|
|
|
5451
5633
|
return;
|
|
5452
5634
|
}
|
|
5453
5635
|
this.seen.add(message.id);
|
|
5636
|
+
if (message.deadlineAt !== undefined && (!Number.isFinite(message.deadlineAt) || message.deadlineAt <= Date.now())) {
|
|
5637
|
+
send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "queue_wait_expired", message: "Caller deadline expired; no action was dispatched." }, result: { executionState: "not_started", retrySafe: true } });
|
|
5638
|
+
return;
|
|
5639
|
+
}
|
|
5454
5640
|
if (message.op === "runtime_health") {
|
|
5455
5641
|
send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
|
|
5456
5642
|
return;
|
|
@@ -5460,35 +5646,92 @@ class Relay {
|
|
|
5460
5646
|
return;
|
|
5461
5647
|
}
|
|
5462
5648
|
if (message.op === "session_end") {
|
|
5649
|
+
this.flushWaiting("queue_scope_ended", "Session ended while waiting. No action was dispatched.", message.scope);
|
|
5463
5650
|
if (this.active && sameScope3(this.active.scope, message.scope))
|
|
5464
|
-
this.interrupt();
|
|
5651
|
+
this.interrupt("queue_interrupted");
|
|
5465
5652
|
await this.runtime.endSession(message.scope);
|
|
5653
|
+
this.drain();
|
|
5466
5654
|
send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
|
|
5467
5655
|
return;
|
|
5468
5656
|
}
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5657
|
+
const reject = (code2, text, extra = {}) => send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message: text }, result: { operationId: message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, quarantined: false, ...extra } });
|
|
5658
|
+
if (this.active && (this.active.timedOut || this.active.interrupted)) {
|
|
5659
|
+
reject("blocked_by_prior_operation", "A prior operation is quarantined. No action was queued or dispatched.", { category: "runtime_quarantined", blocker: this.blocker(this.active, message.scope), quarantined: true, recovery: "Call browser_runtime_health. Never replay the prior mutation; wait for natural late settlement or request approved recovery." });
|
|
5472
5660
|
return;
|
|
5473
5661
|
}
|
|
5474
|
-
|
|
5475
|
-
|
|
5662
|
+
if (this.waiting.length >= QUEUE_LIMITS.maxWaiting || this.waiting.filter((w) => sameScope3(w.message.scope, message.scope)).length >= QUEUE_LIMITS.maxWaitingPerScope) {
|
|
5663
|
+
reject("queue_full", "The bounded runtime queue or this scope's waiting allowance is full. No action was dispatched.", { queueLimits: QUEUE_LIMITS, retryAfterMs: 250, recovery: "Wait for outstanding requests to settle; then retry only this never-dispatched request with a fresh request ID." });
|
|
5664
|
+
return;
|
|
5665
|
+
}
|
|
5666
|
+
const now = Date.now(), timeoutMs = Math.max(1, Math.min(120000, Number(message.timeoutMs) || 30000));
|
|
5667
|
+
const deadlineAt = message.deadlineAt === undefined ? now + timeoutMs : Number(message.deadlineAt);
|
|
5668
|
+
if (!Number.isFinite(deadlineAt) || deadlineAt <= now) {
|
|
5669
|
+
reject("queue_wait_expired", "Caller deadline expired before admission. No action was dispatched.");
|
|
5670
|
+
return;
|
|
5671
|
+
}
|
|
5672
|
+
let guard;
|
|
5673
|
+
try {
|
|
5674
|
+
guard = this.runtime.admissionGuard(message.args, message.scope);
|
|
5675
|
+
guard();
|
|
5676
|
+
} catch {
|
|
5677
|
+
reject("stale_queued_request", "Scope or target is unavailable. No action was dispatched.");
|
|
5678
|
+
return;
|
|
5679
|
+
}
|
|
5680
|
+
await new Promise((finish) => {
|
|
5681
|
+
const waitMs = Math.max(1, Math.min(QUEUE_LIMITS.maxWaitMs, message.queueWaitMs === undefined ? QUEUE_LIMITS.maxWaitMs : Number(message.queueWaitMs) || 1));
|
|
5682
|
+
const entry = { message, socket, send, guard, timeoutMs, deadlineAt: Math.min(deadlineAt, now + 120000), waitUntil: Math.min(deadlineAt, now + waitMs), checking: false, authorized: false, finish };
|
|
5683
|
+
this.waiting.push(entry);
|
|
5684
|
+
entry.timer = setTimeout(() => {
|
|
5685
|
+
this.rejectWaiting(entry, "queue_wait_expired", "Queue wait or caller deadline expired. No action was dispatched.");
|
|
5686
|
+
this.drain();
|
|
5687
|
+
}, Math.max(1, entry.waitUntil - now));
|
|
5688
|
+
this.drain();
|
|
5689
|
+
});
|
|
5690
|
+
}
|
|
5691
|
+
async execute(entry) {
|
|
5692
|
+
const { message, socket, send } = entry;
|
|
5693
|
+
let finish, interrupt, expire;
|
|
5694
|
+
const active = { id: message.id, scope: { ...message.scope }, socket, tabId: typeof message.args.tabId === "string" ? message.args.tabId : undefined, op: message.op, startedAt: Date.now(), deadlineAt: Math.min(entry.deadlineAt, Date.now() + entry.timeoutMs), timedOut: false, interrupted: false, settled: false, recovering: false, dispatched: false, done: new Promise((resolve2) => {
|
|
5476
5695
|
finish = resolve2;
|
|
5477
|
-
}) };
|
|
5696
|
+
}), interrupt: () => interrupt(), expire: () => expire() };
|
|
5478
5697
|
this.active = active;
|
|
5479
5698
|
let stage = "execute", timer;
|
|
5480
5699
|
const expired = new Promise((resolve2) => {
|
|
5481
|
-
|
|
5482
|
-
active.
|
|
5483
|
-
|
|
5484
|
-
|
|
5700
|
+
const terminal = (cancelled) => {
|
|
5701
|
+
if (active.interrupted || active.settled)
|
|
5702
|
+
return;
|
|
5703
|
+
if (active.timedOut) {
|
|
5704
|
+
if (cancelled) {
|
|
5705
|
+
active.interrupted = true;
|
|
5706
|
+
this.runtime.cancelOperation(active.id);
|
|
5707
|
+
}
|
|
5708
|
+
return;
|
|
5709
|
+
}
|
|
5710
|
+
if (cancelled)
|
|
5711
|
+
active.interrupted = true;
|
|
5712
|
+
else
|
|
5713
|
+
active.timedOut = true;
|
|
5714
|
+
clearTimeout(timer);
|
|
5715
|
+
send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
|
|
5716
|
+
this.flushWaiting("blocked_by_prior_operation", "A prior operation timed out or was interrupted. This waiting request was never dispatched.");
|
|
5717
|
+
if (cancelled)
|
|
5718
|
+
this.runtime.cancelOperation(active.id);
|
|
5485
5719
|
resolve2();
|
|
5486
|
-
}
|
|
5720
|
+
};
|
|
5721
|
+
interrupt = () => terminal(true);
|
|
5722
|
+
expire = () => terminal(false);
|
|
5723
|
+
timer = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
|
|
5487
5724
|
});
|
|
5488
5725
|
const task = (async () => {
|
|
5489
5726
|
let response;
|
|
5490
5727
|
try {
|
|
5491
|
-
const
|
|
5728
|
+
const beforeDispatch = () => {
|
|
5729
|
+
if (active.timedOut || active.interrupted || this.stopping || this.paused || socket !== this.socket || socket.readyState !== WebSocket2.OPEN || Date.now() >= active.deadlineAt)
|
|
5730
|
+
throw new RuntimeFault("queue_wait_expired", "Request expired or was interrupted before browser dispatch.", true);
|
|
5731
|
+
entry.guard(!active.dispatched);
|
|
5732
|
+
active.dispatched = true;
|
|
5733
|
+
};
|
|
5734
|
+
const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch);
|
|
5492
5735
|
if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5493
5736
|
return;
|
|
5494
5737
|
this.runtime.validateScope(message.scope);
|
|
@@ -5506,9 +5749,9 @@ class Relay {
|
|
|
5506
5749
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5507
5750
|
for (const item of result.exports) {
|
|
5508
5751
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5509
|
-
if (
|
|
5752
|
+
if (path9.basename(filename) !== filename)
|
|
5510
5753
|
throw new Error("Invalid export file");
|
|
5511
|
-
const filenamePath =
|
|
5754
|
+
const filenamePath = path9.join(this.previewDirectory, filename);
|
|
5512
5755
|
const stat = await fs9.lstat(filenamePath);
|
|
5513
5756
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5514
5757
|
throw new Error("Invalid export file");
|
|
@@ -5518,14 +5761,19 @@ class Relay {
|
|
|
5518
5761
|
}
|
|
5519
5762
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5520
5763
|
for (const artifact2 of result.artifacts)
|
|
5521
|
-
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact",
|
|
5522
|
-
result.artifacts = result.artifacts.map((a) => ({ filename:
|
|
5764
|
+
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path9.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
|
|
5765
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path9.basename(a.filename) }));
|
|
5523
5766
|
}
|
|
5524
5767
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5525
5768
|
throw new Error("Result budget exceeded");
|
|
5526
5769
|
response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
|
|
5527
5770
|
} catch (error) {
|
|
5528
5771
|
const failure = failureFor(error, message.op, message.id, stage);
|
|
5772
|
+
if (failure.error.code === "context_destroyed" && active.tabId) {
|
|
5773
|
+
for (const waiting of [...this.waiting])
|
|
5774
|
+
if (waiting.message.args.tabId === active.tabId)
|
|
5775
|
+
this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
|
|
5776
|
+
}
|
|
5529
5777
|
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5530
5778
|
} finally {
|
|
5531
5779
|
clearTimeout(timer);
|
|
@@ -5533,11 +5781,12 @@ class Relay {
|
|
|
5533
5781
|
finish();
|
|
5534
5782
|
if (active.timedOut || active.interrupted)
|
|
5535
5783
|
this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
|
|
5536
|
-
if (this.active === active && !active.interrupted && !active.recovering)
|
|
5784
|
+
if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
|
|
5537
5785
|
this.active = undefined;
|
|
5538
5786
|
}
|
|
5539
5787
|
if (response && !active.timedOut && !active.interrupted)
|
|
5540
5788
|
send(response);
|
|
5789
|
+
this.drain();
|
|
5541
5790
|
})();
|
|
5542
5791
|
await Promise.race([task, expired]);
|
|
5543
5792
|
}
|
|
@@ -5550,6 +5799,7 @@ class Relay {
|
|
|
5550
5799
|
return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
|
|
5551
5800
|
if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
|
|
5552
5801
|
return reject("approval_required", "Explicit user approval to close the blocked tab is required. This may discard unsaved page state; profile data is retained.");
|
|
5802
|
+
this.flushWaiting("queue_recovery", "Recovery invalidated waiting requests. No action was dispatched.");
|
|
5553
5803
|
active.recovering = true;
|
|
5554
5804
|
const work = (async () => {
|
|
5555
5805
|
await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
|
|
@@ -5581,8 +5831,8 @@ class Relay {
|
|
|
5581
5831
|
return { blobId, role, name, mimeType, size: bytes.length, sha256 };
|
|
5582
5832
|
}
|
|
5583
5833
|
async pause() {
|
|
5584
|
-
this.interrupt();
|
|
5585
5834
|
this.paused = true;
|
|
5835
|
+
this.interrupt("queue_paused");
|
|
5586
5836
|
this.state = "paused";
|
|
5587
5837
|
this.socket?.close();
|
|
5588
5838
|
await this.live?.stop();
|
|
@@ -5592,8 +5842,8 @@ class Relay {
|
|
|
5592
5842
|
this.paused = false;
|
|
5593
5843
|
}
|
|
5594
5844
|
async stop() {
|
|
5595
|
-
this.interrupt();
|
|
5596
5845
|
this.stopping = true;
|
|
5846
|
+
this.interrupt("queue_shutdown");
|
|
5597
5847
|
this.socket?.close();
|
|
5598
5848
|
await this.live?.stop();
|
|
5599
5849
|
await this.runtime.disconnect();
|
|
@@ -5601,12 +5851,12 @@ class Relay {
|
|
|
5601
5851
|
}
|
|
5602
5852
|
|
|
5603
5853
|
// cli/src/data/index.ts
|
|
5604
|
-
import { mkdir as mkdir2, open as
|
|
5605
|
-
import { createReadStream, createWriteStream } from "node:fs";
|
|
5606
|
-
import { randomUUID as randomUUID7, createHash as
|
|
5854
|
+
import { mkdir as mkdir2, open as open3, rename, unlink as unlink2, rmdir as rmdir2, lstat as lstat2 } from "node:fs/promises";
|
|
5855
|
+
import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
|
|
5856
|
+
import { randomUUID as randomUUID7, createHash as createHash7 } from "node:crypto";
|
|
5607
5857
|
import { join as join2, basename } from "node:path";
|
|
5608
|
-
import { Readable, Transform } from "node:stream";
|
|
5609
|
-
import { pipeline } from "node:stream/promises";
|
|
5858
|
+
import { Readable, Transform as Transform2 } from "node:stream";
|
|
5859
|
+
import { pipeline as pipeline2 } from "node:stream/promises";
|
|
5610
5860
|
|
|
5611
5861
|
// cli/src/data/vault.ts
|
|
5612
5862
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
@@ -5727,6 +5977,129 @@ class SecretVault {
|
|
|
5727
5977
|
}
|
|
5728
5978
|
}
|
|
5729
5979
|
|
|
5980
|
+
// cli/src/data/download-capture.ts
|
|
5981
|
+
import { constants as constants3, createWriteStream } from "node:fs";
|
|
5982
|
+
import { open as open2 } from "node:fs/promises";
|
|
5983
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
5984
|
+
import { Transform } from "node:stream";
|
|
5985
|
+
import { pipeline } from "node:stream/promises";
|
|
5986
|
+
class CaptureError extends Error {
|
|
5987
|
+
code;
|
|
5988
|
+
constructor(code2) {
|
|
5989
|
+
super(code2);
|
|
5990
|
+
this.code = code2;
|
|
5991
|
+
}
|
|
5992
|
+
}
|
|
5993
|
+
async function duringCapture(work, signal) {
|
|
5994
|
+
let abort;
|
|
5995
|
+
const cancelled = new Promise((_, reject) => {
|
|
5996
|
+
abort = () => reject(new CaptureError("download_capture_cancelled"));
|
|
5997
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
5998
|
+
if (signal.aborted)
|
|
5999
|
+
abort();
|
|
6000
|
+
});
|
|
6001
|
+
try {
|
|
6002
|
+
return await Promise.race([work, cancelled]);
|
|
6003
|
+
} finally {
|
|
6004
|
+
signal.removeEventListener("abort", abort);
|
|
6005
|
+
}
|
|
6006
|
+
}
|
|
6007
|
+
function contentValidation(name, size) {
|
|
6008
|
+
if (size !== 0)
|
|
6009
|
+
return { status: "not-validated" };
|
|
6010
|
+
if (/\.(pdf|eml)$/i.test(name))
|
|
6011
|
+
return {
|
|
6012
|
+
status: "empty-document",
|
|
6013
|
+
code: "empty_document",
|
|
6014
|
+
warning: "The completed browser file is empty. These are not usable document bytes. Do not automatically repeat the website action."
|
|
6015
|
+
};
|
|
6016
|
+
return {
|
|
6017
|
+
status: "empty-file",
|
|
6018
|
+
code: "empty_file",
|
|
6019
|
+
warning: "The completed browser file is empty. This may be intentional; no document validity is implied."
|
|
6020
|
+
};
|
|
6021
|
+
}
|
|
6022
|
+
async function captureDownload(download, destination, signal, evidence) {
|
|
6023
|
+
const failure = await duringCapture(download.failure(), signal);
|
|
6024
|
+
evidence.browserCompletion = failure === null ? "completed" : "failed";
|
|
6025
|
+
if (failure !== null)
|
|
6026
|
+
throw new CaptureError("download_capture_browser_failed");
|
|
6027
|
+
const path10 = await duringCapture(download.path(), signal);
|
|
6028
|
+
signal.throwIfAborted();
|
|
6029
|
+
evidence.stage = "browser-file";
|
|
6030
|
+
let source;
|
|
6031
|
+
let retained2;
|
|
6032
|
+
try {
|
|
6033
|
+
source = await open2(path10, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
6034
|
+
const before = await source.stat();
|
|
6035
|
+
if (!before.isFile())
|
|
6036
|
+
throw new CaptureError("download_capture_source_unavailable");
|
|
6037
|
+
evidence.browser = { size: before.size };
|
|
6038
|
+
if (before.size > LIMITS.file)
|
|
6039
|
+
throw new CaptureError("download_quota_exceeded");
|
|
6040
|
+
signal.throwIfAborted();
|
|
6041
|
+
evidence.stage = "copy";
|
|
6042
|
+
let size = 0;
|
|
6043
|
+
const hash = createHash6("sha256");
|
|
6044
|
+
const bound = new Transform({ transform(chunk, _encoding, callback) {
|
|
6045
|
+
size += chunk.length;
|
|
6046
|
+
if (size > LIMITS.file)
|
|
6047
|
+
return callback(new CaptureError("download_quota_exceeded"));
|
|
6048
|
+
hash.update(chunk);
|
|
6049
|
+
callback(null, chunk);
|
|
6050
|
+
} });
|
|
6051
|
+
await pipeline(source.createReadStream({ start: 0, autoClose: false }), bound, createWriteStream(destination, { flags: "wx", mode: 384 }), { signal });
|
|
6052
|
+
const sourceHash = hash.digest("hex");
|
|
6053
|
+
evidence.browser.sha256 = sourceHash;
|
|
6054
|
+
evidence.stage = "verification";
|
|
6055
|
+
retained2 = await open2(destination, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
6056
|
+
const disk = await retained2.stat();
|
|
6057
|
+
if (!disk.isFile() || disk.size > LIMITS.file)
|
|
6058
|
+
throw new CaptureError("download_capture_mismatch");
|
|
6059
|
+
let diskSize = 0;
|
|
6060
|
+
const diskHash = createHash6("sha256");
|
|
6061
|
+
for await (const chunk of retained2.createReadStream({ start: 0, autoClose: false, signal })) {
|
|
6062
|
+
diskSize += chunk.length;
|
|
6063
|
+
if (diskSize > LIMITS.file)
|
|
6064
|
+
throw new CaptureError("download_quota_exceeded");
|
|
6065
|
+
diskHash.update(chunk);
|
|
6066
|
+
}
|
|
6067
|
+
evidence.retained = { size: diskSize, sha256: diskHash.digest("hex") };
|
|
6068
|
+
const after = await source.stat();
|
|
6069
|
+
const diskAfter = await retained2.stat();
|
|
6070
|
+
if (size !== before.size || disk.size !== size || diskSize !== size || evidence.retained.sha256 !== sourceHash || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs || diskAfter.size !== disk.size || diskAfter.mtimeMs !== disk.mtimeMs || diskAfter.ctimeMs !== disk.ctimeMs) {
|
|
6071
|
+
evidence.comparison = "mismatched";
|
|
6072
|
+
throw new CaptureError("download_capture_mismatch");
|
|
6073
|
+
}
|
|
6074
|
+
signal.throwIfAborted();
|
|
6075
|
+
evidence.comparison = "matched";
|
|
6076
|
+
evidence.stage = "verified";
|
|
6077
|
+
return { size, sha256: sourceHash };
|
|
6078
|
+
} finally {
|
|
6079
|
+
try {
|
|
6080
|
+
await retained2?.close();
|
|
6081
|
+
} finally {
|
|
6082
|
+
await source?.close();
|
|
6083
|
+
}
|
|
6084
|
+
}
|
|
6085
|
+
}
|
|
6086
|
+
async function cleanupDownload(download, evidence) {
|
|
6087
|
+
let timer;
|
|
6088
|
+
try {
|
|
6089
|
+
const deleted = await Promise.race([
|
|
6090
|
+
download.delete().then(() => true, () => false),
|
|
6091
|
+
new Promise((resolve2) => {
|
|
6092
|
+
timer = setTimeout(() => resolve2(false), 2000);
|
|
6093
|
+
timer.unref?.();
|
|
6094
|
+
})
|
|
6095
|
+
]);
|
|
6096
|
+
if (evidence)
|
|
6097
|
+
evidence.cleanup = deleted ? "deleted" : "browser-context";
|
|
6098
|
+
} finally {
|
|
6099
|
+
clearTimeout(timer);
|
|
6100
|
+
}
|
|
6101
|
+
}
|
|
6102
|
+
|
|
5730
6103
|
// cli/src/data/index.ts
|
|
5731
6104
|
var safeName = (s) => {
|
|
5732
6105
|
const name = basename(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
|
|
@@ -5753,7 +6126,7 @@ async function createDataPlugin(access, options) {
|
|
|
5753
6126
|
return meta(get(scope, id));
|
|
5754
6127
|
}
|
|
5755
6128
|
function meta(r) {
|
|
5756
|
-
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? "ready" : "pending", retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
|
|
6129
|
+
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : "pending", capture: r.capture, contentValidation: r.contentValidation, retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
|
|
5757
6130
|
}
|
|
5758
6131
|
function get(scope, id) {
|
|
5759
6132
|
const r = resources.get(String(id));
|
|
@@ -5776,8 +6149,8 @@ async function createDataPlugin(access, options) {
|
|
|
5776
6149
|
r.terminalCode ??= "download_revoked";
|
|
5777
6150
|
r.abort.abort();
|
|
5778
6151
|
r.state = "cancelled";
|
|
5779
|
-
remember(r);
|
|
5780
6152
|
await r.task?.catch(() => {});
|
|
6153
|
+
remember(r);
|
|
5781
6154
|
r.bytes?.fill(0);
|
|
5782
6155
|
r.bytes = undefined;
|
|
5783
6156
|
if (r.path && owned.has(r.path)) {
|
|
@@ -5808,20 +6181,20 @@ async function createDataPlugin(access, options) {
|
|
|
5808
6181
|
await mkdir2(dir, { mode: 448 });
|
|
5809
6182
|
ownedDirs.add(dir);
|
|
5810
6183
|
const part = join2(options.directory, `${r.id}.partial`), dest = join2(dir, r.name);
|
|
5811
|
-
const h = await
|
|
6184
|
+
const h = await open3(part, "wx", 384);
|
|
5812
6185
|
await h.close();
|
|
5813
6186
|
owned.add(part);
|
|
5814
6187
|
r.path = part;
|
|
5815
6188
|
let size = 0;
|
|
5816
|
-
const hash =
|
|
5817
|
-
const check = new
|
|
6189
|
+
const hash = createHash7("sha256");
|
|
6190
|
+
const check = new Transform2({ transform(chunk, _enc, cb) {
|
|
5818
6191
|
size += chunk.length;
|
|
5819
6192
|
if (size > r.size)
|
|
5820
6193
|
return cb(new Error("Size exceeded"));
|
|
5821
6194
|
hash.update(chunk);
|
|
5822
6195
|
cb(null, chunk);
|
|
5823
6196
|
} });
|
|
5824
|
-
await
|
|
6197
|
+
await pipeline2(Readable.fromWeb(response.body), check, createWriteStream2(part, { flags: "r+", mode: 384 }), { signal: r.abort.signal });
|
|
5825
6198
|
const actual = hash.digest("hex");
|
|
5826
6199
|
if (size !== r.size || r.expectedHash && actual !== r.expectedHash)
|
|
5827
6200
|
throw new Error("Verification failed");
|
|
@@ -5844,7 +6217,7 @@ async function createDataPlugin(access, options) {
|
|
|
5844
6217
|
body = Readable.toWeb(createReadStream(r.path));
|
|
5845
6218
|
}
|
|
5846
6219
|
const response = await fetch(g.url, { method: "PUT", headers: g.headers, body, duplex: "half", redirect: "error", signal: r.abort.signal });
|
|
5847
|
-
if (!response.ok)
|
|
6220
|
+
if (!response.ok || r.abort.signal.aborted || r.state === "cancelled")
|
|
5848
6221
|
throw new Error("Transfer failed");
|
|
5849
6222
|
r.state = "ready";
|
|
5850
6223
|
}
|
|
@@ -5901,9 +6274,9 @@ async function createDataPlugin(access, options) {
|
|
|
5901
6274
|
return meta(r);
|
|
5902
6275
|
}
|
|
5903
6276
|
if (op === "create_download") {
|
|
5904
|
-
const r = get(
|
|
5905
|
-
if (r.purpose !== "download" || r.state !== "ready")
|
|
5906
|
-
throw new
|
|
6277
|
+
const r = resources.get(String(args.downloadId ?? args.fileId ?? args.resourceId));
|
|
6278
|
+
if (!r || !sameScope(r.scope, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
|
|
6279
|
+
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);
|
|
5907
6280
|
return meta(r);
|
|
5908
6281
|
}
|
|
5909
6282
|
if (op === "transfer_status") {
|
|
@@ -5922,7 +6295,7 @@ async function createDataPlugin(access, options) {
|
|
|
5922
6295
|
const r = get(scope, args.resourceId);
|
|
5923
6296
|
const grant = args.dataGrant;
|
|
5924
6297
|
validateGrant(grant, options.serverOrigin, r.id, options.allowInsecureLoopback);
|
|
5925
|
-
if (r.authorized || grant.purpose !== r.purpose || grant.method !== (r.purpose === "upload" ? "GET" : "PUT") || grant.limits.maxBytes !== r.size)
|
|
6298
|
+
if (r.authorized || r.purpose === "download" && (r.state !== "ready" || !r.hash) || grant.purpose !== r.purpose || grant.method !== (r.purpose === "upload" ? "GET" : "PUT") || grant.limits.maxBytes !== r.size)
|
|
5926
6299
|
throw new Error("Invalid data authorization");
|
|
5927
6300
|
r.authorized = true;
|
|
5928
6301
|
r.task = transfer(r, grant);
|
|
@@ -5988,6 +6361,7 @@ async function createDataPlugin(access, options) {
|
|
|
5988
6361
|
async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
|
|
5989
6362
|
let r;
|
|
5990
6363
|
let timeout2;
|
|
6364
|
+
let cancel;
|
|
5991
6365
|
try {
|
|
5992
6366
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
5993
6367
|
resources.delete(r.id);
|
|
@@ -5995,55 +6369,47 @@ async function createDataPlugin(access, options) {
|
|
|
5995
6369
|
resources.set(r.id, r);
|
|
5996
6370
|
r.tabId = tabId;
|
|
5997
6371
|
r.generation = generation;
|
|
5998
|
-
r.
|
|
6372
|
+
r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
|
|
6373
|
+
cancel = () => {
|
|
5999
6374
|
download.cancel().catch(() => {});
|
|
6000
|
-
}
|
|
6375
|
+
};
|
|
6376
|
+
r.abort.signal.addEventListener("abort", cancel, { once: true });
|
|
6001
6377
|
timeout2 = setTimeout(() => {
|
|
6002
|
-
r.terminalCode
|
|
6378
|
+
r.terminalCode ??= "download_capture_timeout";
|
|
6003
6379
|
r.abort.abort();
|
|
6004
|
-
download.cancel().catch(() => {});
|
|
6005
6380
|
}, LIMITS.duration);
|
|
6006
6381
|
timeout2.unref?.();
|
|
6007
6382
|
const captured = r;
|
|
6008
6383
|
r.task = (async () => {
|
|
6009
|
-
const
|
|
6010
|
-
captured.path =
|
|
6011
|
-
owned.add(
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
hash.update(chunk);
|
|
6024
|
-
callback(null, chunk);
|
|
6025
|
-
} });
|
|
6026
|
-
await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: captured.abort.signal });
|
|
6027
|
-
await chmod(path9, 384);
|
|
6028
|
-
const stat = await lstat2(path9);
|
|
6029
|
-
if (!stat.isFile() || stat.size !== received || captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6384
|
+
const path10 = join2(options.directory, captured.id);
|
|
6385
|
+
captured.path = path10;
|
|
6386
|
+
owned.add(path10);
|
|
6387
|
+
try {
|
|
6388
|
+
const verified = await captureDownload(download, path10, captured.abort.signal, captured.capture);
|
|
6389
|
+
if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6390
|
+
throw new Error("Download revoked");
|
|
6391
|
+
captured.size = verified.size;
|
|
6392
|
+
captured.hash = verified.sha256;
|
|
6393
|
+
captured.contentValidation = contentValidation(captured.name, verified.size);
|
|
6394
|
+
} finally {
|
|
6395
|
+
await cleanupDownload(download, captured.capture);
|
|
6396
|
+
}
|
|
6397
|
+
if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6030
6398
|
throw new Error("Download revoked");
|
|
6031
|
-
captured.size = stat.size;
|
|
6032
|
-
captured.hash = hash.digest("hex");
|
|
6033
6399
|
captured.state = "ready";
|
|
6034
6400
|
})();
|
|
6035
6401
|
await r.task;
|
|
6036
|
-
await download.delete().catch(() => {});
|
|
6037
6402
|
if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
|
|
6038
6403
|
throw new Error("Download revoked");
|
|
6039
|
-
return { ...meta(r), state: "completed"
|
|
6040
|
-
} catch {
|
|
6041
|
-
|
|
6404
|
+
return { ...meta(r), state: "completed" };
|
|
6405
|
+
} catch (error) {
|
|
6406
|
+
download.cancel().catch(() => {});
|
|
6042
6407
|
if (r) {
|
|
6043
|
-
r.terminalCode ??= "download_capture_failed";
|
|
6408
|
+
r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
|
|
6044
6409
|
await remove(r);
|
|
6045
|
-
return
|
|
6410
|
+
return status(scope, downloadId);
|
|
6046
6411
|
}
|
|
6412
|
+
await cleanupDownload(download);
|
|
6047
6413
|
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." };
|
|
6048
6414
|
terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6049
6415
|
while (terminal.size > 128)
|
|
@@ -6052,8 +6418,8 @@ async function createDataPlugin(access, options) {
|
|
|
6052
6418
|
} finally {
|
|
6053
6419
|
if (timeout2)
|
|
6054
6420
|
clearTimeout(timeout2);
|
|
6055
|
-
if (r
|
|
6056
|
-
|
|
6421
|
+
if (r && cancel)
|
|
6422
|
+
r.abort.signal.removeEventListener("abort", cancel);
|
|
6057
6423
|
}
|
|
6058
6424
|
},
|
|
6059
6425
|
async onNavigation(tabId, generation) {
|
|
@@ -6204,7 +6570,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6204
6570
|
for (const signal of signals)
|
|
6205
6571
|
process.on(signal, signalStop);
|
|
6206
6572
|
try {
|
|
6207
|
-
const
|
|
6573
|
+
const requestedRoot = path10.resolve(installationRoot());
|
|
6574
|
+
for (const profile of profiles)
|
|
6575
|
+
assertControlPaths(requestedRoot, controlSocketPath(requestedRoot, profile));
|
|
6576
|
+
const root = await privateDirectory2(requestedRoot);
|
|
6208
6577
|
if (command !== "start") {
|
|
6209
6578
|
const profile = profiles[0], controlPath = controlSocketPath(root, profile);
|
|
6210
6579
|
if (command === "recover") {
|
|
@@ -6222,7 +6591,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6222
6591
|
socket.end();
|
|
6223
6592
|
resolve2();
|
|
6224
6593
|
});
|
|
6225
|
-
socket.once("error", (error) => reject(
|
|
6594
|
+
socket.once("error", (error) => reject(controlFailure("control-connect", error)));
|
|
6226
6595
|
});
|
|
6227
6596
|
return;
|
|
6228
6597
|
}
|
|
@@ -6232,10 +6601,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6232
6601
|
const controlPath = controlSocketPath(root, profile);
|
|
6233
6602
|
const previousSocket = await fs10.lstat(controlPath).catch((error) => {
|
|
6234
6603
|
if (error.code !== "ENOENT")
|
|
6235
|
-
throw error;
|
|
6604
|
+
throw controlFailure("local-control", error);
|
|
6236
6605
|
});
|
|
6237
6606
|
if (previousSocket)
|
|
6238
|
-
throw new Error(`Local control path already exists
|
|
6607
|
+
throw new Error(`Local control path already exists; stage=local-control reason=path-exists. Use a different --profile to launch another browser. If the prior host has stopped, run browser-mcp browser recover --profile ${profile}. Recovery verifies both runtime.lock and the socket; never blindly unlink either.`);
|
|
6239
6608
|
abort.signal.throwIfAborted();
|
|
6240
6609
|
}
|
|
6241
6610
|
const results = await Promise.allSettled(profiles.map(async (profile) => {
|
|
@@ -6284,7 +6653,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6284
6653
|
["Local control", async () => {
|
|
6285
6654
|
for (const client of clients)
|
|
6286
6655
|
client.destroy();
|
|
6287
|
-
|
|
6656
|
+
try {
|
|
6657
|
+
await stopControl?.();
|
|
6658
|
+
} catch (error) {
|
|
6659
|
+
throw controlFailure("control-cleanup", error);
|
|
6660
|
+
}
|
|
6288
6661
|
}],
|
|
6289
6662
|
["Browser session", async () => {
|
|
6290
6663
|
await session?.close();
|
|
@@ -6305,28 +6678,26 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6305
6678
|
if (groupSignal.aborted)
|
|
6306
6679
|
groupStop();
|
|
6307
6680
|
let failure, cleanupFailure;
|
|
6681
|
+
let runtimeStage = "download-quota";
|
|
6308
6682
|
try {
|
|
6309
6683
|
abort.signal.throwIfAborted();
|
|
6310
6684
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
6311
6685
|
session.lifecycle.ended.then(endSession);
|
|
6312
6686
|
abort.signal.throwIfAborted();
|
|
6313
|
-
stopQuota = await enforceDownloadQuota(session.context,
|
|
6687
|
+
stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
|
|
6314
6688
|
abort.signal.throwIfAborted();
|
|
6689
|
+
runtimeStage = "pairing";
|
|
6315
6690
|
const token = await credential(root, server, profile, abort.signal);
|
|
6316
6691
|
abort.signal.throwIfAborted();
|
|
6317
|
-
|
|
6692
|
+
runtimeStage = "runtime-setup";
|
|
6693
|
+
const previews = path10.join(session.runPath, "previews");
|
|
6318
6694
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
6319
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
6695
|
+
runtime.plugins.push(await createDataPlugin(runtime, { directory: path10.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
|
|
6320
6696
|
abort.signal.throwIfAborted();
|
|
6321
6697
|
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
6322
6698
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
6323
|
-
await session.context.route("**/*", async (route) => {
|
|
6324
|
-
if (!runtime.allowURL(route.request().url()))
|
|
6325
|
-
await route.abort("blockedbyclient");
|
|
6326
|
-
else
|
|
6327
|
-
await route.continue();
|
|
6328
|
-
});
|
|
6329
6699
|
abort.signal.throwIfAborted();
|
|
6700
|
+
runtimeStage = "local-control";
|
|
6330
6701
|
local = net3.createServer((socket) => {
|
|
6331
6702
|
clients.add(socket);
|
|
6332
6703
|
socket.once("close", () => clients.delete(socket));
|
|
@@ -6357,24 +6728,21 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6357
6728
|
return;
|
|
6358
6729
|
} else if (cmd !== "status")
|
|
6359
6730
|
throw new Error("Invalid command");
|
|
6360
|
-
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.
|
|
6731
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.15", protocol: 3 }) + `
|
|
6361
6732
|
`);
|
|
6362
6733
|
})().catch(() => socket.destroy());
|
|
6363
6734
|
});
|
|
6364
6735
|
});
|
|
6365
|
-
|
|
6366
|
-
stopControl = await listenControl(local, root, controlPath);
|
|
6367
|
-
} catch (error) {
|
|
6368
|
-
throw new Error(`Cannot bind local control socket ${controlPath}: ${error instanceof Error ? error.message : error}. No existing socket was removed. Stop the previous owner and run browser-mcp browser recover --profile ${profile}; see the recovery documentation if ownership cannot be verified.`);
|
|
6369
|
-
}
|
|
6736
|
+
stopControl = await listenControl(local, root, controlPath);
|
|
6370
6737
|
abort.signal.throwIfAborted();
|
|
6371
6738
|
starting = false;
|
|
6372
6739
|
console.error(`Dedicated Chrome running (${profile}). Local controls: browser-mcp browser pause|resume|status|stop --profile ${profile}. Ctrl-C closes all browsers started by this command.`);
|
|
6740
|
+
runtimeStage = "relay";
|
|
6373
6741
|
await relay.start();
|
|
6374
6742
|
} catch (error) {
|
|
6375
6743
|
if (session) {
|
|
6376
6744
|
if (!session.lifecycle.hasEnded && !abort.signal.aborted)
|
|
6377
|
-
failure = new Error(
|
|
6745
|
+
failure = runtimeStage === "local-control" ? controlFailure("local-control", error) : new Error(`Browser runtime failed; stage=${runtimeStage} reason=operation-failed (private details suppressed). Check local setup and server availability before restarting; do not delete profile data.`);
|
|
6378
6746
|
} else if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
|
|
6379
6747
|
failure = error;
|
|
6380
6748
|
} finally {
|