@ricsam/browser-mcp 0.3.14 → 0.3.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -4
- package/dist/{chunk-y9x8c0rq.js → chunk-g9ksk86v.js} +628 -249
- package/dist/main.js +3 -3
- package/package.json +1 -1
|
@@ -15,13 +15,13 @@ import"./chunk-1sjcwr28.js";
|
|
|
15
15
|
|
|
16
16
|
// cli/src/browser/main.ts
|
|
17
17
|
import fs10 from "node:fs/promises";
|
|
18
|
-
import
|
|
18
|
+
import path10 from "node:path";
|
|
19
19
|
import net3 from "node:net";
|
|
20
20
|
import { setMaxListeners } from "node:events";
|
|
21
21
|
|
|
22
22
|
// cli/src/browser/lifecycle.ts
|
|
23
23
|
import fs3 from "node:fs/promises";
|
|
24
|
-
import
|
|
24
|
+
import path4 from "node:path";
|
|
25
25
|
import os2 from "node:os";
|
|
26
26
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
27
27
|
|
|
@@ -54,7 +54,7 @@ function onceAsync(action) {
|
|
|
54
54
|
// cli/src/browser/owned-chrome.ts
|
|
55
55
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
56
56
|
// cli/package.json
|
|
57
|
-
var version = "0.3.
|
|
57
|
+
var version = "0.3.16";
|
|
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);
|
|
@@ -1968,7 +2015,8 @@ function captureInUtilityWorld({ elements, injected }, options) {
|
|
|
1968
2015
|
if (inActiveBranch(item.element))
|
|
1969
2016
|
priorityRefs.push(ref);
|
|
1970
2017
|
}
|
|
1971
|
-
const
|
|
2018
|
+
const queryRoot = options.scope || options.rootIsScope ? selectedRoot : selectedRoot.ownerDocument;
|
|
2019
|
+
const matches = options.query ? injected.querySelectorAll(injected.parseSelector(options.query), queryRoot).filter((element) => (!options.query.startsWith("aria-ref=") || index.refs.has(element)) && injected.elementState(element, "visible").matches && named(element, options.queryName, options.exact)) : [];
|
|
1972
2020
|
const matchRefs = matches.flatMap((element) => {
|
|
1973
2021
|
const ref = index.refs.get(element);
|
|
1974
2022
|
return ref ? [ref] : [];
|
|
@@ -2072,7 +2120,8 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
2072
2120
|
children.set(ref, await captureFrame(captured.frame, `aria-ref=${ref} >> internal:control=enter-frame >> body,frameset`, {
|
|
2073
2121
|
...frameOptions,
|
|
2074
2122
|
scope: undefined,
|
|
2075
|
-
scopeName: undefined
|
|
2123
|
+
scopeName: undefined,
|
|
2124
|
+
rootIsScope: false
|
|
2076
2125
|
}, false, childPath));
|
|
2077
2126
|
}));
|
|
2078
2127
|
const lines = [];
|
|
@@ -2090,7 +2139,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
2090
2139
|
};
|
|
2091
2140
|
const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
|
|
2092
2141
|
const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
|
|
2093
|
-
document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined } : renderOptions, true)).join(`
|
|
2142
|
+
document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true)).join(`
|
|
2094
2143
|
`);
|
|
2095
2144
|
return document2;
|
|
2096
2145
|
}
|
|
@@ -2140,7 +2189,7 @@ function renderSnapshot(document2, input) {
|
|
|
2140
2189
|
error: `Scope matched ${document2.scopeMatchCount} elements. Use query to inspect matches, then choose a unique scope/ref.`,
|
|
2141
2190
|
scopeMatchCount: document2.scopeMatchCount
|
|
2142
2191
|
} : 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 };
|
|
2192
|
+
const context = { frameContext: input.frames, scope: input.scope ?? null, query: input.query ?? null };
|
|
2144
2193
|
if (failure)
|
|
2145
2194
|
return { ...failure, ...context, text: "", complete: false, truncated: false, snapshotId };
|
|
2146
2195
|
const queryRefs = new Set(document2.matchRefs);
|
|
@@ -2207,6 +2256,8 @@ function renderSnapshot(document2, input) {
|
|
|
2207
2256
|
const nextOffset = input.query && input.offset + returnedMatches < allMatches.length ? input.offset + returnedMatches : null;
|
|
2208
2257
|
const complete = !depthOmitted && !characterLimited && !document2.unavailableFrames.length && (!input.query || !unrepresentedMatches && nextOffset === null && input.offset === 0);
|
|
2209
2258
|
const notes = [];
|
|
2259
|
+
if (input.query && document2.matchCount === 0)
|
|
2260
|
+
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
2261
|
if (depthOmitted)
|
|
2211
2262
|
notes.push(`${depthOmitted} outline lines omitted by depth ${input.depth}. Read a scope/ref, search with query, or omit depth.`);
|
|
2212
2263
|
if (characterLimited)
|
|
@@ -2214,7 +2265,7 @@ function renderSnapshot(document2, input) {
|
|
|
2214
2265
|
if (document2.unavailableFrames.length)
|
|
2215
2266
|
notes.push("Some frames disappeared or were unavailable during capture; refresh before treating the observation as complete.");
|
|
2216
2267
|
if (unrepresentedMatches)
|
|
2217
|
-
notes.push(`${unrepresentedMatches} matching elements
|
|
2268
|
+
notes.push(`${unrepresentedMatches} visible matching elements are not represented by a ref in the ARIA outline. Use browser_inspect with a unique selector for exact DOM details, or read that unique scope for its represented subtree. Pagination only includes represented matches.`);
|
|
2218
2269
|
if (nextOffset !== null)
|
|
2219
2270
|
notes.push(`Continue query with offset ${nextOffset} and this snapshotId. A changed observation requires restarting the search.`);
|
|
2220
2271
|
return {
|
|
@@ -3393,25 +3444,27 @@ class RuntimeFault extends Error {
|
|
|
3393
3444
|
}
|
|
3394
3445
|
var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
|
|
3395
3446
|
var messages = {
|
|
3396
|
-
unsupported_target: "
|
|
3447
|
+
unsupported_target: "Chrome does not expose the interface required by this operation on this target.",
|
|
3448
|
+
browser_operation_unsupported: "Chrome reported that this operation or protocol method is not supported on this target.",
|
|
3397
3449
|
tab_closed: "The tab is closed or detached.",
|
|
3398
3450
|
runtime_disconnected: "The runtime or browser connection ended.",
|
|
3399
3451
|
context_destroyed: "The document execution context changed during the operation.",
|
|
3400
3452
|
execution_timeout: "The browser operation exceeded its internal wait budget.",
|
|
3401
3453
|
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3402
3454
|
transfer_failed: "The file transfer failed or its completion could not be confirmed.",
|
|
3455
|
+
resource_unavailable: "The requested resource is unavailable. No download link was created.",
|
|
3403
3456
|
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3404
3457
|
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3405
3458
|
};
|
|
3406
3459
|
function failureFor(error, op, operationId, stage) {
|
|
3407
3460
|
const text = error instanceof Error ? error.message : "";
|
|
3408
|
-
let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
|
|
3461
|
+
let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : /Protocol error.*(?:not supported|not allowed|wasn't found|Method not found)|Printing is not available|not available in an isolated browser context/i.test(text) ? "browser_operation_unsupported" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
|
|
3409
3462
|
const observation = OBSERVATION_OPERATIONS.has(op);
|
|
3410
3463
|
const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
|
|
3411
|
-
const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
|
|
3464
|
+
const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "browser_operation_unsupported" ? "Use browser_capabilities for interface prerequisites. Other operations, including navigation away, may still work. For original document bytes use an available website/viewer download control, browser_list_downloads and browser_create_download. Do not replay an uncertain mutation." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
|
|
3412
3465
|
const diagnosticId = randomUUID4();
|
|
3413
3466
|
console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
|
|
3414
|
-
return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: "settled", cancellationConfirmed: false } };
|
|
3467
|
+
return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: outcome === "not_dispatched" ? "not_started" : "settled", cancellationConfirmed: false } };
|
|
3415
3468
|
}
|
|
3416
3469
|
|
|
3417
3470
|
// cli/src/browser/browser-runtime.ts
|
|
@@ -3540,22 +3593,22 @@ class BrowserRuntime {
|
|
|
3540
3593
|
return id;
|
|
3541
3594
|
}
|
|
3542
3595
|
safeDownloadFilename(suggestedFilename) {
|
|
3543
|
-
const basename =
|
|
3596
|
+
const basename = path8.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
3544
3597
|
if (!basename || basename === "." || basename === "..")
|
|
3545
3598
|
return "download";
|
|
3546
|
-
const extension =
|
|
3547
|
-
let stem = basename.slice(0, basename.length -
|
|
3599
|
+
const extension = path8.extname(basename).slice(0, 30);
|
|
3600
|
+
let stem = basename.slice(0, basename.length - path8.extname(basename).length) || "download";
|
|
3548
3601
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
3549
3602
|
stem = stem.slice(0, -1);
|
|
3550
3603
|
return `${stem || "download"}${extension}`;
|
|
3551
3604
|
}
|
|
3552
3605
|
availableDownloadPath(suggestedFilename) {
|
|
3553
3606
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
3554
|
-
const extension =
|
|
3607
|
+
const extension = path8.extname(filename);
|
|
3555
3608
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
3556
3609
|
for (let suffix = 1;; suffix += 1) {
|
|
3557
3610
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
3558
|
-
const candidatePath =
|
|
3611
|
+
const candidatePath = path8.join(this.downloadsPath, candidate);
|
|
3559
3612
|
if (!fs8.existsSync(candidatePath))
|
|
3560
3613
|
return candidatePath;
|
|
3561
3614
|
}
|
|
@@ -3564,7 +3617,7 @@ class BrowserRuntime {
|
|
|
3564
3617
|
const failure = await download.failure();
|
|
3565
3618
|
if (failure)
|
|
3566
3619
|
throw new Error(failure);
|
|
3567
|
-
const temporary =
|
|
3620
|
+
const temporary = path8.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
3568
3621
|
let targetPath;
|
|
3569
3622
|
try {
|
|
3570
3623
|
await download.saveAs(temporary);
|
|
@@ -3573,9 +3626,9 @@ class BrowserRuntime {
|
|
|
3573
3626
|
} finally {
|
|
3574
3627
|
fs8.rmSync(temporary, { force: true });
|
|
3575
3628
|
}
|
|
3576
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3629
|
+
process.stdout.write(`[r5d-browser] downloaded ${path8.basename(targetPath)}
|
|
3577
3630
|
`);
|
|
3578
|
-
return { downloadId: this.downloadId(
|
|
3631
|
+
return { downloadId: this.downloadId(path8.basename(targetPath)) };
|
|
3579
3632
|
}
|
|
3580
3633
|
downloadId(filename) {
|
|
3581
3634
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -3584,10 +3637,10 @@ class BrowserRuntime {
|
|
|
3584
3637
|
if (typeof downloadId !== "string" || !downloadId)
|
|
3585
3638
|
throw new Error("downloadId is required.");
|
|
3586
3639
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
3587
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3640
|
+
if (this.downloadId(filename) !== downloadId || filename !== path8.basename(filename) || filename.includes("\x00")) {
|
|
3588
3641
|
throw new Error("Invalid downloadId.");
|
|
3589
3642
|
}
|
|
3590
|
-
const filePath =
|
|
3643
|
+
const filePath = path8.join(this.downloadsPath, filename);
|
|
3591
3644
|
let stats;
|
|
3592
3645
|
try {
|
|
3593
3646
|
stats = fs8.lstatSync(filePath);
|
|
@@ -3865,6 +3918,8 @@ class BrowserRuntime {
|
|
|
3865
3918
|
async dispatch(action, input, execution) {
|
|
3866
3919
|
if (typeof input.tabId === "string" && action !== "close_tab")
|
|
3867
3920
|
await this.guardPage?.(this.page(input.tabId));
|
|
3921
|
+
if (typeof input.tabId !== "string")
|
|
3922
|
+
execution.beforeDispatch?.();
|
|
3868
3923
|
if (action === "upload_abort") {
|
|
3869
3924
|
this.uploads.abort(input.uploadId, input.tabId);
|
|
3870
3925
|
return { aborted: true };
|
|
@@ -3915,6 +3970,7 @@ class BrowserRuntime {
|
|
|
3915
3970
|
input = { ...input, ...input.from ? { from: map(input.from), to: map(input.to) } : map({ x: Number(input.x), y: Number(input.y) }) };
|
|
3916
3971
|
delete input.screenshot;
|
|
3917
3972
|
}
|
|
3973
|
+
execution.beforeDispatch?.();
|
|
3918
3974
|
if (!["screenshot", "read_page", "inspect", "events", "diagnostics", "capabilities"].includes(action))
|
|
3919
3975
|
this.screenshots.delete(tabId);
|
|
3920
3976
|
if (action === "mouse_click" || action === "keyboard") {
|
|
@@ -3935,7 +3991,9 @@ class BrowserRuntime {
|
|
|
3935
3991
|
const webmcp = await this.webmcp.get(page).list();
|
|
3936
3992
|
return {
|
|
3937
3993
|
tabId,
|
|
3938
|
-
observation:
|
|
3994
|
+
observation: null,
|
|
3995
|
+
screenshot: { supported: null, requires: "Chrome screenshot and document geometry APIs" },
|
|
3996
|
+
runJs: { supported: null, requires: "An execution context exposed by Chrome" },
|
|
3939
3997
|
batch: { maxSteps: 8, maxBudgetMs: 30000, adaptive: false },
|
|
3940
3998
|
diagnostics: true,
|
|
3941
3999
|
dialogs: true,
|
|
@@ -3952,6 +4010,7 @@ class BrowserRuntime {
|
|
|
3952
4010
|
requires: "Origin permission and browser focus; permissions are never auto-granted"
|
|
3953
4011
|
},
|
|
3954
4012
|
export: {
|
|
4013
|
+
supported: null,
|
|
3955
4014
|
formats: ["text", "html", "pdf", "assets"],
|
|
3956
4015
|
pdf: "Requires Chrome printToPDF",
|
|
3957
4016
|
assets: "Only already observed, uncompressed image/font/CSS responses with a bounded Content-Length"
|
|
@@ -4063,7 +4122,7 @@ class BrowserRuntime {
|
|
|
4063
4122
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
4064
4123
|
fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
4065
4124
|
return {
|
|
4066
|
-
downloadId: this.downloadId(
|
|
4125
|
+
downloadId: this.downloadId(path8.basename(target2)),
|
|
4067
4126
|
filename: file.filename,
|
|
4068
4127
|
size: file.bytes.length,
|
|
4069
4128
|
mimeType: file.mimeType
|
|
@@ -4540,11 +4599,13 @@ class NativeRuntime {
|
|
|
4540
4599
|
plugins = [];
|
|
4541
4600
|
owners = new Map;
|
|
4542
4601
|
generations = new Map;
|
|
4543
|
-
|
|
4602
|
+
tracking = new WeakMap;
|
|
4544
4603
|
ended = new Set;
|
|
4545
4604
|
epochs = new Map;
|
|
4546
4605
|
controllers = new Map;
|
|
4547
4606
|
disconnected = false;
|
|
4607
|
+
connectionEpoch = 0;
|
|
4608
|
+
downloadAdmissionEpoch = 0;
|
|
4548
4609
|
operations = new Map;
|
|
4549
4610
|
hooks = Promise.resolve();
|
|
4550
4611
|
browserId;
|
|
@@ -4553,7 +4614,7 @@ class NativeRuntime {
|
|
|
4553
4614
|
this.instanceId = instanceId;
|
|
4554
4615
|
this.serverOrigin = serverOrigin;
|
|
4555
4616
|
installCancellation(context);
|
|
4556
|
-
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), (page) => this.
|
|
4617
|
+
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), async (page) => this.assertPageAvailable(page));
|
|
4557
4618
|
context.on("page", (page) => {
|
|
4558
4619
|
this.track(page);
|
|
4559
4620
|
});
|
|
@@ -4565,14 +4626,20 @@ class NativeRuntime {
|
|
|
4565
4626
|
this.disconnected = true;
|
|
4566
4627
|
});
|
|
4567
4628
|
}
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4629
|
+
track(page) {
|
|
4630
|
+
let pending = this.tracking.get(page);
|
|
4631
|
+
if (!pending) {
|
|
4632
|
+
pending = this.trackPage(page);
|
|
4633
|
+
this.tracking.set(page, pending);
|
|
4634
|
+
}
|
|
4635
|
+
return pending;
|
|
4636
|
+
}
|
|
4637
|
+
async trackPage(page) {
|
|
4572
4638
|
const id = await this.engine.idFor(page);
|
|
4573
4639
|
this.generations.set(id, 0);
|
|
4574
4640
|
const opener = await page.opener();
|
|
4575
4641
|
if (opener) {
|
|
4642
|
+
await this.track(opener);
|
|
4576
4643
|
const openerId = await this.engine.idFor(opener), owner = this.owners.get(openerId);
|
|
4577
4644
|
if (owner)
|
|
4578
4645
|
this.owners.set(id, { ...owner });
|
|
@@ -4586,6 +4653,7 @@ class NativeRuntime {
|
|
|
4586
4653
|
});
|
|
4587
4654
|
});
|
|
4588
4655
|
page.on("close", () => {
|
|
4656
|
+
this.downloadAdmissionEpoch++;
|
|
4589
4657
|
this.generations.delete(id);
|
|
4590
4658
|
this.owners.delete(id);
|
|
4591
4659
|
this.enqueue(async () => {
|
|
@@ -4595,9 +4663,15 @@ class NativeRuntime {
|
|
|
4595
4663
|
});
|
|
4596
4664
|
}
|
|
4597
4665
|
async download(download, page, downloadId) {
|
|
4666
|
+
const admissionEpoch = this.downloadAdmissionEpoch, connectionEpoch = this.connectionEpoch;
|
|
4667
|
+
await this.track(page);
|
|
4598
4668
|
const id = await this.engine.idFor(page), scope = this.owners.get(id);
|
|
4599
|
-
|
|
4600
|
-
|
|
4669
|
+
try {
|
|
4670
|
+
if (!scope || page.isClosed() || admissionEpoch !== this.downloadAdmissionEpoch || connectionEpoch !== this.connectionEpoch)
|
|
4671
|
+
throw new Error("Download ownership changed");
|
|
4672
|
+
this.validateScope(scope);
|
|
4673
|
+
} catch {
|
|
4674
|
+
await download.cancel().catch(() => {});
|
|
4601
4675
|
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4602
4676
|
}
|
|
4603
4677
|
const handler = this.plugins.find((p) => p.onDownload);
|
|
@@ -4615,51 +4689,15 @@ class NativeRuntime {
|
|
|
4615
4689
|
if (!scope || Object.values(scope).some((v) => typeof v !== "string" || !v) || !scope.browserId || !scope.tokenId || !scope.sessionKey || scope.instanceId !== this.instanceId || this.browserId && scope.browserId !== this.browserId || this.ended.has(scopeKey(scope)) || this.disconnected)
|
|
4616
4690
|
throw new Error("Invalid or revoked runtime scope");
|
|
4617
4691
|
}
|
|
4618
|
-
|
|
4619
|
-
if (value === "about:blank" || value === "about:srcdoc")
|
|
4620
|
-
return true;
|
|
4621
|
-
try {
|
|
4622
|
-
const u = new URL(value);
|
|
4623
|
-
return ["https:", "http:"].includes(u.protocol) && u.origin !== this.serverOrigin && !u.username && !u.password;
|
|
4624
|
-
} catch {
|
|
4625
|
-
return false;
|
|
4626
|
-
}
|
|
4627
|
-
}
|
|
4628
|
-
assertPage(page) {
|
|
4692
|
+
assertPageAvailable(page) {
|
|
4629
4693
|
if (page.isClosed())
|
|
4630
4694
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4631
|
-
if (page.frames().some((f) => !this.allowURL(f.url())))
|
|
4632
|
-
throw new RuntimeFault("unsupported_target", "Call browser_capabilities. For documents use the website download, browser_list_downloads, then browser_create_download; do not screenshot or evaluate an internal viewer.", true);
|
|
4633
|
-
}
|
|
4634
|
-
async assertPageDeep(page) {
|
|
4635
|
-
this.assertPage(page);
|
|
4636
|
-
const visited = new Set;
|
|
4637
|
-
let opener = await page.opener();
|
|
4638
|
-
while (opener && !visited.has(opener)) {
|
|
4639
|
-
visited.add(opener);
|
|
4640
|
-
this.assertPage(opener);
|
|
4641
|
-
opener = await opener.opener();
|
|
4642
|
-
}
|
|
4643
|
-
const cdp = await this.context.newCDPSession(page);
|
|
4644
|
-
try {
|
|
4645
|
-
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
4646
|
-
const check = (tree) => {
|
|
4647
|
-
const origin = tree.frame.securityOrigin;
|
|
4648
|
-
if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
|
|
4649
|
-
throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
|
|
4650
|
-
for (const child of tree.childFrames ?? [])
|
|
4651
|
-
check(child);
|
|
4652
|
-
};
|
|
4653
|
-
check(frameTree);
|
|
4654
|
-
} finally {
|
|
4655
|
-
await cdp.detach();
|
|
4656
|
-
}
|
|
4657
4695
|
}
|
|
4658
4696
|
async resolveTarget(tabId, scope, frames = []) {
|
|
4659
4697
|
this.validateScope(scope);
|
|
4660
|
-
const page = this.claimPage(tabId, scope);
|
|
4698
|
+
const page = await this.claimPage(tabId, scope);
|
|
4661
4699
|
await this.track(page);
|
|
4662
|
-
|
|
4700
|
+
this.assertPageAvailable(page);
|
|
4663
4701
|
let frame = page.mainFrame();
|
|
4664
4702
|
for (const selector of frames) {
|
|
4665
4703
|
const locator = frame.locator(selector);
|
|
@@ -4676,7 +4714,7 @@ class NativeRuntime {
|
|
|
4676
4714
|
const scopeEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4677
4715
|
const assertCurrent = () => {
|
|
4678
4716
|
this.validateScope(scope);
|
|
4679
|
-
this.
|
|
4717
|
+
this.assertPageAvailable(page);
|
|
4680
4718
|
if ((this.epochs.get(scopeKey(scope)) ?? 0) !== scopeEpoch || frame.isDetached() || this.generations.get(tabId) !== generation || scopeKey(this.owners.get(tabId)) !== scopeKey(scope))
|
|
4681
4719
|
throw new Error("Stale document or scope");
|
|
4682
4720
|
};
|
|
@@ -4690,7 +4728,7 @@ class NativeRuntime {
|
|
|
4690
4728
|
throw new Error("File input unavailable");
|
|
4691
4729
|
try {
|
|
4692
4730
|
const frame = await element.ownerFrame();
|
|
4693
|
-
if (!frame ||
|
|
4731
|
+
if (!frame || frame.isDetached())
|
|
4694
4732
|
throw new Error("File input frame unavailable");
|
|
4695
4733
|
const valid = await element.evaluate((el) => el instanceof HTMLInputElement && el.type === "file" && !el.webkitdirectory && el.isConnected);
|
|
4696
4734
|
target2.assertCurrent();
|
|
@@ -4712,7 +4750,7 @@ class NativeRuntime {
|
|
|
4712
4750
|
events.diagnosticsSuppressed = false;
|
|
4713
4751
|
}
|
|
4714
4752
|
}
|
|
4715
|
-
claimPage(tabId, scope) {
|
|
4753
|
+
async claimPage(tabId, scope) {
|
|
4716
4754
|
this.validateScope(scope);
|
|
4717
4755
|
let page;
|
|
4718
4756
|
try {
|
|
@@ -4720,17 +4758,52 @@ class NativeRuntime {
|
|
|
4720
4758
|
} catch {
|
|
4721
4759
|
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4722
4760
|
}
|
|
4761
|
+
await this.track(page);
|
|
4762
|
+
this.validateScope(scope);
|
|
4723
4763
|
const owner = this.owners.get(tabId);
|
|
4724
4764
|
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4725
4765
|
throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
|
|
4726
4766
|
this.owners.set(tabId, { ...scope });
|
|
4727
4767
|
return page;
|
|
4728
4768
|
}
|
|
4729
|
-
targetCapabilities(tabId, scope) {
|
|
4730
|
-
const page = this.claimPage(tabId, scope);
|
|
4731
|
-
const
|
|
4732
|
-
|
|
4733
|
-
|
|
4769
|
+
async targetCapabilities(tabId, scope) {
|
|
4770
|
+
const page = await this.claimPage(tabId, scope);
|
|
4771
|
+
const urls = page.frames().map((frame) => frame.url());
|
|
4772
|
+
let pdf = urls.some((url) => url.startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/"));
|
|
4773
|
+
let frameMetadataAvailable = false;
|
|
4774
|
+
const cdp = await this.context.newCDPSession(page).catch(() => {
|
|
4775
|
+
return;
|
|
4776
|
+
});
|
|
4777
|
+
try {
|
|
4778
|
+
if (cdp) {
|
|
4779
|
+
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
4780
|
+
const visit = (tree) => {
|
|
4781
|
+
pdf ||= tree.frame.mimeType === "application/pdf";
|
|
4782
|
+
for (const child of tree.childFrames ?? [])
|
|
4783
|
+
visit(child);
|
|
4784
|
+
};
|
|
4785
|
+
visit(frameTree);
|
|
4786
|
+
frameMetadataAvailable = true;
|
|
4787
|
+
}
|
|
4788
|
+
} catch {} finally {
|
|
4789
|
+
await cdp?.detach().catch(() => {
|
|
4790
|
+
return;
|
|
4791
|
+
});
|
|
4792
|
+
}
|
|
4793
|
+
const possiblePdf = pdf || /\.pdf(?:[?#]|$)/i.test(page.url());
|
|
4794
|
+
const internal = urls.some((url) => /^(?:chrome(?:-untrusted|-extension)?|devtools|about):/.test(url) && !/^about:(?:blank|srcdoc)(?:[?#]|$)/.test(url));
|
|
4795
|
+
return {
|
|
4796
|
+
targetKind: pdf ? "pdf_viewer" : possiblePdf ? "possible_pdf" : internal ? "internal" : /^https?:/.test(page.url()) ? "web" : "document",
|
|
4797
|
+
documentAccess: "owner_authorized",
|
|
4798
|
+
targetPolicyRestricted: false,
|
|
4799
|
+
pageToolsSupported: null,
|
|
4800
|
+
capabilityProbe: "metadata_and_webmcp",
|
|
4801
|
+
frameMetadataAvailable,
|
|
4802
|
+
pdfDetected: pdf,
|
|
4803
|
+
requiresDocumentTools: possiblePdf ? true : null,
|
|
4804
|
+
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.",
|
|
4805
|
+
...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." } : {}
|
|
4806
|
+
};
|
|
4734
4807
|
}
|
|
4735
4808
|
async closeBlockedTab(tabId, scope, operationId) {
|
|
4736
4809
|
this.validateScope(scope);
|
|
@@ -4744,7 +4817,33 @@ class NativeRuntime {
|
|
|
4744
4817
|
this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
|
|
4745
4818
|
return { closed: true };
|
|
4746
4819
|
}
|
|
4747
|
-
|
|
4820
|
+
admissionGuard(args, scope) {
|
|
4821
|
+
const epoch = this.scopeEpoch(scope), connectionEpoch = this.connectionEpoch;
|
|
4822
|
+
const tabId = typeof args.tabId === "string" ? args.tabId : undefined;
|
|
4823
|
+
const page = tabId ? this.engine.page(tabId) : undefined;
|
|
4824
|
+
const generation = tabId ? this.generations.get(tabId) : undefined;
|
|
4825
|
+
return (checkDocument = true) => {
|
|
4826
|
+
if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
|
|
4827
|
+
throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
|
|
4828
|
+
if (tabId) {
|
|
4829
|
+
let current2;
|
|
4830
|
+
try {
|
|
4831
|
+
current2 = this.engine.page(tabId);
|
|
4832
|
+
} catch {
|
|
4833
|
+
throw new RuntimeFault("tab_closed", "Select an open tab before submitting a new request.", true);
|
|
4834
|
+
}
|
|
4835
|
+
if (current2 !== page || checkDocument && this.generations.get(tabId) !== generation)
|
|
4836
|
+
throw new RuntimeFault("stale_queued_target", "The target document changed while waiting. Observe it again before submitting a new request.", true);
|
|
4837
|
+
const owner = this.owners.get(tabId);
|
|
4838
|
+
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4839
|
+
throw new RuntimeFault("scope_rejected", "The target is no longer owned by this session.", true);
|
|
4840
|
+
}
|
|
4841
|
+
};
|
|
4842
|
+
}
|
|
4843
|
+
cancelOperation(operationId) {
|
|
4844
|
+
this.operations.get(operationId)?.abort(new Error("Runtime operation interrupted; page effects remain uncertain"));
|
|
4845
|
+
}
|
|
4846
|
+
async execute(op, args, scope, operationId, beforeDispatch) {
|
|
4748
4847
|
if (op === "session_end") {
|
|
4749
4848
|
await this.endSession(scope);
|
|
4750
4849
|
return { ended: true };
|
|
@@ -4758,7 +4857,7 @@ class NativeRuntime {
|
|
|
4758
4857
|
set.add(controller);
|
|
4759
4858
|
this.operations.set(operationId, controller);
|
|
4760
4859
|
try {
|
|
4761
|
-
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
|
|
4860
|
+
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId, beforeDispatch));
|
|
4762
4861
|
} finally {
|
|
4763
4862
|
this.operations.delete(operationId);
|
|
4764
4863
|
set.delete(controller);
|
|
@@ -4766,42 +4865,38 @@ class NativeRuntime {
|
|
|
4766
4865
|
this.controllers.delete(key);
|
|
4767
4866
|
}
|
|
4768
4867
|
}
|
|
4769
|
-
async executeInner(op, args, scope, operationId) {
|
|
4868
|
+
async executeInner(op, args, scope, operationId, beforeDispatch) {
|
|
4869
|
+
let dispatched = false;
|
|
4870
|
+
const begin = () => {
|
|
4871
|
+
this.validateScope(scope);
|
|
4872
|
+
beforeDispatch?.();
|
|
4873
|
+
dispatched = true;
|
|
4874
|
+
};
|
|
4770
4875
|
await this.hooks;
|
|
4771
4876
|
this.validateScope(scope);
|
|
4772
|
-
if (args.url !== undefined && !this.allowURL(String(args.url)))
|
|
4773
|
-
throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
|
|
4774
|
-
if (op === "capabilities" && typeof args.tabId === "string") {
|
|
4775
|
-
const target2 = this.targetCapabilities(args.tabId, scope);
|
|
4776
|
-
if (!target2.pageToolsSupported || target2.pdfDetected)
|
|
4777
|
-
return { tabId: args.tabId, ...target2, observation: target2.pageToolsSupported ? null : false, screenshot: { supported: target2.pageToolsSupported ? null : false }, runJs: { supported: target2.pageToolsSupported ? null : false }, export: { supported: target2.pageToolsSupported ? null : false }, capabilityProbe: "metadata_only" };
|
|
4778
|
-
}
|
|
4779
4877
|
if (typeof args.tabId === "string") {
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4783
|
-
await this.resolveTarget(args.tabId, scope);
|
|
4878
|
+
const page = await this.claimPage(args.tabId, scope);
|
|
4879
|
+
await this.track(page);
|
|
4880
|
+
this.assertPageAvailable(page);
|
|
4784
4881
|
}
|
|
4785
|
-
if (op === "batch" && Array.isArray(args.steps))
|
|
4786
|
-
for (const step of args.steps) {
|
|
4787
|
-
if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
|
|
4788
|
-
throw new Error("Unsupported batch navigation origin");
|
|
4789
|
-
}
|
|
4790
4882
|
if (op === "session_end") {
|
|
4791
4883
|
await this.endSession(scope);
|
|
4792
4884
|
return { ended: true };
|
|
4793
4885
|
}
|
|
4794
4886
|
if (op === "release_tab") {
|
|
4795
4887
|
const tabId = String(args.tabId);
|
|
4796
|
-
|
|
4797
|
-
|
|
4888
|
+
begin();
|
|
4889
|
+
this.downloadAdmissionEpoch++;
|
|
4798
4890
|
this.owners.delete(tabId);
|
|
4799
4891
|
this.generations.set(tabId, (this.generations.get(tabId) ?? 0) + 1);
|
|
4892
|
+
for (const p of this.plugins)
|
|
4893
|
+
await p.onHandoff?.(tabId, scope);
|
|
4800
4894
|
return { released: true, tabId };
|
|
4801
4895
|
}
|
|
4802
4896
|
const operationEpoch = this.epochs.get(scopeKey(scope)) ?? 0;
|
|
4803
4897
|
const plugin = this.plugins.find((p) => p.operations.includes(op));
|
|
4804
4898
|
if (plugin) {
|
|
4899
|
+
begin();
|
|
4805
4900
|
if (op === "cancel_transfer" && args.eventId && args.tabId)
|
|
4806
4901
|
return this.engine.execute("cancel_transfer", args, { operationId });
|
|
4807
4902
|
return plugin.execute(op, args, scope);
|
|
@@ -4809,23 +4904,25 @@ class NativeRuntime {
|
|
|
4809
4904
|
if (!BROWSER_OPERATIONS.includes(op))
|
|
4810
4905
|
throw new Error("Unsupported operation");
|
|
4811
4906
|
if (op === "list_tabs") {
|
|
4907
|
+
begin();
|
|
4812
4908
|
const tabs = await this.engine.listTabs();
|
|
4813
|
-
|
|
4909
|
+
await Promise.all(this.context.pages().map((page) => this.track(page)));
|
|
4910
|
+
this.validateScope(scope);
|
|
4911
|
+
return { tabs: tabs.filter((t) => !this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope)) };
|
|
4814
4912
|
}
|
|
4815
4913
|
try {
|
|
4816
|
-
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
|
|
4914
|
+
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId, beforeDispatch: begin });
|
|
4915
|
+
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4916
|
+
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4917
|
+
const target2 = op === "capabilities" && typeof args.tabId === "string" ? await this.targetCapabilities(args.tabId, scope) : undefined;
|
|
4817
4918
|
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4818
4919
|
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4819
|
-
if (typeof args.tabId === "string" && op !== "close_tab")
|
|
4820
|
-
await this.assertPageDeep(this.engine.page(args.tabId));
|
|
4821
4920
|
if (op === "open_tab" && typeof result?.tab?.tabId === "string")
|
|
4822
4921
|
this.owners.set(result.tab.tabId, { ...scope });
|
|
4823
|
-
|
|
4824
|
-
return { ...result, ...this.targetCapabilities(args.tabId, scope) };
|
|
4825
|
-
return result;
|
|
4922
|
+
return target2 ? { ...result, ...target2 } : result;
|
|
4826
4923
|
} catch (error) {
|
|
4827
4924
|
if (error instanceof RuntimeFault)
|
|
4828
|
-
throw new RuntimeFault(error.code, error.recovery,
|
|
4925
|
+
throw new RuntimeFault(error.code, error.recovery, !dispatched && error.beforeDispatch);
|
|
4829
4926
|
throw error;
|
|
4830
4927
|
}
|
|
4831
4928
|
}
|
|
@@ -4835,11 +4932,12 @@ class NativeRuntime {
|
|
|
4835
4932
|
this.epochs.set(key, (this.epochs.get(key) ?? 0) + 1);
|
|
4836
4933
|
for (const controller of this.controllers.get(key) ?? [])
|
|
4837
4934
|
controller.abort(new Error("Runtime scope revoked"));
|
|
4838
|
-
|
|
4839
|
-
await p.onSessionEnd?.(scope);
|
|
4935
|
+
this.downloadAdmissionEpoch++;
|
|
4840
4936
|
for (const [id, owner] of this.owners)
|
|
4841
4937
|
if (scopeKey(owner) === key)
|
|
4842
4938
|
this.owners.delete(id);
|
|
4939
|
+
for (const p of this.plugins)
|
|
4940
|
+
await p.onSessionEnd?.(scope);
|
|
4843
4941
|
this.ended.delete(key);
|
|
4844
4942
|
}
|
|
4845
4943
|
async shutdown() {
|
|
@@ -4852,6 +4950,7 @@ class NativeRuntime {
|
|
|
4852
4950
|
}
|
|
4853
4951
|
async disconnect() {
|
|
4854
4952
|
this.disconnected = true;
|
|
4953
|
+
this.connectionEpoch++;
|
|
4855
4954
|
for (const controllers of this.controllers.values())
|
|
4856
4955
|
for (const controller of controllers)
|
|
4857
4956
|
controller.abort(new Error("Runtime disconnected"));
|
|
@@ -4871,7 +4970,7 @@ class NativeRuntime {
|
|
|
4871
4970
|
import WebSocket2 from "ws";
|
|
4872
4971
|
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4873
4972
|
import fs9 from "node:fs/promises";
|
|
4874
|
-
import
|
|
4973
|
+
import path9 from "node:path";
|
|
4875
4974
|
|
|
4876
4975
|
// cli/src/live/producer.ts
|
|
4877
4976
|
import WebSocket from "ws";
|
|
@@ -5250,6 +5349,7 @@ class NativeLiveProducer {
|
|
|
5250
5349
|
|
|
5251
5350
|
// cli/src/runtime/relay.ts
|
|
5252
5351
|
var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
5352
|
+
var QUEUE_LIMITS = Object.freeze({ maxWaiting: 16, maxWaitingPerScope: 8, maxWaitMs: 5000 });
|
|
5253
5353
|
var LIMIT = 2 * 1024 * 1024;
|
|
5254
5354
|
function wireResult(op, value) {
|
|
5255
5355
|
if (!value || typeof value !== "object")
|
|
@@ -5294,6 +5394,7 @@ class Relay {
|
|
|
5294
5394
|
live;
|
|
5295
5395
|
seen = new Set;
|
|
5296
5396
|
active;
|
|
5397
|
+
waiting = [];
|
|
5297
5398
|
recent = [];
|
|
5298
5399
|
blocker(active, scope) {
|
|
5299
5400
|
const quarantined = active.timedOut || active.interrupted;
|
|
@@ -5304,11 +5405,91 @@ class Relay {
|
|
|
5304
5405
|
}
|
|
5305
5406
|
health(scope) {
|
|
5306
5407
|
const active = this.active;
|
|
5307
|
-
|
|
5408
|
+
const quarantined = !!active && (active.timedOut || active.interrupted);
|
|
5409
|
+
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) };
|
|
5410
|
+
}
|
|
5411
|
+
interrupt(code2 = "queue_interrupted") {
|
|
5412
|
+
this.active?.interrupt();
|
|
5413
|
+
this.flushWaiting(code2, "The runtime was interrupted. Waiting work was never dispatched; reconnect and re-observe before submitting a fresh request.");
|
|
5414
|
+
}
|
|
5415
|
+
rejectWaiting(entry, code2, message) {
|
|
5416
|
+
const index = this.waiting.indexOf(entry);
|
|
5417
|
+
if (index < 0)
|
|
5418
|
+
return;
|
|
5419
|
+
this.waiting.splice(index, 1);
|
|
5420
|
+
clearTimeout(entry.timer);
|
|
5421
|
+
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." };
|
|
5422
|
+
entry.send({ type: "result", id: entry.message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message }, result });
|
|
5423
|
+
this.recent.push({ scope: entry.message.scope, result });
|
|
5424
|
+
if (this.recent.length > 32)
|
|
5425
|
+
this.recent.shift();
|
|
5426
|
+
entry.finish();
|
|
5427
|
+
}
|
|
5428
|
+
flushWaiting(code2, message, scope) {
|
|
5429
|
+
for (const entry of [...this.waiting])
|
|
5430
|
+
if (!scope || sameScope3(entry.message.scope, scope))
|
|
5431
|
+
this.rejectWaiting(entry, code2, message);
|
|
5432
|
+
}
|
|
5433
|
+
cancel(id, socket, reason) {
|
|
5434
|
+
const entry = this.waiting.find((w) => w.message.id === id && w.socket === socket);
|
|
5435
|
+
if (entry) {
|
|
5436
|
+
this.rejectWaiting(entry, reason === "deadline" ? "queue_wait_expired" : "queue_cancelled", "Cancelled or expired while waiting; no action was dispatched.");
|
|
5437
|
+
this.drain();
|
|
5438
|
+
return;
|
|
5439
|
+
}
|
|
5440
|
+
if (this.active?.id === id && this.active.socket === socket) {
|
|
5441
|
+
if (reason === "deadline")
|
|
5442
|
+
this.active.expire();
|
|
5443
|
+
else
|
|
5444
|
+
this.interrupt("queue_interrupted");
|
|
5445
|
+
}
|
|
5308
5446
|
}
|
|
5309
|
-
|
|
5310
|
-
|
|
5311
|
-
|
|
5447
|
+
dispatchReady(message, socket) {
|
|
5448
|
+
const entry = this.waiting[0];
|
|
5449
|
+
if (!entry || entry.socket !== socket || entry.message.id !== message.id || !entry.checking)
|
|
5450
|
+
return;
|
|
5451
|
+
if (message.allowed !== true) {
|
|
5452
|
+
this.rejectWaiting(entry, "scope_rejected", "Authority expired or was revoked while waiting. No action was dispatched.");
|
|
5453
|
+
this.drain();
|
|
5454
|
+
return;
|
|
5455
|
+
}
|
|
5456
|
+
entry.authorized = true;
|
|
5457
|
+
this.drain();
|
|
5458
|
+
}
|
|
5459
|
+
drain() {
|
|
5460
|
+
if (this.active || this.paused || this.stopping)
|
|
5461
|
+
return;
|
|
5462
|
+
const entry = this.waiting[0];
|
|
5463
|
+
if (!entry)
|
|
5464
|
+
return;
|
|
5465
|
+
const { message, socket } = entry;
|
|
5466
|
+
if (socket !== this.socket || socket.readyState !== WebSocket2.OPEN) {
|
|
5467
|
+
this.rejectWaiting(entry, "queue_disconnected", "Connection changed while waiting. No action was dispatched.");
|
|
5468
|
+
this.drain();
|
|
5469
|
+
return;
|
|
5470
|
+
}
|
|
5471
|
+
if (Date.now() >= entry.waitUntil || Date.now() >= entry.deadlineAt) {
|
|
5472
|
+
this.rejectWaiting(entry, "queue_wait_expired", "Queue wait or caller deadline expired. No action was dispatched.");
|
|
5473
|
+
this.drain();
|
|
5474
|
+
return;
|
|
5475
|
+
}
|
|
5476
|
+
try {
|
|
5477
|
+
entry.guard();
|
|
5478
|
+
} catch {
|
|
5479
|
+
this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
|
|
5480
|
+
this.drain();
|
|
5481
|
+
return;
|
|
5482
|
+
}
|
|
5483
|
+
if (message.revalidate === true && !entry.authorized) {
|
|
5484
|
+
if (!entry.checking) {
|
|
5485
|
+
entry.checking = true;
|
|
5486
|
+
entry.send({ type: "dispatch_check", id: message.id });
|
|
5487
|
+
}
|
|
5488
|
+
return;
|
|
5489
|
+
}
|
|
5490
|
+
this.waiting.shift();
|
|
5491
|
+
clearTimeout(entry.timer);
|
|
5492
|
+
this.execute(entry).catch(() => socket.close(1011)).finally(entry.finish);
|
|
5312
5493
|
}
|
|
5313
5494
|
remember(active, result) {
|
|
5314
5495
|
this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
|
|
@@ -5347,7 +5528,7 @@ class Relay {
|
|
|
5347
5528
|
await new Promise((resolve2, reject) => {
|
|
5348
5529
|
socket.once("error", reject);
|
|
5349
5530
|
socket.once("close", () => {
|
|
5350
|
-
this.interrupt();
|
|
5531
|
+
this.interrupt("queue_disconnected");
|
|
5351
5532
|
clearInterval(heartbeat);
|
|
5352
5533
|
resolve2();
|
|
5353
5534
|
});
|
|
@@ -5357,8 +5538,10 @@ class Relay {
|
|
|
5357
5538
|
}, 20000);
|
|
5358
5539
|
heartbeat.unref();
|
|
5359
5540
|
socket.once("open", () => {
|
|
5541
|
+
if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5542
|
+
return;
|
|
5360
5543
|
this.state = "authenticating";
|
|
5361
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
5544
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.16", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "runtime-quarantine.v1", "binary-artifacts.v1", "browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
|
|
5362
5545
|
});
|
|
5363
5546
|
socket.on("message", (bytes, binary) => {
|
|
5364
5547
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5373,6 +5556,8 @@ class Relay {
|
|
|
5373
5556
|
return;
|
|
5374
5557
|
}
|
|
5375
5558
|
if (message.type === "ready") {
|
|
5559
|
+
if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5560
|
+
return;
|
|
5376
5561
|
if (message.protocol !== 3 || typeof message.browserId !== "string" || !Number.isSafeInteger(message.credentialEpoch) || message.credentialEpoch < 1 || this.state !== "authenticating") {
|
|
5377
5562
|
socket.close(1002);
|
|
5378
5563
|
return;
|
|
@@ -5380,18 +5565,19 @@ class Relay {
|
|
|
5380
5565
|
this.state = "initializing";
|
|
5381
5566
|
(async () => {
|
|
5382
5567
|
await this.runtime.reconnect(message.browserId);
|
|
5568
|
+
if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5569
|
+
return;
|
|
5383
5570
|
this.state = "connected";
|
|
5384
5571
|
this.live = new NativeLiveProducer({ mediaUrl: mediaURL(this.server), token: this.token, instanceId: this.runtime.instanceId, credentialEpoch: message.credentialEpoch, context: this.runtime.context, authorizePage: async (page) => {
|
|
5385
5572
|
try {
|
|
5386
|
-
|
|
5573
|
+
this.runtime.assertPageAvailable(page);
|
|
5387
5574
|
return true;
|
|
5388
5575
|
} catch {
|
|
5389
5576
|
return false;
|
|
5390
5577
|
}
|
|
5391
5578
|
}, getPage: (id) => {
|
|
5392
5579
|
try {
|
|
5393
|
-
|
|
5394
|
-
return page.frames().every((f) => this.runtime.allowURL(f.url())) ? page : undefined;
|
|
5580
|
+
return this.runtime.engine.page(id);
|
|
5395
5581
|
} catch {
|
|
5396
5582
|
return;
|
|
5397
5583
|
}
|
|
@@ -5406,6 +5592,10 @@ class Relay {
|
|
|
5406
5592
|
this.live?.onWatch(message).catch(() => {});
|
|
5407
5593
|
} else if (message.type === "ping")
|
|
5408
5594
|
socket.send(JSON.stringify({ type: "pong" }));
|
|
5595
|
+
else if (message.type === "cancel" && typeof message.id === "string")
|
|
5596
|
+
this.cancel(message.id, socket, message.reason);
|
|
5597
|
+
else if (message.type === "dispatch_ready")
|
|
5598
|
+
this.dispatchReady(message, socket);
|
|
5409
5599
|
else if (message.type === "command") {
|
|
5410
5600
|
if (this.state !== "connected" || this.paused) {
|
|
5411
5601
|
socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: this.paused ? "runtime_paused" : "runtime_initializing", message: "Runtime is paused or initializing; no action was dispatched." }, result: { executionState: "not_started", retrySafe: true, recovery: "Use local browser-mcp browser status for independent health. Resume locally if paused; retry health after the runtime connects." } }));
|
|
@@ -5451,6 +5641,10 @@ class Relay {
|
|
|
5451
5641
|
return;
|
|
5452
5642
|
}
|
|
5453
5643
|
this.seen.add(message.id);
|
|
5644
|
+
if (message.deadlineAt !== undefined && (!Number.isFinite(message.deadlineAt) || message.deadlineAt <= Date.now())) {
|
|
5645
|
+
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 } });
|
|
5646
|
+
return;
|
|
5647
|
+
}
|
|
5454
5648
|
if (message.op === "runtime_health") {
|
|
5455
5649
|
send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
|
|
5456
5650
|
return;
|
|
@@ -5460,35 +5654,92 @@ class Relay {
|
|
|
5460
5654
|
return;
|
|
5461
5655
|
}
|
|
5462
5656
|
if (message.op === "session_end") {
|
|
5657
|
+
this.flushWaiting("queue_scope_ended", "Session ended while waiting. No action was dispatched.", message.scope);
|
|
5463
5658
|
if (this.active && sameScope3(this.active.scope, message.scope))
|
|
5464
|
-
this.interrupt();
|
|
5659
|
+
this.interrupt("queue_interrupted");
|
|
5465
5660
|
await this.runtime.endSession(message.scope);
|
|
5661
|
+
this.drain();
|
|
5466
5662
|
send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
|
|
5467
5663
|
return;
|
|
5468
5664
|
}
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5665
|
+
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 } });
|
|
5666
|
+
if (this.active && (this.active.timedOut || this.active.interrupted)) {
|
|
5667
|
+
reject("blocked_by_prior_operation", "A prior operation is quarantined. No action was queued or dispatched.", { category: "runtime_quarantined", blocker: this.blocker(this.active, message.scope), quarantined: true, recovery: "Call browser_runtime_health. Never replay the prior mutation; wait for natural late settlement or request approved recovery." });
|
|
5472
5668
|
return;
|
|
5473
5669
|
}
|
|
5474
|
-
|
|
5475
|
-
|
|
5670
|
+
if (this.waiting.length >= QUEUE_LIMITS.maxWaiting || this.waiting.filter((w) => sameScope3(w.message.scope, message.scope)).length >= QUEUE_LIMITS.maxWaitingPerScope) {
|
|
5671
|
+
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." });
|
|
5672
|
+
return;
|
|
5673
|
+
}
|
|
5674
|
+
const now = Date.now(), timeoutMs = Math.max(1, Math.min(120000, Number(message.timeoutMs) || 30000));
|
|
5675
|
+
const deadlineAt = message.deadlineAt === undefined ? now + timeoutMs : Number(message.deadlineAt);
|
|
5676
|
+
if (!Number.isFinite(deadlineAt) || deadlineAt <= now) {
|
|
5677
|
+
reject("queue_wait_expired", "Caller deadline expired before admission. No action was dispatched.");
|
|
5678
|
+
return;
|
|
5679
|
+
}
|
|
5680
|
+
let guard;
|
|
5681
|
+
try {
|
|
5682
|
+
guard = this.runtime.admissionGuard(message.args, message.scope);
|
|
5683
|
+
guard();
|
|
5684
|
+
} catch {
|
|
5685
|
+
reject("stale_queued_request", "Scope or target is unavailable. No action was dispatched.");
|
|
5686
|
+
return;
|
|
5687
|
+
}
|
|
5688
|
+
await new Promise((finish) => {
|
|
5689
|
+
const waitMs = Math.max(1, Math.min(QUEUE_LIMITS.maxWaitMs, message.queueWaitMs === undefined ? QUEUE_LIMITS.maxWaitMs : Number(message.queueWaitMs) || 1));
|
|
5690
|
+
const entry = { message, socket, send, guard, timeoutMs, deadlineAt: Math.min(deadlineAt, now + 120000), waitUntil: Math.min(deadlineAt, now + waitMs), checking: false, authorized: false, finish };
|
|
5691
|
+
this.waiting.push(entry);
|
|
5692
|
+
entry.timer = setTimeout(() => {
|
|
5693
|
+
this.rejectWaiting(entry, "queue_wait_expired", "Queue wait or caller deadline expired. No action was dispatched.");
|
|
5694
|
+
this.drain();
|
|
5695
|
+
}, Math.max(1, entry.waitUntil - now));
|
|
5696
|
+
this.drain();
|
|
5697
|
+
});
|
|
5698
|
+
}
|
|
5699
|
+
async execute(entry) {
|
|
5700
|
+
const { message, socket, send } = entry;
|
|
5701
|
+
let finish, interrupt, expire;
|
|
5702
|
+
const active = { id: message.id, scope: { ...message.scope }, socket, tabId: typeof message.args.tabId === "string" ? message.args.tabId : undefined, op: message.op, startedAt: Date.now(), deadlineAt: Math.min(entry.deadlineAt, Date.now() + entry.timeoutMs), timedOut: false, interrupted: false, settled: false, recovering: false, dispatched: false, done: new Promise((resolve2) => {
|
|
5476
5703
|
finish = resolve2;
|
|
5477
|
-
}) };
|
|
5704
|
+
}), interrupt: () => interrupt(), expire: () => expire() };
|
|
5478
5705
|
this.active = active;
|
|
5479
5706
|
let stage = "execute", timer;
|
|
5480
5707
|
const expired = new Promise((resolve2) => {
|
|
5481
|
-
|
|
5482
|
-
active.
|
|
5483
|
-
|
|
5484
|
-
|
|
5708
|
+
const terminal = (cancelled) => {
|
|
5709
|
+
if (active.interrupted || active.settled)
|
|
5710
|
+
return;
|
|
5711
|
+
if (active.timedOut) {
|
|
5712
|
+
if (cancelled) {
|
|
5713
|
+
active.interrupted = true;
|
|
5714
|
+
this.runtime.cancelOperation(active.id);
|
|
5715
|
+
}
|
|
5716
|
+
return;
|
|
5717
|
+
}
|
|
5718
|
+
if (cancelled)
|
|
5719
|
+
active.interrupted = true;
|
|
5720
|
+
else
|
|
5721
|
+
active.timedOut = true;
|
|
5722
|
+
clearTimeout(timer);
|
|
5723
|
+
send({ type: "result", id: message.id, ok: false, outcome: !active.dispatched ? "not_dispatched" : OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: cancelled ? "runtime_interrupted" : "runtime_timeout", message: active.dispatched ? "Execution is not confirmed cancelled; do not replay a mutation." : "Interrupted or expired before browser dispatch; no action was dispatched." }, result: { operationId: active.id, diagnosticId: active.id, category: cancelled ? "execution_interrupted" : "execution_timeout", stage, callerDeadline: cancelled ? "interrupted" : "expired", executionState: active.dispatched ? "unresolved" : "not_started", quarantined: true, cancellationConfirmed: !active.dispatched, retrySafe: !active.dispatched, recovery: "Use browser_runtime_health independently. Never replay uncertain work; request explicit user-approved recovery if needed." } });
|
|
5724
|
+
this.flushWaiting("blocked_by_prior_operation", "A prior operation timed out or was interrupted. This waiting request was never dispatched.");
|
|
5725
|
+
if (cancelled)
|
|
5726
|
+
this.runtime.cancelOperation(active.id);
|
|
5485
5727
|
resolve2();
|
|
5486
|
-
}
|
|
5728
|
+
};
|
|
5729
|
+
interrupt = () => terminal(true);
|
|
5730
|
+
expire = () => terminal(false);
|
|
5731
|
+
timer = setTimeout(expire, Math.max(1, active.deadlineAt - Date.now()));
|
|
5487
5732
|
});
|
|
5488
5733
|
const task = (async () => {
|
|
5489
5734
|
let response;
|
|
5490
5735
|
try {
|
|
5491
|
-
const
|
|
5736
|
+
const beforeDispatch = () => {
|
|
5737
|
+
if (active.timedOut || active.interrupted || this.stopping || this.paused || socket !== this.socket || socket.readyState !== WebSocket2.OPEN || Date.now() >= active.deadlineAt)
|
|
5738
|
+
throw new RuntimeFault("queue_wait_expired", "Request expired or was interrupted before browser dispatch.", true);
|
|
5739
|
+
entry.guard(!active.dispatched);
|
|
5740
|
+
active.dispatched = true;
|
|
5741
|
+
};
|
|
5742
|
+
const result = await this.runtime.execute(message.op, message.args, message.scope, message.id, beforeDispatch);
|
|
5492
5743
|
if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5493
5744
|
return;
|
|
5494
5745
|
this.runtime.validateScope(message.scope);
|
|
@@ -5506,9 +5757,9 @@ class Relay {
|
|
|
5506
5757
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5507
5758
|
for (const item of result.exports) {
|
|
5508
5759
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5509
|
-
if (
|
|
5760
|
+
if (path9.basename(filename) !== filename)
|
|
5510
5761
|
throw new Error("Invalid export file");
|
|
5511
|
-
const filenamePath =
|
|
5762
|
+
const filenamePath = path9.join(this.previewDirectory, filename);
|
|
5512
5763
|
const stat = await fs9.lstat(filenamePath);
|
|
5513
5764
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5514
5765
|
throw new Error("Invalid export file");
|
|
@@ -5518,14 +5769,19 @@ class Relay {
|
|
|
5518
5769
|
}
|
|
5519
5770
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5520
5771
|
for (const artifact2 of result.artifacts)
|
|
5521
|
-
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact",
|
|
5522
|
-
result.artifacts = result.artifacts.map((a) => ({ filename:
|
|
5772
|
+
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path9.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
|
|
5773
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path9.basename(a.filename) }));
|
|
5523
5774
|
}
|
|
5524
5775
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5525
5776
|
throw new Error("Result budget exceeded");
|
|
5526
5777
|
response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
|
|
5527
5778
|
} catch (error) {
|
|
5528
5779
|
const failure = failureFor(error, message.op, message.id, stage);
|
|
5780
|
+
if (failure.error.code === "context_destroyed" && active.tabId) {
|
|
5781
|
+
for (const waiting of [...this.waiting])
|
|
5782
|
+
if (waiting.message.args.tabId === active.tabId)
|
|
5783
|
+
this.rejectWaiting(waiting, "stale_queued_request", "The target document changed while waiting. No action was dispatched; observe it again before submitting a fresh request.");
|
|
5784
|
+
}
|
|
5529
5785
|
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5530
5786
|
} finally {
|
|
5531
5787
|
clearTimeout(timer);
|
|
@@ -5533,11 +5789,12 @@ class Relay {
|
|
|
5533
5789
|
finish();
|
|
5534
5790
|
if (active.timedOut || active.interrupted)
|
|
5535
5791
|
this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
|
|
5536
|
-
if (this.active === active && !active.interrupted && !active.recovering)
|
|
5792
|
+
if (this.active === active && (!active.interrupted || !active.dispatched) && !active.recovering)
|
|
5537
5793
|
this.active = undefined;
|
|
5538
5794
|
}
|
|
5539
5795
|
if (response && !active.timedOut && !active.interrupted)
|
|
5540
5796
|
send(response);
|
|
5797
|
+
this.drain();
|
|
5541
5798
|
})();
|
|
5542
5799
|
await Promise.race([task, expired]);
|
|
5543
5800
|
}
|
|
@@ -5550,6 +5807,7 @@ class Relay {
|
|
|
5550
5807
|
return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
|
|
5551
5808
|
if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
|
|
5552
5809
|
return reject("approval_required", "Explicit user approval to close the blocked tab is required. This may discard unsaved page state; profile data is retained.");
|
|
5810
|
+
this.flushWaiting("queue_recovery", "Recovery invalidated waiting requests. No action was dispatched.");
|
|
5553
5811
|
active.recovering = true;
|
|
5554
5812
|
const work = (async () => {
|
|
5555
5813
|
await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
|
|
@@ -5581,19 +5839,22 @@ class Relay {
|
|
|
5581
5839
|
return { blobId, role, name, mimeType, size: bytes.length, sha256 };
|
|
5582
5840
|
}
|
|
5583
5841
|
async pause() {
|
|
5584
|
-
this.interrupt();
|
|
5585
5842
|
this.paused = true;
|
|
5843
|
+
this.interrupt("queue_paused");
|
|
5586
5844
|
this.state = "paused";
|
|
5587
5845
|
this.socket?.close();
|
|
5588
5846
|
await this.live?.stop();
|
|
5589
5847
|
await this.runtime.disconnect();
|
|
5590
5848
|
}
|
|
5591
5849
|
resume() {
|
|
5850
|
+
if (!this.paused)
|
|
5851
|
+
return;
|
|
5592
5852
|
this.paused = false;
|
|
5853
|
+
this.state = "reconnecting";
|
|
5593
5854
|
}
|
|
5594
5855
|
async stop() {
|
|
5595
|
-
this.interrupt();
|
|
5596
5856
|
this.stopping = true;
|
|
5857
|
+
this.interrupt("queue_shutdown");
|
|
5597
5858
|
this.socket?.close();
|
|
5598
5859
|
await this.live?.stop();
|
|
5599
5860
|
await this.runtime.disconnect();
|
|
@@ -5601,12 +5862,12 @@ class Relay {
|
|
|
5601
5862
|
}
|
|
5602
5863
|
|
|
5603
5864
|
// cli/src/data/index.ts
|
|
5604
|
-
import { mkdir as mkdir2, open as
|
|
5605
|
-
import { createReadStream, createWriteStream } from "node:fs";
|
|
5606
|
-
import { randomUUID as randomUUID7, createHash as
|
|
5865
|
+
import { mkdir as mkdir2, open as open3, rename, unlink as unlink2, rmdir as rmdir2, lstat as lstat2 } from "node:fs/promises";
|
|
5866
|
+
import { createReadStream, createWriteStream as createWriteStream2 } from "node:fs";
|
|
5867
|
+
import { randomUUID as randomUUID7, createHash as createHash7 } from "node:crypto";
|
|
5607
5868
|
import { join as join2, basename } from "node:path";
|
|
5608
|
-
import { Readable, Transform } from "node:stream";
|
|
5609
|
-
import { pipeline } from "node:stream/promises";
|
|
5869
|
+
import { Readable, Transform as Transform2 } from "node:stream";
|
|
5870
|
+
import { pipeline as pipeline2 } from "node:stream/promises";
|
|
5610
5871
|
|
|
5611
5872
|
// cli/src/data/vault.ts
|
|
5612
5873
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
@@ -5727,6 +5988,129 @@ class SecretVault {
|
|
|
5727
5988
|
}
|
|
5728
5989
|
}
|
|
5729
5990
|
|
|
5991
|
+
// cli/src/data/download-capture.ts
|
|
5992
|
+
import { constants as constants3, createWriteStream } from "node:fs";
|
|
5993
|
+
import { open as open2 } from "node:fs/promises";
|
|
5994
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
5995
|
+
import { Transform } from "node:stream";
|
|
5996
|
+
import { pipeline } from "node:stream/promises";
|
|
5997
|
+
class CaptureError extends Error {
|
|
5998
|
+
code;
|
|
5999
|
+
constructor(code2) {
|
|
6000
|
+
super(code2);
|
|
6001
|
+
this.code = code2;
|
|
6002
|
+
}
|
|
6003
|
+
}
|
|
6004
|
+
async function duringCapture(work, signal) {
|
|
6005
|
+
let abort;
|
|
6006
|
+
const cancelled = new Promise((_, reject) => {
|
|
6007
|
+
abort = () => reject(new CaptureError("download_capture_cancelled"));
|
|
6008
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
6009
|
+
if (signal.aborted)
|
|
6010
|
+
abort();
|
|
6011
|
+
});
|
|
6012
|
+
try {
|
|
6013
|
+
return await Promise.race([work, cancelled]);
|
|
6014
|
+
} finally {
|
|
6015
|
+
signal.removeEventListener("abort", abort);
|
|
6016
|
+
}
|
|
6017
|
+
}
|
|
6018
|
+
function contentValidation(name, size) {
|
|
6019
|
+
if (size !== 0)
|
|
6020
|
+
return { status: "not-validated" };
|
|
6021
|
+
if (/\.(pdf|eml)$/i.test(name))
|
|
6022
|
+
return {
|
|
6023
|
+
status: "empty-document",
|
|
6024
|
+
code: "empty_document",
|
|
6025
|
+
warning: "The completed browser file is empty. These are not usable document bytes. Do not automatically repeat the website action."
|
|
6026
|
+
};
|
|
6027
|
+
return {
|
|
6028
|
+
status: "empty-file",
|
|
6029
|
+
code: "empty_file",
|
|
6030
|
+
warning: "The completed browser file is empty. This may be intentional; no document validity is implied."
|
|
6031
|
+
};
|
|
6032
|
+
}
|
|
6033
|
+
async function captureDownload(download, destination, signal, evidence) {
|
|
6034
|
+
const failure = await duringCapture(download.failure(), signal);
|
|
6035
|
+
evidence.browserCompletion = failure === null ? "completed" : "failed";
|
|
6036
|
+
if (failure !== null)
|
|
6037
|
+
throw new CaptureError("download_capture_browser_failed");
|
|
6038
|
+
const path10 = await duringCapture(download.path(), signal);
|
|
6039
|
+
signal.throwIfAborted();
|
|
6040
|
+
evidence.stage = "browser-file";
|
|
6041
|
+
let source;
|
|
6042
|
+
let retained2;
|
|
6043
|
+
try {
|
|
6044
|
+
source = await open2(path10, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
6045
|
+
const before = await source.stat();
|
|
6046
|
+
if (!before.isFile())
|
|
6047
|
+
throw new CaptureError("download_capture_source_unavailable");
|
|
6048
|
+
evidence.browser = { size: before.size };
|
|
6049
|
+
if (before.size > LIMITS.file)
|
|
6050
|
+
throw new CaptureError("download_quota_exceeded");
|
|
6051
|
+
signal.throwIfAborted();
|
|
6052
|
+
evidence.stage = "copy";
|
|
6053
|
+
let size = 0;
|
|
6054
|
+
const hash = createHash6("sha256");
|
|
6055
|
+
const bound = new Transform({ transform(chunk, _encoding, callback) {
|
|
6056
|
+
size += chunk.length;
|
|
6057
|
+
if (size > LIMITS.file)
|
|
6058
|
+
return callback(new CaptureError("download_quota_exceeded"));
|
|
6059
|
+
hash.update(chunk);
|
|
6060
|
+
callback(null, chunk);
|
|
6061
|
+
} });
|
|
6062
|
+
await pipeline(source.createReadStream({ start: 0, autoClose: false }), bound, createWriteStream(destination, { flags: "wx", mode: 384 }), { signal });
|
|
6063
|
+
const sourceHash = hash.digest("hex");
|
|
6064
|
+
evidence.browser.sha256 = sourceHash;
|
|
6065
|
+
evidence.stage = "verification";
|
|
6066
|
+
retained2 = await open2(destination, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
6067
|
+
const disk = await retained2.stat();
|
|
6068
|
+
if (!disk.isFile() || disk.size > LIMITS.file)
|
|
6069
|
+
throw new CaptureError("download_capture_mismatch");
|
|
6070
|
+
let diskSize = 0;
|
|
6071
|
+
const diskHash = createHash6("sha256");
|
|
6072
|
+
for await (const chunk of retained2.createReadStream({ start: 0, autoClose: false, signal })) {
|
|
6073
|
+
diskSize += chunk.length;
|
|
6074
|
+
if (diskSize > LIMITS.file)
|
|
6075
|
+
throw new CaptureError("download_quota_exceeded");
|
|
6076
|
+
diskHash.update(chunk);
|
|
6077
|
+
}
|
|
6078
|
+
evidence.retained = { size: diskSize, sha256: diskHash.digest("hex") };
|
|
6079
|
+
const after = await source.stat();
|
|
6080
|
+
const diskAfter = await retained2.stat();
|
|
6081
|
+
if (size !== before.size || disk.size !== size || diskSize !== size || evidence.retained.sha256 !== sourceHash || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs || diskAfter.size !== disk.size || diskAfter.mtimeMs !== disk.mtimeMs || diskAfter.ctimeMs !== disk.ctimeMs) {
|
|
6082
|
+
evidence.comparison = "mismatched";
|
|
6083
|
+
throw new CaptureError("download_capture_mismatch");
|
|
6084
|
+
}
|
|
6085
|
+
signal.throwIfAborted();
|
|
6086
|
+
evidence.comparison = "matched";
|
|
6087
|
+
evidence.stage = "verified";
|
|
6088
|
+
return { size, sha256: sourceHash };
|
|
6089
|
+
} finally {
|
|
6090
|
+
try {
|
|
6091
|
+
await retained2?.close();
|
|
6092
|
+
} finally {
|
|
6093
|
+
await source?.close();
|
|
6094
|
+
}
|
|
6095
|
+
}
|
|
6096
|
+
}
|
|
6097
|
+
async function cleanupDownload(download, evidence) {
|
|
6098
|
+
let timer;
|
|
6099
|
+
try {
|
|
6100
|
+
const deleted = await Promise.race([
|
|
6101
|
+
download.delete().then(() => true, () => false),
|
|
6102
|
+
new Promise((resolve2) => {
|
|
6103
|
+
timer = setTimeout(() => resolve2(false), 2000);
|
|
6104
|
+
timer.unref?.();
|
|
6105
|
+
})
|
|
6106
|
+
]);
|
|
6107
|
+
if (evidence)
|
|
6108
|
+
evidence.cleanup = deleted ? "deleted" : "browser-context";
|
|
6109
|
+
} finally {
|
|
6110
|
+
clearTimeout(timer);
|
|
6111
|
+
}
|
|
6112
|
+
}
|
|
6113
|
+
|
|
5730
6114
|
// cli/src/data/index.ts
|
|
5731
6115
|
var safeName = (s) => {
|
|
5732
6116
|
const name = basename(s.replace(/\\/g, "/")).replace(/[\x00-\x1f\x7f]/g, "_").slice(0, 200);
|
|
@@ -5753,7 +6137,7 @@ async function createDataPlugin(access, options) {
|
|
|
5753
6137
|
return meta(get(scope, id));
|
|
5754
6138
|
}
|
|
5755
6139
|
function meta(r) {
|
|
5756
|
-
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? "ready" : "pending", retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
|
|
6140
|
+
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? r.size === 0 ? "ready-with-warning" : "ready" : "pending", capture: r.capture, contentValidation: r.contentValidation, retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
|
|
5757
6141
|
}
|
|
5758
6142
|
function get(scope, id) {
|
|
5759
6143
|
const r = resources.get(String(id));
|
|
@@ -5776,8 +6160,8 @@ async function createDataPlugin(access, options) {
|
|
|
5776
6160
|
r.terminalCode ??= "download_revoked";
|
|
5777
6161
|
r.abort.abort();
|
|
5778
6162
|
r.state = "cancelled";
|
|
5779
|
-
remember(r);
|
|
5780
6163
|
await r.task?.catch(() => {});
|
|
6164
|
+
remember(r);
|
|
5781
6165
|
r.bytes?.fill(0);
|
|
5782
6166
|
r.bytes = undefined;
|
|
5783
6167
|
if (r.path && owned.has(r.path)) {
|
|
@@ -5808,20 +6192,20 @@ async function createDataPlugin(access, options) {
|
|
|
5808
6192
|
await mkdir2(dir, { mode: 448 });
|
|
5809
6193
|
ownedDirs.add(dir);
|
|
5810
6194
|
const part = join2(options.directory, `${r.id}.partial`), dest = join2(dir, r.name);
|
|
5811
|
-
const h = await
|
|
6195
|
+
const h = await open3(part, "wx", 384);
|
|
5812
6196
|
await h.close();
|
|
5813
6197
|
owned.add(part);
|
|
5814
6198
|
r.path = part;
|
|
5815
6199
|
let size = 0;
|
|
5816
|
-
const hash =
|
|
5817
|
-
const check = new
|
|
6200
|
+
const hash = createHash7("sha256");
|
|
6201
|
+
const check = new Transform2({ transform(chunk, _enc, cb) {
|
|
5818
6202
|
size += chunk.length;
|
|
5819
6203
|
if (size > r.size)
|
|
5820
6204
|
return cb(new Error("Size exceeded"));
|
|
5821
6205
|
hash.update(chunk);
|
|
5822
6206
|
cb(null, chunk);
|
|
5823
6207
|
} });
|
|
5824
|
-
await
|
|
6208
|
+
await pipeline2(Readable.fromWeb(response.body), check, createWriteStream2(part, { flags: "r+", mode: 384 }), { signal: r.abort.signal });
|
|
5825
6209
|
const actual = hash.digest("hex");
|
|
5826
6210
|
if (size !== r.size || r.expectedHash && actual !== r.expectedHash)
|
|
5827
6211
|
throw new Error("Verification failed");
|
|
@@ -5844,7 +6228,7 @@ async function createDataPlugin(access, options) {
|
|
|
5844
6228
|
body = Readable.toWeb(createReadStream(r.path));
|
|
5845
6229
|
}
|
|
5846
6230
|
const response = await fetch(g.url, { method: "PUT", headers: g.headers, body, duplex: "half", redirect: "error", signal: r.abort.signal });
|
|
5847
|
-
if (!response.ok)
|
|
6231
|
+
if (!response.ok || r.abort.signal.aborted || r.state === "cancelled")
|
|
5848
6232
|
throw new Error("Transfer failed");
|
|
5849
6233
|
r.state = "ready";
|
|
5850
6234
|
}
|
|
@@ -5901,9 +6285,9 @@ async function createDataPlugin(access, options) {
|
|
|
5901
6285
|
return meta(r);
|
|
5902
6286
|
}
|
|
5903
6287
|
if (op === "create_download") {
|
|
5904
|
-
const r = get(
|
|
5905
|
-
if (r.purpose !== "download" || r.state !== "ready")
|
|
5906
|
-
throw new
|
|
6288
|
+
const r = resources.get(String(args.downloadId ?? args.fileId ?? args.resourceId));
|
|
6289
|
+
if (!r || !sameScope(r.scope, scope) || r.expiresAt < Date.now() || r.purpose !== "download" || r.state !== "ready")
|
|
6290
|
+
throw new RuntimeFault("resource_unavailable", "Use browser_list_downloads to select an available retained downloadId in this session. If no retained bytes are available, ask before recreating them; never automatically replay the website action, export or script.", true);
|
|
5907
6291
|
return meta(r);
|
|
5908
6292
|
}
|
|
5909
6293
|
if (op === "transfer_status") {
|
|
@@ -5922,7 +6306,7 @@ async function createDataPlugin(access, options) {
|
|
|
5922
6306
|
const r = get(scope, args.resourceId);
|
|
5923
6307
|
const grant = args.dataGrant;
|
|
5924
6308
|
validateGrant(grant, options.serverOrigin, r.id, options.allowInsecureLoopback);
|
|
5925
|
-
if (r.authorized || grant.purpose !== r.purpose || grant.method !== (r.purpose === "upload" ? "GET" : "PUT") || grant.limits.maxBytes !== r.size)
|
|
6309
|
+
if (r.authorized || r.purpose === "download" && (r.state !== "ready" || !r.hash) || grant.purpose !== r.purpose || grant.method !== (r.purpose === "upload" ? "GET" : "PUT") || grant.limits.maxBytes !== r.size)
|
|
5926
6310
|
throw new Error("Invalid data authorization");
|
|
5927
6311
|
r.authorized = true;
|
|
5928
6312
|
r.task = transfer(r, grant);
|
|
@@ -5988,6 +6372,7 @@ async function createDataPlugin(access, options) {
|
|
|
5988
6372
|
async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
|
|
5989
6373
|
let r;
|
|
5990
6374
|
let timeout2;
|
|
6375
|
+
let cancel;
|
|
5991
6376
|
try {
|
|
5992
6377
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
5993
6378
|
resources.delete(r.id);
|
|
@@ -5995,55 +6380,47 @@ async function createDataPlugin(access, options) {
|
|
|
5995
6380
|
resources.set(r.id, r);
|
|
5996
6381
|
r.tabId = tabId;
|
|
5997
6382
|
r.generation = generation;
|
|
5998
|
-
r.
|
|
6383
|
+
r.capture = { method: "completed-browser-file", stage: "completion", browserCompletion: "pending", comparison: "pending" };
|
|
6384
|
+
cancel = () => {
|
|
5999
6385
|
download.cancel().catch(() => {});
|
|
6000
|
-
}
|
|
6386
|
+
};
|
|
6387
|
+
r.abort.signal.addEventListener("abort", cancel, { once: true });
|
|
6001
6388
|
timeout2 = setTimeout(() => {
|
|
6002
|
-
r.terminalCode
|
|
6389
|
+
r.terminalCode ??= "download_capture_timeout";
|
|
6003
6390
|
r.abort.abort();
|
|
6004
|
-
download.cancel().catch(() => {});
|
|
6005
6391
|
}, LIMITS.duration);
|
|
6006
6392
|
timeout2.unref?.();
|
|
6007
6393
|
const captured = r;
|
|
6008
6394
|
r.task = (async () => {
|
|
6009
|
-
const
|
|
6010
|
-
captured.path =
|
|
6011
|
-
owned.add(
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
hash.update(chunk);
|
|
6024
|
-
callback(null, chunk);
|
|
6025
|
-
} });
|
|
6026
|
-
await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: captured.abort.signal });
|
|
6027
|
-
await chmod(path9, 384);
|
|
6028
|
-
const stat = await lstat2(path9);
|
|
6029
|
-
if (!stat.isFile() || stat.size !== received || captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6395
|
+
const path10 = join2(options.directory, captured.id);
|
|
6396
|
+
captured.path = path10;
|
|
6397
|
+
owned.add(path10);
|
|
6398
|
+
try {
|
|
6399
|
+
const verified = await captureDownload(download, path10, captured.abort.signal, captured.capture);
|
|
6400
|
+
if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6401
|
+
throw new Error("Download revoked");
|
|
6402
|
+
captured.size = verified.size;
|
|
6403
|
+
captured.hash = verified.sha256;
|
|
6404
|
+
captured.contentValidation = contentValidation(captured.name, verified.size);
|
|
6405
|
+
} finally {
|
|
6406
|
+
await cleanupDownload(download, captured.capture);
|
|
6407
|
+
}
|
|
6408
|
+
if (captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6030
6409
|
throw new Error("Download revoked");
|
|
6031
|
-
captured.size = stat.size;
|
|
6032
|
-
captured.hash = hash.digest("hex");
|
|
6033
6410
|
captured.state = "ready";
|
|
6034
6411
|
})();
|
|
6035
6412
|
await r.task;
|
|
6036
|
-
await download.delete().catch(() => {});
|
|
6037
6413
|
if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
|
|
6038
6414
|
throw new Error("Download revoked");
|
|
6039
|
-
return { ...meta(r), state: "completed"
|
|
6040
|
-
} catch {
|
|
6041
|
-
|
|
6415
|
+
return { ...meta(r), state: "completed" };
|
|
6416
|
+
} catch (error) {
|
|
6417
|
+
download.cancel().catch(() => {});
|
|
6042
6418
|
if (r) {
|
|
6043
|
-
r.terminalCode ??= "download_capture_failed";
|
|
6419
|
+
r.terminalCode ??= error instanceof CaptureError ? error.code : "download_capture_failed";
|
|
6044
6420
|
await remove(r);
|
|
6045
|
-
return
|
|
6421
|
+
return status(scope, downloadId);
|
|
6046
6422
|
}
|
|
6423
|
+
await cleanupDownload(download);
|
|
6047
6424
|
const failed = { downloadId, resourceId: downloadId, state: "failed", readiness: "unavailable", code: "download_capture_rejected", recovery: "Capture could not be reserved. Do not automatically repeat the website action." };
|
|
6048
6425
|
terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6049
6426
|
while (terminal.size > 128)
|
|
@@ -6052,8 +6429,8 @@ async function createDataPlugin(access, options) {
|
|
|
6052
6429
|
} finally {
|
|
6053
6430
|
if (timeout2)
|
|
6054
6431
|
clearTimeout(timeout2);
|
|
6055
|
-
if (r
|
|
6056
|
-
|
|
6432
|
+
if (r && cancel)
|
|
6433
|
+
r.abort.signal.removeEventListener("abort", cancel);
|
|
6057
6434
|
}
|
|
6058
6435
|
},
|
|
6059
6436
|
async onNavigation(tabId, generation) {
|
|
@@ -6204,7 +6581,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6204
6581
|
for (const signal of signals)
|
|
6205
6582
|
process.on(signal, signalStop);
|
|
6206
6583
|
try {
|
|
6207
|
-
const
|
|
6584
|
+
const requestedRoot = path10.resolve(installationRoot());
|
|
6585
|
+
for (const profile of profiles)
|
|
6586
|
+
assertControlPaths(requestedRoot, controlSocketPath(requestedRoot, profile));
|
|
6587
|
+
const root = await privateDirectory2(requestedRoot);
|
|
6208
6588
|
if (command !== "start") {
|
|
6209
6589
|
const profile = profiles[0], controlPath = controlSocketPath(root, profile);
|
|
6210
6590
|
if (command === "recover") {
|
|
@@ -6222,7 +6602,7 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6222
6602
|
socket.end();
|
|
6223
6603
|
resolve2();
|
|
6224
6604
|
});
|
|
6225
|
-
socket.once("error", (error) => reject(
|
|
6605
|
+
socket.once("error", (error) => reject(controlFailure("control-connect", error)));
|
|
6226
6606
|
});
|
|
6227
6607
|
return;
|
|
6228
6608
|
}
|
|
@@ -6232,10 +6612,10 @@ Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI
|
|
|
6232
6612
|
const controlPath = controlSocketPath(root, profile);
|
|
6233
6613
|
const previousSocket = await fs10.lstat(controlPath).catch((error) => {
|
|
6234
6614
|
if (error.code !== "ENOENT")
|
|
6235
|
-
throw error;
|
|
6615
|
+
throw controlFailure("local-control", error);
|
|
6236
6616
|
});
|
|
6237
6617
|
if (previousSocket)
|
|
6238
|
-
throw new Error(`Local control path already exists
|
|
6618
|
+
throw new Error(`Local control path already exists; stage=local-control reason=path-exists. Use a different --profile to launch another browser. If the prior host has stopped, run browser-mcp browser recover --profile ${profile}. Recovery verifies both runtime.lock and the socket; never blindly unlink either.`);
|
|
6239
6619
|
abort.signal.throwIfAborted();
|
|
6240
6620
|
}
|
|
6241
6621
|
const results = await Promise.allSettled(profiles.map(async (profile) => {
|
|
@@ -6284,7 +6664,11 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6284
6664
|
["Local control", async () => {
|
|
6285
6665
|
for (const client of clients)
|
|
6286
6666
|
client.destroy();
|
|
6287
|
-
|
|
6667
|
+
try {
|
|
6668
|
+
await stopControl?.();
|
|
6669
|
+
} catch (error) {
|
|
6670
|
+
throw controlFailure("control-cleanup", error);
|
|
6671
|
+
}
|
|
6288
6672
|
}],
|
|
6289
6673
|
["Browser session", async () => {
|
|
6290
6674
|
await session?.close();
|
|
@@ -6305,28 +6689,26 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6305
6689
|
if (groupSignal.aborted)
|
|
6306
6690
|
groupStop();
|
|
6307
6691
|
let failure, cleanupFailure;
|
|
6692
|
+
let runtimeStage = "download-quota";
|
|
6308
6693
|
try {
|
|
6309
6694
|
abort.signal.throwIfAborted();
|
|
6310
6695
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
6311
6696
|
session.lifecycle.ended.then(endSession);
|
|
6312
6697
|
abort.signal.throwIfAborted();
|
|
6313
|
-
stopQuota = await enforceDownloadQuota(session.context,
|
|
6698
|
+
stopQuota = await enforceDownloadQuota(session.context, path10.join(session.runPath, "chrome-downloads"));
|
|
6314
6699
|
abort.signal.throwIfAborted();
|
|
6700
|
+
runtimeStage = "pairing";
|
|
6315
6701
|
const token = await credential(root, server, profile, abort.signal);
|
|
6316
6702
|
abort.signal.throwIfAborted();
|
|
6317
|
-
|
|
6703
|
+
runtimeStage = "runtime-setup";
|
|
6704
|
+
const previews = path10.join(session.runPath, "previews");
|
|
6318
6705
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
6319
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
6706
|
+
runtime.plugins.push(await createDataPlugin(runtime, { directory: path10.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
|
|
6320
6707
|
abort.signal.throwIfAborted();
|
|
6321
6708
|
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
6322
6709
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
6323
|
-
await session.context.route("**/*", async (route) => {
|
|
6324
|
-
if (!runtime.allowURL(route.request().url()))
|
|
6325
|
-
await route.abort("blockedbyclient");
|
|
6326
|
-
else
|
|
6327
|
-
await route.continue();
|
|
6328
|
-
});
|
|
6329
6710
|
abort.signal.throwIfAborted();
|
|
6711
|
+
runtimeStage = "local-control";
|
|
6330
6712
|
local = net3.createServer((socket) => {
|
|
6331
6713
|
clients.add(socket);
|
|
6332
6714
|
socket.once("close", () => clients.delete(socket));
|
|
@@ -6357,24 +6739,21 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6357
6739
|
return;
|
|
6358
6740
|
} else if (cmd !== "status")
|
|
6359
6741
|
throw new Error("Invalid command");
|
|
6360
|
-
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.
|
|
6742
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.16", protocol: 3 }) + `
|
|
6361
6743
|
`);
|
|
6362
6744
|
})().catch(() => socket.destroy());
|
|
6363
6745
|
});
|
|
6364
6746
|
});
|
|
6365
|
-
|
|
6366
|
-
stopControl = await listenControl(local, root, controlPath);
|
|
6367
|
-
} catch (error) {
|
|
6368
|
-
throw new Error(`Cannot bind local control socket ${controlPath}: ${error instanceof Error ? error.message : error}. No existing socket was removed. Stop the previous owner and run browser-mcp browser recover --profile ${profile}; see the recovery documentation if ownership cannot be verified.`);
|
|
6369
|
-
}
|
|
6747
|
+
stopControl = await listenControl(local, root, controlPath);
|
|
6370
6748
|
abort.signal.throwIfAborted();
|
|
6371
6749
|
starting = false;
|
|
6372
6750
|
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.`);
|
|
6751
|
+
runtimeStage = "relay";
|
|
6373
6752
|
await relay.start();
|
|
6374
6753
|
} catch (error) {
|
|
6375
6754
|
if (session) {
|
|
6376
6755
|
if (!session.lifecycle.hasEnded && !abort.signal.aborted)
|
|
6377
|
-
failure = new Error(
|
|
6756
|
+
failure = runtimeStage === "local-control" ? controlFailure("local-control", error) : new Error(`Browser runtime failed; stage=${runtimeStage} reason=operation-failed (private details suppressed). Check local setup and server availability before restarting; do not delete profile data.`);
|
|
6378
6757
|
} else if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
|
|
6379
6758
|
failure = error;
|
|
6380
6759
|
} finally {
|