@ricsam/browser-mcp 0.3.13 → 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-6kc5yfp5.js → chunk-g3yyvtve.js} +1 -1
- package/dist/{chunk-vw3wanmm.js → chunk-ts4nynm9.js} +713 -270
- package/dist/{chunk-k9cpr8vk.js → chunk-v483gpt7.js} +3 -2
- package/dist/{chunk-6dypb4ga.js → chunk-zv1900tw.js} +1 -1
- package/dist/main.js +5 -5
- 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)
|
|
@@ -2856,15 +2905,18 @@ class BrowserPageEvents {
|
|
|
2856
2905
|
this.pending = pending;
|
|
2857
2906
|
return await Promise.race([work, interrupted]);
|
|
2858
2907
|
}
|
|
2859
|
-
startDownload(download) {
|
|
2908
|
+
startDownload(download, downloadId) {
|
|
2860
2909
|
const event = this.record("download", {
|
|
2861
2910
|
state: "started",
|
|
2911
|
+
downloadId,
|
|
2912
|
+
resourceId: downloadId,
|
|
2913
|
+
readiness: "pending",
|
|
2862
2914
|
filename: download.suggestedFilename().slice(0, 255),
|
|
2863
2915
|
url: diagnosticUrl(download.url())
|
|
2864
2916
|
});
|
|
2865
2917
|
this.downloads.set(event.eventId, download);
|
|
2866
2918
|
return (data) => {
|
|
2867
|
-
this.record("download", { ...data, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
|
|
2919
|
+
this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
|
|
2868
2920
|
this.downloads.delete(event.eventId);
|
|
2869
2921
|
};
|
|
2870
2922
|
}
|
|
@@ -3390,25 +3442,27 @@ class RuntimeFault extends Error {
|
|
|
3390
3442
|
}
|
|
3391
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"]);
|
|
3392
3444
|
var messages = {
|
|
3393
|
-
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.",
|
|
3394
3447
|
tab_closed: "The tab is closed or detached.",
|
|
3395
3448
|
runtime_disconnected: "The runtime or browser connection ended.",
|
|
3396
3449
|
context_destroyed: "The document execution context changed during the operation.",
|
|
3397
3450
|
execution_timeout: "The browser operation exceeded its internal wait budget.",
|
|
3398
3451
|
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3399
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.",
|
|
3400
3454
|
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3401
3455
|
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3402
3456
|
};
|
|
3403
3457
|
function failureFor(error, op, operationId, stage) {
|
|
3404
3458
|
const text = error instanceof Error ? error.message : "";
|
|
3405
|
-
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";
|
|
3406
3460
|
const observation = OBSERVATION_OPERATIONS.has(op);
|
|
3407
3461
|
const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
|
|
3408
|
-
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.";
|
|
3409
3463
|
const diagnosticId = randomUUID4();
|
|
3410
3464
|
console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
|
|
3411
|
-
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 } };
|
|
3412
3466
|
}
|
|
3413
3467
|
|
|
3414
3468
|
// cli/src/browser/browser-runtime.ts
|
|
@@ -3506,17 +3560,17 @@ class BrowserRuntime {
|
|
|
3506
3560
|
await this.setViewport(page, state.tabId, state.viewport);
|
|
3507
3561
|
}).catch(() => {}));
|
|
3508
3562
|
page.on("download", (download) => {
|
|
3509
|
-
const
|
|
3563
|
+
const downloadId = crypto.randomUUID();
|
|
3564
|
+
const finish = this.events.get(page).startDownload(download, downloadId);
|
|
3510
3565
|
const saving = Promise.resolve().then(async () => {
|
|
3511
3566
|
if (this.downloadHandler) {
|
|
3512
|
-
await this.downloadHandler(download, page);
|
|
3513
|
-
finish({ state: "completed" });
|
|
3567
|
+
finish(await this.downloadHandler(download, page, downloadId));
|
|
3514
3568
|
} else {
|
|
3515
3569
|
await download.cancel();
|
|
3516
|
-
finish({ state: "canceled" });
|
|
3570
|
+
finish({ state: "canceled", readiness: "unavailable", code: "capture_unavailable" });
|
|
3517
3571
|
}
|
|
3518
3572
|
}).catch((error) => {
|
|
3519
|
-
finish({ state: "failed", code: "
|
|
3573
|
+
finish({ state: "failed", readiness: "unavailable", code: "download_capture_failed", recovery: "Inspect browser_list_downloads or browser_transfer_status with resourceId equal to downloadId. Do not automatically replay the website action." });
|
|
3520
3574
|
process.stderr.write(`[r5d-browser] failed to save download
|
|
3521
3575
|
`);
|
|
3522
3576
|
}).finally(() => this.savingDownloads.delete(saving));
|
|
@@ -3537,22 +3591,22 @@ class BrowserRuntime {
|
|
|
3537
3591
|
return id;
|
|
3538
3592
|
}
|
|
3539
3593
|
safeDownloadFilename(suggestedFilename) {
|
|
3540
|
-
const basename =
|
|
3594
|
+
const basename = path8.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
3541
3595
|
if (!basename || basename === "." || basename === "..")
|
|
3542
3596
|
return "download";
|
|
3543
|
-
const extension =
|
|
3544
|
-
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";
|
|
3545
3599
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
3546
3600
|
stem = stem.slice(0, -1);
|
|
3547
3601
|
return `${stem || "download"}${extension}`;
|
|
3548
3602
|
}
|
|
3549
3603
|
availableDownloadPath(suggestedFilename) {
|
|
3550
3604
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
3551
|
-
const extension =
|
|
3605
|
+
const extension = path8.extname(filename);
|
|
3552
3606
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
3553
3607
|
for (let suffix = 1;; suffix += 1) {
|
|
3554
3608
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
3555
|
-
const candidatePath =
|
|
3609
|
+
const candidatePath = path8.join(this.downloadsPath, candidate);
|
|
3556
3610
|
if (!fs8.existsSync(candidatePath))
|
|
3557
3611
|
return candidatePath;
|
|
3558
3612
|
}
|
|
@@ -3561,7 +3615,7 @@ class BrowserRuntime {
|
|
|
3561
3615
|
const failure = await download.failure();
|
|
3562
3616
|
if (failure)
|
|
3563
3617
|
throw new Error(failure);
|
|
3564
|
-
const temporary =
|
|
3618
|
+
const temporary = path8.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
3565
3619
|
let targetPath;
|
|
3566
3620
|
try {
|
|
3567
3621
|
await download.saveAs(temporary);
|
|
@@ -3570,9 +3624,9 @@ class BrowserRuntime {
|
|
|
3570
3624
|
} finally {
|
|
3571
3625
|
fs8.rmSync(temporary, { force: true });
|
|
3572
3626
|
}
|
|
3573
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3627
|
+
process.stdout.write(`[r5d-browser] downloaded ${path8.basename(targetPath)}
|
|
3574
3628
|
`);
|
|
3575
|
-
return { downloadId: this.downloadId(
|
|
3629
|
+
return { downloadId: this.downloadId(path8.basename(targetPath)) };
|
|
3576
3630
|
}
|
|
3577
3631
|
downloadId(filename) {
|
|
3578
3632
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -3581,10 +3635,10 @@ class BrowserRuntime {
|
|
|
3581
3635
|
if (typeof downloadId !== "string" || !downloadId)
|
|
3582
3636
|
throw new Error("downloadId is required.");
|
|
3583
3637
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
3584
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3638
|
+
if (this.downloadId(filename) !== downloadId || filename !== path8.basename(filename) || filename.includes("\x00")) {
|
|
3585
3639
|
throw new Error("Invalid downloadId.");
|
|
3586
3640
|
}
|
|
3587
|
-
const filePath =
|
|
3641
|
+
const filePath = path8.join(this.downloadsPath, filename);
|
|
3588
3642
|
let stats;
|
|
3589
3643
|
try {
|
|
3590
3644
|
stats = fs8.lstatSync(filePath);
|
|
@@ -3862,6 +3916,8 @@ class BrowserRuntime {
|
|
|
3862
3916
|
async dispatch(action, input, execution) {
|
|
3863
3917
|
if (typeof input.tabId === "string" && action !== "close_tab")
|
|
3864
3918
|
await this.guardPage?.(this.page(input.tabId));
|
|
3919
|
+
if (typeof input.tabId !== "string")
|
|
3920
|
+
execution.beforeDispatch?.();
|
|
3865
3921
|
if (action === "upload_abort") {
|
|
3866
3922
|
this.uploads.abort(input.uploadId, input.tabId);
|
|
3867
3923
|
return { aborted: true };
|
|
@@ -3912,6 +3968,7 @@ class BrowserRuntime {
|
|
|
3912
3968
|
input = { ...input, ...input.from ? { from: map(input.from), to: map(input.to) } : map({ x: Number(input.x), y: Number(input.y) }) };
|
|
3913
3969
|
delete input.screenshot;
|
|
3914
3970
|
}
|
|
3971
|
+
execution.beforeDispatch?.();
|
|
3915
3972
|
if (!["screenshot", "read_page", "inspect", "events", "diagnostics", "capabilities"].includes(action))
|
|
3916
3973
|
this.screenshots.delete(tabId);
|
|
3917
3974
|
if (action === "mouse_click" || action === "keyboard") {
|
|
@@ -3932,7 +3989,9 @@ class BrowserRuntime {
|
|
|
3932
3989
|
const webmcp = await this.webmcp.get(page).list();
|
|
3933
3990
|
return {
|
|
3934
3991
|
tabId,
|
|
3935
|
-
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" },
|
|
3936
3995
|
batch: { maxSteps: 8, maxBudgetMs: 30000, adaptive: false },
|
|
3937
3996
|
diagnostics: true,
|
|
3938
3997
|
dialogs: true,
|
|
@@ -3949,6 +4008,7 @@ class BrowserRuntime {
|
|
|
3949
4008
|
requires: "Origin permission and browser focus; permissions are never auto-granted"
|
|
3950
4009
|
},
|
|
3951
4010
|
export: {
|
|
4011
|
+
supported: null,
|
|
3952
4012
|
formats: ["text", "html", "pdf", "assets"],
|
|
3953
4013
|
pdf: "Requires Chrome printToPDF",
|
|
3954
4014
|
assets: "Only already observed, uncompressed image/font/CSS responses with a bounded Content-Length"
|
|
@@ -4060,13 +4120,19 @@ class BrowserRuntime {
|
|
|
4060
4120
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
4061
4121
|
fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
4062
4122
|
return {
|
|
4063
|
-
downloadId: this.downloadId(
|
|
4123
|
+
downloadId: this.downloadId(path8.basename(target2)),
|
|
4064
4124
|
filename: file.filename,
|
|
4065
4125
|
size: file.bytes.length,
|
|
4066
4126
|
mimeType: file.mimeType
|
|
4067
4127
|
};
|
|
4068
4128
|
});
|
|
4069
|
-
return { tabId, exported: true, format: input.format, exports
|
|
4129
|
+
return { tabId, exported: true, format: input.format, exports, ...input.format === "pdf" ? {
|
|
4130
|
+
exportKind: "page_print",
|
|
4131
|
+
printMode: "css_print",
|
|
4132
|
+
contentCompleteness: "unverified",
|
|
4133
|
+
limitations: "PDF bytes were generated from the current page using Chrome print CSS, not a native document/message export. Nested scroll containers, lazy/unloaded content, collapsed sections, images, and application print styles may omit content; successful generation does not verify all source content.",
|
|
4134
|
+
guidance: "Inspect every PDF page for expected text and images. For an original message/document use the website's native download/export. If authorized, open the site's dedicated print view using its normal controls and export that tab; no print view, expansion, scrolling, or page modification is performed automatically."
|
|
4135
|
+
} : {} };
|
|
4070
4136
|
}
|
|
4071
4137
|
case "webmcp_list":
|
|
4072
4138
|
return { tabId, ...await this.webmcp.get(page).list() };
|
|
@@ -4531,11 +4597,13 @@ class NativeRuntime {
|
|
|
4531
4597
|
plugins = [];
|
|
4532
4598
|
owners = new Map;
|
|
4533
4599
|
generations = new Map;
|
|
4534
|
-
|
|
4600
|
+
tracking = new WeakMap;
|
|
4535
4601
|
ended = new Set;
|
|
4536
4602
|
epochs = new Map;
|
|
4537
4603
|
controllers = new Map;
|
|
4538
4604
|
disconnected = false;
|
|
4605
|
+
connectionEpoch = 0;
|
|
4606
|
+
downloadAdmissionEpoch = 0;
|
|
4539
4607
|
operations = new Map;
|
|
4540
4608
|
hooks = Promise.resolve();
|
|
4541
4609
|
browserId;
|
|
@@ -4544,7 +4612,7 @@ class NativeRuntime {
|
|
|
4544
4612
|
this.instanceId = instanceId;
|
|
4545
4613
|
this.serverOrigin = serverOrigin;
|
|
4546
4614
|
installCancellation(context);
|
|
4547
|
-
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page) => this.download(download, page), (page) => this.
|
|
4615
|
+
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page));
|
|
4548
4616
|
context.on("page", (page) => {
|
|
4549
4617
|
this.track(page);
|
|
4550
4618
|
});
|
|
@@ -4556,14 +4624,20 @@ class NativeRuntime {
|
|
|
4556
4624
|
this.disconnected = true;
|
|
4557
4625
|
});
|
|
4558
4626
|
}
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
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) {
|
|
4563
4636
|
const id = await this.engine.idFor(page);
|
|
4564
4637
|
this.generations.set(id, 0);
|
|
4565
4638
|
const opener = await page.opener();
|
|
4566
4639
|
if (opener) {
|
|
4640
|
+
await this.track(opener);
|
|
4567
4641
|
const openerId = await this.engine.idFor(opener), owner = this.owners.get(openerId);
|
|
4568
4642
|
if (owner)
|
|
4569
4643
|
this.owners.set(id, { ...owner });
|
|
@@ -4577,6 +4651,7 @@ class NativeRuntime {
|
|
|
4577
4651
|
});
|
|
4578
4652
|
});
|
|
4579
4653
|
page.on("close", () => {
|
|
4654
|
+
this.downloadAdmissionEpoch++;
|
|
4580
4655
|
this.generations.delete(id);
|
|
4581
4656
|
this.owners.delete(id);
|
|
4582
4657
|
this.enqueue(async () => {
|
|
@@ -4585,19 +4660,24 @@ class NativeRuntime {
|
|
|
4585
4660
|
});
|
|
4586
4661
|
});
|
|
4587
4662
|
}
|
|
4588
|
-
async download(download, page) {
|
|
4663
|
+
async download(download, page, downloadId) {
|
|
4664
|
+
const admissionEpoch = this.downloadAdmissionEpoch, connectionEpoch = this.connectionEpoch;
|
|
4665
|
+
await this.track(page);
|
|
4589
4666
|
const id = await this.engine.idFor(page), scope = this.owners.get(id);
|
|
4590
|
-
|
|
4591
|
-
|
|
4592
|
-
|
|
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(() => {});
|
|
4673
|
+
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4593
4674
|
}
|
|
4594
|
-
const
|
|
4595
|
-
if (!
|
|
4675
|
+
const handler = this.plugins.find((p) => p.onDownload);
|
|
4676
|
+
if (!handler) {
|
|
4596
4677
|
await download.cancel();
|
|
4597
|
-
return;
|
|
4678
|
+
return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
|
|
4598
4679
|
}
|
|
4599
|
-
|
|
4600
|
-
await p.onDownload(download, id, scope, this.generations.get(id) ?? 0);
|
|
4680
|
+
return handler.onDownload(download, id, scope, this.generations.get(id) ?? 0, downloadId);
|
|
4601
4681
|
}
|
|
4602
4682
|
scopeEpoch(scope) {
|
|
4603
4683
|
this.validateScope(scope);
|
|
@@ -4607,51 +4687,15 @@ class NativeRuntime {
|
|
|
4607
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)
|
|
4608
4688
|
throw new Error("Invalid or revoked runtime scope");
|
|
4609
4689
|
}
|
|
4610
|
-
|
|
4611
|
-
if (value === "about:blank" || value === "about:srcdoc")
|
|
4612
|
-
return true;
|
|
4613
|
-
try {
|
|
4614
|
-
const u = new URL(value);
|
|
4615
|
-
return ["https:", "http:"].includes(u.protocol) && u.origin !== this.serverOrigin && !u.username && !u.password;
|
|
4616
|
-
} catch {
|
|
4617
|
-
return false;
|
|
4618
|
-
}
|
|
4619
|
-
}
|
|
4620
|
-
assertPage(page) {
|
|
4690
|
+
assertPageAvailable(page) {
|
|
4621
4691
|
if (page.isClosed())
|
|
4622
4692
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4623
|
-
if (page.frames().some((f) => !this.allowURL(f.url())))
|
|
4624
|
-
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);
|
|
4625
|
-
}
|
|
4626
|
-
async assertPageDeep(page) {
|
|
4627
|
-
this.assertPage(page);
|
|
4628
|
-
const visited = new Set;
|
|
4629
|
-
let opener = await page.opener();
|
|
4630
|
-
while (opener && !visited.has(opener)) {
|
|
4631
|
-
visited.add(opener);
|
|
4632
|
-
this.assertPage(opener);
|
|
4633
|
-
opener = await opener.opener();
|
|
4634
|
-
}
|
|
4635
|
-
const cdp = await this.context.newCDPSession(page);
|
|
4636
|
-
try {
|
|
4637
|
-
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
4638
|
-
const check = (tree) => {
|
|
4639
|
-
const origin = tree.frame.securityOrigin;
|
|
4640
|
-
if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
|
|
4641
|
-
throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
|
|
4642
|
-
for (const child of tree.childFrames ?? [])
|
|
4643
|
-
check(child);
|
|
4644
|
-
};
|
|
4645
|
-
check(frameTree);
|
|
4646
|
-
} finally {
|
|
4647
|
-
await cdp.detach();
|
|
4648
|
-
}
|
|
4649
4693
|
}
|
|
4650
4694
|
async resolveTarget(tabId, scope, frames = []) {
|
|
4651
4695
|
this.validateScope(scope);
|
|
4652
|
-
const page = this.claimPage(tabId, scope);
|
|
4696
|
+
const page = await this.claimPage(tabId, scope);
|
|
4653
4697
|
await this.track(page);
|
|
4654
|
-
|
|
4698
|
+
this.assertPageAvailable(page);
|
|
4655
4699
|
let frame = page.mainFrame();
|
|
4656
4700
|
for (const selector of frames) {
|
|
4657
4701
|
const locator = frame.locator(selector);
|
|
@@ -4668,7 +4712,7 @@ class NativeRuntime {
|
|
|
4668
4712
|
const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4669
4713
|
const assertCurrent = () => {
|
|
4670
4714
|
this.validateScope(scope);
|
|
4671
|
-
this.
|
|
4715
|
+
this.assertPageAvailable(page);
|
|
4672
4716
|
if ((this.epochs.get(scopeKey(scope)) ?? 0) !== scopeEpoch || frame.isDetached() || this.generations.get(tabId) !== generation || scopeKey(this.owners.get(tabId)) !== scopeKey(scope))
|
|
4673
4717
|
throw new Error("Stale document or scope");
|
|
4674
4718
|
};
|
|
@@ -4682,7 +4726,7 @@ class NativeRuntime {
|
|
|
4682
4726
|
throw new Error("File input unavailable");
|
|
4683
4727
|
try {
|
|
4684
4728
|
const frame = await element.ownerFrame();
|
|
4685
|
-
if (!frame ||
|
|
4729
|
+
if (!frame || frame.isDetached())
|
|
4686
4730
|
throw new Error("File input frame unavailable");
|
|
4687
4731
|
const valid = await element.evaluate((el) => el instanceof HTMLInputElement && el.type === "file" && !el.webkitdirectory && el.isConnected);
|
|
4688
4732
|
target2.assertCurrent();
|
|
@@ -4704,7 +4748,7 @@ class NativeRuntime {
|
|
|
4704
4748
|
events.diagnosticsSuppressed = false;
|
|
4705
4749
|
}
|
|
4706
4750
|
}
|
|
4707
|
-
claimPage(tabId, scope) {
|
|
4751
|
+
async claimPage(tabId, scope) {
|
|
4708
4752
|
this.validateScope(scope);
|
|
4709
4753
|
let page;
|
|
4710
4754
|
try {
|
|
@@ -4712,17 +4756,52 @@ class NativeRuntime {
|
|
|
4712
4756
|
} catch {
|
|
4713
4757
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4714
4758
|
}
|
|
4759
|
+
await this.track(page);
|
|
4760
|
+
this.validateScope(scope);
|
|
4715
4761
|
const owner = this.owners.get(tabId);
|
|
4716
4762
|
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4717
4763
|
throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
|
|
4718
4764
|
this.owners.set(tabId, { ...scope });
|
|
4719
4765
|
return page;
|
|
4720
4766
|
}
|
|
4721
|
-
targetCapabilities(tabId, scope) {
|
|
4722
|
-
const page = this.claimPage(tabId, scope);
|
|
4723
|
-
const
|
|
4724
|
-
|
|
4725
|
-
|
|
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
|
+
};
|
|
4726
4805
|
}
|
|
4727
4806
|
async closeBlockedTab(tabId, scope, operationId) {
|
|
4728
4807
|
this.validateScope(scope);
|
|
@@ -4736,7 +4815,33 @@ class NativeRuntime {
|
|
|
4736
4815
|
this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
|
|
4737
4816
|
return { closed: true };
|
|
4738
4817
|
}
|
|
4739
|
-
|
|
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) {
|
|
4740
4845
|
if (op === "session_end") {
|
|
4741
4846
|
await this.endSession(scope);
|
|
4742
4847
|
return { ended: true };
|
|
@@ -4750,7 +4855,7 @@ class NativeRuntime {
|
|
|
4750
4855
|
set.add(controller);
|
|
4751
4856
|
this.operations.set(operationId, controller);
|
|
4752
4857
|
try {
|
|
4753
|
-
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
|
|
4858
|
+
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch));
|
|
4754
4859
|
} finally {
|
|
4755
4860
|
this.operations.delete(operationId);
|
|
4756
4861
|
set.delete(controller);
|
|
@@ -4758,42 +4863,38 @@ class NativeRuntime {
|
|
|
4758
4863
|
this.controllers.delete(key);
|
|
4759
4864
|
}
|
|
4760
4865
|
}
|
|
4761
|
-
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
|
+
};
|
|
4762
4873
|
await this.hooks;
|
|
4763
4874
|
this.validateScope(scope);
|
|
4764
|
-
if (args.url !== undefined && !this.allowURL(String(args.url)))
|
|
4765
|
-
throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
|
|
4766
|
-
if (op === "capabilities" && typeof args.tabId === "string") {
|
|
4767
|
-
const target2 = this.targetCapabilities(args.tabId, scope);
|
|
4768
|
-
if (!target2.pageToolsSupported || target2.pdfDetected)
|
|
4769
|
-
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" };
|
|
4770
|
-
}
|
|
4771
4875
|
if (typeof args.tabId === "string") {
|
|
4772
|
-
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
await this.resolveTarget(args.tabId, scope);
|
|
4876
|
+
const page = await this.claimPage(args.tabId, scope);
|
|
4877
|
+
await this.track(page);
|
|
4878
|
+
this.assertPageAvailable(page);
|
|
4776
4879
|
}
|
|
4777
|
-
if (op === "batch" && Array.isArray(args.steps))
|
|
4778
|
-
for (const step of args.steps) {
|
|
4779
|
-
if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
|
|
4780
|
-
throw new Error("Unsupported batch navigation origin");
|
|
4781
|
-
}
|
|
4782
4880
|
if (op === "session_end") {
|
|
4783
4881
|
await this.endSession(scope);
|
|
4784
4882
|
return { ended: true };
|
|
4785
4883
|
}
|
|
4786
4884
|
if (op === "release_tab") {
|
|
4787
4885
|
const tabId = String(args.tabId);
|
|
4788
|
-
|
|
4789
|
-
|
|
4886
|
+
begin();
|
|
4887
|
+
this.downloadAdmissionEpoch++;
|
|
4790
4888
|
this.owners.delete(tabId);
|
|
4791
4889
|
this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
|
|
4890
|
+
for (const p of this.plugins)
|
|
4891
|
+
await p.onHandoff?.(tabId, scope);
|
|
4792
4892
|
return { released: true, tabId };
|
|
4793
4893
|
}
|
|
4794
4894
|
const operationEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4795
4895
|
const plugin = this.plugins.find((p) => p.operations.includes(op));
|
|
4796
4896
|
if (plugin) {
|
|
4897
|
+
begin();
|
|
4797
4898
|
if (op === "cancel_transfer" && args.eventId && args.tabId)
|
|
4798
4899
|
return this.engine.execute("cancel_transfer", args, { operationId });
|
|
4799
4900
|
return plugin.execute(op, args, scope);
|
|
@@ -4801,23 +4902,25 @@ class NativeRuntime {
|
|
|
4801
4902
|
if (!BROWSER_OPERATIONS.includes(op))
|
|
4802
4903
|
throw new Error("Unsupported operation");
|
|
4803
4904
|
if (op === "list_tabs") {
|
|
4905
|
+
begin();
|
|
4804
4906
|
const tabs = await this.engine.listTabs();
|
|
4805
|
-
|
|
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)) };
|
|
4806
4910
|
}
|
|
4807
4911
|
try {
|
|
4808
|
-
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;
|
|
4809
4916
|
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4810
4917
|
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4811
|
-
if (typeof args.tabId === "string" && op !== "close_tab")
|
|
4812
|
-
await this.assertPageDeep(this.engine.page(args.tabId));
|
|
4813
4918
|
if (op === "open_tab" && typeof result?.tab?.tabId === "string")
|
|
4814
4919
|
this.owners.set(result.tab.tabId, { ...scope });
|
|
4815
|
-
|
|
4816
|
-
return { ...result, ...this.targetCapabilities(args.tabId, scope) };
|
|
4817
|
-
return result;
|
|
4920
|
+
return target2 ? { ...result, ...target2 } : result;
|
|
4818
4921
|
} catch (error) {
|
|
4819
4922
|
if (error instanceof RuntimeFault)
|
|
4820
|
-
throw new RuntimeFault(error.code, error.recovery,
|
|
4923
|
+
throw new RuntimeFault(error.code, error.recovery, !dispatched && error.beforeDispatch);
|
|
4821
4924
|
throw error;
|
|
4822
4925
|
}
|
|
4823
4926
|
}
|
|
@@ -4827,11 +4930,12 @@ class NativeRuntime {
|
|
|
4827
4930
|
this.epochs.set(key, (this.epochs.get(key) ?? 0) + 1);
|
|
4828
4931
|
for (const controller of this.controllers.get(key) ?? [])
|
|
4829
4932
|
controller.abort(new Error("Runtime scope revoked"));
|
|
4830
|
-
|
|
4831
|
-
await p.onSessionEnd?.(scope);
|
|
4933
|
+
this.downloadAdmissionEpoch++;
|
|
4832
4934
|
for (const [id, owner] of this.owners)
|
|
4833
4935
|
if (scopeKey(owner) === key)
|
|
4834
4936
|
this.owners.delete(id);
|
|
4937
|
+
for (const p of this.plugins)
|
|
4938
|
+
await p.onSessionEnd?.(scope);
|
|
4835
4939
|
this.ended.delete(key);
|
|
4836
4940
|
}
|
|
4837
4941
|
async shutdown() {
|
|
@@ -4844,6 +4948,7 @@ class NativeRuntime {
|
|
|
4844
4948
|
}
|
|
4845
4949
|
async disconnect() {
|
|
4846
4950
|
this.disconnected = true;
|
|
4951
|
+
this.connectionEpoch++;
|
|
4847
4952
|
for (const controllers of this.controllers.values())
|
|
4848
4953
|
for (const controller of controllers)
|
|
4849
4954
|
controller.abort(new Error("Runtime disconnected"));
|
|
@@ -4863,7 +4968,7 @@ class NativeRuntime {
|
|
|
4863
4968
|
import WebSocket2 from "ws";
|
|
4864
4969
|
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4865
4970
|
import fs9 from "node:fs/promises";
|
|
4866
|
-
import
|
|
4971
|
+
import path9 from "node:path";
|
|
4867
4972
|
|
|
4868
4973
|
// cli/src/live/producer.ts
|
|
4869
4974
|
import WebSocket from "ws";
|
|
@@ -5242,6 +5347,7 @@ class NativeLiveProducer {
|
|
|
5242
5347
|
|
|
5243
5348
|
// cli/src/runtime/relay.ts
|
|
5244
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 });
|
|
5245
5351
|
var LIMIT = 2 * 1024 * 1024;
|
|
5246
5352
|
function wireResult(op, value) {
|
|
5247
5353
|
if (!value || typeof value !== "object")
|
|
@@ -5286,14 +5392,102 @@ class Relay {
|
|
|
5286
5392
|
live;
|
|
5287
5393
|
seen = new Set;
|
|
5288
5394
|
active;
|
|
5395
|
+
waiting = [];
|
|
5289
5396
|
recent = [];
|
|
5397
|
+
blocker(active, scope) {
|
|
5398
|
+
const quarantined = active.timedOut || active.interrupted;
|
|
5399
|
+
const state = { quarantined, executionState: active.settled ? active.interrupted ? "settled_after_interruption" : "settled_late" : quarantined ? "unresolved" : "in_progress" };
|
|
5400
|
+
if (scope && !sameScope3(active.scope, scope))
|
|
5401
|
+
return { ...state, ownedByAnotherScope: true };
|
|
5402
|
+
return { ...state, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
|
|
5403
|
+
}
|
|
5290
5404
|
health(scope) {
|
|
5291
|
-
const active = this.active
|
|
5292
|
-
|
|
5405
|
+
const active = this.active;
|
|
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();
|
|
5293
5456
|
}
|
|
5294
|
-
|
|
5295
|
-
if (this.active)
|
|
5296
|
-
|
|
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);
|
|
5297
5491
|
}
|
|
5298
5492
|
remember(active, result) {
|
|
5299
5493
|
this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
|
|
@@ -5332,7 +5526,7 @@ class Relay {
|
|
|
5332
5526
|
await new Promise((resolve2, reject) => {
|
|
5333
5527
|
socket.once("error", reject);
|
|
5334
5528
|
socket.once("close", () => {
|
|
5335
|
-
this.interrupt();
|
|
5529
|
+
this.interrupt("queue_disconnected");
|
|
5336
5530
|
clearInterval(heartbeat);
|
|
5337
5531
|
resolve2();
|
|
5338
5532
|
});
|
|
@@ -5343,7 +5537,7 @@ class Relay {
|
|
|
5343
5537
|
heartbeat.unref();
|
|
5344
5538
|
socket.once("open", () => {
|
|
5345
5539
|
this.state = "authenticating";
|
|
5346
|
-
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 } } }));
|
|
5347
5541
|
});
|
|
5348
5542
|
socket.on("message", (bytes, binary) => {
|
|
5349
5543
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5368,15 +5562,14 @@ class Relay {
|
|
|
5368
5562
|
this.state = "connected";
|
|
5369
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) => {
|
|
5370
5564
|
try {
|
|
5371
|
-
|
|
5565
|
+
this.runtime.assertPageAvailable(page);
|
|
5372
5566
|
return true;
|
|
5373
5567
|
} catch {
|
|
5374
5568
|
return false;
|
|
5375
5569
|
}
|
|
5376
5570
|
}, getPage: (id) => {
|
|
5377
5571
|
try {
|
|
5378
|
-
|
|
5379
|
-
return page.frames().every((f) => this.runtime.allowURL(f.url())) ? page : undefined;
|
|
5572
|
+
return this.runtime.engine.page(id);
|
|
5380
5573
|
} catch {
|
|
5381
5574
|
return;
|
|
5382
5575
|
}
|
|
@@ -5391,6 +5584,10 @@ class Relay {
|
|
|
5391
5584
|
this.live?.onWatch(message).catch(() => {});
|
|
5392
5585
|
} else if (message.type === "ping")
|
|
5393
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);
|
|
5394
5591
|
else if (message.type === "command") {
|
|
5395
5592
|
if (this.state !== "connected" || this.paused) {
|
|
5396
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." } }));
|
|
@@ -5436,6 +5633,10 @@ class Relay {
|
|
|
5436
5633
|
return;
|
|
5437
5634
|
}
|
|
5438
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
|
+
}
|
|
5439
5640
|
if (message.op === "runtime_health") {
|
|
5440
5641
|
send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
|
|
5441
5642
|
return;
|
|
@@ -5445,33 +5646,92 @@ class Relay {
|
|
|
5445
5646
|
return;
|
|
5446
5647
|
}
|
|
5447
5648
|
if (message.op === "session_end") {
|
|
5649
|
+
this.flushWaiting("queue_scope_ended", "Session ended while waiting. No action was dispatched.", message.scope);
|
|
5448
5650
|
if (this.active && sameScope3(this.active.scope, message.scope))
|
|
5449
|
-
this.interrupt();
|
|
5651
|
+
this.interrupt("queue_interrupted");
|
|
5450
5652
|
await this.runtime.endSession(message.scope);
|
|
5653
|
+
this.drain();
|
|
5451
5654
|
send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
|
|
5452
5655
|
return;
|
|
5453
5656
|
}
|
|
5454
|
-
|
|
5455
|
-
|
|
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." });
|
|
5456
5660
|
return;
|
|
5457
5661
|
}
|
|
5458
|
-
|
|
5459
|
-
|
|
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) => {
|
|
5460
5695
|
finish = resolve2;
|
|
5461
|
-
}) };
|
|
5696
|
+
}), interrupt: () => interrupt(), expire: () => expire() };
|
|
5462
5697
|
this.active = active;
|
|
5463
5698
|
let stage = "execute", timer;
|
|
5464
5699
|
const expired = new Promise((resolve2) => {
|
|
5465
|
-
|
|
5466
|
-
active.
|
|
5467
|
-
|
|
5468
|
-
|
|
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);
|
|
5469
5719
|
resolve2();
|
|
5470
|
-
}
|
|
5720
|
+
};
|
|
5721
|
+
interrupt = () => terminal(true);
|
|
5722
|
+
expire = () => terminal(false);
|
|
5723
|
+
timer = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
|
|
5471
5724
|
});
|
|
5472
5725
|
const task = (async () => {
|
|
5726
|
+
let response;
|
|
5473
5727
|
try {
|
|
5474
|
-
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);
|
|
5475
5735
|
if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5476
5736
|
return;
|
|
5477
5737
|
this.runtime.validateScope(message.scope);
|
|
@@ -5489,9 +5749,9 @@ class Relay {
|
|
|
5489
5749
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5490
5750
|
for (const item of result.exports) {
|
|
5491
5751
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5492
|
-
if (
|
|
5752
|
+
if (path9.basename(filename) !== filename)
|
|
5493
5753
|
throw new Error("Invalid export file");
|
|
5494
|
-
const filenamePath =
|
|
5754
|
+
const filenamePath = path9.join(this.previewDirectory, filename);
|
|
5495
5755
|
const stat = await fs9.lstat(filenamePath);
|
|
5496
5756
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5497
5757
|
throw new Error("Invalid export file");
|
|
@@ -5501,26 +5761,32 @@ class Relay {
|
|
|
5501
5761
|
}
|
|
5502
5762
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5503
5763
|
for (const artifact2 of result.artifacts)
|
|
5504
|
-
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact",
|
|
5505
|
-
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) }));
|
|
5506
5766
|
}
|
|
5507
5767
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5508
5768
|
throw new Error("Result budget exceeded");
|
|
5509
|
-
|
|
5510
|
-
send({ type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" });
|
|
5769
|
+
response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
|
|
5511
5770
|
} catch (error) {
|
|
5512
5771
|
const failure = failureFor(error, message.op, message.id, stage);
|
|
5513
|
-
if (
|
|
5514
|
-
|
|
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
|
+
}
|
|
5777
|
+
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5515
5778
|
} finally {
|
|
5516
5779
|
clearTimeout(timer);
|
|
5517
5780
|
active.settled = true;
|
|
5518
5781
|
finish();
|
|
5519
5782
|
if (active.timedOut || active.interrupted)
|
|
5520
5783
|
this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
|
|
5521
|
-
if (this.active === active && !active.interrupted && !active.recovering)
|
|
5784
|
+
if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
|
|
5522
5785
|
this.active = undefined;
|
|
5523
5786
|
}
|
|
5787
|
+
if (response && !active.timedOut && !active.interrupted)
|
|
5788
|
+
send(response);
|
|
5789
|
+
this.drain();
|
|
5524
5790
|
})();
|
|
5525
5791
|
await Promise.race([task, expired]);
|
|
5526
5792
|
}
|
|
@@ -5533,6 +5799,7 @@ class Relay {
|
|
|
5533
5799
|
return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
|
|
5534
5800
|
if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
|
|
5535
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.");
|
|
5536
5803
|
active.recovering = true;
|
|
5537
5804
|
const work = (async () => {
|
|
5538
5805
|
await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
|
|
@@ -5564,8 +5831,8 @@ class Relay {
|
|
|
5564
5831
|
return { blobId, role, name, mimeType, size: bytes.length, sha256 };
|
|
5565
5832
|
}
|
|
5566
5833
|
async pause() {
|
|
5567
|
-
this.interrupt();
|
|
5568
5834
|
this.paused = true;
|
|
5835
|
+
this.interrupt("queue_paused");
|
|
5569
5836
|
this.state = "paused";
|
|
5570
5837
|
this.socket?.close();
|
|
5571
5838
|
await this.live?.stop();
|
|
@@ -5575,8 +5842,8 @@ class Relay {
|
|
|
5575
5842
|
this.paused = false;
|
|
5576
5843
|
}
|
|
5577
5844
|
async stop() {
|
|
5578
|
-
this.interrupt();
|
|
5579
5845
|
this.stopping = true;
|
|
5846
|
+
this.interrupt("queue_shutdown");
|
|
5580
5847
|
this.socket?.close();
|
|
5581
5848
|
await this.live?.stop();
|
|
5582
5849
|
await this.runtime.disconnect();
|
|
@@ -5584,12 +5851,12 @@ class Relay {
|
|
|
5584
5851
|
}
|
|
5585
5852
|
|
|
5586
5853
|
// cli/src/data/index.ts
|
|
5587
|
-
import { mkdir as mkdir2, open as
|
|
5588
|
-
import { createReadStream, createWriteStream } from "node:fs";
|
|
5589
|
-
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";
|
|
5590
5857
|
import { join as join2, basename } from "node:path";
|
|
5591
|
-
import { Readable, Transform } from "node:stream";
|
|
5592
|
-
import { pipeline } from "node:stream/promises";
|
|
5858
|
+
import { Readable, Transform as Transform2 } from "node:stream";
|
|
5859
|
+
import { pipeline as pipeline2 } from "node:stream/promises";
|
|
5593
5860
|
|
|
5594
5861
|
// cli/src/data/vault.ts
|
|
5595
5862
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
@@ -5710,6 +5977,129 @@ class SecretVault {
|
|
|
5710
5977
|
}
|
|
5711
5978
|
}
|
|
5712
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
|
+
|
|
5713
6103
|
// cli/src/data/index.ts
|
|
5714
6104
|
var safeName = (s) => {
|
|
5715
6105
|
const name = basename(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
|
|
@@ -5721,8 +6111,22 @@ async function createDataPlugin(access, options) {
|
|
|
5721
6111
|
await mkdir2(options.directory, { mode: 448 });
|
|
5722
6112
|
const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
|
|
5723
6113
|
let stopped = false;
|
|
6114
|
+
const terminal = new Map;
|
|
6115
|
+
function remember(r) {
|
|
6116
|
+
if (r.purpose !== "download")
|
|
6117
|
+
return;
|
|
6118
|
+
terminal.set(r.id, { scope: r.scope, meta: { ...meta(r), state: r.terminalCode?.startsWith("download_capture") || r.terminalCode === "download_quota_exceeded" ? "failed" : r.terminalCode === "download_expired" ? "expired" : "cancelled", size: r.hash ? r.size : undefined, maxBytes: undefined, retrieval: undefined, readiness: "unavailable", code: r.terminalCode ?? "download_revoked", recovery: "Retained bytes are unavailable. Do not automatically replay the source action; ask before recreating the download." }, until: Date.now() + LIMITS.ttl });
|
|
6119
|
+
while (terminal.size > 128)
|
|
6120
|
+
terminal.delete(terminal.keys().next().value);
|
|
6121
|
+
}
|
|
6122
|
+
function status(scope, id) {
|
|
6123
|
+
const t = terminal.get(String(id));
|
|
6124
|
+
if (t && t.until >= Date.now() && sameScope(t.scope, scope))
|
|
6125
|
+
return t.meta;
|
|
6126
|
+
return meta(get(scope, id));
|
|
6127
|
+
}
|
|
5724
6128
|
function meta(r) {
|
|
5725
|
-
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: 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 } } } : {} };
|
|
5726
6130
|
}
|
|
5727
6131
|
function get(scope, id) {
|
|
5728
6132
|
const r = resources.get(String(id));
|
|
@@ -5742,9 +6146,11 @@ async function createDataPlugin(access, options) {
|
|
|
5742
6146
|
return r;
|
|
5743
6147
|
}
|
|
5744
6148
|
async function remove(r) {
|
|
6149
|
+
r.terminalCode ??= "download_revoked";
|
|
5745
6150
|
r.abort.abort();
|
|
5746
6151
|
r.state = "cancelled";
|
|
5747
6152
|
await r.task?.catch(() => {});
|
|
6153
|
+
remember(r);
|
|
5748
6154
|
r.bytes?.fill(0);
|
|
5749
6155
|
r.bytes = undefined;
|
|
5750
6156
|
if (r.path && owned.has(r.path)) {
|
|
@@ -5775,20 +6181,20 @@ async function createDataPlugin(access, options) {
|
|
|
5775
6181
|
await mkdir2(dir, { mode: 448 });
|
|
5776
6182
|
ownedDirs.add(dir);
|
|
5777
6183
|
const part = join2(options.directory, `${r.id}.partial`), dest = join2(dir, r.name);
|
|
5778
|
-
const h = await
|
|
6184
|
+
const h = await open3(part, "wx", 384);
|
|
5779
6185
|
await h.close();
|
|
5780
6186
|
owned.add(part);
|
|
5781
6187
|
r.path = part;
|
|
5782
6188
|
let size = 0;
|
|
5783
|
-
const hash =
|
|
5784
|
-
const check = new
|
|
6189
|
+
const hash = createHash7("sha256");
|
|
6190
|
+
const check = new Transform2({ transform(chunk, _enc, cb) {
|
|
5785
6191
|
size += chunk.length;
|
|
5786
6192
|
if (size > r.size)
|
|
5787
6193
|
return cb(new Error("Size exceeded"));
|
|
5788
6194
|
hash.update(chunk);
|
|
5789
6195
|
cb(null, chunk);
|
|
5790
6196
|
} });
|
|
5791
|
-
await
|
|
6197
|
+
await pipeline2(Readable.fromWeb(response.body), check, createWriteStream2(part, { flags: "r+", mode: 384 }), { signal: r.abort.signal });
|
|
5792
6198
|
const actual = hash.digest("hex");
|
|
5793
6199
|
if (size !== r.size || r.expectedHash && actual !== r.expectedHash)
|
|
5794
6200
|
throw new Error("Verification failed");
|
|
@@ -5811,7 +6217,7 @@ async function createDataPlugin(access, options) {
|
|
|
5811
6217
|
body = Readable.toWeb(createReadStream(r.path));
|
|
5812
6218
|
}
|
|
5813
6219
|
const response = await fetch(g.url, { method: "PUT", headers: g.headers, body, duplex: "half", redirect: "error", signal: r.abort.signal });
|
|
5814
|
-
if (!response.ok)
|
|
6220
|
+
if (!response.ok || r.abort.signal.aborted || r.state === "cancelled")
|
|
5815
6221
|
throw new Error("Transfer failed");
|
|
5816
6222
|
r.state = "ready";
|
|
5817
6223
|
}
|
|
@@ -5835,8 +6241,20 @@ async function createDataPlugin(access, options) {
|
|
|
5835
6241
|
}
|
|
5836
6242
|
}
|
|
5837
6243
|
}
|
|
6244
|
+
async function sweepExpired() {
|
|
6245
|
+
await revoke((r) => {
|
|
6246
|
+
if (r.expiresAt < Date.now() && r.state !== "attached") {
|
|
6247
|
+
r.terminalCode = "download_expired";
|
|
6248
|
+
return true;
|
|
6249
|
+
}
|
|
6250
|
+
return false;
|
|
6251
|
+
});
|
|
6252
|
+
for (const [id, t] of terminal)
|
|
6253
|
+
if (t.until < Date.now())
|
|
6254
|
+
terminal.delete(id);
|
|
6255
|
+
}
|
|
5838
6256
|
let sweep = setInterval(() => {
|
|
5839
|
-
|
|
6257
|
+
sweepExpired();
|
|
5840
6258
|
}, 1e4);
|
|
5841
6259
|
sweep.unref?.();
|
|
5842
6260
|
return {
|
|
@@ -5856,17 +6274,20 @@ async function createDataPlugin(access, options) {
|
|
|
5856
6274
|
return meta(r);
|
|
5857
6275
|
}
|
|
5858
6276
|
if (op === "create_download") {
|
|
5859
|
-
const r = get(
|
|
5860
|
-
if (r.purpose !== "download" || r.state !== "ready")
|
|
5861
|
-
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);
|
|
5862
6280
|
return meta(r);
|
|
5863
6281
|
}
|
|
5864
|
-
if (op === "transfer_status")
|
|
5865
|
-
|
|
6282
|
+
if (op === "transfer_status") {
|
|
6283
|
+
await sweepExpired();
|
|
6284
|
+
return status(scope, args.resourceId ?? args.transferId);
|
|
6285
|
+
}
|
|
5866
6286
|
if (op === "cancel_transfer") {
|
|
5867
6287
|
const r = get(scope, args.resourceId ?? args.transferId);
|
|
5868
6288
|
if (r.state === "attached")
|
|
5869
6289
|
throw new Error("Attached files retained until document ends");
|
|
6290
|
+
r.terminalCode = "download_cancelled";
|
|
5870
6291
|
await remove(r);
|
|
5871
6292
|
return { cancelled: true };
|
|
5872
6293
|
}
|
|
@@ -5874,14 +6295,16 @@ async function createDataPlugin(access, options) {
|
|
|
5874
6295
|
const r = get(scope, args.resourceId);
|
|
5875
6296
|
const grant = args.dataGrant;
|
|
5876
6297
|
validateGrant(grant, options.serverOrigin, r.id, options.allowInsecureLoopback);
|
|
5877
|
-
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)
|
|
5878
6299
|
throw new Error("Invalid data authorization");
|
|
5879
6300
|
r.authorized = true;
|
|
5880
6301
|
r.task = transfer(r, grant);
|
|
5881
6302
|
return { resourceId: r.id, state: "transferring" };
|
|
5882
6303
|
}
|
|
5883
|
-
if (op === "list_downloads")
|
|
5884
|
-
|
|
6304
|
+
if (op === "list_downloads") {
|
|
6305
|
+
await sweepExpired();
|
|
6306
|
+
return { files: [...resources.values()].filter((r) => sameScope(r.scope, scope) && r.purpose === "download").map(meta), terminal: [...terminal.values()].filter((t) => sameScope(t.scope, scope)).map((t) => t.meta) };
|
|
6307
|
+
}
|
|
5885
6308
|
if (op === "upload_files") {
|
|
5886
6309
|
const ids = args.fileIds;
|
|
5887
6310
|
if (!Array.isArray(ids) || !ids.length || ids.length > 100 || new Set(ids).size !== ids.length)
|
|
@@ -5935,54 +6358,72 @@ async function createDataPlugin(access, options) {
|
|
|
5935
6358
|
}
|
|
5936
6359
|
throw new Error("Unsupported data operation");
|
|
5937
6360
|
},
|
|
5938
|
-
async onDownload(download, tabId, scope, generation) {
|
|
6361
|
+
async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
|
|
5939
6362
|
let r;
|
|
6363
|
+
let timeout2;
|
|
6364
|
+
let cancel;
|
|
5940
6365
|
try {
|
|
5941
6366
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
6367
|
+
resources.delete(r.id);
|
|
6368
|
+
r.id = downloadId;
|
|
6369
|
+
resources.set(r.id, r);
|
|
5942
6370
|
r.tabId = tabId;
|
|
5943
6371
|
r.generation = generation;
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
|
|
5947
|
-
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
5953
|
-
if (received > LIMITS.file)
|
|
5954
|
-
return callback(new Error("Download quota exceeded"));
|
|
5955
|
-
callback(null, chunk);
|
|
5956
|
-
} });
|
|
5957
|
-
const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
6372
|
+
r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
|
|
6373
|
+
cancel = () => {
|
|
6374
|
+
download.cancel().catch(() => {});
|
|
6375
|
+
};
|
|
6376
|
+
r.abort.signal.addEventListener("abort", cancel, { once: true });
|
|
6377
|
+
timeout2 = setTimeout(() => {
|
|
6378
|
+
r.terminalCode ??= "download_capture_timeout";
|
|
6379
|
+
r.abort.abort();
|
|
6380
|
+
}, LIMITS.duration);
|
|
5958
6381
|
timeout2.unref?.();
|
|
5959
|
-
|
|
5960
|
-
|
|
5961
|
-
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
6382
|
+
const captured = r;
|
|
6383
|
+
r.task = (async () => {
|
|
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)
|
|
6398
|
+
throw new Error("Download revoked");
|
|
6399
|
+
captured.state = "ready";
|
|
6400
|
+
})();
|
|
6401
|
+
await r.task;
|
|
6402
|
+
if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
|
|
5974
6403
|
throw new Error("Download revoked");
|
|
5975
|
-
r
|
|
5976
|
-
} catch {
|
|
5977
|
-
|
|
5978
|
-
if (r)
|
|
6404
|
+
return { ...meta(r), state: "completed" };
|
|
6405
|
+
} catch (error) {
|
|
6406
|
+
download.cancel().catch(() => {});
|
|
6407
|
+
if (r) {
|
|
6408
|
+
r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
|
|
5979
6409
|
await remove(r);
|
|
6410
|
+
return status(scope, downloadId);
|
|
6411
|
+
}
|
|
6412
|
+
await cleanupDownload(download);
|
|
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." };
|
|
6414
|
+
terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6415
|
+
while (terminal.size > 128)
|
|
6416
|
+
terminal.delete(terminal.keys().next().value);
|
|
6417
|
+
return failed;
|
|
5980
6418
|
} finally {
|
|
5981
|
-
|
|
6419
|
+
if (timeout2)
|
|
6420
|
+
clearTimeout(timeout2);
|
|
6421
|
+
if (r && cancel)
|
|
6422
|
+
r.abort.signal.removeEventListener("abort", cancel);
|
|
5982
6423
|
}
|
|
5983
6424
|
},
|
|
5984
6425
|
async onNavigation(tabId, generation) {
|
|
5985
|
-
await revoke((r) => r.tabId === tabId && r.generation !== generation);
|
|
6426
|
+
await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
|
|
5986
6427
|
},
|
|
5987
6428
|
async onTabClose(tabId) {
|
|
5988
6429
|
await revoke((r) => r.tabId === tabId);
|
|
@@ -6010,7 +6451,7 @@ async function createDataPlugin(access, options) {
|
|
|
6010
6451
|
await mkdir2(options.directory, { mode: 448 });
|
|
6011
6452
|
stopped = false;
|
|
6012
6453
|
sweep = setInterval(() => {
|
|
6013
|
-
|
|
6454
|
+
sweepExpired();
|
|
6014
6455
|
}, 1e4);
|
|
6015
6456
|
sweep.unref?.();
|
|
6016
6457
|
}
|
|
@@ -6129,7 +6570,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6129
6570
|
for (const signal of signals)
|
|
6130
6571
|
process.on(signal, signalStop);
|
|
6131
6572
|
try {
|
|
6132
|
-
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);
|
|
6133
6577
|
if (command !== "start") {
|
|
6134
6578
|
const profile = profiles[0], controlPath = controlSocketPath(root, profile);
|
|
6135
6579
|
if (command === "recover") {
|
|
@@ -6147,7 +6591,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6147
6591
|
socket.end();
|
|
6148
6592
|
resolve2();
|
|
6149
6593
|
});
|
|
6150
|
-
socket.once("error", (error) => reject(
|
|
6594
|
+
socket.once("error", (error) => reject(controlFailure("control-connect", error)));
|
|
6151
6595
|
});
|
|
6152
6596
|
return;
|
|
6153
6597
|
}
|
|
@@ -6157,10 +6601,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6157
6601
|
const controlPath = controlSocketPath(root, profile);
|
|
6158
6602
|
const previousSocket = await fs10.lstat(controlPath).catch((error) => {
|
|
6159
6603
|
if (error.code !== "ENOENT")
|
|
6160
|
-
throw error;
|
|
6604
|
+
throw controlFailure("local-control", error);
|
|
6161
6605
|
});
|
|
6162
6606
|
if (previousSocket)
|
|
6163
|
-
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.`);
|
|
6164
6608
|
abort.signal.throwIfAborted();
|
|
6165
6609
|
}
|
|
6166
6610
|
const results = await Promise.allSettled(profiles.map(async (profile) => {
|
|
@@ -6209,7 +6653,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6209
6653
|
["Local control", async () => {
|
|
6210
6654
|
for (const client of clients)
|
|
6211
6655
|
client.destroy();
|
|
6212
|
-
|
|
6656
|
+
try {
|
|
6657
|
+
await stopControl?.();
|
|
6658
|
+
} catch (error) {
|
|
6659
|
+
throw controlFailure("control-cleanup", error);
|
|
6660
|
+
}
|
|
6213
6661
|
}],
|
|
6214
6662
|
["Browser session", async () => {
|
|
6215
6663
|
await session?.close();
|
|
@@ -6230,28 +6678,26 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6230
6678
|
if (groupSignal.aborted)
|
|
6231
6679
|
groupStop();
|
|
6232
6680
|
let failure, cleanupFailure;
|
|
6681
|
+
let runtimeStage = "download-quota";
|
|
6233
6682
|
try {
|
|
6234
6683
|
abort.signal.throwIfAborted();
|
|
6235
6684
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
6236
6685
|
session.lifecycle.ended.then(endSession);
|
|
6237
6686
|
abort.signal.throwIfAborted();
|
|
6238
|
-
stopQuota = await enforceDownloadQuota(session.context,
|
|
6687
|
+
stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
|
|
6239
6688
|
abort.signal.throwIfAborted();
|
|
6689
|
+
runtimeStage = "pairing";
|
|
6240
6690
|
const token = await credential(root, server, profile, abort.signal);
|
|
6241
6691
|
abort.signal.throwIfAborted();
|
|
6242
|
-
|
|
6692
|
+
runtimeStage = "runtime-setup";
|
|
6693
|
+
const previews = path10.join(session.runPath, "previews");
|
|
6243
6694
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
6244
|
-
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:" }));
|
|
6245
6696
|
abort.signal.throwIfAborted();
|
|
6246
6697
|
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
6247
6698
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
6248
|
-
await session.context.route("**/*", async (route) => {
|
|
6249
|
-
if (!runtime.allowURL(route.request().url()))
|
|
6250
|
-
await route.abort("blockedbyclient");
|
|
6251
|
-
else
|
|
6252
|
-
await route.continue();
|
|
6253
|
-
});
|
|
6254
6699
|
abort.signal.throwIfAborted();
|
|
6700
|
+
runtimeStage = "local-control";
|
|
6255
6701
|
local = net3.createServer((socket) => {
|
|
6256
6702
|
clients.add(socket);
|
|
6257
6703
|
socket.once("close", () => clients.delete(socket));
|
|
@@ -6282,24 +6728,21 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6282
6728
|
return;
|
|
6283
6729
|
} else if (cmd !== "status")
|
|
6284
6730
|
throw new Error("Invalid command");
|
|
6285
|
-
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 }) + `
|
|
6286
6732
|
`);
|
|
6287
6733
|
})().catch(() => socket.destroy());
|
|
6288
6734
|
});
|
|
6289
6735
|
});
|
|
6290
|
-
|
|
6291
|
-
stopControl = await listenControl(local, root, controlPath);
|
|
6292
|
-
} catch (error) {
|
|
6293
|
-
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.`);
|
|
6294
|
-
}
|
|
6736
|
+
stopControl = await listenControl(local, root, controlPath);
|
|
6295
6737
|
abort.signal.throwIfAborted();
|
|
6296
6738
|
starting = false;
|
|
6297
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";
|
|
6298
6741
|
await relay.start();
|
|
6299
6742
|
} catch (error) {
|
|
6300
6743
|
if (session) {
|
|
6301
6744
|
if (!session.lifecycle.hasEnded && !abort.signal.aborted)
|
|
6302
|
-
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.`);
|
|
6303
6746
|
} else if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
|
|
6304
6747
|
failure = error;
|
|
6305
6748
|
} finally {
|