UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

413 lines (412 loc) • 16.7 kB
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { n as info, t as danger } from "./globals-CgepmiqE.mjs"; import { n as inheritOptionFromParent } from "./command-options-D76J8Wl7.mjs"; import { n as redactCdpUrl } from "./browser-cdp-DYGt86Rj.mjs"; import "./text-utility-runtime-Ds8jsG0J.mjs"; import "./number-runtime-W4chuk8B.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import "./cli-runtime-DeVPX2l7.mjs"; import { t as formatBrowserGraphicsSummary } from "./chrome.graphics-DL1rMyGS.mjs"; import { a as printBrowserJsonResult, c as runBrowserCliCommand, i as parseBrowserPositiveIntegerOption, l as runBrowserCliRequest, n as callBrowserRequest, o as printBrowserList, s as resolveBrowserProfileQuery, t as BROWSER_TAB_REFERENCE_HELP } from "./browser-cli-shared-BEDAHNiM.mjs"; //#region extensions/browser/src/cli/browser-cli-manage.ts const BROWSER_MANAGE_REQUEST_TIMEOUT_MS = 45e3; function resolveBrowserManagementTimeout(e, t = BROWSER_MANAGE_REQUEST_TIMEOUT_MS) { const n = inheritOptionFromParent(e, "timeout", "cli"); return n === void 0 ? t : parseBrowserPositiveIntegerOption(n, "--timeout"); } function sanitizeTableCell(e) { return e.replace(/\p{Cc}/gu, " "); } async function fetchBrowserManagement(e, t, n, r) { return await callBrowserRequest(t, { method: "GET", path: n, query: r }, { timeoutMs: resolveBrowserManagementTimeout(e) }); } async function runBrowserToggle(e, t, n) { const r = t.browserProfile; await callBrowserRequest(t, { method: "POST", path: n.path, query: resolveBrowserProfileQuery(r, n.query) }); const i = await fetchBrowserManagement(e, t, "/", resolveBrowserProfileQuery(r)); if (printBrowserJsonResult(t, i)) return; const a = i.profile ?? "openclaw"; const o = n.path === "/start" && i.headless ? " (headless)" : ""; defaultRuntime.log(info(`🦞 browser [${a}] running: ${i.running}${o}`)); } function parseTabIndex(e) { return parseStrictPositiveInteger(e) ?? NaN; } function logBrowserTabs(e) { printBrowserList(e, "No tabs (browser closed or no targets).", (e, t) => { const n = e.label ? `label:${e.label}` : void 0; const r = [ e.suggestedTargetId ? `use: ${e.suggestedTargetId}` : void 0, e.tabId ? `tab: ${e.tabId}` : void 0, n ].filter(Boolean).join(" "); return `${t + 1}. ${e.title || "(untitled)"}${r ? ` [${r}]` : ""}\n ${e.url}\n id: ${e.targetId}`; }); } function formatDoctorLine(e) { return `${e.warning ? "WARN" : e.info ? "INFO" : e.ok ? "OK" : "FAIL"} ${e.name}${e.detail ? `: ${e.detail}` : ""}`; } function formatBrowserDoctorGatewayError(e) { if (e instanceof Error && (e.name === "GatewaySecretRefUnavailableError" || e.code === "GATEWAY_SECRET_REF_UNAVAILABLE")) return "Gateway auth SecretRef is unavailable in this command path; browser doctor cannot reach the admin-scoped browser.request endpoint. Set OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD, then retry."; return String(e); } async function runBrowserDoctor(e, t, n, r) { const i = []; const probe = async (e, t) => { try { i.push({ name: e, ...await t() }); } catch (t) { i.push({ name: e, ok: false, detail: String(t) }); } }; let a; try { a = await fetchBrowserManagement(e, t, "/doctor", resolveBrowserProfileQuery(n)); i.push({ name: "gateway", ok: true, detail: "browser control endpoint reachable" }); } catch (e) { i.push({ name: "gateway", ok: false, detail: formatBrowserDoctorGatewayError(e) }); return { ok: false, checks: i }; } const o = a.status; i.push({ name: "plugin", ok: o.enabled, detail: o.enabled ? "enabled" : "disabled in config" }); i.push({ name: "profile", ok: true, detail: `${o.profile ?? "openclaw"} (${usesChromeMcpTransport(o) ? "chrome-mcp" : o.transport ?? "cdp"})` }); i.push({ name: "browser", ok: o.running, detail: o.running ? `running${o.cdpReady === false ? ", CDP not ready" : ""}` : "not running; run `openclaw browser start`" }); const s = a.checks.find((e) => e.id === "extension-version"); if (s) i.push({ name: s.id, ok: s.status !== "fail", warning: s.status === "warn", info: s.status === "info", detail: `${s.summary}${s.fixHint ? `; ${s.fixHint}` : ""}` }); if (o.graphics) i.push({ name: "graphics", ok: true, warning: o.graphics.status === "unavailable", detail: formatBrowserGraphicsSummary(o.graphics) }); await probe("profiles", async () => { return { ok: true, detail: `${(await fetchBrowserManagement(e, t, "/profiles")).profiles?.length ?? 0} configured` }; }); if (o.running) await probe("tabs", async () => { const r = (await fetchBrowserManagement(e, t, "/tabs", resolveBrowserProfileQuery(n))).tabs ?? []; return { ok: true, detail: `${r.length} visible${r.length > 0 && r[0]?.suggestedTargetId ? `, use tab reference ${r[0].suggestedTargetId}` : ""}` }; }); if (r && o.running) await probe("live-snapshot", async () => { const e = await callBrowserRequest(t, { method: "GET", path: "/snapshot", query: resolveBrowserProfileQuery(n, { format: "aria", limit: 25 }) }, { timeoutMs: 1e4 }); const r = e.format === "aria" ? Array.isArray(e.nodes) ? e.nodes.length : 0 : typeof e.snapshot === "string" ? e.snapshot.split("\n").length : 0; return { ok: r > 0, detail: r > 0 ? `${r} nodes/lines` : "snapshot returned no content" }; }); return { ok: i.every((e) => e.ok), checks: i, status: o }; } function usesChromeMcpTransport(e) { return e.transport === "chrome-mcp" || e.driver === "existing-session"; } function formatBrowserConnectionSummary(e) { if (usesChromeMcpTransport(e)) { if (e.cdpUrl) return `transport: chrome-mcp, cdpUrl: ${redactCdpUrl(e.cdpUrl)}`; const t = e.userDataDir ? shortenHomePath(e.userDataDir) : null; return t ? `transport: chrome-mcp, userDataDir: ${t}` : "transport: chrome-mcp"; } if (e.transport === "extension" || e.driver === "extension") return `transport: extension, relayPort: ${e.cdpPort ?? "(unset)"}`; if (e.isRemote) return `cdpUrl: ${e.cdpUrl ? redactCdpUrl(e.cdpUrl) : "(unset)"}`; return `port: ${e.cdpPort ?? "(unset)"}`; } function registerBrowserManageCommands(e, t) { const runManagementRequest = (e, n) => runBrowserCliRequest({ parent: t(e), ...n, timeoutMs: resolveBrowserManagementTimeout(e) }); e.command("status").description("Show browser status").action(async (e, n) => { const r = t(n); await runBrowserCliCommand(async () => { const e = await fetchBrowserManagement(n, r, "/", resolveBrowserProfileQuery(r?.browserProfile)); if (printBrowserJsonResult(r, e)) return; const t = e.detectedExecutablePath ?? e.executablePath; const i = t ? shortenHomePath(t) : "auto"; defaultRuntime.log([ `profile: ${e.profile ?? "openclaw"}`, `enabled: ${e.enabled}`, `running: ${e.running}`, `transport: ${usesChromeMcpTransport(e) ? "chrome-mcp" : e.transport ?? "cdp"}`, ...!usesChromeMcpTransport(e) ? [`cdpPort: ${e.cdpPort ?? "(unset)"}`, `cdpUrl: ${redactCdpUrl(e.cdpUrl ?? `http://127.0.0.1:${e.cdpPort}`)}`] : e.cdpUrl ? [`cdpUrl: ${redactCdpUrl(e.cdpUrl)}`] : e.userDataDir ? [`userDataDir: ${shortenHomePath(e.userDataDir)}`] : [], `browser: ${e.chosenBrowser ?? "unknown"}`, `detectedBrowser: ${e.detectedBrowser ?? "unknown"}`, `detectedPath: ${i}`, `headless: ${e.headless}${e.headlessSource ? ` (${e.headlessSource})` : ""}`, `profileColor: ${e.color}`, ...e.graphics ? [`graphics: ${formatBrowserGraphicsSummary(e.graphics)}`] : [], ...e.detectError ? [`detectError: ${e.detectError}`] : [] ].join("\n")); }); }); e.command("doctor").description("Check browser plugin readiness").option("--deep", "Run a live snapshot check").action(async (e, n) => { const r = t(n); const i = r?.browserProfile; await runBrowserCliCommand(async () => { const t = await runBrowserDoctor(n, r, i, e.deep === true); if (!printBrowserJsonResult(r, t)) defaultRuntime.log(t.checks.map(formatDoctorLine).join("\n")); if (!t.ok) process.exitCode = 1; }); }); for (const [n, r] of [["start", "Start the browser (no-op if already running)"], ["stop", "Stop the browser (best-effort)"]]) { const i = e.command(n).description(r); if (n === "start") i.option("--headless", "Launch a local managed browser headless for this start"); i.action(async (e, r) => { const i = t(r); await runBrowserCliCommand(async () => { await runBrowserToggle(r, i, { path: `/${n}`, query: n === "start" && e.headless ? { headless: true } : void 0 }); }); }); } e.command("reset-profile").description("Reset browser profile (moves it to Trash)").action(async (e, n) => { await runBrowserCliRequest({ parent: t(n), path: "/reset-profile", print: (e) => { if (!e.moved) { defaultRuntime.log(info(`🦞 browser profile already missing.`)); return; } const t = e.to ?? e.from; defaultRuntime.log(info(`🦞 browser profile moved to Trash (${t})`)); } }); }); e.command("tabs").description("List open tabs").action(async (e, t) => { await runManagementRequest(t, { method: "GET", path: "/tabs", json: (e) => ({ tabs: e.tabs ?? [] }), print: (e) => logBrowserTabs(e.tabs ?? []) }); }); const n = e.command("tab").description("Tab shortcuts (index-based)").action(async (e, t) => { await runManagementRequest(t, { path: "/tabs/action", body: { action: "list" }, json: (e) => ({ tabs: e.tabs ?? [] }), print: (e) => logBrowserTabs(e.tabs ?? []) }); }); n.command("new").description("Open a new tab (about:blank)").option("--label <label>", "Assign a friendly tab label").action(async (e, t) => { await runManagementRequest(t, { path: "/tabs/action", body: { action: "new", label: e.label }, successMessage: ({ tab: e }) => e?.tabId ? `opened new tab ${e.tabId}${e.label ? ` (${e.label})` : ""}` : "opened new tab" }); }); n.command("label").description("Assign a friendly label to a tab").argument("<targetId>", BROWSER_TAB_REFERENCE_HELP).argument("<label>", "Friendly label").action(async (e, t, n, r) => { await runManagementRequest(r, { path: "/tabs/action", body: { action: "label", targetId: e, label: t }, successMessage: ({ tab: n }) => `labeled tab ${n?.tabId ?? e} as ${n?.label ?? t}` }); }); for (const [e, r, i] of [[ "select", "Focus tab by index (1-based)", "<index>" ], [ "close", "Close tab by index (1-based); default: first tab", "[index]" ]]) n.command(e).description(r).argument(i, "Tab index (1-based)", parseTabIndex).action(async (n, r, i) => { const a = t(i); if (n !== void 0 && (!Number.isSafeInteger(n) || n < 1)) { const e = "index must be a positive integer"; if (a.json) throw new Error(e); defaultRuntime.error(danger(e)); defaultRuntime.exit(1); return; } await runBrowserCliRequest({ parent: a, path: "/tabs/action", body: { action: e, index: n === void 0 ? void 0 : n - 1 }, timeoutMs: resolveBrowserManagementTimeout(i), successMessage: e === "select" ? `selected tab ${n}` : "closed tab" }); }); e.command("open").description("Open a URL in a new tab").argument("<url>", "URL to open").option("--label <label>", "Assign a friendly tab label").action(async (e, t, n) => { await runManagementRequest(n, { path: "/tabs/open", body: { url: e, ...t.label ? { label: t.label } : {} }, successMessage: (e) => `opened: ${e.url}\n${e.tabId ? `tab: ${e.tabId}\n` : ""}${e.label ? `label: ${e.label}\n` : ""}id: ${e.targetId}` }); }); e.command("focus").description("Focus a tab by tab reference").argument("<targetId>", BROWSER_TAB_REFERENCE_HELP).action(async (e, t, n) => { await runManagementRequest(n, { path: "/tabs/focus", body: { targetId: e }, json: () => ({ ok: true }), successMessage: `focused tab ${e}` }); }); e.command("close").description("Close a tab (tab reference optional)").argument("[targetId]", `${BROWSER_TAB_REFERENCE_HELP} (optional)`).action(async (e, t, n) => { const r = e?.trim(); await runManagementRequest(n, { method: r ? "DELETE" : "POST", path: r ? `/tabs/${encodeURIComponent(r)}` : "/act", body: r ? void 0 : { kind: "close" }, json: () => ({ ok: true }), successMessage: "closed tab" }); }); e.command("profiles").description("List all browser profiles").action(async (e, t) => { await runManagementRequest(t, { profile: null, method: "GET", path: "/profiles", json: (e) => ({ profiles: e.profiles ?? [] }), print: (e) => printBrowserList(e.profiles ?? [], "No profiles configured.", (e) => { const t = e.running ? "running" : "stopped"; const n = e.running ? ` (${e.tabCount} tabs)` : ""; const r = e.isDefault ? " [default]" : ""; const i = formatBrowserConnectionSummary(e); const a = e.isRemote ? " [remote]" : ""; const o = e.driver !== "openclaw" ? ` [${e.driver}]` : ""; return `${e.name}: ${t}${n}${r}${a}${o}\n ${i}, color: ${e.color}`; }) }); }); e.command("system-profiles").description("List Chrome-family profiles available for cookie import").option("--browser <browser>", "System browser (chrome|brave|edge|chromium); omit to list all").action(async (e, t) => { await runManagementRequest(t, { profile: null, method: "GET", path: "/system-profiles", query: e.browser ? { browser: e.browser } : void 0, json: (e) => ({ systemProfiles: e.systemProfiles ?? [] }), print: (e) => printBrowserList(e.systemProfiles ?? [], "No system browser profiles found.", (e) => [ e.browser, e.id, e.name, e.hasCookies ? "yes" : "no" ].map(sanitizeTableCell).join(" "), "browser id name hasCookies") }); }); e.command("import-profile").description("Import cookies from a macOS Chrome-family profile").option("--browser <browser>", "System browser (chrome|brave|edge|chromium)", "chrome").option("--system <profile>", "System profile directory", "Default").option("--into <profile>", "Managed target profile", "imported").option("--domains <domains>", "Comma-separated domain filter").action(async (e, n) => { const r = e.domains?.split(",").map((e) => e.trim()).filter(Boolean); await runBrowserCliRequest({ parent: t(n), profile: null, path: "/profiles/import", body: { browser: e.browser, systemProfile: e.system, into: e.into, domains: r }, timeoutMs: resolveBrowserManagementTimeout(n, 12e4), successMessage: (e) => info(`Imported cookies into "${e.into}": ${e.cookies.imported}/${e.cookies.total} imported, ${e.cookies.failed} failed, ${e.cookies.skipped} skipped; ${e.domains.length} domains`) }); }); e.command("create-profile").description("Create a new browser profile").requiredOption("--name <name>", "Profile name (lowercase, numbers, hyphens)").option("--color <hex>", "Profile color (hex format, e.g. #0066CC)").option("--cdp-url <url>", "DevTools endpoint URL (http/https/ws/wss)").option("--user-data-dir <path>", "User data dir for existing-session Chromium attach").option("--driver <driver>", "Profile driver (openclaw|existing-session). Default: openclaw").action(async (e, n) => { const r = t(n); await runBrowserCliCommand(async () => { if (e.driver !== void 0 && e.driver !== "openclaw" && e.driver !== "existing-session") throw new Error("--driver must be openclaw or existing-session"); const t = await callBrowserRequest(r, { method: "POST", path: "/profiles/create", body: { name: e.name, color: e.color, cdpUrl: e.cdpUrl, userDataDir: e.userDataDir, driver: e.driver === "existing-session" ? "existing-session" : void 0 } }); if (printBrowserJsonResult(r, t)) return; const n = ` ${formatBrowserConnectionSummary(t)}`; defaultRuntime.log(info(`🦞 Created profile "${t.profile}"\n${n}\n color: ${t.color}${t.userDataDir ? `\n userDataDir: ${shortenHomePath(t.userDataDir)}` : ""}${e.driver === "existing-session" ? "\n driver: existing-session" : ""}`)); }); }); e.command("delete-profile").description("Delete a browser profile").requiredOption("--name <name>", "Profile name to delete").action(async (e, n) => { await runBrowserCliRequest({ parent: t(n), profile: null, method: "DELETE", path: `/profiles/${encodeURIComponent(e.name)}`, successMessage: (e) => info(e.deleted ? `🦞 Deleted profile "${e.profile}" (user data removed)` : `🦞 Deleted profile "${e.profile}" (user data removal not confirmed)`) }); }); } //#endregion export { registerBrowserManageCommands };