UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

332 lines (331 loc) • 10.9 kB
import { o as writeRuntimeJson, r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import "./config-CMA-J084.mjs"; import { n as isWSL2Sync } from "./wsl-I_VtUW9p.mjs"; import { t as detectBrowserOpenSupport } from "./browser-open-3VrAKw25.mjs"; import { t as isRemoteEnvironment } from "./remote-env-D-VXpuMv.mjs"; import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs"; import { r as promptYesNo } from "./prompt-C7WCe3kl.mjs"; import { i as formatControlUiSshHint } from "./onboard-helpers-I6fwzX78.mjs"; import { l as gatewayProbeResultSawGateway } from "./gateway-health-auth-diagnostic-XnQcuBP6.mjs"; import { t as openUrlPrivately } from "./browser-handoff-CY4VU7Zl.mjs"; import { i as waitForControlUiDocument, n as issueControlUiBrowserHandoff, r as resolveControlUiHandoffTarget, t as hasVerifiedControlUiLoopbackAlias } from "./control-ui-handoff-LPT0PZQ2.mjs"; import { Buffer } from "node:buffer"; //#region src/infra/clipboard.ts const WSL_CLIPBOARD_ARGV = [ "/bin/sh", "-c", "exec /mnt/c/Windows/System32/clip.exe" ]; const POWERSHELL_CLIPBOARD_ARGV = [ "powershell", "-NoProfile", "-NonInteractive", "-Command", "$encoded = [Console]::In.ReadToEnd(); $bytes = [Convert]::FromBase64String($encoded); Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString($bytes))" ]; async function copyToClipboard(e) { const t = [ ...isWSL2Sync() ? [{ argv: WSL_CLIPBOARD_ARGV, input: e }] : [], { argv: ["pbcopy"], input: e }, { argv: [ "xclip", "-selection", "clipboard" ], input: e }, { argv: ["wl-copy"], input: e }, { argv: ["clip.exe"], input: e }, { argv: POWERSHELL_CLIPBOARD_ARGV, input: Buffer.from(e, "utf8").toString("base64") } ]; for (const e of t) try { const t = await runCommandWithTimeout(e.argv, { timeoutMs: 3e3, input: e.input }); if (t.code === 0 && !t.killed) return true; } catch {} return false; } //#endregion //#region src/commands/dashboard.ts const quietRuntime = { log: () => {}, error: () => {}, exit: () => {} }; const gatewayPasswordJsonKey = ["gateway", "Password"].join(""); async function resolveDashboardTarget() { const e = await readConfigFileSnapshot(); if (e.exists && !e.valid) throw new Error(`OpenClaw config is invalid: ${e.path}. Run \`openclaw doctor --fix\` or \`openclaw config validate\`.`); return await resolveControlUiHandoffTarget({ config: e.valid ? e.sourceConfig ?? e.config : {}, env: process.env }); } function activeProbePortStatus(e) { const t = e.rpc?.url ?? e.gateway?.probeUrl; const n = t ? (() => { try { return Number(new URL(t).port); } catch { return NaN; } })() : NaN; if (Number.isFinite(n) && e.portCli?.port === n) return e.portCli; return e.port; } function gatewayIsReady(e) { return e.rpc?.ok === true || activeProbePortStatus(e)?.status === "busy" && Boolean(e.rpc && gatewayProbeResultSawGateway(e.rpc)); } function gatewayLooksStopped(e) { if (e.rpc && gatewayProbeResultSawGateway(e.rpc)) return false; const t = activeProbePortStatus(e); if (t?.status === "busy") return false; if (t?.status === "free") return true; if (e.service.runtime?.status === "stopped") return true; const n = e.rpc?.error ?? ""; return /\bECONNREFUSED\b|couldn't connect|connection refused/i.test(n); } function gatewayServiceIsInstalled(e) { return Boolean(e.service.command || e.service.loadState.status === "loaded"); } function nativeServiceTargetsGateway(e) { return e.service.targetRole !== "diagnostic-only"; } function readinessFailureReason(e) { if (gatewayLooksStopped(e)) return "Gateway is not running."; return e.rpc?.error ? `Gateway check failed: ${e.rpc.error}` : "Gateway is not healthy."; } function printGatewayNotReadyHints(e, t, n = true) { e.log(t); e.log("Run `openclaw gateway status --deep` for details."); if (!n) { e.log("Use the owning environment or supervisor to start or repair the selected Gateway."); return; } e.log("Run `openclaw gateway start` to start a managed gateway."); e.log("Run `openclaw gateway run` for a foreground gateway."); } async function ensureDashboardTargetReady(e) { const { runtime: t, yes: n, allowRecovery: r } = e; const i = e.target.probeUrl; const gatherStatus = async () => { const { gatherDaemonStatus: e } = await import("./status.gather-zCT6rmfM.mjs"); return e({ rpc: i ? { url: i } : {}, probe: true, requireRpc: false, deep: false }); }; const a = await gatherStatus(); if (gatewayIsReady(a)) return { ready: true, recovered: false }; const o = readinessFailureReason(a); const s = nativeServiceTargetsGateway(a); const c = gatewayLooksStopped(a) && s; const l = c && !gatewayServiceIsInstalled(a); if (!c || l && r === false) { printGatewayNotReadyHints(t, o, c); return { ready: false, reason: o }; } const u = l ? "No background Gateway service was detected for this profile. Install and start one to open the dashboard?" : "The background Gateway service is not running. Start it to open the dashboard?"; const d = r !== false && process.stdin.isTTY; if (!(n || d && await promptYesNo(u, true))) { printGatewayNotReadyHints(t, o); return { ready: false, reason: o, declined: d }; } if (l) { const { runDaemonInstall: e } = await import("./install-Bw7nT2Qa.mjs"); await e({ json: false }); } else { const { runDaemonStart: e } = await import("./lifecycle-z2ThHck5.mjs"); await e({ json: false }); } let f = await gatherStatus(); for (let e = 1; e < 20 && !gatewayIsReady(f); e += 1) { await sleep(500); f = await gatherStatus(); } if (gatewayIsReady(f)) return { ready: true, recovered: true }; const p = readinessFailureReason(f); printGatewayNotReadyHints(t, p, gatewayLooksStopped(f) && nativeServiceTargetsGateway(f)); return { ready: false, reason: p }; } function dashboardJsonFailure(e, t) { const n = formatCliJsonFailure(t); writeRuntimeJson(e, { ...n, reason: t }, 0); e.error(`${n.error.message}\nRun \`openclaw gateway status --deep\` for details, then retry \`openclaw dashboard --json\`.`); e.exit(1); } async function dashboardCommand(e = defaultRuntime, t = {}) { if (t.json) { try { const t = await resolveDashboardTarget(); const n = await ensureDashboardTargetReady({ target: t, runtime: quietRuntime, allowRecovery: false }); if (!n.ready) { dashboardJsonFailure(e, n.reason); return; } if (!await hasVerifiedControlUiLoopbackAlias(t)) { dashboardJsonFailure(e, "Dashboard loopback listener could not be verified as the configured Gateway."); return; } const r = getAsyncWorkSignal(); const i = await waitForControlUiDocument({ url: t.documentUrl, tlsConfig: t.tlsConfig, waitForPending: false, ...r ? { signal: r } : {} }); if (r?.aborted) return; if (!i.ready) { dashboardJsonFailure(e, i.reason); return; } const a = await issueControlUiBrowserHandoff(t.links); writeRuntimeJson(e, { ok: true, url: t.dashboardUrl, httpUrl: t.links.httpUrl, wsUrl: t.links.wsUrl, port: t.port, tokenIncluded: t.includeTokenInUrl, browserUrl: a.browserUrl, browserBootstrapExpiresAtMs: a.expiresAtMs, ...t.gatewayAuthHandoff ? { [gatewayPasswordJsonKey]: t.gatewayAuthHandoff } : {}, ...i.tlsFingerprint ? { tlsFingerprint: i.tlsFingerprint } : {} }, 0); } catch (t) { if (t instanceof ExitError) throw t; dashboardJsonFailure(e, (t instanceof Error ? t.message : String(t)) || "Dashboard target resolution failed."); } return; } let n; try { n = await resolveDashboardTarget(); } catch (t) { e.error(t instanceof Error ? t.message : String(t)); e.exit(1); return; } const r = await ensureDashboardTargetReady({ target: n, runtime: e, yes: t.yes }); if (!r.ready) { if (!r.declined) e.exit(1); return; } const i = r.recovered ? await resolveDashboardTarget() : n; const a = i.probeUrl !== n.probeUrl; if (r.recovered && a) { if (!(await ensureDashboardTargetReady({ target: i, runtime: e, allowRecovery: false })).ready) { e.exit(1); return; } } if (!await hasVerifiedControlUiLoopbackAlias(i)) { e.error("Dashboard loopback listener could not be verified as the configured Gateway; refusing to copy or open an authenticated URL."); e.log("Restart the Gateway, then run `openclaw gateway status --deep` for details."); e.exit(1); return; } const o = getAsyncWorkSignal(); const s = await waitForControlUiDocument({ url: i.documentUrl, tlsConfig: i.tlsConfig, onPending: () => e.log("Control UI assets are preparing; waiting for the dashboard…"), ...o ? { signal: o } : {} }); if (o?.aborted) return; if (!s.ready) { e.error(s.reason); e.log("Run `openclaw gateway status --deep` for details."); e.exit(1); return; } let c; try { c = (await issueControlUiBrowserHandoff(i.links)).browserUrl; } catch (t) { e.error(`Could not create a one-time browser pairing link: ${t instanceof Error ? t.message : String(t)}`); e.log("Run `openclaw doctor`, then retry `openclaw dashboard`."); e.exit(1); return; } const { port: l, basePath: u, links: d, includeTokenInUrl: f, tlsConfig: p } = i; e.log(`Dashboard URL: ${d.httpUrl}`); e.log("One-time browser pairing included in browser/clipboard URL."); const m = await copyToClipboard(c).catch(() => false); e.log(m ? "Copied to clipboard." : "Copy to clipboard unavailable."); let h = false; let g; if (!t.noOpen) { const e = await detectBrowserOpenSupport(); if (e.ok) h = await openUrlPrivately(c); if (!e.ok || !h && !m && isRemoteEnvironment()) g = formatControlUiSshHint({ port: l, basePath: u, tlsEnabled: p?.enabled === true }); else g = h ? void 0 : m ? "Browser launch failed. Open the one-time pairing URL copied to clipboard." : "Browser launch failed. Open the Dashboard URL above manually."; } else g = m ? "Browser launch disabled (--no-open). One-time browser pairing URL copied to clipboard." : "Browser launch disabled (--no-open). Use the URL above."; const _ = !m && !h; const v = t.noOpen === true && _; if (h) e.log("Opened in your browser. Keep that tab to control OpenClaw."); else if (g && !v) e.log(g); if (_) e.log(f ? "Token auto-auth not delivered. Append your gateway token (from OPENCLAW_GATEWAY_TOKEN or gateway.auth.token) as a URL fragment with key `token` to authenticate." : "One-time pairing URL not delivered. Run `openclaw dashboard --json` and open its `browserUrl` within ten minutes."); } //#endregion export { dashboardCommand };