UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

581 lines (580 loc) • 18.6 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { c as readDirectoryEntriesSync, i as executableFileExistsSync } from "./path-existence-Co7-GyVr.mjs"; import { f as pathExistsSync } from "./fs-safe-BbWvmdVn.mjs"; import "./path-existence-runtime-LOpU--Vt.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./security-runtime-C-zE_Zy_.mjs"; import { c as BrowserProfileUnavailableError } from "./errors-C9QQGqVs.mjs"; import fs from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; import os from "node:os"; import { execFileSync } from "node:child_process"; //#region extensions/browser/src/browser/chrome.executable-probe.ts const CHROME_VERSION_RE = /\b(\d+)(?:\.\d+){1,3}\b/g; const BROWSER_VERSION_TIMEOUT_MS = 6e3; const MAC_PLISTBUDDY_TIMEOUT_MS = 800; const WINDOWS_FILE_METADATA_TIMEOUT_MS = 4e3; function execBrowserProbe(e, t, n = 1200, r = 1048576, i) { try { const a = execFileSync(e, t, { timeout: n, encoding: "utf8", maxBuffer: r, stdio: [ "ignore", "pipe", "ignore" ], ...i ? { env: { ...process.env, ...i } } : {} }); return normalizeOptionalString(a) ?? null; } catch { return null; } } function readBrowserVersion(e) { if (process.platform === "darwin") { const t = readMacBundleBrowserVersion(e); if (t) return t; } if (process.platform === "win32") return readWindowsBrowserVersion(e); const t = execBrowserProbe(e, ["--version"], BROWSER_VERSION_TIMEOUT_MS); if (!t) return null; return t.replace(/\s+/g, " "); } function readMacBundleBrowserVersion(e) { const t = resolveMacAppBundlePath(e); if (!t) return null; return execBrowserProbe("/usr/libexec/PlistBuddy", [ "-c", "Print :CFBundleShortVersionString", path.join(t, "Contents", "Info.plist") ], MAC_PLISTBUDDY_TIMEOUT_MS); } const WINDOWS_VERSION_DIR_RE = /^\d+(?:\.\d+){1,3}$/; function readWindowsBrowserVersion(e) { const t = normalizeOptionalString(process.env.SystemRoot); const n = t && path.win32.isAbsolute(t) ? t : "C:\\Windows"; const r = execBrowserProbe(path.win32.join(n, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), [ "-NoProfile", "-NonInteractive", "-Command", "[System.Diagnostics.FileVersionInfo]::GetVersionInfo($env:OPENCLAW_BROWSER_EXECUTABLE_PATH).ProductVersion" ], WINDOWS_FILE_METADATA_TIMEOUT_MS, void 0, { OPENCLAW_BROWSER_EXECUTABLE_PATH: e }); if (r) return r.replace(/\s+/g, " "); const i = readDirectoryEntriesSync(path.win32.dirname(e)).filter((e) => e.isDirectory() && WINDOWS_VERSION_DIR_RE.test(e.name)); return i.length === 1 ? i[0]?.name ?? null : null; } function resolveMacAppBundlePath(e) { const t = path.normalize(e).split(path.sep); const n = t.findIndex((e) => e.endsWith(".app")); if (n < 0) return null; return t.slice(0, n + 1).join(path.sep) || path.sep; } function parseBrowserMajorVersion(e) { const t = [...(e ?? "").matchAll(CHROME_VERSION_RE)].at(-1); if (!t?.[1]) return null; const n = Number.parseInt(t[1], 10); return Number.isFinite(n) ? n : null; } //#endregion //#region extensions/browser/src/browser/chrome.playwright-cache.ts /** Discover installed Playwright browsers without loading its runtime or downloading anything. */ function getPlaywrightEnv(e) { const t = e.toLowerCase(); return process.env[e] ?? process.env[`npm_config_${t}`] ?? process.env[`npm_package_config_${t}`]; } function cachePaths(e) { const t = e === "win32" ? path.win32 : path; const n = t.join; const r = getPlaywrightEnv("PLAYWRIGHT_BROWSERS_PATH"); const i = [n(e === "darwin" ? n(os.homedir(), "Library", "Caches") : e === "win32" ? normalizeOptionalString(process.env.LOCALAPPDATA) ?? n(os.homedir(), "AppData", "Local") : normalizeOptionalString(process.env.XDG_CACHE_HOME) ?? n(os.homedir(), ".cache"), "ms-playwright")]; if (r === "0") try { const e = path.dirname(fileURLToPath(import.meta.resolve("playwright-core/package.json"))); i.unshift(n(e, ".local-browsers")); } catch {} else if (r) i.unshift(r); const a = getPlaywrightEnv("INIT_CWD") || process.cwd(); return [...new Set(i.map((e) => t.resolve(a, e)))]; } /** The cache is only a fallback; explicit executables and installed browsers keep precedence. */ function findPlaywrightChromiumExecutable(e) { if (e !== "linux" && e !== "darwin" && e !== "win32") return null; const t = e === "win32" ? path.win32.join : path.join; const n = e === "darwin" && os.cpus().some((e) => e.model.includes("Apple")); const r = e === "linux" ? [[`chrome-${process.arch === "arm64" ? "linux-arm64" : "linux64"}`, "chrome"], ["chrome-linux", "chrome"]] : e === "darwin" ? [[ `chrome-mac-${n ? "arm64" : "x64"}`, "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing" ], [ "chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium" ]] : [["chrome-win64", "chrome.exe"], ["chrome-win", "chrome.exe"]]; for (const n of cachePaths(e)) { let i; try { i = fs.readdirSync(n).toSorted((e, t) => t.localeCompare(e, void 0, { numeric: true })); } catch { continue; } for (const a of i) { if (!a.startsWith("chromium-")) continue; for (const i of r) { const r = t(n, a, ...i); if (executableFileExistsSync(r, e)) return { kind: "chromium", path: r }; } } } return null; } //#endregion //#region extensions/browser/src/browser/chrome.executables.ts const DEFAULT_WINDOWS_PROGRAM_FILES = "C:\\Program Files"; const DEFAULT_WINDOWS_PROGRAM_FILES_X86 = "C:\\Program Files (x86)"; const CHROMIUM_BUNDLE_IDS = /* @__PURE__ */ new Set([ "com.google.Chrome", "com.google.Chrome.beta", "com.google.Chrome.canary", "com.google.Chrome.dev", "com.brave.Browser", "com.brave.Browser.beta", "com.brave.Browser.nightly", "com.microsoft.Edge", "com.microsoft.EdgeBeta", "com.microsoft.EdgeDev", "com.microsoft.EdgeCanary", "com.microsoft.edgemac", "com.microsoft.edgemac.beta", "com.microsoft.edgemac.dev", "com.microsoft.edgemac.canary", "org.chromium.Chromium", "com.vivaldi.Vivaldi", "com.operasoftware.Opera", "com.operasoftware.OperaGX", "com.yandex.desktop.yandex-browser", "company.thebrowser.Browser" ]); const CHROMIUM_LINUX_NAMES = [ "google-chrome", "google-chrome-beta", "google-chrome-unstable", "brave-browser", "microsoft-edge", "microsoft-edge-beta", "microsoft-edge-dev", "microsoft-edge-canary", "chromium", "chromium-browser", "vivaldi", "vivaldi-stable", "opera", "opera-gx", "yandex-browser" ]; const CHROMIUM_DESKTOP_IDS = /* @__PURE__ */ new Set([...CHROMIUM_LINUX_NAMES.map((e) => `${e}.desktop`), "org.chromium.Chromium.desktop"]); const CHROMIUM_EXE_NAMES = /* @__PURE__ */ new Set([ "chrome.exe", "msedge.exe", "brave.exe", "brave-browser.exe", "chromium.exe", "vivaldi.exe", "opera.exe", "yandex.exe", "yandexbrowser.exe", "google chrome", "google chrome canary", "brave browser", "microsoft edge", "chrome", "brave", "msedge", "google-chrome-stable", "opera-stable", ...CHROMIUM_LINUX_NAMES ]); function inferKindFromIdentifier(e) { const t = normalizeLowercaseStringOrEmpty(e); for (const e of [ "brave", "edge", "chromium", "canary" ]) if (t.includes(e)) return e; return /opera|vivaldi|yandex|thebrowser/.test(t) ? "chromium" : "chrome"; } function detectDefaultChromiumExecutable(e) { if (e === "darwin") { const e = path.join(os.homedir(), "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"); if (!pathExistsSync(e)) return null; const t = execBrowserProbe("/usr/bin/plutil", [ "-extract", "LSHandlers", "json", "-o", "-", "--", e ], 2e3, 5242880); if (!t) return null; let n; try { n = JSON.parse(t); } catch { return null; } if (!Array.isArray(n)) return null; const resolveScheme = (e) => { let t = null; for (const r of n) { if (!r || typeof r !== "object") continue; const n = r; if (n.LSHandlerURLScheme !== e) continue; const i = typeof n.LSHandlerRoleAll === "string" && n.LSHandlerRoleAll || typeof n.LSHandlerRoleViewer === "string" && n.LSHandlerRoleViewer || null; if (i) t = i; } return t; }; const r = resolveScheme("http") ?? resolveScheme("https"); if (!r || !CHROMIUM_BUNDLE_IDS.has(r)) return null; const i = execBrowserProbe("/usr/bin/osascript", ["-e", `POSIX path of (path to application id "${r}")`]); if (!i) return null; const a = i.replace(/\/$/, ""); const o = execBrowserProbe("/usr/bin/defaults", [ "read", path.join(a, "Contents", "Info"), "CFBundleExecutable" ]); if (!o) return null; const s = path.join(a, "Contents", "MacOS", o); if (!executableFileExistsSync(s, "darwin")) return null; return { kind: inferKindFromIdentifier(r), path: s }; } if (e === "linux") { const e = execBrowserProbe("xdg-settings", ["get", "default-web-browser"]) || execBrowserProbe("xdg-mime", [ "query", "default", "x-scheme-handler/http" ]); if (!e) return null; if (!CHROMIUM_DESKTOP_IDS.has(e)) return null; const t = [ path.join(os.homedir(), ".local", "share", "applications", e), path.join("/usr/local/share/applications", e), path.join("/usr/share/applications", e), path.join("/var/lib/snapd/desktop/applications", e) ].find((e) => pathExistsSync(e)) ?? null; if (!t) return null; let n; try { n = fs.readFileSync(t, "utf8").split(/\r?\n/).find((e) => e.startsWith("Exec="))?.slice(5).trim() ?? null; } catch { return null; } if (!n) return null; const r = []; let i = ""; let a = ""; for (const e of n) { if ((e === "\"" || e === "'") && (!a || e === a)) { a = a ? "" : e; continue; } if (!a && /\s/.test(e)) { if (i) { r.push(i); i = ""; } continue; } i += e; } if (i) r.push(i); const o = r.find((e) => e && e !== "env" && !(e.includes("=") && !e.startsWith("/") && !e.includes("\\")))?.replace(/^["']|["']$/g, "") ?? null; if (!o) return null; const s = o.trim().replace(/%[a-zA-Z]/g, ""); if (!s) return null; const c = s.startsWith("/") ? s : execBrowserProbe("which", [s], 800); if (!c || !executableFileExistsSync(c, "linux")) return null; const l = normalizeLowercaseStringOrEmpty(path.posix.basename(c)); if (!CHROMIUM_EXE_NAMES.has(l)) return null; return { kind: inferKindFromIdentifier(l), path: c }; } if (e === "win32") { const e = readWindowsProgId(); const t = (e ? readWindowsCommandForProgId(e) : null) || readWindowsCommandForProgId("http"); if (!t) return null; const n = resolveWindowsBrowserInstallRoots(); const r = { localappdata: n.localAppData, programfiles: n.programFiles, "programfiles(x86)": n.programFilesX86 }; const i = t.replace(/%([^%]+)%/g, (e, t) => { const n = normalizeOptionalString(t); if (!n) return e; return normalizeOptionalString(process.env[n]) ?? r[n.toLowerCase()] ?? `%${n}%`; }); const a = i.match(/"([^"]+\.exe)"/i)?.[1] ?? i.match(/^\s*(\S+\.exe)(?:\s|$)/i)?.[1] ?? null; if (!a) return null; if (!executableFileExistsSync(a, "win32")) return null; const o = resolveDirectWindowsBrowserExecutable(a); if (!o) return null; const s = normalizeLowercaseStringOrEmpty(path.win32.basename(o)); if (!CHROMIUM_EXE_NAMES.has(s)) return null; return { kind: inferKindFromIdentifier(s), path: o }; } return null; } /** Resolve launchers that hand off to another process into a directly owned browser binary. */ function resolveDirectWindowsBrowserExecutable(e) { if (normalizeLowercaseStringOrEmpty(path.win32.basename(e)) !== "launcher.exe") return e; const t = path.win32.dirname(e); try { const e = JSON.parse(fs.readFileSync(path.win32.join(t, "installation_status.json"), "utf8")); const n = e && typeof e === "object" ? Reflect.get(e, "_subfolder") : null; if (typeof n !== "string" || !WINDOWS_VERSION_DIR_RE.test(n)) return null; const r = path.win32.join(t, n, "opera.exe"); return pathExistsSync(r) ? r : null; } catch { return null; } } function readWindowsProgId() { const e = execBrowserProbe("reg", [ "query", "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice", "/v", "ProgId" ]); if (!e) return null; return e.match(/ProgId\s+REG_\w+\s+(.+)$/im)?.[1]?.trim() || null; } function readWindowsCommandForProgId(e) { const t = `HKCR\\${e}\\shell\\open\\command`; const n = execBrowserProbe("reg", [ "query", t, "/ve" ]); if (!n) return null; const r = n.match(/REG_\w+\s+(.+)$/im); return normalizeOptionalString(r?.[1]) ?? null; } function resolveWindowsBrowserInstallRoots() { return { localAppData: normalizeOptionalString(process.env.LOCALAPPDATA) ?? path.win32.join(os.homedir(), "AppData", "Local"), programFiles: normalizeOptionalString(process.env.ProgramFiles) ?? DEFAULT_WINDOWS_PROGRAM_FILES, programFilesX86: normalizeOptionalString(process.env["ProgramFiles(x86)"]) ?? DEFAULT_WINDOWS_PROGRAM_FILES_X86 }; } function chromeExecutableCandidates(e) { switch (e) { case "darwin": { const e = [ ["chrome", "Google Chrome"], ["brave", "Brave Browser"], ["edge", "Microsoft Edge"], ["chromium", "Chromium"], ["canary", "Google Chrome Canary"] ]; const t = ["/Applications", path.join(os.homedir(), "Applications")]; return e.flatMap(([e, n]) => t.map((t) => ({ kind: e, path: path.join(t, `${n}.app`, "Contents", "MacOS", n) }))); } case "linux": return [ { kind: "chrome", path: "/usr/bin/google-chrome" }, { kind: "chrome", path: "/usr/bin/google-chrome-stable" }, { kind: "chrome", path: "/usr/bin/chrome" }, { kind: "chrome", path: "/opt/google/chrome/chrome" }, { kind: "brave", path: "/usr/bin/brave-browser" }, { kind: "brave", path: "/usr/bin/brave-browser-stable" }, { kind: "brave", path: "/usr/bin/brave" }, { kind: "brave", path: "/snap/bin/brave" }, { kind: "brave", path: "/opt/brave.com/brave/brave-browser" }, { kind: "edge", path: "/usr/bin/microsoft-edge" }, { kind: "edge", path: "/usr/bin/microsoft-edge-stable" }, { kind: "chromium", path: "/usr/bin/chromium" }, { kind: "chromium", path: "/usr/bin/chromium-browser" }, { kind: "chromium", path: "/usr/lib/chromium/chromium" }, { kind: "chromium", path: "/usr/lib/chromium-browser/chromium-browser" }, { kind: "chromium", path: "/snap/bin/chromium" } ]; case "win32": { const { localAppData: e, programFiles: t, programFilesX86: n } = resolveWindowsBrowserInstallRoots(); const r = [ [ "chrome", "Google", "Chrome", "Application", "chrome.exe" ], [ "brave", "BraveSoftware", "Brave-Browser", "Application", "brave.exe" ], [ "edge", "Microsoft", "Edge", "Application", "msedge.exe" ], [ "chromium", "Chromium", "Application", "chrome.exe" ], [ "canary", "Google", "Chrome SxS", "Application", "chrome.exe" ] ]; const i = r.map(([t, ...n]) => ({ kind: t, path: path.win32.join(e, ...n) })); for (const [e, ...a] of r.slice(0, 3)) for (const r of [t, n]) i.push({ kind: e, path: path.win32.join(r, ...a) }); return i; } default: return []; } } function resolveGoogleChromeExecutableForPlatform(e) { const t = (e === "linux" ? [ "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome-beta", "/usr/bin/google-chrome-unstable", "/opt/google/chrome/chrome", "/snap/bin/google-chrome" ] : chromeExecutableCandidates(e).filter(({ kind: e }) => e === "chrome" || e === "canary").map((e) => e.path)).find((t) => executableFileExistsSync(t, e)); if (!t) return null; const n = normalizeLowercaseStringOrEmpty(t); return { kind: [ "beta", "canary", "sxs", "unstable" ].some((e) => n.includes(e)) ? "canary" : "chrome", path: t }; } function resolveBrowserExecutableForPlatform(e, t) { if (e.executablePath) { if (!pathExistsSync(e.executablePath)) throw new Error(`browser.executablePath not found: ${e.executablePath}`); const n = t === "win32" ? resolveDirectWindowsBrowserExecutable(e.executablePath) : e.executablePath; if (!n) throw new Error(`browser.executablePath must point to the browser executable, not a handoff launcher: ${e.executablePath}`); return { kind: "custom", path: n }; } return detectDefaultChromiumExecutable(t) ?? chromeExecutableCandidates(t).find((e) => executableFileExistsSync(e.path, t)) ?? findPlaywrightChromiumExecutable(t); } /** Launch suitability is not executable identity: cleanup can inspect a one-shot headless launch. */ function assertBrowserExecutableSupportsLaunch(e, t, n) { if (!/(?:^|[\\/])(?:chrome-headless-shell|headless_shell)(?:\.exe)?$/i.test(e.path)) return; if (!t) throw new Error("Chromium headless shell cannot open a headed window; use headless mode or a full Chromium executable."); if (n !== "linux" && n !== "darwin") throw new BrowserProfileUnavailableError("Managed headless shell is unsupported on this platform; use full Chromium or attach to an externally managed browser."); } function processCommandUsesHeadlessChrome(e) { return (e.argv ?? e.text.split(/\s+/)).some((e) => /^['"]?--headless(?:=.*)?['"]?$/i.test(e)) || /(?:^|[\\/])(?:chrome-headless-shell|headless_shell)(?=\s|$|["'])/i.test(e.text); } /** Match executable metadata while the lifecycle owner proves PID, port, and profile identity. */ function isChromeExecutableFamilyMatch(e, t) { const n = e.toLowerCase(); const r = t.path.toLowerCase(); const i = path.basename(t.path).toLowerCase(); if (n.includes(r) || i.length > 0 && n.includes(i)) return true; if (t.kind === "chrome" || t.kind === "canary") return /\b(google chrome|google-chrome|chrome|chromium)\b/i.test(e); if (t.kind === "chromium") return /\b(chromium|chromium-browser)\b/i.test(e); if (t.kind === "brave") return /\b(brave browser|brave-browser|brave)\b/i.test(e); if (t.kind === "edge") return /\b(microsoft edge|microsoft-edge|msedge)\b/i.test(e); return false; } //#endregion export { resolveGoogleChromeExecutableForPlatform as a, resolveBrowserExecutableForPlatform as i, isChromeExecutableFamilyMatch as n, parseBrowserMajorVersion as o, processCommandUsesHeadlessChrome as r, readBrowserVersion as s, assertBrowserExecutableSupportsLaunch as t };