openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,268 lines (1,267 loc) • 44.5 kB
JavaScript
import { g as readStringValue, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as addTimerTimeoutGraceMs } from "./number-coercion-D6u-4YD8.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { o as racePromiseWithAbortSignal, s as raceWithTimeout } from "./src-BPmQBLJp.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as createPermitPool } from "./permit-pool-DR3Z0pxU.mjs";
import { n as runExec } from "./exec-aRIvS9s4.mjs";
import { i as withTempDownloadPath } from "./temp-download-BCncM5Fr.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./logging-core-DxpUImpb.mjs";
import { n as redactCdpUrl } from "./browser-cdp-DYGt86Rj.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import { n as normalizeChromeMcpOptions, t as buildChromeMcpSessionCacheKey } from "./chrome-mcp-options-Br21YuDA.mjs";
import { c as BrowserProfileUnavailableError, d as BrowserTabNotFoundError, i as BrowserCdpEndpointBlockedError } from "./errors-C9QQGqVs.mjs";
import "./number-runtime-W4chuk8B.mjs";
import { u as resolveBrowserNavigationTimeoutMs } from "./act-policy-fWdzY2YP.mjs";
import "./time-runtime-DoAwjF0T.mjs";
import "./error-runtime-BM740gJj.mjs";
import "./concurrency-runtime-CY4L3doa.mjs";
import "./temp-path-CW7QMeae.mjs";
import { a as fetchJson, d as redactCdpErrorText, f as resolveCdpTabOwnership, l as normalizeCdpHttpBaseForJsonEndpoints, o as fetchOk, t as appendCdpPath } from "./cdp.helpers-Bxe-G5Kr.mjs";
import { a as isSensitiveFieldDescriptor, c as redactSnapshotFieldValue, i as findValuedSnapshotFields, o as parseFieldDescriptor, t as createBoundedUtf8Tail } from "./bounded-utf8-tail-DU7XQcP9.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import { setTimeout } from "node:timers/promises";
import { Readable } from "node:stream";
import { finished } from "node:stream/promises";
import { Client, SdkError, SdkErrorCode } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
//#region extensions/browser/src/browser/chrome-mcp-contracts.ts
var ChromeMcpDocumentUnavailableError = class extends Error {
constructor(e, t) {
super(e, t);
this.name = "ChromeMcpDocumentUnavailableError";
}
};
function rethrowChromeMcpDocumentError(e) {
const t = e instanceof Error ? e.message : String(e);
if (/Element (?:with )?uid .* (?:not found|no longer exists) on (?:the )?page|Snapshot document (?:changed|disappeared)\. Take a new snapshot\.|Execution context was destroyed|Cannot find context with specified id|Frame (?:was |is )?detached|detached Frame|Node is detached from document/i.test(t)) throw new ChromeMcpDocumentUnavailableError(t, { cause: e });
throw e;
}
const MCP_REQUEST_TIMEOUT_CODE = SdkErrorCode.RequestTimeout;
const CHROME_MCP_NEW_PAGE_TIMEOUT_MS = 5e3;
const CHROME_MCP_NAVIGATE_TIMEOUT_MS = 2e4;
const CHROME_MCP_HANDSHAKE_TIMEOUT_MS = 3e4;
const CHROME_MCP_STDERR_MAX_BYTES = 8192;
const DEVTOOLS_ACTIVE_PORT_RE = /\bDevToolsActivePort\b/i;
const CHROME_CONNECTION_TOOL_ERROR_RE = /(?:Could not connect to Chrome|DevToolsActivePort|ECONNREFUSED|ECONNRESET|websocket|timed out)/i;
const STALE_SELECTED_PAGE_ERROR = "The selected page has been closed. Call list_pages to see open pages.";
const CHROME_MCP_SESSION_TARGET_PREFIX = "chrome-mcp:";
const CHROME_MCP_SNAPSHOT_REF_PREFIX = "mcp-ref:";
var ChromeMcpReconnectRequiredError = class extends Error {};
var ChromeMcpProcessSnapshotError = class extends Error {};
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-diagnostics.ts
function drainStderr(e) {
const t = e.stderr;
if (!t) return () => "";
const n = createBoundedUtf8Tail(CHROME_MCP_STDERR_MAX_BYTES);
t.on("data", (e) => {
n.append(e);
});
t.on("error", () => {});
return () => n.text().trim();
}
function redactChromeMcpDiagnosticTextWithLocalPaths(e) {
const t = normalizeOptionalString(os.homedir());
const n = t ? path.resolve(t) : void 0;
const r = n ? e.split(n).join("~") : e;
return redactCdpErrorText(r);
}
function redactChromeMcpLocalPathForDiagnostic(e) {
const t = normalizeOptionalString(os.homedir());
if (!t || !path.isAbsolute(e)) return redactCdpErrorText(e);
const n = path.relative(path.resolve(t), path.resolve(e));
if (n === "") return "~";
if (!n.startsWith("..") && !path.isAbsolute(n)) return redactCdpErrorText(`~/${n.split(path.sep).join("/")}`);
return redactCdpErrorText(e);
}
function redactChromeMcpProfileLabelForDiagnostic(e) {
return path.isAbsolute(e) ? redactChromeMcpLocalPathForDiagnostic(e) : redactCdpErrorText(e);
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-process.ts
function readChromeMcpTransportPid(e) {
const t = e.pid;
return typeof t === "number" && Number.isInteger(t) && t > 0 && t !== process.pid ? t : void 0;
}
function parseChromeMcpLinuxStat(e, t) {
const n = t.slice(t.lastIndexOf(")") + 2).split(/\s+/);
const r = Number.parseInt(n[1] ?? "", 10);
const i = normalizeOptionalString(n[19]);
return Number.isInteger(r) && i ? {
pid: e,
ppid: r,
identity: `linux:${i}`
} : null;
}
async function listChromeMcpLinuxProcesses() {
const e = (await fs.readdir("/proc")).filter((e) => /^\d+$/.test(e)).map((e) => Number.parseInt(e, 10));
const t = [];
for (const n of e) try {
const e = parseChromeMcpLinuxStat(n, await fs.readFile(`/proc/${n}/stat`, "utf8"));
if (e) t.push(e);
} catch {}
return t;
}
function parseChromeMcpDelimitedProcessList(e, t) {
return e.split(/\r?\n/).flatMap((e) => {
const [n, r, i, ...a] = e.split(" ");
const o = Number.parseInt(n ?? "", 10);
const s = Number.parseInt(r ?? "", 10);
const c = normalizeOptionalString(i);
const l = normalizeOptionalString(a.join(" "));
return Number.isInteger(o) && Number.isInteger(s) && c && l ? [{
pid: o,
ppid: s,
identity: `${t}:${c}|${l}`
}] : [];
});
}
function parseChromeMcpUnixProcessList(e, t) {
return parseChromeMcpDelimitedProcessList(e.replace(/^\s*(\d+)\s+(\d+)\s+(.{24})\s+(.+)$/gm, "$1 $2 $3 $4"), t);
}
async function listChromeMcpPlatformProcesses() {
try {
const e = process.platform;
if (e === "linux") return await listChromeMcpLinuxProcesses();
const t = e === "win32";
const { stdout: n } = await runExec(t ? "powershell.exe" : "ps", t ? [
"-NoProfile",
"-NonInteractive",
"-Command",
"Get-CimInstance Win32_Process | ForEach-Object { \"{0}`t{1}`t{2:o}`t{3}\" -f $_.ProcessId,$_.ParentProcessId,$_.CreationDate,$_.ExecutablePath }"
] : [
"-axww",
"-o",
"pid=,ppid=,lstart=,command="
], {
env: t ? void 0 : {
...process.env,
LC_ALL: "C",
TZ: "UTC"
},
logOutput: false,
maxBuffer: 4194304,
timeoutMs: 2e3
});
if (t) return parseChromeMcpDelimitedProcessList(n, e);
return parseChromeMcpUnixProcessList(n, e);
} catch (e) {
throw new ChromeMcpProcessSnapshotError(e instanceof Error ? e.message : "Unable to inspect the Chrome MCP process tree.", { cause: e });
}
}
function captureChromeMcpProcessTarget(e, t) {
const n = t.findLast((t) => t.pid === e);
if (!n) throw new ChromeMcpProcessSnapshotError(`Chrome MCP process identity unavailable for pid ${e}.`);
const r = /* @__PURE__ */ new Map();
for (const e of t) {
const t = r.get(e.ppid) ?? [];
t.push(e);
r.set(e.ppid, t);
}
const i = [];
const a = [...r.get(e) ?? []];
for (const t of a) {
if (t.pid === process.pid || t.pid === e) continue;
i.push({
pid: t.pid,
identity: t.identity
});
a.push(...r.get(t.pid) ?? []);
}
return {
root: {
pid: n.pid,
identity: n.identity
},
descendants: i
};
}
function cleanupTarget(e) {
return e.status === "tracked" || e.status === "uncertain" ? e.target : void 0;
}
async function refreshChromeMcpCleanupProcess(e) {
const t = e.processCleanup;
if (!t || t.status === "closed") return;
if (e.processCleanupRefresh) return await e.processCleanupRefresh;
const n = (async () => {
const n = cleanupTarget(t);
const r = n?.root.pid ?? readChromeMcpTransportPid(e.transport);
if (!r) {
if (t.status === "uncertain") throw new Error("Chrome MCP subprocess tree cleanup could not be verified.");
return;
}
const i = await listChromeMcpPlatformProcesses();
if (e.processCleanup?.status === "closed") return;
const a = i.find((e) => e.pid === r);
if (n && a?.identity !== n.root.identity) {
if (t.status === "uncertain") throw new Error("Chrome MCP subprocess tree cleanup could not be verified.");
return;
}
const o = captureChromeMcpProcessTarget(r, i);
e.processCleanup = {
status: "tracked",
target: {
root: n?.root ?? o.root,
descendants: [...new Map([...n?.descendants ?? [], ...o.descendants].map((e) => [e.pid, e])).values()]
}
};
})();
e.processCleanupRefresh = n;
try {
await n;
} catch (n) {
if (e.processCleanup?.status !== "closed") {
const n = cleanupTarget(t);
e.processCleanup = {
status: "uncertain",
...n ? { target: n } : {}
};
}
throw n;
} finally {
e.processCleanupRefresh = void 0;
}
}
async function taskkillChromeMcpProcessTree(e) {
await runExec("taskkill", [
"/pid",
String(e),
"/t",
"/f"
], {
logOutput: false,
maxBuffer: 65536,
timeoutMs: 2e3
});
}
async function currentChromeMcpProcesses(e) {
const t = await listChromeMcpPlatformProcesses();
const n = new Map(t.map((e) => [e.pid, e.identity]));
return e.filter((e) => n.get(e.pid) === e.identity);
}
async function terminateChromeMcpProcessTree(e) {
if (!e) return;
const t = [...e.descendants.toReversed(), e.root];
let n = await currentChromeMcpProcesses(t);
if (n.length === 0) return;
let r;
const i = process.platform === "win32";
for (const a of [false, true]) {
if (i) {
const t = a ? n.filter(({ pid: t }) => t !== e.root.pid) : n.filter(({ pid: t }) => t === e.root.pid).slice(0, 1);
for (const e of t) {
if (a && (await currentChromeMcpProcesses([e])).length === 0) continue;
try {
await taskkillChromeMcpProcessTree(e.pid);
} catch (e) {
r ??= toErrorObject(e, "Chrome MCP process-tree cleanup failed.");
}
}
} else for (const e of n) try {
process.kill(e.pid, a ? "SIGKILL" : "SIGTERM");
} catch {}
await setTimeout(250);
n = await currentChromeMcpProcesses(t);
if (n.length === 0) return;
}
throw r ?? /* @__PURE__ */ new Error(`Chrome MCP process cleanup failed for pid ${n.map(({ pid: e }) => e).join(", ")}.`);
}
async function closeChromeMcpSessionHandle(e) {
let t;
let n = e.processCleanup?.status === "uncertain";
const attempt = async (e) => {
try {
await e();
} catch (e) {
n ||= e instanceof ChromeMcpProcessSnapshotError;
t ??= toErrorObject(e, "Chrome MCP session cleanup failed.");
}
};
await attempt(async () => await refreshChromeMcpCleanupProcess(e));
const r = e.processCleanup ? cleanupTarget(e.processCleanup) : void 0;
const i = Boolean(r) && process.platform === "win32";
if (i) await attempt(async () => await terminateChromeMcpProcessTree(r));
await attempt(async () => await e.closeTransport());
if (!i) await attempt(async () => await terminateChromeMcpProcessTree(r));
if (t) {
if (n) e.processCleanup = {
status: "uncertain",
...r ? { target: r } : {}
};
throw t;
}
e.processCleanup = { status: "closed" };
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-connect.ts
const log = createSubsystemLogger("browser").child("chrome-mcp");
function createChromeMcpSession(e, t, n) {
const r = new StdioClientTransport({
command: n.command,
args: n.args,
env: n.env,
stderr: "pipe"
});
const i = new Client({
name: "openclaw-browser",
version: "0.0.0"
}, { versionNegotiation: { mode: "legacy" } });
const a = drainStderr(r);
const o = r.start.bind(r);
let s = false;
const c = {
client: i,
transport: r,
closeTransport: r.close.bind(r),
ready: Promise.resolve(),
processCleanup: { status: "open" }
};
r.start = async () => {
await o();
s = true;
await refreshChromeMcpCleanupProcess(c);
};
i.close = r.close = () => e.close(c);
const l = (async () => {
try {
await waitForChromeMcpOperation((async () => {
await i.connect(r);
const e = await i.request({ method: "tools/list" });
c.tools = e.tools;
if (!e.tools.some((e) => e.name === "list_pages")) throw new Error("Chrome MCP server did not expose the expected navigation tools.");
await refreshChromeMcpCleanupProcess(c);
})(), void 0, {
ms: CHROME_MCP_HANDSHAKE_TIMEOUT_MS,
error: () => /* @__PURE__ */ new Error("Chrome MCP handshake timed out"),
unref: true
});
} catch (e) {
try {
await r.close();
const e = r.stderr;
if (s && e instanceof Readable) await finished(e, {
readable: true,
writable: false,
cleanup: true
});
} finally {
const e = a();
if (e) log.warn(`Chrome MCP attach failed for profile "${redactChromeMcpProfileLabelForDiagnostic(t)}". Subprocess stderr:\n${redactChromeMcpDiagnosticTextWithLocalPaths(e)}`);
}
const i = n.browserUrl ? `the configured Chrome endpoint (${redactToolPayloadText(redactCdpUrl(n.browserUrl) ?? n.browserUrl)})` : n.userDataDir ? `the configured Chromium user data dir (${redactChromeMcpLocalPathForDiagnostic(n.userDataDir)})` : "Google Chrome's default profile";
const o = redactChromeMcpDiagnosticTextWithLocalPaths(e instanceof Error ? e.message : String(e));
throw new BrowserProfileUnavailableError(`Chrome MCP existing-session attach failed for profile "${redactChromeMcpProfileLabelForDiagnostic(t)}". Make sure ${i} is running locally with remote debugging enabled. Details: ${o}`);
}
})();
l.catch(() => {});
c.ready = l;
return c;
}
async function waitForChromeMcpReady(e, t, n, r) {
await waitForChromeMcpOperation(e.ready, r, n && n > 0 ? {
ms: n,
error: () => new BrowserProfileUnavailableError(`Chrome MCP existing-session attach for profile "${redactChromeMcpProfileLabelForDiagnostic(t)}" timed out after ${n}ms.`)
} : void 0);
}
async function waitForChromeMcpOperation(e, t, n) {
if (t?.aborted) throw t.reason ?? /* @__PURE__ */ new Error("aborted");
const abortError = (e) => toErrorObject(e.reason ?? /* @__PURE__ */ new Error("aborted"), "Non-Error rejection");
if (!n) return await racePromiseWithAbortSignal(e, t, abortError);
return await raceWithTimeout(e, n.ms, () => {
throw n.error();
}, {
ref: !n.unref,
signal: t,
onAbort: (e) => {
throw abortError(e);
}
});
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-session.ts
const owners = /* @__PURE__ */ new Map();
var ChromeMcpSessionOwner = class {
constructor(e, t, n) {
this.profileName = e;
this.options = t;
this.key = n;
this.retired = /* @__PURE__ */ new Map();
this.temporary = 0;
this.admissions = 0;
}
forgetIfEmpty() {
if (!this.session && !this.pending && !this.retired.size && !this.temporary && !this.admissions && owners.get(this.key) === this) owners.delete(this.key);
}
isCurrent(e) {
return this.session?.transport === e.transport;
}
get pid() {
if (this.session) return this.session.transport.pid ?? null;
const e = this.retired.keys().next().value;
return (e?.processCleanup && cleanupTarget(e.processCleanup))?.root.pid ?? e?.transport.pid ?? null;
}
close(e) {
if (this.session?.transport === e.transport) this.session = void 0;
if (e.processCleanup?.status === "closed") {
this.retired.delete(e);
this.forgetIfEmpty();
return Promise.resolve();
}
const t = this.retired.get(e);
if (t) return t;
e.transport.send = async () => {
throw new Error("Chrome MCP session is closing");
};
owners.set(this.key, this);
const n = closeChromeMcpSessionHandle(e).then(() => {
this.retired.delete(e);
}).finally(() => {
if (this.retired.has(e)) this.retired.set(e, void 0);
this.forgetIfEmpty();
});
this.retired.set(e, n);
n.catch(() => {});
return n;
}
async drainRetired() {
const e = (await Promise.allSettled([...this.retired.keys()].map((e) => this.close(e)))).find((e) => e.status === "rejected");
if (e?.status === "rejected") throw e.reason;
}
async drainPending(e) {
try {
await this.close(e.session);
} finally {
if (this.pending === e) this.pending = void 0;
}
}
async stop() {
const e = Boolean(this.pending || this.session || this.retired.size);
if (this.pending) {
this.pending.cancelled = true;
await this.drainPending(this.pending);
}
await this.drainRetired();
if (this.session) await this.close(this.session);
this.forgetIfEmpty();
return e;
}
start() {
const e = createChromeMcpSession(this, this.profileName, this.options);
const t = {
session: e,
waiters: 0,
cancelled: false
};
this.session = e;
this.pending = t;
owners.set(this.key, this);
return t;
}
async join(e, t) {
e.waiters++;
let n = false;
const release = async (t) => {
if (n) return;
n = true;
if (--e.waiters !== 0) return;
if (t) {
e.cancelled = true;
await this.close(e.session);
}
if (this.pending === e) this.pending = void 0;
this.forgetIfEmpty();
};
let r;
const abort = () => {
r ??= release(true);
r.catch(() => {});
};
t.signal?.addEventListener("abort", abort, { once: true });
if (t.signal?.aborted) abort();
try {
await waitForChromeMcpReady(e.session, this.profileName, t.timeoutMs, t.signal);
return e.session;
} catch (n) {
await (r ?? release(t.signal?.aborted === true || e.waiters <= 1));
throw n;
} finally {
t.signal?.removeEventListener("abort", abort);
await release(false);
}
}
async lease(e) {
this.admissions++;
try {
if (!e.ephemeral) await stopOwners(this.profileName, this);
e.signal?.throwIfAborted();
return await this.acquire(e);
} finally {
this.admissions--;
this.forgetIfEmpty();
}
}
async acquire(e) {
if (this.pending?.cancelled) await this.drainPending(this.pending);
await this.drainRetired();
e.signal?.throwIfAborted();
if (this.session?.transport.pid === null) await this.close(this.session);
const t = Boolean(e.ephemeral && (this.pending || !this.session));
let n = this.pending ? void 0 : this.session;
if (t) {
n = createChromeMcpSession(this, this.profileName, this.options);
this.temporary++;
try {
await waitForChromeMcpReady(n, this.profileName, e.timeoutMs, e.signal);
} catch (e) {
try {
await this.close(n);
} finally {
this.temporary--;
this.forgetIfEmpty();
}
throw e;
}
} else if (n) try {
await waitForChromeMcpReady(n, this.profileName, e.timeoutMs, e.signal);
} catch (t) {
if (!e.ephemeral || !e.signal?.aborted) await this.close(n);
throw t;
}
else n = await this.join(this.pending ?? this.start(), e);
if (!e.ephemeral && n.transport.pid === null) {
if (this.pending?.session === n) this.pending = void 0;
await this.close(n);
throw new BrowserProfileUnavailableError(`Chrome MCP existing-session attach failed for profile "${redactChromeMcpProfileLabelForDiagnostic(this.profileName)}". The Chrome MCP subprocess exited before it became usable.`);
}
return {
session: n,
temporary: t,
owner: this,
release: async () => {
if (t) try {
await this.close(n);
} finally {
this.temporary--;
this.forgetIfEmpty();
}
}
};
}
};
function getChromeMcpSessionOwner(e, t) {
const n = buildChromeMcpSessionCacheKey(e, t);
let r = owners.get(n);
if (!r) {
r = new ChromeMcpSessionOwner(e, t, n);
owners.set(n, r);
}
return r;
}
async function stopOwners(e, t) {
const n = await Promise.allSettled([...owners.values()].filter((n) => n !== t && n.profileName === e).map((e) => e.stop()));
const r = n.find((e) => e.status === "rejected");
if (r?.status === "rejected") throw toErrorObject(r.reason, "Chrome MCP session cleanup failed.");
return n.some((e) => e.status === "fulfilled" && e.value);
}
function getChromeMcpPid(e) {
for (const t of owners.values()) if (t.profileName === e && t.pid !== null) return t.pid;
return null;
}
async function closeChromeMcpSession(e) {
return await stopOwners(e);
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-result.ts
function asPages(e) {
if (!Array.isArray(e)) return [];
const t = [];
for (const n of e) {
const e = asNullableRecord(n);
if (!e || typeof e.id !== "number") continue;
t.push({
id: e.id,
url: readStringValue(e.url),
selected: e.selected === true
});
}
return t;
}
function extractStructuredContent(e) {
return asNullableRecord(e.structuredContent) ?? {};
}
function extractTextContent(e) {
return (Array.isArray(e.content) ? e.content : []).map((e) => {
const t = asNullableRecord(e);
return t && typeof t.text === "string" ? t.text : "";
}).filter(Boolean);
}
function extractTextPages(e) {
const t = [];
for (const n of extractTextContent(e)) for (const e of n.split(/\r?\n/)) {
const n = e.match(/^\s*(\d+):\s+(.+?)(?:\s+\[(selected)\])?\s*$/i);
if (!n) continue;
t.push({
id: Number.parseInt(n[1] ?? "", 10),
url: normalizeOptionalString(n[2]),
selected: Boolean(n[3])
});
}
return t;
}
function extractStructuredPages(e) {
const t = asPages(extractStructuredContent(e).pages);
return t.length > 0 ? t : extractTextPages(e);
}
function normalizeSnapshotFields(e) {
const t = e.value;
return {
id: readStringValue(e.id),
role: readStringValue(e.role),
name: readStringValue(e.name),
...typeof t === "string" || typeof t === "number" || typeof t === "boolean" ? { value: t } : {},
description: readStringValue(e.description)
};
}
function extractSnapshot(e) {
const t = extractStructuredContent(e);
const n = asNullableRecord(t.snapshot);
if (!n) throw new Error("Chrome MCP snapshot response was missing structured snapshot data.");
const r = normalizeSnapshotFields(n);
const i = [{
record: n,
node: r
}];
while (i.length > 0) {
const e = i.pop();
if (!e || !Array.isArray(e.record.children)) continue;
const t = [];
for (const n of e.record.children) {
const e = asNullableRecord(n);
if (!e) continue;
const r = normalizeSnapshotFields(e);
t.push(r);
i.push({
record: e,
node: r
});
}
e.node.children = t;
}
return r;
}
function extractMessageText(e) {
const t = extractStructuredContent(e).message;
if (typeof t === "string" && t.trim()) return t;
return extractTextContent(e).find((e) => e.trim()) ?? "";
}
function extractChromeMcpToolError(e, t, n) {
if (e.isError || t === "close_page" && extractStructuredPages(e).some((e) => e.id === n.pageId)) return extractMessageText(e).trim() || `Chrome MCP tool "${t}" failed.`;
if (t !== "navigate_page") return;
return [extractMessageText(e), ...extractTextContent(e)].flatMap((e) => e.split(/\r?\n/)).find((e) => e.startsWith("Unable to navigate in the selected page:"));
}
function formatChromeMcpToolErrorMessage(e) {
const t = redactChromeMcpDiagnosticTextWithLocalPaths(e.message);
const n = redactChromeMcpProfileLabelForDiagnostic(e.profileName);
if (e.options.browserUrl && CHROME_CONNECTION_TOOL_ERROR_RE.test(e.message)) return `Chrome MCP tool "${e.toolName}" failed for profile "${n}" while using the configured Chrome endpoint (${redactToolPayloadText(redactCdpUrl(e.options.browserUrl) ?? e.options.browserUrl)}). Details: ${t}`;
if (!e.options.browserUrl && e.options.userDataDir && DEVTOOLS_ACTIVE_PORT_RE.test(e.message)) return `${t} If this browser was started with --remote-debugging-port, set ${path.isAbsolute(e.profileName) ? "this existing-session profile's cdpUrl" : `browser.profiles.${e.profileName}.cdpUrl`} to that DevTools endpoint instead of relying on Chrome MCP auto-connect.`;
return t;
}
function extractJsonMessage(e) {
const t = [extractMessageText(e), ...extractTextContent(e)].filter((e) => e.trim());
let n;
for (const e of t) try {
const t = e.match(/^[\t ]*```json[\t ]*\r?\n([\s\S]*?)\r?\n[\t ]*```[\t ]*\r?$/im)?.[1]?.trim() || e.trim();
return t === "undefined" ? void 0 : JSON.parse(t);
} catch (e) {
n = e;
}
if (n) throw toErrorObject(n, "Non-Error thrown");
return null;
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-routing.ts
function getChromeMcpRoutingState(e) {
e.routing ??= {
sessionNonce: randomUUID().replaceAll("-", "").slice(0, 12),
operationPermits: createPermitPool(1),
targetIdByPageId: /* @__PURE__ */ new Map(),
nextTargetHandleId: 1,
snapshotsByTarget: /* @__PURE__ */ new Map(),
nextSnapshotRefId: 1
};
return e.routing;
}
/** UID-only MCP actions cannot distinguish collisions between renderer documents. */
function validateChromeMcpSnapshotRefs(e) {
const t = /* @__PURE__ */ new Map();
const n = [{
node: e,
document: e,
documentUid: normalizeOptionalString(e.id)
}];
for (let e = n.pop(); e; e = n.pop()) {
const r = e.node.role?.trim().toLowerCase();
const i = r === "rootwebarea" ? e.node : e.document;
const a = normalizeOptionalString(e.node.id);
const o = r === "rootwebarea" ? a : e.documentUid;
if (a) {
const n = t.get(a);
if (n && n.document !== i) throw new Error("Chrome MCP returned ambiguous element IDs across documents. The snapshot and its refs were discarded. Use a managed browser profile for this page; ref-free screenshots remain available.");
if (n) n.nodes.push(e.node);
else t.set(a, {
document: i,
documentUid: o,
nodes: [e.node]
});
}
for (const t of e.node.children?.toReversed() ?? []) n.push({
node: t,
document: r === "iframe" ? e.node : i,
documentUid: r === "iframe" ? void 0 : o
});
}
return t;
}
function registerChromeMcpSnapshot(e, t, n) {
const r = extractSnapshot(n);
const i = normalizeOptionalString(r.id);
if (!i || r.role?.trim().toLowerCase() !== "rootwebarea") throw new Error("Chrome MCP snapshot did not contain a top-level document uid");
const a = validateChromeMcpSnapshotRefs(r);
const o = getChromeMcpRoutingState(e);
const s = /* @__PURE__ */ new Map();
for (const [e, t] of a) {
const n = `${CHROME_MCP_SNAPSHOT_REF_PREFIX}${o.sessionNonce}:${o.nextSnapshotRefId}`;
o.nextSnapshotRefId += 1;
s.set(n, {
uid: e,
documentUid: t.documentUid
});
for (const e of t.nodes) e.id = n;
}
o.snapshotsByTarget.set(t, {
documentUid: i,
refs: s
});
return {
root: r,
documentUid: i
};
}
function resolveChromeMcpSnapshotRef(e, t, n) {
const r = getChromeMcpRoutingState(e).snapshotsByTarget.get(t)?.refs.get(n);
if (!r) throw new Error(`Unknown ref "${n}". Run a new snapshot and use a ref from that snapshot.`);
return r;
}
async function callTool(e, t, n, r, i, a) {
const o = i.timeoutMs;
const s = i.signal;
if (s?.aborted) throw s.reason ?? /* @__PURE__ */ new Error("aborted");
const c = {
name: n,
arguments: r
};
const l = a.session.tools?.find((e) => e.name === n);
const u = a.session.client.callTool(c, {
...o !== void 0 && o > 0 ? { timeout: o } : {},
...s ? { signal: s } : {},
...l ? { toolDefinition: l } : {}
});
let d;
try {
d = await u;
} catch (e) {
if (!a.temporary && a.owner.isCurrent(a.session)) await a.owner.close(a.session);
if (s?.aborted) throw toErrorObject(s.reason ?? e, "Non-Error abort reason");
if (o && e instanceof SdkError && e.code === MCP_REQUEST_TIMEOUT_CODE) throw new Error(`Chrome MCP "${n}" timed out after ${o}ms. Session reset for reconnect.`, { cause: e });
throw e;
}
const f = extractChromeMcpToolError(d, n, r);
if (f) {
if (n === "list_pages" && f.includes("The selected page has been closed. Call list_pages to see open pages.")) {
if (!a.temporary && a.owner.isCurrent(a.session)) await a.owner.close(a.session);
throw new ChromeMcpReconnectRequiredError(f);
}
throw new Error(formatChromeMcpToolErrorMessage({
profileName: e,
options: t,
toolName: n,
message: f
}));
}
return d;
}
async function callTargetTool(e, t, n) {
return await withChromeMcpTarget(e, async (e) => {
const r = typeof n === "function" ? n(e.session) : n;
return await e.callTool(t, {
...r,
pageId: e.pageId
});
});
}
async function withChromeMcpLease(e, t, n, r) {
const i = normalizeChromeMcpOptions(t);
n.signal?.throwIfAborted();
const a = await getChromeMcpSessionOwner(e, i).lease(n);
try {
const t = n.signal;
if (t?.aborted) throw t.reason ?? /* @__PURE__ */ new Error("aborted");
const o = n.timeoutMs;
const s = await getChromeMcpRoutingState(a.session).operationPermits.acquire({
signal: t,
deadlineAtMs: o !== void 0 && o > 0 ? Date.now() + o : void 0
});
if (!s) {
if (t?.aborted) throw toErrorObject(t.reason ?? /* @__PURE__ */ new Error("aborted"), "Chrome MCP operation cancelled");
throw new Error(`Chrome MCP operation timed out after ${o}ms while waiting for another operation.`);
}
try {
if (t?.aborted) throw t.reason ?? /* @__PURE__ */ new Error("aborted");
if (!a.temporary && (!a.owner.isCurrent(a.session) || a.session.transport.pid === null)) throw new BrowserProfileUnavailableError(`Chrome MCP session for profile "${redactChromeMcpProfileLabelForDiagnostic(e)}" changed before the operation could start. Run the browser command again to reconnect.`);
const call = (t, r, o = n) => callTool(e, i, t, r, o, a);
return await r({
session: a.session,
profileOptions: i,
callTool: call,
listTargets: async (e = n) => registerChromeMcpTargets(a.session, extractStructuredPages(await call("list_pages", {}, e)))
});
} finally {
s();
}
} finally {
await a.release();
}
}
function registerChromeMcpTargets(e, t, n = {}) {
const r = getChromeMcpRoutingState(e);
const i = n.authoritative === false ? new Map(r.targetIdByPageId) : /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Set();
const o = [];
for (const e of t) {
if (a.has(e.id)) throw new Error(`Chrome MCP returned duplicate numeric page id ${e.id}.`);
a.add(e.id);
let t = r.targetIdByPageId.get(e.id);
if (!t) {
t = `${CHROME_MCP_SESSION_TARGET_PREFIX}${r.sessionNonce}:${r.nextTargetHandleId}`;
r.nextTargetHandleId += 1;
}
i.set(e.id, t);
o.push({
page: e,
targetId: t
});
}
for (const [e, t] of r.targetIdByPageId) if (!i.has(e)) r.snapshotsByTarget.delete(t);
r.targetIdByPageId = i;
return o;
}
async function withChromeMcpTarget(e, t) {
return await withChromeMcpLease(e.profileName, e.profile, e, async (n) => {
const r = [...getChromeMcpRoutingState(n.session).targetIdByPageId].find(([, t]) => t === e.targetId)?.[0];
if (r === void 0) throw new BrowserTabNotFoundError({ input: e.targetId });
return await t({
...n,
pageId: r
});
});
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-actions.ts
async function redactChromeMcpSensitiveFieldValues(e, t, n) {
const r = /* @__PURE__ */ new Map();
for (const i of findValuedSnapshotFields(n)) {
const n = i.id;
if (!n) {
redactSnapshotFieldValue(i);
continue;
}
const a = resolveChromeMcpSnapshotRef(e.session, t, n);
const o = a.documentUid;
if (!o) {
redactSnapshotFieldValue(i);
continue;
}
const s = r.get(o) ?? [];
s.push({
node: i,
uid: a.uid
});
r.set(o, s);
}
for (const [t, n] of r) {
let r;
try {
r = extractJsonMessage(await e.callTool("evaluate_script", {
pageId: e.pageId,
function: `(documentRoot, ...elements) => elements.map((element) => {
if (!element || element.nodeType !== 1) return null;
return {
tagName: element.tagName,
type: element.getAttribute("type"),
autocomplete: element.getAttribute("autocomplete"),
};
})`,
args: [t, ...n.map(({ uid: e }) => e)],
waitForStableDom: false
}));
} catch (t) {
if (e.session.transport.pid === null) throw t;
r = null;
}
const i = Array.isArray(r) ? r : [];
for (const [e, { node: t }] of n.entries()) {
const n = parseFieldDescriptor(i[e]);
if (!n || isSensitiveFieldDescriptor(n)) redactSnapshotFieldValue(t);
}
}
}
async function focusChromeMcpTab(e, t, n, r = {}) {
await callTargetTool({
profileName: e,
profile: n,
targetId: t,
...r
}, "select_page", { bringToFront: true });
}
async function closeChromeMcpTab(e, t, n, r = {}) {
await withChromeMcpTarget({
profileName: e,
profile: n,
targetId: t,
...r
}, async (e) => {
await e.callTool("close_page", { pageId: e.pageId });
const n = getChromeMcpRoutingState(e.session);
n.targetIdByPageId.delete(e.pageId);
n.snapshotsByTarget.delete(t);
});
}
async function navigateChromeMcpPage(e) {
const t = resolveBrowserNavigationTimeoutMs(e.timeoutMs);
const n = resolveChromeMcpNavigateCallTimeoutMs(t);
return await withChromeMcpTarget({
...e,
timeoutMs: n
}, async (n) => {
return { url: (await navigateChromeMcpPageOnTarget({
...e,
timeoutMs: t
}, n, "Chrome MCP tab identity changed while navigation was running; the navigation outcome is unknown.")).url ?? e.url };
});
}
async function navigateChromeMcpPageOnTarget(e, t, n) {
const r = {
timeoutMs: resolveChromeMcpNavigateCallTimeoutMs(e.timeoutMs),
signal: e.signal
};
await t.callTool("navigate_page", {
pageId: t.pageId,
type: "url",
url: e.url,
timeout: e.timeoutMs
}, r);
const i = (await t.listTargets(r)).find((t) => t.targetId === e.targetId)?.page;
if (!i) throw new Error(n);
return i;
}
function resolveChromeMcpNavigateCallTimeoutMs(e) {
return addTimerTimeoutGraceMs(e) ?? 1;
}
async function takeChromeMcpSnapshot(e) {
return await withChromeMcpTarget(e, async (t) => {
getChromeMcpRoutingState(t.session).snapshotsByTarget.delete(e.targetId);
const n = await t.callTool("take_snapshot", { pageId: t.pageId });
const { root: r } = registerChromeMcpSnapshot(t.session, e.targetId, n);
await redactChromeMcpSensitiveFieldValues(t, e.targetId, r);
return r;
});
}
/** Run document-bound evaluations without releasing the target/session lock. */
async function withChromeMcpDocument(e, t) {
return await withChromeMcpTarget(e, async (n) => {
const r = getChromeMcpRoutingState(n.session);
try {
let i = r.snapshotsByTarget.get(e.targetId)?.documentUid;
if (!i) {
const t = await n.callTool("take_snapshot", {
pageId: n.pageId,
verbose: true
}).catch(rethrowChromeMcpDocumentError);
i = registerChromeMcpSnapshot(n.session, e.targetId, t).documentUid;
}
return await t({ evaluate: async (e) => {
return extractJsonMessage(await n.callTool("evaluate_script", {
pageId: n.pageId,
function: e,
args: [i],
waitForStableDom: false
}).catch(rethrowChromeMcpDocumentError));
} });
} catch (t) {
if (t instanceof ChromeMcpDocumentUnavailableError) r.snapshotsByTarget.delete(e.targetId);
throw t;
}
});
}
/** Capture within an existing target operation, including its snapshot ref lifetime. */
async function takeChromeMcpScreenshotOnTarget(e, t) {
return await withTempDownloadPath({
prefix: "openclaw-chrome-mcp",
fileName: "screenshot"
}, async (n) => {
const r = e.format ?? "png";
await t.callTool("take_screenshot", {
pageId: t.pageId,
filePath: n,
format: r,
...e.uid ? { uid: resolveChromeMcpSnapshotRef(t.session, e.targetId, e.uid).uid } : {},
...e.fullPage ? { fullPage: true } : {}
}, e);
return await fs.readFile(`${n}.${r}`);
});
}
async function takeChromeMcpScreenshot(e) {
return await withChromeMcpTarget(e, (t) => takeChromeMcpScreenshotOnTarget(e, t));
}
async function clickChromeMcpElement(e) {
await callTargetTool(e, "click", (t) => ({
uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.uid).uid,
...e.doubleClick ? { dblClick: true } : {}
}));
}
async function clickChromeMcpCoords(e) {
await callTargetTool(e, "click_at", {
x: e.x,
y: e.y,
...e.doubleClick ? { dblClick: true } : {}
});
}
/** Select an HTML option by value; MCP fill selects by visible label instead. */
async function selectChromeMcpOption(e) {
await evaluateChromeMcpScript({
...e,
args: [e.uid],
fn: `(el) => {
if (!(el instanceof HTMLSelectElement)) throw new Error("Element is not a select");
if (el.matches(":disabled")) throw new Error("Select element is disabled");
const option = Array.from(el.options).find((entry) => entry.value === ${JSON.stringify(e.value)});
if (!option) throw new Error("No option has the requested value");
el.value = option.value;
el.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
return el.value;
}`
});
}
async function fillChromeMcpElement(e) {
await callTargetTool(e, "fill", (t) => ({
uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.uid).uid,
value: e.value
}));
}
async function fillChromeMcpForm(e) {
await callTargetTool(e, "fill_form", (t) => ({ elements: e.elements.map((n) => ({
...n,
uid: resolveChromeMcpSnapshotRef(t, e.targetId, n.uid).uid
})) }));
}
async function hoverChromeMcpElement(e) {
await callTargetTool(e, "hover", (t) => ({ uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.uid).uid }));
}
async function dragChromeMcpElement(e) {
await callTargetTool(e, "drag", (t) => ({
from_uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.fromUid).uid,
to_uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.toUid).uid
}));
}
async function uploadChromeMcpFile(e) {
await callTargetTool(e, "upload_file", (t) => ({
uid: resolveChromeMcpSnapshotRef(t, e.targetId, e.uid).uid,
filePaths: e.filePaths
}));
}
async function pressChromeMcpKey(e) {
await callTargetTool(e, "press_key", { key: e.key });
}
async function resizeChromeMcpPage(e) {
await callTargetTool(e, "resize_page", {
width: e.width,
height: e.height
});
}
async function evaluateChromeMcpScript(e) {
const t = await callTargetTool(e, "evaluate_script", (t) => ({
function: e.fn,
...e.args?.length ? { args: e.args.map((n) => resolveChromeMcpSnapshotRef(t, e.targetId, n).uid) } : {}
}));
return extractJsonMessage(t);
}
//#endregion
//#region extensions/browser/src/browser/chrome-mcp-tabs.ts
async function ensureChromeMcpAvailable(e, t, n = {}) {
await withChromeMcpLease(e, t, n, async (e) => {
if (!n.pageProbe) return;
try {
const t = await e.listTargets({
...n,
timeoutMs: n.pageProbe.timeoutMs?.() ?? n.timeoutMs
});
n.pageProbe.onResult(t.length);
} catch {
n.signal?.throwIfAborted();
n.pageProbe.onResult(null);
}
});
}
/** List Chrome MCP pages converted to persistent BrowserTab handles. */
async function listChromeMcpTabs(e, t, n = {}) {
for (let r = 0;; r += 1) try {
return await withChromeMcpLease(e, t, n, async (e) => (await e.listTargets()).map(({ page: e, targetId: t }) => ({
targetId: t,
title: "",
url: e.url ?? "",
type: "page"
})));
} catch (e) {
if (e instanceof ChromeMcpReconnectRequiredError && r === 0) continue;
throw e;
}
}
async function lookupChromeMcpMarkerNativeTarget(e) {
const t = normalizeCdpHttpBaseForJsonEndpoints(e.browserUrl);
const n = await fetchJson(appendCdpPath(t, "/json/list"), e.options.cdpTimeouts?.httpTimeoutMs, { signal: e.options.signal }, e.options.cdpPolicy);
if (!Array.isArray(n)) throw new Error("CDP target list response was not an array");
if (n.some((e) => !e || typeof e !== "object")) throw new Error("CDP target list response contained a malformed entry");
const r = n.filter((t) => t.url === e.markerUrl && typeof t.id === "string" && t.id.trim() && (t.type === void 0 || t.type === "page"));
if (r.length !== 1) return;
const i = r[0]?.id;
return typeof i === "string" ? i.trim() || void 0 : void 0;
}
async function captureChromeMcpTabOwnership(e) {
if (!e.browserUrl || !e.markerUrl) return { ownership: {
status: "non-durable",
reason: "explicit-cdp-url-required"
} };
let t;
try {
t = await lookupChromeMcpMarkerNativeTarget({
browserUrl: e.browserUrl,
markerUrl: e.markerUrl,
options: e.options
});
} catch (t) {
if (e.options.signal?.aborted) throw e.options.signal.reason ?? t;
if (t instanceof BrowserCdpEndpointBlockedError) throw t;
return { ownership: {
status: "non-durable",
reason: "target-marker-lookup-failed"
} };
}
if (!t) return { ownership: {
status: "non-durable",
reason: "target-marker-not-unique"
} };
return {
ownership: await resolveCdpTabOwnership({
profileName: e.profileName,
cdpUrl: e.browserUrl,
nativeTargetId: t,
timeoutMs: e.options.cdpTimeouts?.httpTimeoutMs,
signal: e.options.signal,
ssrfPolicy: e.options.cdpPolicy
}),
nativeTargetId: t
};
}
async function openChromeMcpTab(e, t, n, r = {}) {
const i = t.trim() || "about:blank";
return await withChromeMcpLease(e, n, r, async (t) => {
const { session: n, profileOptions: a } = t;
const o = (await t.listTargets({
timeoutMs: CHROME_MCP_NEW_PAGE_TIMEOUT_MS,
signal: r.signal
})).length > 0;
if (!o && !a.browserUrl) throw new Error("Chrome MCP cannot safely open the first page without an explicit CDP endpoint.");
const s = a.browserUrl ? `about:blank#openclaw-${randomUUID()}` : void 0;
const c = s ?? "about:blank";
const l = await t.callTool("new_page", {
url: c,
timeout: CHROME_MCP_NEW_PAGE_TIMEOUT_MS
});
const u = registerChromeMcpTargets(n, extractStructuredPages(l), { authoritative: false });
const d = u.find(({ page: e }) => e.selected) ?? u.at(-1);
if (!d) throw new Error("Chrome MCP did not return the created page.");
let f;
const closeUntrackedPage = async () => {
let e;
if (a.browserUrl && s) try {
const e = f ?? await lookupChromeMcpMarkerNativeTarget({
browserUrl: a.browserUrl,
markerUrl: s,
options: {
...r,
signal: void 0
}
});
if (e) {
const t = normalizeCdpHttpBaseForJsonEndpoints(a.browserUrl);
await fetchOk(appendCdpPath(t, `/json/close/${encodeURIComponent(e)}`), r.cdpTimeouts?.httpTimeoutMs, void 0, r.cdpPolicy);
const i = getChromeMcpRoutingState(n);
i.targetIdByPageId.delete(d.page.id);
i.snapshotsByTarget.delete(d.targetId);
return;
}
} catch (t) {
e = t;
}
if (!o) throw e instanceof Error ? e : new Error("Could not resolve the created Chrome MCP target", { cause: e });
await t.callTool("close_page", { pageId: d.page.id }, { timeoutMs: CHROME_MCP_NEW_PAGE_TIMEOUT_MS });
const i = getChromeMcpRoutingState(n);
i.targetIdByPageId.delete(d.page.id);
i.snapshotsByTarget.delete(d.targetId);
};
try {
const n = await captureChromeMcpTabOwnership({
profileName: e,
browserUrl: a.browserUrl,
markerUrl: s,
options: r
});
f = n.nativeTargetId;
if (!o && n.ownership.status !== "durable") throw new Error("Chrome MCP cannot safely track the first page without durable CDP ownership.");
let l = d.page;
if (i !== c) l = await navigateChromeMcpPageOnTarget({
targetId: d.targetId,
url: i,
timeoutMs: CHROME_MCP_NAVIGATE_TIMEOUT_MS,
signal: r.signal
}, {
...t,
pageId: d.page.id
}, "Chrome MCP created page identity changed before navigation completed.");
return {
targetId: d.targetId,
title: "",
url: l.url ?? i,
type: "page",
ownership: n.ownership
};
} catch (e) {
try {
await closeUntrackedPage();
} catch (t) {
throw Object.assign(new Error("Failed to open a tracked Chrome MCP page and close its marker", { cause: e }), { errors: [e, t] });
}
throw e;
}
});
}
//#endregion
export { resolveChromeMcpSnapshotRef as C, getChromeMcpPid as D, closeChromeMcpSession as E, ChromeMcpDocumentUnavailableError as O, withChromeMcpDocument as S, extractJsonMessage as T, selectChromeMcpOption as _, clickChromeMcpElement as a, takeChromeMcpSnapshot as b, evaluateChromeMcpScript as c, focusChromeMcpTab as d, hoverChromeMcpElement as f, resolveChromeMcpNavigateCallTimeoutMs as g, resizeChromeMcpPage as h, clickChromeMcpCoords as i, rethrowChromeMcpDocumentError as k, fillChromeMcpElement as l, pressChromeMcpKey as m, listChromeMcpTabs as n, closeChromeMcpTab as o, navigateChromeMcpPage as p, openChromeMcpTab as r, dragChromeMcpElement as s, ensureChromeMcpAvailable as t, fillChromeMcpForm as u, takeChromeMcpScreenshot as v, withChromeMcpTarget as w, uploadChromeMcpFile as x, takeChromeMcpScreenshotOnTarget as y };