openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,451 lines • 87.5 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { P as resolveIntegerOption } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, r as asNullableRecord, t as asNonArrayRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode, r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs";
import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { s as redactSensitiveText, u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { t as CONFIG_DIR } from "./utils-C8YECn2Q.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { i as isPidAlive, t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs";
import { s as withFileLock } from "./file-lock-D9Tpq9ra.mjs";
import { h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs";
import { c as isPrivateNetworkAllowedByPolicy, p as resolvePinnedHostnameWithPolicy, u as matchesHostnameAllowlist } from "./ssrf-DHBNJw0c.mjs";
import { t as prepareOomScoreAdjustedSpawn } from "./linux-oom-score-C9goq_Pr.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./logging-core-DxpUImpb.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import { r as ensurePortAvailable } from "./ports-VdrN6cKU.mjs";
import { n as redactCdpUrl } from "./browser-cdp-DYGt86Rj.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import { o as resolveManagedBrowserHeadlessMode, t as getManagedBrowserMissingDisplayError } from "./config-ccOD-Wrr.mjs";
import { t as stripGatewayAllocatorEnv } from "./child-env-CrZt0xN6.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import { c as BrowserProfileUnavailableError, i as BrowserCdpEndpointBlockedError, n as BROWSER_ERROR_REASONS } from "./errors-C9QQGqVs.mjs";
import { h as DEFAULT_OPENCLAW_BROWSER_PROFILE_NAME, p as DEFAULT_OPENCLAW_BROWSER_COLOR } from "./constants-ClfCwK7f.mjs";
import "./retry-runtime-DOUvdfOa.mjs";
import "./number-runtime-W4chuk8B.mjs";
import { t as normalizeBrowserTimerDelayMs } from "./timer-delay-vTpJN_mI.mjs";
import "./error-runtime-BM740gJj.mjs";
import { t as expectDefined } from "./expect-runtime-DT3P17Ul.mjs";
import "./temp-path-CW7QMeae.mjs";
import "./provider-http-LcawLneq.mjs";
import { r as writeJsonFileAtomically, t as loadJsonFile } from "./json-store-CwdRcxNy.mjs";
import { A as CHROME_STOP_TIMEOUT_MS, D as CHROME_BOOTSTRAP_PREFS_TIMEOUT_MS, E as CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS, P as resolveCdpReachabilityTimeouts, a as fetchJson, b as assertManagedProxyAllowsCdpUrl, c as isWebSocketUrl, g as CdpSocketError, i as fetchCdpChecked, j as MANAGED_CDP_READY_HTTP_TIMEOUT_MS, k as CHROME_STDERR_HINT_MAX_CHARS, l as normalizeCdpHttpBaseForJsonEndpoints, m as scopeCdpPolicyToConfiguredEndpoint, n as assertCdpEndpointAllowed, p as resolveCdpWebSocketDiscovery, s as isDirectCdpWebSocketEndpoint, t as appendCdpPath, u as normalizeCdpWsUrl, v as withCdpSocket } from "./cdp.helpers-Bxe-G5Kr.mjs";
import { l as axValue, n as REDACTED_FIELD_VALUE, r as VALUE_FIELD_ROLES, s as redactSensitiveAXNodeValues, t as createBoundedUtf8Tail } from "./bounded-utf8-tail-DU7XQcP9.mjs";
import { i as resolveBrowserExecutableForPlatform, n as isChromeExecutableFamilyMatch, r as processCommandUsesHeadlessChrome, t as assertBrowserExecutableSupportsLaunch } from "./chrome.executables-BXILxwVX.mjs";
import { t as ensureOutputDirectory } from "./output-directories-xJXFgYMl.mjs";
import { t as DEFAULT_DOWNLOAD_DIR } from "./paths-YzGx8hkK.mjs";
import fs from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import os from "node:os";
import { AsyncLocalStorage } from "node:async_hooks";
import { execFileSync, spawn } from "node:child_process";
import { isIP } from "node:net";
import { once } from "node:events";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
//#region extensions/browser/src/browser/browser-proxy-mode.ts
const PROXY_ROUTING_CHROME_ARGS = /* @__PURE__ */ new Set([
"--proxy-auto-detect",
"--proxy-pac-url",
"--proxy-server"
]);
const PROXY_CONTROL_CHROME_ARGS = /* @__PURE__ */ new Set(["--no-proxy-server", ...PROXY_ROUTING_CHROME_ARGS]);
const CHROME_PROXY_ENV_KEYS = [
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"NO_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
"no_proxy"
];
function chromeArgName(e) {
return e.trim().split("=", 1)[0]?.toLowerCase() ?? "";
}
function hasChromeProxyControlArg(e) {
return e.some((e) => PROXY_CONTROL_CHROME_ARGS.has(chromeArgName(e)));
}
function hasExplicitChromeProxyRoutingArg(e) {
return e.some((e) => PROXY_ROUTING_CHROME_ARGS.has(chromeArgName(e)));
}
/** Remove inherited proxy env so launched Chrome follows only configured args. */
function omitChromeProxyEnv(e) {
const t = { ...e };
for (const e of CHROME_PROXY_ENV_KEYS) delete t[e];
return t;
}
function resolveBrowserNavigationProxyMode(e) {
if (e.profile.driver === "openclaw" && e.profile.cdpIsLoopback && !e.profile.attachOnly && hasExplicitChromeProxyRoutingArg(e.resolved.extraArgs)) return "explicit-browser-proxy";
return "direct";
}
//#endregion
//#region extensions/browser/src/browser/cdp-page-session.ts
const CDP_TARGET_NAVIGATION_RESULT_TIMEOUT_MS = 2e3;
const CDP_TARGET_NAVIGATION_RESULT_POLL_MS = 50;
const CDP_TARGET_NAVIGATION_STABILITY_MS = 250;
function readCommittedFrameUrl(e) {
const t = typeof e?.unreachableUrl === "string" ? e.unreachableUrl.trim() : "";
if (t) return t;
const n = typeof e?.url === "string" ? e.url.trim() : "";
if (n === ":") return;
const r = typeof e?.urlFragment === "string" ? e.urlFragment.trim() : "";
return n ? `${n}${r}` : void 0;
}
/** Read committed document identities together so snapshot facts share one browser observation. */
async function readCdpDocumentIdentities(e) {
const t = (await e("Page.getFrameTree").catch(() => null))?.frameTree;
const n = t?.frame?.loaderId;
const r = { mainFrame: typeof n === "string" && n.trim() ? `cdp:${n.trim()}` : void 0 };
const i = t ? [t] : [];
const a = [];
while (i.length) {
const e = i.pop();
const t = e.frame?.id;
const n = e.frame?.loaderId;
if (typeof t !== "string" || !t.trim() || typeof n !== "string" || !n.trim()) return r;
a.push([t.trim(), n.trim()]);
for (const t of e.childFrames ?? []) i.push(t);
}
if (a.length) {
a.sort(([e], [t]) => e < t ? -1 : e > t ? 1 : 0);
r.frameTree = `cdp-tree:${createHash("sha256").update(JSON.stringify(a)).digest("hex")}`;
}
return r;
}
async function waitForCdpNavigationResult(e, t, n, r) {
const i = performance.now() + CDP_TARGET_NAVIGATION_RESULT_TIMEOUT_MS;
const a = n.trim() === "" || n.trim() === "about:blank";
let o;
while (performance.now() < i) {
r?.throwIfAborted();
const n = await e("Page.getFrameTree", void 0, t).catch(() => null);
r?.throwIfAborted();
const i = n?.frameTree?.frame;
const s = readCommittedFrameUrl(i);
if (a && s === "about:blank") return s;
const c = typeof i?.loaderId === "string" ? i.loaderId.trim() : "";
if (s && s !== "about:blank" && c) {
const e = `${c}\n${s}`;
const t = performance.now();
if (o?.key === e) {
if (t - o.since >= CDP_TARGET_NAVIGATION_STABILITY_MS) return s;
} else o = {
key: e,
since: t
};
} else o = void 0;
await sleepWithAbort(CDP_TARGET_NAVIGATION_RESULT_POLL_MS);
}
}
/** Enable the page domains shared by target preparation and page operations. */
async function prepareCdpPageSession(e, t) {
await Promise.all([
e("Page.enable", void 0, t).catch(() => {}),
e("Runtime.enable", void 0, t).catch(() => {}),
e("Network.enable", void 0, t).catch(() => {}),
e("DOM.enable", void 0, t).catch(() => {}),
e("Accessibility.enable", void 0, t).catch(() => {})
]);
await e("Runtime.runIfWaitingForDebugger", void 0, t).catch(() => {});
}
/** Prepare a created target and optionally observe its committed document URL. */
async function prepareCdpTargetSession(e, t, n, r) {
const i = await e("Target.attachToTarget", {
targetId: t,
flatten: true
}).catch(() => null);
const a = typeof i?.sessionId === "string" ? i.sessionId : void 0;
if (!a) return;
try {
await prepareCdpPageSession(e, a);
return n === void 0 ? void 0 : await waitForCdpNavigationResult(e, a, n, r);
} finally {
await e("Target.detachFromTarget", { sessionId: a }).catch(() => {});
}
}
/** Read the committed document URL from a page-level CDP WebSocket. */
async function waitForCdpCommittedNavigationUrl(e) {
const t = await assertCdpEndpointAllowed(e.wsUrl, e.cdpPolicy, {
source: "discovered",
configuredUrl: e.configuredCdpUrl
});
e.signal?.throwIfAborted();
try {
return await withCdpSocket(e.wsUrl, async (t) => {
e.signal?.throwIfAborted();
await t("Page.enable");
return await waitForCdpNavigationResult(t, void 0, e.requestedUrl, e.signal);
}, {
commandTimeoutMs: e.timeouts?.httpTimeoutMs ?? CDP_TARGET_NAVIGATION_RESULT_TIMEOUT_MS,
handshakeTimeoutMs: e.timeouts?.handshakeTimeoutMs,
handshakeRetries: 0,
lookup: t?.lookup
});
} catch {
e.signal?.throwIfAborted();
return;
}
}
//#endregion
//#region extensions/browser/src/browser/navigation-guard.ts
/**
* Validates page navigation URLs and redirect chains before or after browser
* navigation while accounting for browser proxy routing.
*/
const NETWORK_NAVIGATION_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
const SAFE_NON_NETWORK_URLS = /* @__PURE__ */ new Set(["about:blank"]);
const BROWSER_NAVIGATION_CREDENTIALS_BLOCKED_MESSAGE = "Navigation blocked: URL-embedded credentials are not supported for page navigation. Set HTTP Basic auth with `openclaw browser set credentials <username> <password>` or use an authenticated browser profile.";
function isAllowedNonNetworkNavigationUrl(e) {
return SAFE_NON_NETWORK_URLS.has(e.href);
}
var InvalidBrowserNavigationUrlError = class extends Error {
constructor(e) {
super(e);
this.name = "InvalidBrowserNavigationUrlError";
}
};
/** Parse a page-navigation URL and reject credentials before any transport dispatch. */
function parseBrowserNavigationUrl(e) {
const t = e.trim();
if (!t) throw new InvalidBrowserNavigationUrlError("url is required");
const n = URL.parse(t);
if (!n) {
const e = t.includes("@") ? "[redacted credential-bearing URL]" : t;
throw new InvalidBrowserNavigationUrlError(`Invalid URL: ${e}`);
}
if (n.username || n.password) throw new InvalidBrowserNavigationUrlError(BROWSER_NAVIGATION_CREDENTIALS_BLOCKED_MESSAGE);
return n;
}
/** Build a navigation-policy object while omitting default direct proxy mode. */
function withBrowserNavigationPolicy(e, t) {
return {
...e ? { ssrfPolicy: e } : {},
...t?.standingSsrfPolicy ? { standingSsrfPolicy: t.standingSsrfPolicy } : {},
...t?.assertNavigationCurrent ? { assertNavigationCurrent: t.assertNavigationCurrent } : {},
...t?.browserProxyMode && t.browserProxyMode !== "direct" ? { browserProxyMode: t.browserProxyMode } : {}
};
}
/** Return true when a URL needs redirect inspection under strict policy. */
function requiresInspectableBrowserNavigationRedirectsForUrl(e, t) {
if (t?.dangerouslyAllowPrivateNetwork !== false) return false;
return NETWORK_NAVIGATION_PROTOCOLS.has(URL.parse(e)?.protocol ?? "");
}
function isExplicitlyAllowedBrowserHostname(e, t) {
const n = normalizeHostname(e);
const r = (t?.allowedHostnames ?? []).map((e) => normalizeHostname(e)).filter(Boolean);
return r.length > 0 ? matchesHostnameAllowlist(n, r) : false;
}
/** Assert that a requested browser navigation URL is policy-allowed. */
async function assertBrowserNavigationAllowed(e) {
e.signal?.throwIfAborted();
e.assertNavigationCurrent?.();
const t = parseBrowserNavigationUrl(e.url);
if (!NETWORK_NAVIGATION_PROTOCOLS.has(t.protocol)) {
if (isAllowedNonNetworkNavigationUrl(t)) return;
throw new InvalidBrowserNavigationUrlError(`Navigation blocked: unsupported protocol "${t.protocol}"`);
}
if (e.browserProxyMode === "explicit-browser-proxy" && !isPrivateNetworkAllowedByPolicy(e.ssrfPolicy)) throw new InvalidBrowserNavigationUrlError("Navigation blocked: strict browser SSRF policy cannot be enforced while this browser profile is proxy-routed");
if (e.ssrfPolicy && e.ssrfPolicy.dangerouslyAllowPrivateNetwork === false && !isPrivateNetworkAllowedByPolicy(e.ssrfPolicy) && isIP(normalizeHostname(t.hostname)) === 0 && !isExplicitlyAllowedBrowserHostname(t.hostname, e.ssrfPolicy)) throw new InvalidBrowserNavigationUrlError("Navigation blocked: strict browser SSRF policy requires an IP-literal URL because browser DNS rebinding protections are unavailable for hostname-based navigation");
await resolvePinnedHostnameWithPolicy(t.hostname, {
lookupFn: e.lookupFn,
policy: e.ssrfPolicy,
signal: e.signal
});
e.assertNavigationCurrent?.();
}
/**
* Preflight a Chrome MCP navigation. Chrome MCP dispatches through opaque
* `navigate_page`/`new_page` tool calls, so strict policy cannot fence redirect
* hops before Chrome sends them and refuses network navigation instead.
*/
async function assertChromeMcpNavigationAllowed(e) {
await assertBrowserNavigationAllowed(e);
if (requiresInspectableBrowserNavigationRedirectsForUrl(e.url, e.ssrfPolicy)) throw new InvalidBrowserNavigationUrlError("Navigation blocked: strict browser SSRF policy requires redirect-hop inspection, which existing-session (Chrome MCP) profiles cannot provide; use a profile with driver \"openclaw\" for strict navigation");
}
/**
* Best-effort post-navigation guard for final page URLs.
* Only validates network URLs (http/https) and about:blank to avoid false
* positives on browser-internal error pages (e.g. chrome-error://). In strict
* mode this intentionally re-applies the hostname gate after redirects.
*/
async function assertBrowserNavigationResultAllowed(e) {
e.signal?.throwIfAborted();
const t = e.url.trim();
if (!t) return;
const n = URL.parse(t);
if (!n) return;
if (NETWORK_NAVIGATION_PROTOCOLS.has(n.protocol) || isAllowedNonNetworkNavigationUrl(n)) await assertBrowserNavigationAllowed(e);
}
/** Assert that every URL in a browser redirect chain is policy-allowed. */
async function assertBrowserNavigationRedirectChainAllowed(e) {
e.signal?.throwIfAborted();
const t = [];
let n = e.request ?? null;
while (n) {
t.push(n.url());
n = n.redirectedFrom();
}
for (const n of t.toReversed()) await assertBrowserNavigationAllowed({
url: n,
lookupFn: e.lookupFn,
ssrfPolicy: e.ssrfPolicy,
browserProxyMode: e.browserProxyMode,
assertNavigationCurrent: e.assertNavigationCurrent,
signal: e.signal
});
}
//#endregion
//#region extensions/browser/src/browser/snapshot-depth-limit.ts
const ROLE_SNAPSHOT_DEPTH_TRUNCATION_MARKER = "[...TRUNCATED - accessibility tree too deep]";
function appendRoleSnapshotDepthTruncationMarker(e) {
return e ? `${e}\n\n${ROLE_SNAPSHOT_DEPTH_TRUNCATION_MARKER}` : ROLE_SNAPSHOT_DEPTH_TRUNCATION_MARKER;
}
//#endregion
//#region extensions/browser/src/browser/snapshot-roles.ts
/**
* Shared ARIA role classification sets used by both the Playwright and Chrome MCP
* snapshot paths. Keep these in sync — divergence causes the two drivers to produce
* different snapshot output for the same page.
*/
/** Roles that represent user-interactive elements and always get a ref. */
const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
"button",
"checkbox",
"combobox",
"link",
"listbox",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
"radio",
"searchbox",
"slider",
"spinbutton",
"switch",
"tab",
"textbox",
"treeitem"
]);
/** Roles that carry meaningful content and get a ref when named. */
const CONTENT_ROLES = /* @__PURE__ */ new Set([
"article",
"cell",
"columnheader",
"gridcell",
"heading",
"listitem",
"main",
"navigation",
"region",
"rowheader"
]);
/** Structural/container roles — typically skipped in compact mode. */
const STRUCTURAL_ROLES = /* @__PURE__ */ new Set([
"application",
"directory",
"document",
"generic",
"grid",
"group",
"ignored",
"list",
"menu",
"menubar",
"none",
"presentation",
"row",
"rowgroup",
"table",
"tablist",
"toolbar",
"tree",
"treegrid"
]);
//#endregion
//#region extensions/browser/src/browser/cdp-role-snapshot-tree.ts
function buildRoleTree(e, t) {
const n = /* @__PURE__ */ new Map();
const r = [];
for (const i of e) {
const e = i.nodeId ?? "";
if (!e) continue;
const a = axValue(i.role) || "unknown";
const o = axValue(i.name);
const s = a.toLowerCase();
n.set(e, r.length);
r.push({
raw: i,
role: a,
name: o,
value: axValue(i.value),
backendDOMNodeId: typeof i.backendDOMNodeId === "number" && i.backendDOMNodeId > 0 ? Math.floor(i.backendDOMNodeId) : void 0,
children: [],
...t !== void 0 ? { transparent: i.ignored === true || [
"none",
"presentation",
"fragment"
].includes(s) || s === "generic" && !o } : {}
});
}
for (const [e, t] of r.entries()) for (const i of t.raw.childIds ?? []) {
const a = n.get(i);
if (a === void 0) continue;
t.children.push(a);
r[a].parent = e;
}
const i = [];
if (t !== void 0) {
const e = r.findIndex((e) => e.backendDOMNodeId === t);
if (e < 0) throw new Error("Snapshot root is no longer present in the accessibility tree; retry.");
i.push(e);
} else for (const [e, t] of r.entries()) if (t.parent === void 0) i.push(e);
return {
tree: r,
roots: i.length ? i : r.length ? [0] : []
};
}
function shouldIncludeRoleNode(e, t) {
if (e.transparent) return false;
const n = e.role.toLowerCase();
if (t.interactive) return INTERACTIVE_ROLES.has(n) || n === "iframe" || Boolean(e.cursorInfo);
if (t.compact && STRUCTURAL_ROLES.has(n) && !e.name && !e.ref) return false;
return true;
}
function roleStateSuffix(e) {
const t = new Map((e.properties ?? []).map(({ name: e, value: t }) => [e, t.value]));
return [
"checked",
"disabled",
"expanded",
"pressed",
"selected",
"level",
"invalid"
].flatMap((e) => {
const n = t.get(e);
if (n === true || n === "true") return [` [${e}]`];
if (n === "mixed" || e === "level" && typeof n === "number" || e === "invalid" && typeof n === "string" && n !== "false") return [` [${e}=${n}]`];
return [];
}).join("");
}
function cursorSuffix(e) {
if (!e) return "";
const t = [
e.hasCursorPointer ? "cursor:pointer" : void 0,
e.hasOnClick ? "onclick" : void 0,
e.hasTabIndex ? "tabindex" : void 0,
e.isEditable ? "contenteditable" : void 0,
e.hiddenInputType ? `hidden-${e.hiddenInputType}` : void 0
].filter(Boolean);
return t.length ? ` [${t.join(", ")}]` : "";
}
function renderRoleTree(e, t, n, r, i, a = 0) {
const o = e[t];
if (r.maxDepth !== void 0 && a > r.maxDepth) return;
if (a > 100) {
i.truncated = true;
return;
}
if (shouldIncludeRoleNode(o, r)) {
const e = " ".repeat(i.flattenInteractive && r.interactive ? 0 : a);
const t = o.name ? ` ${JSON.stringify(o.name)}` : "";
const s = o.ref ? ` [ref=${o.ref}]` : "";
const c = o.nth !== void 0 && o.nth > 0 ? ` [nth=${o.nth}]` : "";
const l = o.value ? ` value=${JSON.stringify(o.value)}` : "";
const u = o.url ? ` [url=${o.url}]` : "";
if (i.recordIframePositions && o.ref && o.frameId) o.iframeLineIndex ??= n.length;
n.push(`${e}- ${o.role}${t}${s}${c}${roleStateSuffix(o.raw)}${l}${u}${cursorSuffix(o.cursorInfo)}`);
}
for (const t of o.children) renderRoleTree(e, t, n, r, i, a + (o.transparent ? 0 : 1));
}
//#endregion
//#region extensions/browser/src/browser/pw-role-snapshot.ts
const ROLE_SNAPSHOT_TRUNCATION_MARKER = "[...TRUNCATED - page too large]";
/** Read formatter-owned refs without interpreting names or scalar page content. */
function findRoleSnapshotLineRef(e) {
return parseSnapshotLine(e)?.ref;
}
function getRoleSnapshotIdentityKey(e, t, n) {
return n === "aria" ? e : `${t.role}\0${t.name ?? ""}\0${t.nth ?? 0}`;
}
/** Build the stable identity set used for per-tab snapshot deltas. */
function getRoleSnapshotIdentityKeys(e, t) {
return new Set(Object.entries(e).map(([e, n]) => getRoleSnapshotIdentityKey(e, n, t)));
}
function truncateRoleSnapshot(e, t) {
const n = t >= 31 ? ROLE_SNAPSHOT_TRUNCATION_MARKER : "…";
let r = "";
let i = 0;
for (const a of e) {
const e = r ? `${r}\n${a}` : a;
if (e.length + 2 + n.length > t) break;
r = e;
i += 1;
}
return {
snapshot: r ? `${r}\n\n${n}` : n,
lineCount: i
};
}
/** Apply the final output budget, then keep only refs present on complete output lines. */
function finalizeRoleSnapshot(e) {
const t = typeof e.maxChars === "number" && Number.isFinite(e.maxChars) && e.maxChars > 0 ? Math.floor(e.maxChars) : void 0;
const n = t && t > 0 ? t : void 0;
const r = e.delta;
const i = r?.previousKeys;
const a = e.snapshot.split("\n");
let o;
let s = false;
if (r && i !== void 0) {
o = a.map(findRoleSnapshotLineRef);
const t = /* @__PURE__ */ new Set();
for (const [n, s] of a.entries()) {
const c = o[n];
const l = c && Object.hasOwn(e.refs, c) ? e.refs[c] : void 0;
if (!c || !l) continue;
const u = getRoleSnapshotIdentityKey(c, l, r.mode);
if (i.has(u)) continue;
a[n] = `${s} [new]`;
t.add(u);
}
s = t.size > 0;
if (s) a.push(`${t.size} new element(s) since last snapshot`);
}
const c = s ? a.join("\n") : e.snapshot;
const l = n !== void 0 && c.length > n;
const u = l ? truncateRoleSnapshot(a, n) : void 0;
const d = u?.snapshot ?? c;
const f = l ? d.split("\n") : a;
const p = /* @__PURE__ */ new Set();
const m = u?.lineCount ?? a.length;
for (let e = 0; e < m; e += 1) {
const t = o ? o[e] : findRoleSnapshotLineRef(a[e]);
if (t) p.add(t);
}
const h = [];
const g = i !== void 0 ? /* @__PURE__ */ new Set() : void 0;
let _ = 0;
for (const [t, n] of Object.entries(e.refs)) {
if (!p.has(t)) continue;
h.push([t, n]);
if (INTERACTIVE_ROLES.has(n.role)) _ += 1;
if (g && r && i !== void 0) {
const e = getRoleSnapshotIdentityKey(t, n, r.mode);
if (!i.has(e)) g.add(e);
}
}
const v = Object.fromEntries(h);
const y = g?.size;
const b = {
snapshot: d,
refs: v,
stats: {
lines: d ? f.length : 0,
chars: d.length,
refs: h.length,
interactive: _
},
...y !== void 0 ? { newElements: y } : {}
};
return l ? {
...b,
truncated: true
} : b;
}
function getIndentLevel(e) {
return Math.floor((e.length - e.trimStart().length) / 2);
}
function parseSnapshotLine(e) {
const t = e.match(/^(\s*-\s+)(.*)$/s);
if (!t) return null;
const n = t[1];
const r = t[2];
const i = r.match(/^'((?:[^']|'')*)'(.*)$/s);
const a = (i ? i[1].replaceAll("''", "'") : r).match(/^(\w+)(?:\s+("(?:\\.|[^"\\])*"))?(.*)$/s);
if (!a) return null;
const o = a[1];
let s = a[2];
let c = a[3];
if (s === void 0 && c.startsWith(" /")) {
const e = (i ? c : c.split(/:(?=\s|$)/, 1)[0]).match(/^ (\/(?:.*\/)?)/s);
if (e) {
s = e[1];
c = c.slice(e[0].length);
}
}
const l = (c.match(/^(?:\s+\[[^\][]*\])*/)?.[0])?.match(/\[ref=([^\][]+)\]/)?.[1];
return {
prefix: n,
roleRaw: o,
role: normalizeLowercaseStringOrEmpty(o),
nameToken: s,
ref: l,
suffix: c + (i?.[2] ?? "")
};
}
function decodeSnapshotName(e) {
return e?.startsWith("\"") ? JSON.parse(e) : e;
}
function compactTree(e) {
const t = [];
const n = [];
const finishEntry = () => {
const e = n.pop();
if (!e) return;
e.keep ||= e.hasRef;
const t = n.at(-1);
if (e.hasRef && t) t.hasRef = true;
};
for (const r of e) {
const e = getIndentLevel(r);
while (n.length > 0) {
if (expectDefined(n.at(-1), "non-empty role snapshot stack").indent < e) break;
finishEntry();
}
const i = Boolean(findRoleSnapshotLineRef(r));
const a = {
line: r,
keep: i || r.includes(":") && !r.trimEnd().endsWith(":"),
hasRef: i,
indent: e
};
t.push(a);
n.push(a);
}
while (n.length > 0) finishEntry();
return t.filter((e) => e.keep).map((e) => e.line).join("\n") || "(empty)";
}
function parseRoleRef(e) {
const t = e.trim();
const n = t.startsWith("@") ? t.slice(1) : t.startsWith("ref=") ? t.slice(4) : t;
return /^(?:e\d+|\d{1,9})$/i.test(n) ? n : null;
}
function parseAiSnapshotRef(e) {
return e && /^(?:f\d+)?e\d+$|^\d{1,9}$/i.test(e) ? e : null;
}
/**
* Mask form field values in a Playwright AI snapshot. Playwright prints every input value and
* renders password inputs as plain textboxes, either inline (`- textbox [ref=e1]: value`) or as
* a `- text:` child when the field also has props such as a placeholder. A valued field line
* without a ref is masked because nothing can prove the field safe.
*/
async function redactAiSnapshotFieldValues(e, t) {
const n = e.split("\n");
const r = [];
for (const [e, t] of n.entries()) {
const i = parseSnapshotLine(t);
if (!i || !VALUE_FIELD_ROLES.has(i.role)) continue;
const a = i.suffix.match(/^(?:\s+\[[^\][]*\])*/)?.[0] ?? "";
const o = i.suffix.slice(a.length);
const s = [];
if (/^: \S/.test(o) && t.endsWith(o)) s.push({
index: e,
head: t.slice(0, t.length - o.length + 2)
});
else if (o === ":") {
const r = getIndentLevel(t) + 1;
for (let t = e + 1; t < n.length; t += 1) {
const e = getIndentLevel(n[t]);
if (e < r) break;
const i = n[t].match(/^\s*- text: /);
if (i && e === r) s.push({
index: t,
head: i[0]
});
}
}
if (s.length) r.push({
ref: parseAiSnapshotRef(i.ref),
values: s
});
}
await Promise.all(r.map(async ({ ref: e, values: r }) => {
if (e && !await t(e)) return;
for (const { index: e, head: t } of r) n[e] = `${t}${REDACTED_FIELD_VALUE}`;
}));
return n.join("\n");
}
/**
* Build a role snapshot from Playwright's AI snapshot output while preserving Playwright's own
* aria-ref ids (e.g. ref=e13). This makes the refs self-resolving across calls.
*/
function buildRoleSnapshotFromAiSnapshot(e, t) {
const n = t === void 0 ? {} : t;
const r = e.split("\n");
const i = {};
const a = t === void 0 ? void 0 : [];
for (const e of r) {
const t = getIndentLevel(e);
if (n.maxDepth !== void 0 && t > n.maxDepth) continue;
const r = parseSnapshotLine(e);
if (!r) {
if (!n.interactive) a?.push(e);
continue;
}
const { role: o } = r;
const s = decodeSnapshotName(r.nameToken);
if (n.interactive) {
const e = parseAiSnapshotRef(r.ref);
if (INTERACTIVE_ROLES.has(o) && e) {
i[e] = {
role: o,
...s ? { name: s } : {}
};
let t = `- ${r.roleRaw}`;
if (s) t += ` ${JSON.stringify(s)}`;
t += ` [ref=${e}]`;
t += r.suffix.replace(` [ref=${e}]`, "");
a?.push(t);
}
continue;
}
const c = STRUCTURAL_ROLES.has(o);
if (n.compact && c && !s) continue;
const l = parseAiSnapshotRef(r.ref);
if (l) i[l] = {
role: o,
...s ? { name: s } : {}
};
a?.push(e);
}
return {
snapshot: n.interactive ? a.join("\n") || "(no interactive elements)" : n.compact ? compactTree(a ?? r) : (a ? a.join("\n") : e) || "(empty)",
refs: i
};
}
//#endregion
//#region extensions/browser/src/browser/snapshot-urls.ts
function appendSnapshotUrls(e, t) {
if (t.length === 0) return e;
return `${e}\n\nLinks:\n${t.map((e, t) => `${t + 1}. ${e.text} -> ${e.url}`).join("\n")}`;
}
//#endregion
//#region extensions/browser/src/browser/cdp-role-snapshot.ts
async function findCursorInteractiveElements(e) {
const t = "data-openclaw-cdp-ci";
try {
const n = await e("Runtime.evaluate", {
expression: `(() => {
const out = [];
const roles = new Set(${JSON.stringify([...INTERACTIVE_ROLES])});
const tags = new Set(["a","button","input","select","textarea","details","summary"]);
document.querySelectorAll("[${t}]").forEach((el) => el.removeAttribute("${t}"));
for (const el of document.body ? document.body.querySelectorAll("*") : []) {
if (!(el instanceof HTMLElement) || el.closest("[hidden],[aria-hidden='true']")) continue;
const tagName = el.tagName.toLowerCase();
if (tags.has(tagName)) continue;
const role = String(el.getAttribute("role") || "").toLowerCase();
if (roles.has(role)) continue;
const style = getComputedStyle(el);
const hasCursorPointer = style.cursor === "pointer";
const hasOnClick = el.hasAttribute("onclick") || el.onclick !== null;
const tabIndex = el.getAttribute("tabindex");
const hasTabIndex = tabIndex !== null && tabIndex !== "-1";
const ce = el.getAttribute("contenteditable");
const isEditable = ce === "" || ce === "true";
if (!hasCursorPointer && !hasOnClick && !hasTabIndex && !isEditable) continue;
if (hasCursorPointer && !hasOnClick && !hasTabIndex && !isEditable) {
const parent = el.parentElement;
if (parent && getComputedStyle(parent).cursor === "pointer") continue;
}
const rect = el.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) continue;
let hiddenInputType = "";
const hiddenInput = el.querySelector("input[type='radio'],input[type='checkbox']");
if (hiddenInput instanceof HTMLInputElement) {
const hiddenStyle = getComputedStyle(hiddenInput);
if (hiddenInput.hidden || hiddenStyle.display === "none" || hiddenStyle.visibility === "hidden") {
hiddenInputType = hiddenInput.type;
}
}
el.setAttribute("${t}", String(out.length));
out.push({
text: String(el.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 101),
hasCursorPointer,
hasOnClick,
hasTabIndex,
isEditable,
hiddenInputType,
});
}
return out;
})()`,
returnByValue: true,
awaitPromise: false
}).catch(() => null);
const r = (Array.isArray(n?.result?.value) ? n.result.value : []).map((e) => {
const t = asOptionalRecord(e);
if (typeof t?.text !== "string") return;
return {
text: truncateUtf16Safe(t.text, 100),
hasOnClick: t.hasOnClick === true,
hasCursorPointer: t.hasCursorPointer === true,
hasTabIndex: t.hasTabIndex === true,
isEditable: t.isEditable === true,
hiddenInputType: typeof t.hiddenInputType === "string" ? t.hiddenInputType : void 0
};
});
if (!r.some((e) => e !== void 0)) return /* @__PURE__ */ new Map();
const i = (await e("DOM.getDocument", { depth: 0 }).catch(() => null))?.root?.nodeId;
if (typeof i !== "number") return /* @__PURE__ */ new Map();
const a = await e("DOM.querySelectorAll", {
nodeId: i,
selector: `[${t}]`
}).catch(() => null);
const o = /* @__PURE__ */ new Map();
await Promise.all((a?.nodeIds ?? []).map(async (n) => {
const i = await e("DOM.describeNode", { nodeId: n }).catch(() => null);
const a = i?.node?.attributes ?? [];
const s = a.indexOf(t);
const c = s >= 0 ? a[s + 1] : void 0;
const l = typeof c === "string" ? Number(c) : NaN;
const u = i?.node?.backendNodeId;
if (typeof u === "number" && Number.isInteger(l) && r[l]) o.set(u, r[l]);
}));
return o;
} finally {
await e("Runtime.evaluate", {
expression: `document.querySelectorAll("[${t}]").forEach((el) => el.removeAttribute("${t}"))`,
returnByValue: true
}).catch(() => {});
}
}
async function resolveLinkUrls(e, t) {
const n = /* @__PURE__ */ new Map();
const r = Object.values(t).filter((e) => e.role === "link" && Boolean(e.backendDOMNodeId));
await Promise.all(r.map(async (t) => {
const r = (await e("DOM.resolveNode", { backendNodeId: t.backendDOMNodeId }).catch(() => null))?.object?.objectId;
if (!r) return;
const i = await e("Runtime.callFunctionOn", {
objectId: r,
functionDeclaration: "function() { return this.href || ''; }",
returnByValue: true
}).catch(() => null);
const a = typeof i?.result?.value === "string" ? i.result.value : "";
if (a) n.set(t.backendDOMNodeId, a);
}));
return n;
}
async function resolveIframeFrameIds(e, t) {
const n = /* @__PURE__ */ new Map();
const r = t.filter((e) => e.role.toLowerCase() === "iframe" && Boolean(e.backendDOMNodeId));
await Promise.all(r.map(async (t) => {
const r = await e("DOM.describeNode", {
backendNodeId: t.backendDOMNodeId,
depth: 1
}).catch(() => null);
const i = r?.node?.contentDocument?.frameId ?? r?.node?.frameId ?? "";
if (i) n.set(t.backendDOMNodeId, i);
}));
return n;
}
async function readScopedAXNodes(e, t) {
const n = await e("Accessibility.queryAXTree", { backendNodeId: t });
if (n.nodes.some((e) => e.backendDOMNodeId === t)) return n.nodes;
const r = await e("Accessibility.getPartialAXTree", {
backendNodeId: t,
fetchRelatives: true
});
const i = r.nodes.find((e) => e.backendDOMNodeId === t);
if (!i?.ignored || !i.nodeId) throw new Error("Snapshot root is no longer present in the accessibility tree; retry.");
if (!i.childIds?.length) return [i];
const a = r.nodes.find((e) => e.frameId)?.frameId;
if (!a) throw new Error("Snapshot frame identity is unavailable; retry.");
const o = await e("Accessibility.getFullAXTree", { frameId: a });
const s = new Map(o.nodes.map((e) => [e.nodeId, e]));
const c = [i];
const l = /* @__PURE__ */ new Set([i.nodeId]);
for (const e of c) for (const t of e.childIds ?? []) {
const e = s.get(t);
if (e && !l.has(t)) {
l.add(t);
c.push(e);
}
}
return c;
}
async function buildCdpRoleSnapshot(e) {
const t = e.rootBackendNodeId !== void 0 ? { nodes: await readScopedAXNodes(e.send, e.rootBackendNodeId) } : await e.send("Accessibility.getFullAXTree", e.frameId ? { frameId: e.frameId } : void 0);
const n = Array.isArray(t.nodes) ? t.nodes : [];
await redactSensitiveAXNodeValues(e.send, n);
const { tree: r, roots: i } = buildRoleTree(n, e.rootBackendNodeId);
const a = e.rootBackendNodeId !== void 0 ? /* @__PURE__ */ new Map() : await findCursorInteractiveElements(e.send);
for (const e of r) {
const t = e.backendDOMNodeId ? a.get(e.backendDOMNodeId) : void 0;
if (t !== void 0) {
e.cursorInfo = t;
if (!e.name && t.text) e.name = t.text;
}
}
const o = /* @__PURE__ */ new Map();
const s = {};
for (const t of r) {
const n = t.role.toLowerCase();
if (!(INTERACTIVE_ROLES.has(n) || CONTENT_ROLES.has(n) && Boolean(t.name) || n === "iframe" || Boolean(t.cursorInfo)) || t.transparent) continue;
const r = `${n}:${t.name}`;
const i = o.get(r) ?? 0;
o.set(r, i + 1);
const a = `e${e.nextRef.value}`;
e.nextRef.value += 1;
t.ref = a;
t.nth = i;
s[a] = {
role: n,
...t.name ? { name: t.name } : {},
nth: i,
...t.backendDOMNodeId ? { backendDOMNodeId: t.backendDOMNodeId } : {},
...e.frameId ? { frameId: e.frameId } : {}
};
}
for (const e of r) if (e.ref && o.get(`${e.role.toLowerCase()}:${e.name}`) === 1) delete s[e.ref]?.nth;
const c = await resolveIframeFrameIds(e.send, r);
for (const e of r) {
const t = e.backendDOMNodeId ? c.get(e.backendDOMNodeId) : void 0;
if (t !== void 0) {
e.frameId = t;
const n = e.ref ? s[e.ref] : void 0;
if (n) n.frameId = e.frameId;
}
}
if (e.urls) {
const t = await resolveLinkUrls(e.send, s);
for (const e of r) {
const n = e.backendDOMNodeId ? t.get(e.backendDOMNodeId) : void 0;
if (n !== void 0) e.url = n;
}
}
let l = [];
const u = {
truncated: false,
recordIframePositions: e.recurseIframes,
flattenInteractive: e.rootBackendNodeId !== void 0
};
for (const t of i) renderRoleTree(r, t, l, e.options, u);
if (e.recurseIframes) {
const t = /* @__PURE__ */ new Map();
for (const n of r) {
if (n.iframeLineIndex === void 0 || !n.frameId) continue;
const r = await buildCdpRoleSnapshot({
...e,
frameId: n.frameId,
recurseIframes: false
}).catch(() => null);
if (!r) continue;
u.truncated ||= r.truncated;
if (!r.lines.length) continue;
Object.assign(s, r.refs);
t.set(n.iframeLineIndex, r.lines);
}
l = l.flatMap((e, n) => [e, ...(t.get(n) ?? []).map((e) => ` ${e}`)]);
}
return {
lines: l,
refs: s,
truncated: u.truncated
};
}
/** Capture and format refs with their backend identities on the caller-owned CDP session. */
async function snapshotRoleViaCdpSession(e) {
await prepareCdpPageSession(e.send);
const t = await buildCdpRoleSnapshot({
send: e.send,
rootBackendNodeId: e.rootBackendNodeId,
options: e.options ?? {},
urls: e.urls,
recurseIframes: e.recurseIframes ?? true,
nextRef: { value: 1 }
});
const n = t.lines.join("\n").trim() || (e.options?.interactive ? "(no interactive elements)" : e.rootBackendNodeId !== void 0 ? "(empty)" : "(empty page)");
const r = finalizeRoleSnapshot({
snapshot: appendSnapshotUrls(t.truncated ? appendRoleSnapshotDepthTruncationMarker(n) : n, e.urlEntries ?? []),
refs: t.refs,
maxChars: e.maxChars,
delta: e.delta
});
return t.truncated && !r.truncated ? {
...r,
truncated: true
} : r;
}
async function snapshotRoleViaCdp(e) {
return await withCdpSocket(e.wsUrl, async (t) => await snapshotRoleViaCdpSession({
...e,
send: t
}), {
commandTimeoutMs: e.timeoutMs ?? 5e3,
lookup: e.lookup
});
}
//#endregion
//#region extensions/browser/src/browser/cdp.ts
/** Read committed document identities from a page-level CDP target. */
async function getDocumentIdentitiesViaCdp(e) {
return await withCdpSocket(e.wsUrl, async (e) => await readCdpDocumentIdentities(e), {
commandTimeoutMs: e.timeoutMs ?? 5e3,
...e.lookup ? { lookup: e.lookup } : {}
});
}
async function captureScreenshot(e) {
return await withCdpSocket(e.wsUrl, async (t) => {
await t("Page.enable");
if (e.headless !== false) await t("Page.bringToFront").catch(() => {});
const n = e.format ?? "png";
const r = n === "jpeg" ? Math.max(0, Math.min(100, Math.round(e.quality ?? 85))) : void 0;
const i = (await t("Page.captureScreenshot", {
format: n,
...r !== void 0 ? { quality: r } : {},
...e.fullPage ? { captureBeyondViewport: true } : {}
}))?.data;
if (!i) throw new Error("Screenshot failed: missing data");
return Buffer.from(i, "base64");
}, {
commandTimeoutMs: e.timeoutMs,
lookup: e.lookup
});
}
/** Create a new browser target after applying navigation and CDP SSRF policy. */
async function createTargetViaCdp(e) {
e.signal?.throwIfAborted();
await assertBrowserNavigationAllowed({
url: e.url,
...withBrowserNavigationPolicy(e.ssrfPolicy)
});
const t = await assertCdpEndpointAllowed(e.cdpUrl, e.ssrfPolicy);
const n = scopeCdpPolicyToConfiguredEndpoint(e.cdpUrl, e.ssrfPolicy);
const r = await resolveCdpWebSocketDiscovery(e.cdpUrl, async (t) => {
let r = null;
try {
r = await fetchJson(appendCdpPath(t, "/json/version"), e.timeouts?.httpTimeoutMs, { signal: e.signal }, n);
} catch (t) {
if (!isWebSocketUrl(e.cdpUrl)) throw t;
}
return r?.webSocketDebuggerUrl?.trim();
});
if (!r) throw new Error("CDP /json/version missing webSocketDebuggerUrl");
const i = r.url;
const a = isWebSocketUrl(e.cdpUrl) && i !== e.cdpUrl ? [i, e.cdpUrl] : [i];
let o;
for (const r of a) try {
const i = r === e.cdpUrl ? t : await assertCdpEndpointAllowed(r, n, {
source: "discovered",
configuredUrl: e.cdpUrl
});
e.signal?.throwIfAborted();
return await withCdpSocket(r, async (t) => {
e.signal?.throwIfAborted();
const n = (await t("Target.createTarget", {
url: e.url,
background: true
}))?.targetId?.trim() ?? "";
if (!n) throw new Error("CDP Target.createTarget returned no targetId");
try {
e.signal?.throwIfAborted();
const r = await prepareCdpTargetSession(t, n, e.waitForNavigationResult ? e.url : void 0, e.signal);
e.signal?.throwIfAborted();
return r ? {
targetId: n,
finalUrl: r
} : { targetId: n };
} catch (e) {
await t("Target.closeTarget", { targetId: n }).catch(() => {});
throw e;
}
}, {
commandTimeoutMs: e.timeouts?.httpTimeoutMs ?? 5e3,
handshakeTimeoutMs: e.timeouts?.handshakeTimeoutMs,
lookup: i?.lookup
});
} catch (t) {
e.signal?.throwIfAborted();
o = t;
}
if (o instanceof Error) throw o;
throw new Error("CDP Target.createTarget failed");
}
const AX_REF_PREFIX = "ax";
const AX_REF_PATTERN = new RegExp(`^${AX_REF_PREFIX}\\d+$`);
function formatAriaSnapshot(e, t) {
const n = /* @__PURE__ */ new Map();
for (const t of e) if (t.nodeId) n.set(t.nodeId, t);
const r = /* @__PURE__ */ new Set();
for (const t of e) for (const e of t.childIds ?? []) r.add(e);
const i = e.find((e) => e.nodeId && !r.has(e.nodeId)) ?? e[0];
if (!i?.nodeId) return [];
const a = [];
const o = [{
node: n.get(i.nodeId),
depth: 0
}];
while (o.length && a.length < t) {
const { node: e, depth: t } = o.pop();
const r = axValue(e.role);
const i = axValue(e.name);
const s = axValue(e.value);
const c = axValue(e.description);
const l = `${AX_REF_PREFIX}${a.length + 1}`;
a.push({
ref: l,
role: r || "unknown",
name: i || "",
...s ? { value: s } : {},
...c ? { description: c } : {},
...typeof e.backendDOMNodeId === "number" ? { backendDOMNodeId: e.backendDOMNodeId } : {},
depth: t
});
const u = e.childIds ?? [];
for (let e = u.length - 1; e >= 0; e--) {
const r = u[e];
const i = r ? n.get(r) : void 0;
if (i) o.push({
node: i,
depth: t + 1
});
}
}
return a;
}
async function snapshotAria(e) {
const t = resolveIntegerOption(e.limit, 500, {
min: 1,
max: 2e3
});
return await withCdpSocket(e.wsUrl, async (e) => {
await prepareCdpPageSession(e);
const n = await e("Accessibility.getFullAXTree");
const r = Array.isArray(n?.nodes) ? n.nodes : [];
await redactSensitiveAXNodeValues(e, r);
return { nodes: formatAriaSnapshot(r, t) };
}, {
commandTimeoutMs: e.timeoutMs ?? 5e3,
lookup: e.lookup
});
}
//#endregion
//#region extensions/browser/src/browser/chrome.diagnostics.ts
function elapsedSince(e) {
return Math.max(0, Date.now() - e);
}
/** Convert an error and optional cause to redacted diagnostic text. */
function safeChromeCdpErrorMessage(e) {
const t = e instanceof Error ? e.message : String(e);
const n = e instanceof Error ? e.cause : void 0;
const r = n instanceof Error ? n.message : typeof n === "string" ? n : void 0;
if (t && r && !t.includes(r)) return redactSensitiveText(`${t}: ${r}`);
return redactSensitiveText(t || "unknown error");
}
function isConnectionRefused(e) {
return collectErrorGraphCandidates(e, ({ cause: e, errors: t }) => [e, ...Array.isArray(t) ? t : []]).some((e) => extractErrorCode(e) === "ECONNREFUSED");
}
async function readChromeVersion(e, t = 500, n, r = "/json/version", i) {
i?.throwIfAborted();
const a = appendCdpPath(e, r);
const { response: o, release: s } = await fetchCdpChecked(a, t, { signal: i }, n);
try {
const e = await readProviderJsonResponse(o, "cdp-version");
i?.throwIfAborted();
if (!e || typeof e !== "object") throw new Error("CDP /json/version returned non-object JSON");
return e;
} finally {
await s();
}
}
/** Preserve providers that expose only Playwright's trailing-slash route. */
async function readChromeVersionWithCredentialFallback(e, t = 500, n, r) {
let i;
let a;
try {
i = await readChromeVersion(e, t, n, void 0, r);
r?.throwIfAborted();
if (normalizeOptionalString(i.webSocketDebuggerUrl)) return i;
} catch (e) {
r?.throwIfAborted();
a = e;
}
try {
return await readChromeVersion(e, t, n, "/json/version/", r);
} catch {
r?.throwIfAborted();
if (i) return i;
throw a;
}
}
function readObjectString(e, t) {
if (!e || typeof e !== "object") return;
return normalizeOptionalString(e[t]);
}
function chromeVersionFromCdpResult(e) {
const t = readObjectString(e, "Browser") ?? readObjectString(e, "product");
return t ? { Browser: t } : void 0;
}
async function diagnoseCdpHealthCommand(e, t = 800, n, r) {
r?.throwIfAborted();
const i = normalizeBrowserTimerDelayMs(t);
const a = normalizeBrowserTimerDelayMs(i + Math.min(25, i));
const o = new AbortController();
const s = setTimeout(() => o.abort(/* @__PURE__ */ new Error(`WebSocket handshake did not complete within ${i}ms`)), a);
let c = false;
try {
const t = await withCdpSocket(e, async (e) => {
c = true;
clearTimeout(s);
return await e("Browser.getVersion");
}, {
handshakeTimeoutMs: i,
commandTimeoutMs: a,
handshakeRetries: 0,
lookup: n,
signal: r ? AbortSignal.any([r, o.signal]) : o.signal,
abortScope: "operation"
});
return t && typeof t === "object" ? {
ok: true,
version: chromeVersionFromCdpResult(t)
} : {
ok: false,
code: "websocket_health_command_failed",
message: "Browser.getVersion returned no result object"
};
} catch (e) {
r?.throwIfAborted();
const t = e instanceof CdpSocketError ? e.kind : void 0;
return {
ok: false,
code: !c ? "websocket_handshake_failed" : t === "timeout" ? "websocket_health_command_timeout" : "websocket_health_command_failed",
message: t === "timeout" ? `Browser.getVersion did not respond within ${i}ms` : t === "closed" ? c ? "WebSocket closed before Browser.getVersion completed" : "WebSocket closed before handshake completed" : t === "protocol" ? "Browser.getVersion returned no result object" : safeChromeCdpErrorMessage(e),
error: e
};
} finally {
clearTimeout(s);
}
}
function classifyChromeVersionError(e) {
const t = safeChromeCdpErrorMessage(e);
if (e instanceof BrowserCdpEndpointBlockedError) return {
code: "ssrf_blocked",
message: t
};
if (/^HTTP \d+/.test(t)) return {
code: "http_status_failed",
message: t
};
if (e instanceof SyntaxError || t.includes("cdp-version: malformed JSON response") || t.includes("non-object JSON")) return {
code: "invalid_json",
message: t
};
return {
code: "http_unreachable",
message: t
};
}
function formatChromeCdpDiagnostic(e) {
const t = redactCdpUrl(e.cdpUrl) ?? e.cdpUrl;
const n = redactCdpUrl(e.wsUrl) ?? e.wsUrl;
if (e.ok) {
const r = e.browser ? ` browser=${e.browser}` : "";
return `CDP diagnostic: ready after ${e.elapsedMs}ms; cdp=${t}; websocket=${n}.${r}`;
}
const r = n ? `; websocket=${n}` : "";
const i = e.code === "http_unreachable" && /empty reply|other side closed|socket closed|connection reset|econnreset|terminated before response/i.test(e.message) ? WSL_EMPTY_REPLY_PORTPROXY_HINT : "";
return `CDP diagnostic: ${e.code} after ${e.elapsedMs}ms; cdp=${t}${r}; ${e.message}.${i}`;
}
const WSL_EMPTY_REPLY_PORTPROXY_HINT = " In WSL2-to-Windows Chrome setups, an empty CDP reply can mean netsh is forwarding to the wrong loopback address. On Windows, inspect `netstat -ano | findstr :9222` and `netsh interface portproxy show all`, then curl both 127.0.0.1 and [::1]. Chromium prefers 127.0.0.1 and falls back to [::1] only when the IPv4 bind fails. If svchost/iphlpsvc owns 127.0.0.1:9222, remove the 127.0.0.1:9222 -> 127.0.0.1:9222 self-loop; if chrome.exe listens only on [::1], use v4tov6 with connectaddress=::1 for the WSL2-reachable listener.";
async function diagnoseChromeCdp(e, t = 500, n = 800, r, i) {
i?.throwIfAborted();
const a = Date.now();
const failure = (t, n, r, i) => ({
ok: false,
cdpUrl: e,
wsUrl: r,
code: t,
message: redactSensitiveText(n),
elapsedMs: elapsedSince(a),
...isConnectionRefused(i) ? { connectionRefused: true } : {}
});
const diagnoseEndpoint = async (t, r, o) => {
const s = await diagnoseCdpHealthCommand(t, n, r, i);
i?.throwIfAborted();
return s.ok ? {
ok: true,
cdpUrl: e,
wsUrl: t,
browser: o?.Browser ?? s.version?.Browser,
elapsedMs: elapsedSince(a)
} : failure(s.code, s.message, t, s.error);
};
let o;
try {
o = await assertCdpEndpointAllowed(e, r);
} catch (e) {
i?.throwIfAborted();
return failure("ssrf_blocked", safeChromeCdpErrorMessage(e));
}
i?.throwIfAborted();
const s = scopeCdpPolicyToConfiguredEndpoint(e, r);
const c = isWebSocketUrl(e);
if (isDirectCdpWebSocketEndpoint(e)) return await diagnoseEndpoint(e, o?.lookup);
const l = c ? normalizeCdpHttpBaseForJsonEndpoints(e) : e;
let u;
try {
u = await readChromeVersionWithCredentialFallback(l, t, s, i);
} catch (t) {
i?.throwIfAborted();
if (c) return await diagnoseEndpoint(e, o?.lookup);
const n = classifyChromeVersionError(t);
return failure(n.code, n.message, void 0, t);
}
i?.throwIfAborted();
const d = normalizeOptionalString(u.webSocketDebuggerUrl) ?? "";
if (!d) {
if (c) return await diagnoseEndpoint(e, o?.lookup, u);
return failure("missing_websocket_debugger_url", "CDP /json/version did not include webSocketDebuggerUrl");
}
let f;
try {
f = normalizeCdpWsUrl(d, l);
} catch (e) {
return failure("websocket_handshake_failed", safeChromeCdpErrorMessage(e));
}
let p;
try {
p = await assertCdpEndpointAllowed(f, s, {
source: "discovered",
configuredUrl: e
});
} catch (e) {
i?.throwIfAborted();
return failure("websocket_ssrf_blocked", safeChromeCdpErrorMessage(e), f);
}
const m = await diagnoseEndpoint(f, p?.lookup, u);
if (!m.ok && c && f !== e) {
const t = await diagnoseEndpoint(e, o?.lookup, u);
if (t.ok) return t;
}
return m;
}
//#endregion
//#region extensions/browser/src/browser/chrome.launch-env.ts
function buildChromeLaunchEnv() {
const e = omitChromeProxyEnv(process.env);
e.HOME = os.homedir();
stripGatewayAllocatorEnv(e);
if (process.platform === "linux") {
if (Buffer.byteLength(e.TMPDIR ?? "") > 50) e.TMPDIR = "/tmp";
const t = path.join(resolvePreferredOpenClawTmpDir(), ".chromium");
e.XDG_CONFIG_HOME ??= t;
e.XDG_CACHE_HOME ??= t;
}
return e;
}
//#endregion
//#region extensions/browser/src/browser/chrome.launch-stderr.ts
const CHROME_SINGLETON_IN_USE_PATTERN = /profile appears to be in use by another chromium process/i;
const CHROME_MISSING_DISPLAY_PATTERN = /missing x server|\$DISPLAY/i;
const CHROME_LAUNCH_STDERR_TAIL_MAX_BYTES = 65536;
function createChromeLaunchStderrDiagnostics() {
const e = createBoundedUtf8Tail(CHROME_LAUNCH_STDERR_TAIL_MAX_BYTES);
const t = {
singletonInUse: false,
missingDisplay: false
};
let n = "";
return {
append: (r) => {
e.append(r);
const i = Buffer.isBuffer(r) ? r.toString("utf8") : r;
if (i.length > 0) {
const e = `${n}${i}`;
t.singletonInUse ||= CHROME_SINGLETON_IN_USE_PATTERN.test(e);
t.missingDisplay ||= CHROME_MISSING_DISPLAY_PATTERN.test(e);
n = e.slice(-256);
}
},
hint() {
const t = e.text().trim();
const n = t.match(/^.*\bFATAL:.*$/gmu)?.join("\n");
const r = n ? sliceUtf16Safe(n, 0, CHROME_STDERR_HINT_MAX_CHARS) : sliceUtf16Safe(t, -CHROME_STDERR_HINT_MAX_CHARS);
return r ? `\nChrome stderr:\n${r}` : "";
},
signals() {
return { ...t };
},
clear() {
e.clear();
t.singletonInUse = false;
t.missingDisplay = false;
n = "";
}
};
}
//#endregion
//#region extensions/browser/src/browser/chrome.process-ownership.ts
/** Live process, listener, and exact-profile ownership proof for managed Chromium. */
const TCP_LISTEN_STATE_HEX = "0A";
function readLinuxProcessArgv(e) {
let t;
try {
t = fs.readFileSync(`/proc/${e}/cmdline`);
} catch {
return null;
}
const n = t.toString("utf8").split("\0").filter((e) => e.length > 0);
return n.length > 0 ? n : null;
}
function readPsCommandLine(e) {
try {
return normalizeOptionalString(execFileSync("ps", [
"-ww",
"-p",
String(e),
"-o",
"command="
], {
encoding: "utf8",
timeout: 1e3,
maxBuffer: 65536
})) ?? null;
} catch {
return null;
}
}
function readManagedProcessCommandLine(e) {
if (process.platform !== "linux" && process.platform !== "darwin") return null;
const t = getFileLockProcessStartTime(e);
if (t === null) return null;
const n = process.platform === "linux" ? readLinuxProcessArgv(e) : null;
const r = process.platform === "linux" ? n?.join(" ") : readPsCommandLine(e);
return r ? {
argv: n,
text: r,
startTime: t
} : null;
}
function processCommandFlagValues(e, t) {
const n = `--${t}=`;
if (e.argv) return e.argv.filter((e) => e.startsWith(n)).map((e) => e.slice(n.length));
return [...e.text.matchAll(new RegExp(`(?:^|\\s)${n}(.*?)(?=\\s--|$)`, "g"))].flatMap((e) => e[1] === void 0 ? [] : [e[1]]);
}
function processCommandHasFlag(e, t, n) {
const r = processCommandFlagValues(e, t);
return r.length === 1 && r[0] === n;
}
function parseLinuxTcpListenInodesForPort(e, t) {
const n = t.toString(16).toUpperCase().padStart(4, "0");
const r = /* @__PURE__ */ new Set();
for (const t of e.split(/\r?\n/).slice(1)) {
const e = t.trim().split(/\s+/);
const i = e[1] ?? "";
const a = e[3] ?? "";
const o = e[9] ?? "";
if (i.split(":").at(-1)?.toUpperCase() === n && a === TCP_LISTEN_STATE_HEX && o) r.add(o);
}
return r;
}
function readLinuxTcpListenInodesForPort(e) {
const t = /* @__PURE__ */ new Set();
for (const n of ["/proc/net/tcp", "/proc/net/tcp6"]) try {
for (const r of parseLinuxTcpListenInodesForPort(fs.readFileSync(n, "utf8"), e)) t.add(r);
} catch {}
return t;
}
function linuxPidOwnsAnySocketInode(e, t) {
if (t.size === 0) return false;
let n;
try {
n = fs.readdirSync(`/proc/${e}/fd`);
} catch {
return false;
}
for (const r of n) {
let n;
try {
n = fs.readlinkSync(`/proc/${e}/fd/${r}`);
} catch {
continue;
}
const i = /^socket:\[(?<inode>\d+)\]$/.exec(n);
if (i?.groups?.inode && t.has(i.groups.inode)) return true;
}
return false;
}
function linuxPidListensOnPort(e, t) {
return linuxPidOwnsAnySocketInode(e, readLinuxTcpListenInodesForPort(t));
}
function lsofShowsPidListeningOnPort(e, t) {
try {
return execFileSync("lsof", [
"-nP",
"-a",
"-p",
String(e),
`-iTCP:${t}`,
"-sTCP:LISTEN",
"-Fp"
], {
encoding: "utf8",
timeout: 1e3,
maxBuffer: 65536
}).split(/\r?\n/).some((t) => t === `p${e}`);
} catch {
return false;
}
}
function pidListensOnPort(e, t) {
if (process.platform === "linux") return linuxPidListensOnPort(e, t);
if (process.platform === "darwin") return lsofShowsPidListeningOnPort(e, t);
return false;
}
function readPortListenerPids(e) {
try {
if (process.platform === "linux") {
const t = readLinuxTcpListenInodesForPort(e);
if (t.size === 0) return [];
return fs.readdirSync("/proc").filter((e) => /^\d+$/.test(e)).map(Number).filter((e) => linuxPidOwnsAnySocketInode(e, t));
}
if (process.platform === "darwin") {
const t = execFileSync("lsof", [
"-nP",
`-iTCP:${e}`,
"-sTCP:LISTEN",
"-Fp"
], {
encoding: "utf8",
timeout: 1e3,
maxBuffer: 65536
});
return [...new Set([...t.matchAll(/^p(\d+)$/gm)].map((e) => Number(e[1])))];
}
} catch {}
return [];
}
function isHeadlessShellExecutable(e) {
return /(?:^|[\\/])(?:chrome-headless-shell|headless_shell)(?:\.exe)?$/i.test(e);
}
function headlessShellExecutable(e) {
const t = e.argv?.[0] ?? e.text.split(/\s--/, 1)[0] ?? "";
return isHeadlessShellExecutable(t) ? t : null;
}
function readHeadlessShellProfilePids(e) {
const t = [];
const addProfileOwner = (n, r) => {
if (headlessShellExecutable(r) && processCommandFlagValues(r, "user-data-dir").includes(e) && isPidAlive(n)) t.push(n);
};
try {
if (process.platform === "linux") for (const e of fs.readdirSync("/proc")) {
if (!/^\d+$/.test(e)) continue;
const t = Number(e);
const n = readLinuxProcessArgv(t);
if (n) addProfileOwner(t, {
argv: n,
text: n.join(" ")
});
}
else if (process.platform === "darwin") {
const e = execFileSync("ps", [
"-axww",
"-o",
"pid=,command="
], {
encoding: "utf8",
timeout: 1e3,
maxBuffer: 4194304
});
for (const t of e.split(/\r?\n/)) {
const e = /^\s*(\d+)\s+(.+)$/.exec(t);
if (e?.[1] && e[2] !== void 0) addProfileOwner(Number(e[1]), {
argv: null,
text: e[2]
});
}
}
} catch {
return null;
}
return t;
}
function headlessShellProfileInUseReason(e) {
const t = readHeadlessShellProfilePids(e);
if (t === null) return "Headless shell profile ownership could not be verified";
return t.length > 0 ? "A headless shell process still uses the profile data" : void 0;
}
function sameManagedChromeIdentity(e, t) {
return e.pid === t.pid && e.commandLine === t.commandLine && e.startTime === t.startTime;
}
function readOwnedManagedChromeIdentity(e) {
if (!isPidAlive(e.pid) || !pidListensOnPort(e.pid, e.profile.cdpPort)) return null;
const t = readManagedProcessCommandLine(e.pid);
if (!t || e.headlessShellOnly && !headlessShellExecutable(t) || !(isChromeExecutableFamilyMatch(t.text, e.exe) && processCommandHasFlag(t, "remote-debugging-port", String(e.profile.cdpPort)) && processCommandHasFlag(t, "user-data-dir", e.userDataDir))) return null;
return {
pid: e.pid,
startTime: t.startTime,
commandLine: t.text
};
}
/** A live shell remains owned even when launch discovery changes or its cache is removed. */
function readOwnedManagedHeadlessShell(e) {
const t = readManagedProcessCommandLine(e.pid);
const n = t && headlessShellExecutable(t);
if (!n) return null;
const r = {
kind: "chromium",
path: n
};
const i = readOwnedManagedChromeIdentity({
...e,
exe: r,
headlessShellOnly: true
});
return i ? {
exe: r,
identity: i
} : null;
}
//#endregion
//#region extensions/browser/src/browser/chrome.profile-decoration.ts
const CHROME_NETWORK_PREDICTION_DISABLED = 2;
function safeReadJson(e) {
return asNullableRecord(loadJsonFile(e));
}
function readNestedRecord(e, ...t) {
let n = e;
for (const e of t) n = asNullableRecord(n)?.[e];
return asNullableRecord(n);
}
function ensureNestedRecord(e, ...t) {
return t.reduce((e, t) => e[t] = asNonArrayRecord(e[t]), e);
}
function parseHexRgbToSignedArgbInt(e) {
const t = e.trim().replace(/^#/, "");
if (!/^[0-9a-fA-F]{6}$/.test(t)) return null;
return 255 << 24 | Number.parseInt(t, 16);
}
/** Return whether this profile was initialized with Chromium's automation keychain. */
function usesOpenClawMockKeychain(e) {
return readNestedRecord(safeReadJson(path.join(e, "Local State")), "profile", "info_cache", "Default")?.openclaw_mock_keychain === true;
}
/**
* Prepare managed preferences before launch, preserving unrelated Chrome state.
*/
async function prepareOpenClawProfile(e, t) {
const n = t?.name ?? "openclaw";
const r = (t?.color ?? "#FF4500").toUpperCase();
const i = parseHexRgbToSignedArgbInt(r);
const a = path.join(e, "Local State");
const o = path.join(e, "Default", "Preferences");
const s = safeReadJson(o) ?? {};
ensureNestedRecord(s, "net").network_prediction_options = CHROME_NETWORK_PREDICTION_DISABLED;
s.exit_type = "Normal";
s.exited_cleanly = true;
Object.assign(ensureNestedRecord(s, "profile"), {
name: n,
profile_color: r,
user_color: r
});
if (i != null) {
ensureNestedRecord(s, "autogenerated", "theme").color = i;
ensureNestedRecord(s, "browser", "theme").user_color2 = i;
}
if (t?.downloadDir) {
Object.assign(ensureNestedRecord(s, "download"), {
default_directory: t.downloadDir,
prompt_for_download: false,
directory_upgrade: true
});
ensureNestedRecord(s, "savefile").default_directory = t.downloadDir;
}
await writeJsonFileAtomically(o, s);
const c = safeReadJson(a) ?? {};
const l = ensureNestedRecord(c, "profile", "info_cache", "Default");
Object.assign(l, {
name: n,
shortcut_name: n,
user_name: n
});
if (t?.mockKeychain) l.openclaw_mock_keychain = true;
Object.assign(l, {
profile_color: r,
user_color: r
});
if (i != null) Object.assign(l, {
profile_color_seed: i,
profile_highlight_color: i,
default_avatar_fill_color: i,
default_avatar_stroke_color: i
});
await writeJsonFileAtomically(a, c);
}
//#endregion
//#region extensions/browser/src/browser/chrome.profile-lifecycle-lock.ts
/** Serialize profile writers across Browser runtimes and Gateway processes. */
const operationOwners = new AsyncLocalStorage();
async function withChromeProfileLifecycleLock(e, t) {
const n = path.join(CONFIG_DIR, "browser", `${e}.lifecycle`);
const r = operationOwners.getStore();
const i = r?.get(n) ?? randomUUID();
const a = new Map(r);
a.set(n, i);
return await withFileLock(n, {
retries: {
retries: 600,
factor: 1,
minTimeout: 100,
maxTimeout: 100
},
stale: 6e4,
staleRecovery: "remove-if-definitely-stale",
reentrantOwner: i
}, async () => await operationOwners.run(a, t));
}
//#endregion
//#region extensions/browser/src/browser/server-context.constants.ts
const OPEN_TAB_DISCOVERY_WINDOW_MS = 2e3;
/**
* Chrome acknowledges a tab close before the page is gone. A normal close lists
* the tab for ~10-20ms and a hung renderer for ~500ms (Chrome's unload timeout).
*/
const CLOSE_TAB_VERIFY_WINDOW_MS = 2e3;
//#endregion
//#region extensions/browser/src/browser/chrome.ts
const log = createSubsystemLogger("browser").child("chrome");
const CHROME_SINGLETON_LOCK_PATHS = [
"SingletonLock",
"SingletonSocket",
"SingletonCookie"
];
const CHROME_GRACEFUL_CLOSE_COMMAND_TIMEOUT_MS = 500;
function readSingletonLockTarget(e) {
let t;
try {
t = fs.readlinkSync(path.join(e, "SingletonLock"));
} catch (e) {
return e instanceof Error && "code" in e && e.code === "ENOENT" ? { status: "missing" } : {
status: "invalid",
reason: "Chromium profile lock could not be read"
};
}
const n = /^(?<lockHost>.+)-(?<pid>\d+)$/.exec(t);
if (!n?.groups) return {
status: "invalid",
reason: "Chromium profile lock is malformed"
};
const r = normalizeOptionalString(n.groups.lockHost) ?? "";
const i = Number.parseInt(n.groups.pid ?? "", 10);
if (!r || !Number.isSafeInteger(i) || i <= 0) return {
status: "invalid",
reason: "Chromium profile lock is malformed"
};
return {
status: "owner",
hostname: r,
pid: i
};
}
function unverifiedSingletonLockReason(e) {
if (e.status === "invalid") return e.reason;
if (e.status === "owner" && e.hostname !== os.hostname()) return "Chromium profile lock names another hostname";
}
function resolveOwnedManagedChromeIdentity(e) {
const t = readOwnedManagedHeadlessShell(e);
if (t) return t;
const n = resolveBrowserExecutable(e.resolved, e.profile);
const r = n && readOwnedManagedChromeIdentity({
...e,
exe: n
});
return n && r ? {
exe: n,
identity: r
} : null;
}
function resolveOwnedManagedChromeListener(e) {
if (e.lock.status === "owner") {
if (e.lock.hostname !== os.hostname()) return null;
if (isPidAlive(e.lock.pid)) return resolveOwnedManagedChromeIdentity({
...e,
pid: e.lock.pid
});
} else if (e.lock.status !== "missing") return null;
const t = readPortListenerPids(e.profile.cdpPort);
const [n] = t;
if (t.length !== 1 || n === void 0) return null;
return resolveOwnedManagedChromeIdentity({
...e,
pid: n,
headlessShellOnly: true
});
}
function isPortInUseError(e) {
const t = e?.code;
const n = e instanceof Error ? e.name : "";
const r = e instanceof Error ? e.message : String(e);
return t === "EADDRINUSE" || n === "PortInUseError" || /\bEADDRINUSE\b|already in use/i.test(r);
}
function clearChromeSingletonArtifacts(e) {
for (const t of CHROME_SINGLETON_LOCK_PATHS) try {
fs.rmSync(path.join(e, t), { force: true });
} catch {}
}
function clearStaleChromeSingletonLocks(e, t) {
const n = readSingletonLockTarget(e);
if (n.status !== "owner" || n.hostname !== (t?.hostname ?? os.hostname()) || t && n.pid !== t.pid || isPidAlive(n.pid)) return false;
clearChromeSingletonArtifacts(e);
return true;
}
async function waitForChromeProcessExit(e, t) {
if (e.exitCode != null || e.signalCode != null) return true;
return await new Promise((n) => {
const cleanup = () => {
clearTimeout(r);
e.off("exit", onExit);
e.off("close", onExit);
};
const r = setTimeout(() => {
cleanup();
n(false);
}, t);
const onExit = () => {
cleanup();
n(true);
};
e.once("exit", onExit);
e.once("close", onExit);
if (e.exitCode != null || e.signalCode != null) onExit();
});
}
async function signalChromeProcess(e, t, n) {
if (e.exitCode != null || e.signalCode != null) return true;
try {
e.kill(t);
} catch {}
return await waitForChromeProcessExit(e, n);
}
async function terminateChromeForRetry(e, t) {
if (!await signalChromeProcess(e, "SIGKILL", 5e3)) return false;
clearStaleChromeSingletonLocks(t);
return true;
}
async function waitForPidExit(e, t) {
const n = performance.now() + t;
while (performance.now() < n) {
if (!isPidAlive(e)) return true;
await setTimeout$1(50);
}
return !isPidAlive(e);
}
async function terminateOwnedStaleChromeProcess(e, t = CHROME_STOP_TIMEOUT_MS) {
const readCurrentIdentity = () => readOwnedManagedChromeIdentity({
pid: e.identity.pid,
exe: e.exe,
profile: e.profile,
userDataDir: e.userDataDir
});
for (const [n, r] of [["SIGTERM", t], ["SIGKILL", CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS]]) {
const t = readCurrentIdentity();
if (!t || !sameManagedChromeIdentity(e.identity, t)) return false;
try {
process.kill(e.identity.pid, n);
} catch {
return false;
}
if (await waitForPidExit(e.identity.pid, r)) return true;
}
return false;
}
function clearRecoveredChromeSingletonArtifacts(e, t, n) {
if (isPidAlive(t)) return false;
if (readSingletonLockTarget(e).status === "missing") return true;
return n.status === "owner" && n.hostname === os.hostname() && clearStaleChromeSingletonLocks(e, n);
}
async function recoverOwnedStaleManagedChromeCdpListener(e) {
e.signal?.throwIfAborted();
if (!e.profile.cdpIsLoopback) return false;
const t = readSingletonLockTarget(e.userDataDir);
if (unverifiedSingletonLockReason(t)) return false;
let n;
try {
n = await diagnoseChromeCdp(e.profile.cdpUrl, 500, 800, void 0, e.signal);
} catch {
e.signal?.throwIfAborted();
return false;
}
if (n.ok || n.code !== "websocket_health_command_timeout") return false;
const r = resolveOwnedManagedChromeListener({
...e,
lock: t
});
if (!r) return false;
const { exe: i, identity: a } = r;
const { pid: o } = a;
e.signal?.throwIfAborted();
if (!await terminateOwnedStaleChromeProcess({
identity: a,
exe: i,
profile: e.profile,
userDataDir: e.userDataDir
})) return false;
if (!clearRecoveredChromeSingletonArtifacts(e.userDataDir, o, t) || await managedChromeProfileReleaseReason(e.profile, e.userDataDir)) return false;
log.warn(`Stopped stale managed Chrome CDP listener for profile "${e.profile.name}" (pid ${o}) and retrying launch.`);
return true;
}
async function probeManagedChromePorts(e, t) {
const n = new URL(e.cdpUrl).hostname.replace(/^\[|\]$/g, "");
const r = n === "127.0.0.1" ? [n] : ["127.0.0.1", n];
for (const n of r) {
t?.throwIfAborted();
await ensurePortAvailable(e.cdpPort, n);
}
}
async function ensureManagedChromePortAvailable(e, t, n, r) {
try {
await probeManagedChromePorts(t, r);
return;
} catch (i) {
r?.throwIfAborted();
if (!isPortInUseError(i) || !await recoverOwnedStaleManagedChromeCdpListener({
resolved: e,
profile: t,
userDataDir: n,
signal: r
})) throw i;
}
await probeManagedChromePorts(t, r);
}
/** A managed child survived bounded cancellation and remains actor-owned for retry. */
var ManagedChromeCleanupError = class extends Error {
constructor(e, t) {
super(e);
this.running = t;
this.code = "MANAGED_CHROME_CLEANUP_FAILED";
this.name = "ManagedChromeCleanupError";
}
};
function resolveBrowserExecutable(e, t) {
return resolveBrowserExecutableForPlatform({
...e,
executablePath: t.executablePath ?? e.executablePath
}, process.platform);
}
function resolveOpenClawUserDataDir(e = DEFAULT_OPENCLAW_BROWSER_PROFILE_NAME) {
return path.join(CONFIG_DIR, "browser", e, "user-data");
}
async function canOpenWebSocket(e, t, n, r) {
return await withCdpSocket(e, async () => true, {
handshakeTimeoutMs: t,
handshakeRetries: 0,
lookup: n,
signal: r
});
}
async function isChromeReachable(e, t = 500, n, r) {
r?.throwIfAborted();
try {
const i = await assertCdpEndpointAllowed(e, n);
r?.throwIfAborted();
if (isDirectCdpWebSocketEndpoint(e)) return await canOpenWebSocket(e, t, i?.lookup, r);
if (await fetchChromeVersion(isWebSocketUrl(e) ? normalizeCdpHttpBaseForJsonEndpoints(e) : e, t, n, r)) return true;
if (isWebSocketUrl(e)) return await canOpenWebSocket(e, t, i?.lookup, r);
return false;
} catch {
r?.throwIfAborted();
return false;
}
}
async function fetchChromeVersion(e, t = 500, n, r) {
try {
return await readChromeVersionWithCredentialFallback(e, t, n, r);
} catch {
r?.throwIfAborted();
return null;
}
}
async function getChromeWebSocketEndpoint(e, t = 500, n, r) {
r?.throwIfAborted();
const i = await assertCdpEndpointAllowed(e, n);
r?.throwIfAborted();
const a = scopeCdpPolicyToConfiguredEndpoint(e, n);
const o = await resolveCdpWebSocketDiscovery(e, async (e) => normalizeOptionalString((await fetchChromeVersion(e, t, a, r))?.webSocketDebuggerUrl));
if (!o) return null;
if (!o.discovered) return {
url: o.url,
lookup: i?.lookup
};
const s = await assertCdpEndpointAllowed(o.url, a, {
source: "discovered",
configuredUrl: e
});
r?.throwIfAborted();
return {
url: o.url,
lookup: s?.lookup
};
}
async function isChromeCdpReady(e, t = 500, n = 800, r, i) {
const a = await diagnoseChromeCdp(e, t, n, r, i?.signal);
i?.signal?.throwIfAborted();
if (!a.ok) log.debug(formatChromeCdpDiagnostic(a));
await i?.onDiagnostic?.(a);
i?.signal?.throwIfAborted();
return a.ok;
}
async function waitForManagedLaunchPoll(e, t) {
t?.throwIfAborted();
try {
await setTimeout$1(e, void 0, t ? { signal: t } : void 0);
} catch (e) {
t?.throwIfAborted();
throw e;
}
}
async function launchOpenClawChrome(e, t, n = {}) {
n.signal?.throwIfAborted();
if (!t.cdpIsLoopback) throw new Error(`Profile "${t.name}" is remote; cannot launch local Chrome.`);
return await withChromeProfileLifecycleLock(t.name, async () => launchOpenClawChromeLocked(e, t, n));
}
async function launchOpenClawChromeLocked(e, t, n) {
const { signal: r, ...i } = n;
r?.throwIfAborted();
const a = resolveManagedBrowserHeadlessMode(e, t, i);
const o = getManagedBrowserMissingDisplayError(e, t, i);
if (o) throw new BrowserProfileUnavailableError(o.message, { metadata: {
reason: BROWSER_ERROR_REASONS.noDisplayForHeadedProfile,
details: {
profile: t.name,
requestedHeadless: false,
headlessSource: o.headlessSource,
displayPresent: false
}
} });
try {
assertManagedProxyAllowsCdpUrl(t.cdpUrl);
} catch (e) {
throw new BrowserProfileUnavailableError(`Browser profile "${t.name}" cannot launch: ${e instanceof Error ? e.message : String(e)}`);
}
const s = resolveOpenClawUserDataDir(t.name);
await ensureManagedChromePortAvailable(e, t, s, r);
r?.throwIfAborted();
const c = readSingletonLockTarget(s);
const l = unverifiedSingletonLockReason(c) ?? headlessShellProfileInUseReason(s);
if (l || c.status === "owner" && isPidAlive(c.pid)) throw new BrowserProfileUnavailableError(`Cannot start browser profile "${t.name}": ${l ?? "Chromium still holds its profile lock"}. Close the browser using this profile and check its lock before retrying.`);
const u = resolveBrowserExecutable(e, t);
if (!u) throw new Error("No supported browser found (Chrome/Brave/Edge/Chromium on macOS, Linux, or Windows).");
assertBrowserExecutableSupportsLaunch(u, a.headless, process.platform);
fs.mkdirSync(s, { recursive: true });
await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);
const d = path.join(s, "Local State");
const f = path.join(s, "Default", "Preferences");
const p = !fs.existsSync(d);
const m = !a.headless && (p || !fs.existsSync(f));
const h = process.platform === "darwin" && (usesOpenClawMockKeychain(s) || p && a.headless);
const spawnOnce = async (n) => {
r?.throwIfAborted();
const a = i.platform ?? process.platform;
const o = resolveManagedBrowserHeadlessMode(e, t, i);
const c = [
`--remote-debugging-port=${t.cdpPort}`,
`--user-data-dir=${s}`,
"--no-first-run",
"--no-default-browser-check",
"--disable-sync",
"--disable-background-networking",
"--disable-component-update",
"--disable-features=Translate,MediaRouter",
"--disable-session-crashed-bubble",
"--hide-crash-restore-bubble",
"--password-store=basic"
];
if (a === "darwin" && h) c.push("--use-mock-keychain");
if (o.headless) {
c.push("--headless=new");
c.push("--disable-gpu");
}
if (e.noSandbox) c.push("--no-sandbox");
if (a === "linux") c.push("--disable-dev-shm-usage");
if (!hasChromeProxyControlArg(e.extraArgs)) c.push("--no-proxy-server");
if (e.extraArgs.length > 0) c.push(...e.extraArgs);
const l = prepareOomScoreAdjustedSpawn(u.path, c, { env: buildChromeLaunchEnv() });
const d = spawn(l.command, l.args, {
stdio: [
"ignore",
"ignore",
"pipe"
],
env: l.env
});
const onAbort = () => {
try {
d.kill("SIGKILL");
} catch {}
};
r?.addEventListener("abort", onAbort, { once: true });
if (r?.aborted) onAbort();
d.on("error", (e) => {
log.debug(`managed Chrome process error: ${redactToolPayloadText(String(e))}`);
});
if (n) d.stderr?.on("data", n);
const releaseAbort = () => r?.removeEventListener("abort", onAbort);
try {
if (d.pid == null) await once(d, "spawn");
const e = d.pid;
if (e == null) throw new Error("Managed Chrome process spawned without a pid.");
return {
pid: e,
proc: d,
releaseAbort
};
} catch (e) {
releaseAbort();
if (n) d.stderr?.off("data", n);
throw e;
}
};
const runningForProcess = (e, n) => ({
pid: n,
exe: u,
userDataDir: s,
cdpPort: t.cdpPort,
proc: e,
headless: a.headless,
headlessSource: a.source
});
if (m) {
const { pid: e, proc: t, releaseAbort: n } = await spawnOnce();
let i;
try {
const e = performance.now() + CHROME_BOOTSTRAP_PREFS_TIMEOUT_MS;
while (performance.now() < e) {
r?.throwIfAborted();
if (fs.existsSync(d) && fs.existsSync(f)) break;
await waitForManagedLaunchPoll(100, r);
}
} catch (e) {
i = e instanceof Error ? e : new Error("Managed Chrome bootstrap failed.", { cause: e });
}
let a = await signalChromeProcess(t, "SIGTERM", CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS);
if (!a) a = await signalChromeProcess(t, "SIGKILL", CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS);
n();
if (!a) throw new ManagedChromeCleanupError(`Managed Chrome bootstrap ${e} survived cleanup.`, runningForProcess(t, e));
if (i) throw i;
}
r?.throwIfAborted();
try {
await prepareOpenClawProfile(s, {
name: t.name,
color: t.color,
downloadDir: DEFAULT_DOWNLOAD_DIR,
mockKeychain: h
});
} catch (e) {
log.warn(`openclaw browser profile preparation failed: ${String(e)}`);
}
r?.throwIfAborted();
const launchOnceAndWait = async (n) => {
const a = createChromeLaunchStderrDiagnostics();
const o = a.append;
let c;
let l;
let d = false;
const detachStderr = () => {
c?.stderr?.off("data", o);
a.clear();
};
try {
const f = await spawnOnce(o);
c = f.proc;
l = f.releaseAbort;
const hasExited = () => f.proc.exitCode != null || f.proc.signalCode != null;
const p = performance.now() + e.localLaunchTimeoutMs;
let m = false;
while (performance.now() < p) {
r?.throwIfAborted();
if (hasExited()) break;
const e = await isChromeReachable(t.cdpUrl, MANAGED_CDP_READY_HTTP_TIMEOUT_MS, void 0, r);
if (hasExited()) break;
if (e) {
m = true;
break;
}
await waitForManagedLaunchPoll(200, r);
}
let h = null;
let g = null;
if (!m && !hasExited()) try {
h = await diagnoseChromeCdp(t.cdpUrl, MANAGED_CDP_READY_HTTP_TIMEOUT_MS, 800, void 0, r);
} catch (e) {
g = `CDP diagnostic failed: ${safeChromeCdpErrorMessage(e)}.`;
}
r?.throwIfAborted();
m ||= h !== null && (h.ok || ![
"ssrf_blocked",
"http_unreachable",
"http_status_failed",
"invalid_json"
].includes(h.code));
if (m) {
const n = performance.now() + e.localCdpReadyTimeoutMs;
while (!h?.ok && !hasExited() && performance.now() < n) {
const i = Math.max(75, Math.min(MANAGED_CDP_READY_HTTP_TIMEOUT_MS, n - performance.now()));
const { httpTimeoutMs: a, wsTimeoutMs: o } = resolveCdpReachabilityTimeouts({
profileIsLoopback: t.cdpIsLoopback,
timeoutMs: i,
remoteHttpTimeoutMs: e.remoteCdpTimeoutMs,
remoteHandshakeTimeoutMs: e.remoteCdpHandshakeTimeoutMs
});
h = await diagnoseChromeCdp(t.cdpUrl, a, o, void 0, r);
r?.throwIfAborted();
if (hasExited() || h.ok) break;
await waitForManagedLaunchPoll(100, r);
}
m = !hasExited() && h?.ok === true;
}
if (!m) {
r?.throwIfAborted();
if (hasExited()) {
if (c.stderr && !c.stderr.destroyed && !c.stderr.readableEnded) {
const e = new AbortController();
const t = setTimeout(() => e.abort(), 200);
try {
await once(c.stderr, "close", { signal: r ? AbortSignal.any([r, e.signal]) : e.signal });
} catch {
r?.throwIfAborted();
} finally {
clearTimeout(t);
}
}
r?.throwIfAborted();
h = null;
g = `Chrome process exited before CDP became ready (code ${f.proc.exitCode}, signal ${f.proc.signalCode}).`;
}
const o = h ? formatChromeCdpDiagnostic(h) : g ?? "CDP diagnostic failed.";
const u = a.signals();
if (n && u.singletonInUse && clearStaleChromeSingletonLocks(s)) {
log.warn(`Removed stale Chromium Singleton* locks for profile "${t.name}" and retrying launch.`);
if (!await terminateChromeForRetry(c, s)) throw new ManagedChromeCleanupError(`Managed Chrome process ${f.pid} survived singleton recovery.`, runningForProcess(c, f.pid));
l();
l = void 0;
return await launchOnceAndWait(false);
}
const d = ["Check the browser executable and browser.extraArgs, then retry. If it still fails, use another browser profile or an alternative tool."];
if (process.platform === "linux" && !e.noSandbox) d.push("If running in a container or as root, try setting browser.noSandbox: true.");
const p = resolveManagedBrowserHeadlessMode(e, t, i);
if (u.missingDisplay && !p.headless) d.push("No DISPLAY/X server was detected. Set OPENCLAW_BROWSER_HEADLESS=1, remove the headed override, start Xvfb, or run the Gateway in a desktop session.");
if (u.singletonInUse) d.push(`The Chromium profile "${t.name}" is locked. Stop the existing browser or remove stale Singleton* lock files under ~/.openclaw/browser/${t.name}/user-data.`);
const m = `\nHint: ${d.join("\nHint: ")}`;
const _ = `Failed to start Chrome CDP on port ${t.cdpPort} for profile "${t.name}". ${o}${m}${a.hint()}`;
log.error(_);
throw new Error(redactToolPayloadText(_));
}
r?.throwIfAborted();
const _ = f.pid;
d = true;
log.info(`🦞 openclaw browser started (${u.kind}) profile "${t.name}" on 127.0.0.1:${t.cdpPort} (pid ${_})`);
return runningForProcess(c, _);
} catch (e) {
if (c) {
const e = c.pid;
if (!await signalChromeProcess(c, "SIGKILL", 5e3) && typeof e === "number") throw new ManagedChromeCleanupError(`Managed Chrome process ${e} survived launch cleanup.`, runningForProcess(c, e));
}
if (e instanceof ManagedChromeCleanupError) {
if (e.running.proc !== c) throw e;
throw new Error(`${e.message} Exact child cleanup succeeded on retry.`, { cause: e });
}
throw e;
} finally {
l?.();
if (d && c) c.once("close", (e, n) => {
if (!c?.killed && (e !== 0 || n)) log.error(`Managed Chrome for profile "${t.name}" exited (code ${e}, signal ${n}). Check the browser executable and browser.extraArgs before retrying.${a.hint()}`);
detachStderr();
});
else detachStderr();
}
};
return await launchOnceAndWait(true);
}
function cdpBrowserProcessId(e) {
if (!e || typeof e !== "object" || !("processInfo" in e)) return null;
const t = e.processInfo;
if (!Array.isArray(t)) return null;
return t.find((e) => {
const t = e;
return t?.type === "browser" && typeof t.id === "number" && Number.isSafeInteger(t.id) && t.id > 0;
})?.id ?? null;
}
/** Read the mode of a browser process proven to own this host's loopback CDP port. */
async function inspectLocalChromeHeadlessMode(e) {
e.signal?.throwIfAborted();
if (!e.profile.cdpIsLoopback) return;
try {
const t = Math.max(1, Math.min(e.timeoutMs, 800));
const n = isDirectCdpWebSocketEndpoint(e.profile.cdpUrl) && e.browserWebSocketUrl === e.profile.cdpUrl;
const r = n ? e.ssrfPolicy : scopeCdpPolicyToConfiguredEndpoint(e.profile.cdpUrl, e.ssrfPolicy);
const i = await assertCdpEndpointAllowed(e.browserWebSocketUrl, r, n ? void 0 : {
source: "discovered",
configuredUrl: e.profile.cdpUrl
});
e.signal?.throwIfAborted();
const a = await withCdpSocket(e.browserWebSocketUrl, async (e) => await e("SystemInfo.getProcessInfo"), {
commandTimeoutMs: t,
handshakeRetries: 0,
handshakeTimeoutMs: t,
lookup: i?.lookup,
signal: e.signal
});
e.signal?.throwIfAborted();
const o = cdpBrowserProcessId(a);
if (!o || !isPidAlive(o) || !pidListensOnPort(o, e.profile.cdpPort)) return;
const s = readManagedProcessCommandLine(o);
if (!s || !processCommandHasFlag(s, "remote-debugging-port", String(e.profile.cdpPort))) return;
return processCommandUsesHeadlessChrome(s);
} catch {
e.signal?.throwIfAborted();
return;
}
}
/** Verify that a managed CDP endpoint belongs to the exact spawned browser pid. */
async function isChromeCdpOwnedByPid(e, t, n, r, i) {
i?.throwIfAborted();
try {
const a = await getChromeWebSocketEndpoint(e, n, r, i);
if (!a) return false;
const o = await withCdpSocket(a.url, async (e) => {
i?.throwIfAborted();
return cdpBrowserProcessId(await e("SystemInfo.getProcessInfo")) === t;
}, {
commandTimeoutMs: n,
handshakeRetries: 0,
handshakeTimeoutMs: n,
lookup: a.lookup,
signal: i
});
i?.throwIfAborted();
return o;
} catch {
i?.throwIfAborted();
return false;
}
}
async function requestGracefulChromeClose(e, t, n, r) {
const i = Math.max(1, Math.min(t, CHROME_GRACEFUL_CLOSE_COMMAND_TIMEOUT_MS));
let a = false;
try {
const t = await getChromeWebSocketEndpoint(`http://127.0.0.1:${e.cdpPort}`, Math.min(i, 200), n);
if (!t) return false;
await withCdpSocket(t.url, async (t) => {
if (cdpBrowserProcessId(await t("SystemInfo.getProcessInfo")) !== e.pid || r && !r()) return;
a = true;
await t("Browser.close");
}, {
commandTimeoutMs: i,
handshakeTimeoutMs: i,
handshakeRetries: 0,
lookup: t.lookup
});
return a;
} catch (e) {
log.debug(`Chrome graceful close skipped: ${safeChromeCdpErrorMessage(e)}`);
return a;
}
}
async function managedChromeProfileReleaseReason(e, t) {
try {
await probeManagedChromePorts(e);
} catch {
return "The Chromium CDP port is still occupied or could not be verified free";
}
const n = headlessShellProfileInUseReason(t);
if (n) return n;
const r = readSingletonLockTarget(t);
return unverifiedSingletonLockReason(r) ?? (r.status === "owner" && isPidAlive(r.pid) ? "Chromium still holds the profile lock" : void 0);
}
/** Stop only the exact managed Chrome owned by this profile across runtimes. */
async function stopOwnedOpenClawChrome(e, t, n = CHROME_STOP_TIMEOUT_MS) {
if (!t.cdpIsLoopback || t.attachOnly || t.driver !== "openclaw") return { status: "not-running" };
return await withChromeProfileLifecycleLock(t.name, async () => stopOwnedOpenClawChromeLocked(e, t, n));
}
async function stopOwnedOpenClawChromeLocked(e, t, n) {
const r = resolveOpenClawUserDataDir(t.name);
const i = readSingletonLockTarget(r);
const a = unverifiedSingletonLockReason(i);
if (a) return {
status: "unverified",
reason: a
};
let o;
try {
const n = process.platform !== "linux" && process.platform !== "darwin" ? resolveBrowserExecutable(e, t) : null;
if (n && isHeadlessShellExecutable(n.path)) return {
status: "unverified",
reason: "Cross-runtime headless shell cleanup is unsupported on this platform; use full Chromium for managed profiles"
};
o = resolveOwnedManagedChromeListener({
resolved: e,
profile: t,
userDataDir: r,
lock: i
});
} catch {
return {
status: "unverified",
reason: "Managed browser executable could not be resolved"
};
}
if (!o) {
if (i.status !== "owner" || !isPidAlive(i.pid)) {
const e = await managedChromeProfileReleaseReason(t, r);
return e ? {
status: "unverified",
reason: e
} : { status: "not-running" };
}
return {
status: "unverified",
reason: "The active Chromium profile owner could not be verified"
};
}
const { exe: s, identity: c } = o;
const { pid: l } = c;
if (!(await requestGracefulChromeClose({
pid: l,
cdpPort: t.cdpPort
}, n, e.ssrfPolicy, () => {
const e = readOwnedManagedChromeIdentity({
pid: l,
exe: s,
profile: t,
userDataDir: r
});
return e !== null && sameManagedChromeIdentity(c, e);
}) && await waitForPidExit(l, n)) && isPidAlive(l) && !await terminateOwnedStaleChromeProcess({
identity: c,
exe: s,
profile: t,
userDataDir: r
}, n)) return {
status: "unverified",
reason: "The Chromium profile owner changed or did not stop"
};
if (!clearRecoveredChromeSingletonArtifacts(r, l, i)) return {
status: "unverified",
reason: "The Chromium profile lock changed or its owner is still running"
};
const u = await managedChromeProfileReleaseReason(t, r);
if (u) return {
status: "unverified",
reason: u
};
return { status: "stopped" };
}
async function stopOpenClawChrome(e, t = CHROME_STOP_TIMEOUT_MS) {
const n = e.proc;
if (n.exitCode != null || n.signalCode != null) return;
if (await requestGracefulChromeClose(e, t) && await waitForChromeProcessExit(n, t)) return;
if (await signalChromeProcess(n, "SIGTERM", t)) return;
if (!await signalChromeProcess(n, "SIGKILL", t)) throw new ManagedChromeCleanupError(`Managed Chrome process ${e.pid} survived shutdown.`, e);
}
//#endregion
export { parseRoleRef as A, assertChromeMcpNavigationAllowed as B, snapshotRoleViaCdp as C, finalizeRoleSnapshot as D, buildRoleSnapshotFromAiSnapshot as E, appendRoleSnapshotDepthTruncationMarker as F, waitForCdpCommittedNavigationUrl as G, requiresInspectableBrowserNavigationRedirectsForUrl as H, InvalidBrowserNavigationUrlError as I, resolveBrowserNavigationProxyMode as K, assertBrowserNavigationAllowed as L, CONTENT_ROLES as M, INTERACTIVE_ROLES as N, findRoleSnapshotLineRef as O, STRUCTURAL_ROLES as P, assertBrowserNavigationRedirectChainAllowed as R, snapshotAria as S, appendSnapshotUrls as T, withBrowserNavigationPolicy as U, parseBrowserNavigationUrl as V, readCdpDocumentIdentities as W, AX_REF_PATTERN as _, isChromeCdpReady as a, formatAriaSnapshot as b, resolveOpenClawUserDataDir as c, CLOSE_TAB_VERIFY_WINDOW_MS as d, OPEN_TAB_DISCOVERY_WINDOW_MS as f, formatChromeCdpDiagnostic as g, diagnoseChromeCdp as h, isChromeCdpOwnedByPid as i, redactAiSnapshotFieldValues as j, getRoleSnapshotIdentityKeys as k, stopOpenClawChrome as l, usesOpenClawMockKeychain as m, getChromeWebSocketEndpoint as n, isChromeReachable as o, withChromeProfileLifecycleLock as p, inspectLocalChromeHeadlessMode as r, launchOpenClawChrome as s, ManagedChromeCleanupError as t, stopOwnedOpenClawChrome as u, captureScreenshot as v, snapshotRoleViaCdpSession as w, getDocumentIdentitiesViaCdp as x, createTargetViaCdp as y, assertBrowserNavigationResultAllowed as z };