UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,030 lines (1,029 loc) • 39.5 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "../string-coerce-CCIiB4H7.mjs"; import { l as isValueToken, o as getCommandPositionalsWithRootOptions, t as FLAG_TERMINATOR, u as rewriteUpdateFlagArgv } from "../cli-root-options-xlQx6o4R.mjs"; import { _ as getSubCliCommandMetadata, f as isSimpleCommandHelpInvocation, g as normalizeRootNoColorArgv, h as normalizeRootLogLevelArgv, m as normalizeRootHelpTargetArgv, p as normalizeGeneratedHelpCommandArgv, y as getCoreCliCommandDescriptors } from "../argv-CbnKpH-r.mjs"; import { a as resolveGatewayRunPreBootstrapOptions, i as resolveGatewayCommandPath, n as consumeGatewayRunOptionToken, r as isGatewayRunInvocationArgv, t as consumeGatewayFastPathRootOptionToken } from "../gateway-run-argv-CMDDyZ3j.mjs"; import { t as resolveCliArgvInvocation } from "../argv-invocation-C9SmXUsh.mjs"; import { n as isTruthyEnvValue, r as normalizeEnv } from "../env-HehwidXj.mjs"; import { n as tryProcessCwd } from "../safe-cwd-CZqaxroH.mjs"; import { n as parseCliProfileArgs, t as applyCliProfileEnv } from "../profile-TAKKDhQt.mjs"; import { n as tryRunUpdateAdmissionBeforeStartup } from "../run-main-update-admission-2cBv_sw3.mjs"; import { i as createGatewayDispatchStartupTrace, n as configureGatewayStartupTraceConsoleFormatting, t as configureCliStartupDiagnostics } from "../startup-trace-DWZsuODq.mjs"; import { t as normalizeWindowsArgv } from "../windows-argv-Co4garuq.mjs"; import { r as truncateUtf16Safe } from "../utf16-slice-CuDyEXgS.mjs"; import { n as parseCliContainerArgs, t as maybeRunCliInContainer } from "../container-target-Gm4i9O54.mjs"; import { t as tryOutputPrecomputedCommandHelp } from "../precomputed-help-ENbS88WM.mjs"; import { n as sanitizeTerminalText } from "../safe-text-C80HAQ2e.mjs"; import { r as resolveStateDir } from "../state-dir-DiG0gXzD.mjs"; import { b as resolveGatewayPort } from "../paths-DAcAg5aV.mjs"; import { a as getPluginCache } from "../plugin-cache-B_eRuqTM.mjs"; import { o as registerSignalExitBarrier, t as exitAfterSignalExitBarriers } from "../signal-exit-barrier-BOGtFHQL.mjs"; import { n as withGatewayServiceInstallation } from "../gateway-service-installation-context-CHlb7Eod.mjs"; import { i as formatInvalidConfigDetails, r as createInvalidConfigError } from "../io.invalid-config-DK-BYZ4Y.mjs"; import { t as normalizeWebSocketProtocol } from "../websocket-protocol-Y-CbxPDf.mjs"; import { s as isLoopbackHost, u as isSecureWebSocketUrl } from "../net-BgRayX-P.mjs"; import { t as PROXY_ENV_KEYS } from "../proxy-env-CZP0dXDG.mjs"; import { n as withDeferredDebugProxyCapture } from "../runtime-deferral-BEf6mqc4.mjs"; import { a as withConsoleLogsRoutedToStderrForJson, i as withConsoleLogsRoutedToStderr, n as hasJsonOutputFlag, r as isJsonOutputModeActive } from "../json-output-mode-DSme4Xvd.mjs"; import { r as runCliDisposer, t as closeCliResources } from "../runtime-cleanup-BKu6ZJ6-.mjs"; import { n as requestExitAfterOneShotOutput } from "../one-shot-exit-DkbGSQD5.mjs"; import { r as shouldSkipPluginCommandRegistration, t as isReservedNonPluginCommandRoot } from "../command-registration-policy-DvIjiRvn.mjs"; import { n as resolveCliNetworkProxyPolicy, t as resolveCliCommandPathPolicy } from "../command-path-policy-CLmNyiTh.mjs"; import { t as resolveCliStartupPolicy } from "../command-startup-policy-z6i1gNVg.mjs"; import { t as tryRunGatewayServiceUpdateCapabilityProbe } from "../update-capability-mwfwoB4i.mjs"; import { n as shouldStartLocalOnboarding } from "../fresh-install-config-6qQ4_7BH.mjs"; import { t as getSubCliEntriesCore } from "../subcli-descriptors-BW4TGnMG.mjs"; import { t as withCliPluginInvocation } from "../run-main-plugin-cache-BBtqqzcy.mjs"; import { existsSync } from "node:fs"; import process$1 from "node:process"; import path from "node:path"; //#region src/cli/run-main-options.ts function findCommandOption(e, t) { const n = t.indexOf("="); const r = n === -1 ? t : t.slice(0, n); return e.options.find((e) => e.long === r || e.short === r); } function findSubcommand(e, t) { return e.commands.find((e) => e.name() === t || e.aliases().includes(t)); } function resolveRootOptionRole(e, t, n) { let r = e; let i = false; for (let e = 0; e < n; e += 1) { const a = t[e]; if (!a || a === "--") return "root"; if (i) { i = false; continue; } if (a.startsWith("-")) { const o = findCommandOption(r, a); if (!o && e === n - 1 && !a.includes("=")) return "value"; i = o !== void 0 && !a.includes("=") && (o.required || o.optional && isValueToken(t[e + 1])); continue; } r = findSubcommand(r, a) ?? r; } if (i) return "value"; const a = t[n]; return r !== e && a !== void 0 && findCommandOption(r, a) !== void 0 ? "command" : "root"; } function normalizeRootNoColorArgvForProgram(e, t) { return normalizeRootNoColorArgv(e, { shouldPreserveNoColor: ({ remainingArgs: e, noColorIndex: n }) => resolveRootOptionRole(t, e, n) === "value" }); } //#endregion //#region src/cli/run-main-policy.ts const TUI_REQUIRES_TTY = "OpenClaw TUI needs an interactive TTY. Use `openclaw agent --local ...` for automation."; const ROOT_HELP_ALIASES = /* @__PURE__ */ new Set(["tools", "help"]); const SETUP_ONBOARD_CONFIGURE_HELP_COMMANDS = /* @__PURE__ */ new Set([ "setup", "onboard", "configure" ]); const BARE_PARENT_DEFAULT_HELP_COMMANDS = /* @__PURE__ */ new Set([...getCoreCliCommandDescriptors().filter((e) => e.parentDefaultHelp).map((e) => e.name), ...getSubCliCommandMetadata().filter((e) => e.parentDefaultHelp).map((e) => e.name)]); function shouldLoadCliDotEnv(e) { const t = tryProcessCwd(); if (t && existsSync(path.join(t, ".env"))) return true; return e && existsSync(path.join(resolveStateDir(), ".env")); } function isGatewayRunFastPathArgv(e) { if (resolveCliArgvInvocation(e).hasHelpOrVersion) return false; const t = e.slice(2); let n = false; let r = false; for (let e = 0; e < t.length; e += 1) { const i = t[e]; if (!i || i === "--") return false; const a = consumeGatewayFastPathRootOptionToken(t, e); if (a > 0) { e += a - 1; continue; } if (!n) { if (i !== "gateway") return false; n = true; continue; } const o = consumeGatewayRunOptionToken(t, e); if (o > 0) { e += o - 1; continue; } if (!r && i === "run") { r = true; continue; } return false; } return n; } function isRemoteAgentDispatchInvocation(e, t) { return t === "agent" && !e.includes("--local"); } function isAgentExecInvocation(e) { return e[0] === "agent" && e[1] === "exec"; } function isBareParentDefaultHelpArgv(e) { const t = resolveCliArgvInvocation(e); const [n, r] = t.commandPath; return !t.hasHelpOrVersion && n !== void 0 && r === void 0 ? BARE_PARENT_DEFAULT_HELP_COMMANDS.has(n) : false; } function shouldEnsureCliPath(e) { const t = resolveCliArgvInvocation(e); if (t.hasHelpOrVersion || shouldHandleBareRoot(e) || isBareParentDefaultHelpArgv(e)) return false; return resolveCliCommandPathPolicy(t.commandPath).ensureCliPath; } function shouldUseRootHelpFastPath(e, t = process.env) { const n = resolveCliArgvInvocation(e); return t.OPENCLAW_DISABLE_CLI_STARTUP_HELP_FAST_PATH !== "1" && (n.isRootHelpInvocation || n.commandPath.length === 1 && ROOT_HELP_ALIASES.has(n.commandPath[0] ?? "") && n.hasHelpOrVersion); } function shouldUseSetupOnboardConfigureHelpFastPath(e, t = process.env) { if (t.OPENCLAW_DISABLE_CLI_STARTUP_HELP_FAST_PATH === "1") return false; return isSimpleCommandHelpInvocation(e, SETUP_ONBOARD_CONFIGURE_HELP_COMMANDS); } function shouldHandleBareRoot(e) { return getCommandPositionalsWithRootOptions(e, { commandPath: [], maxPositionals: 1, mode: "command-path" })?.length === 0; } function shouldStartProxyForCli(e) { const t = rewriteUpdateFlagArgv(e); const n = resolveCliArgvInvocation(t); const [r] = n.commandPath; if (n.hasHelpOrVersion || !r) return false; if (isBareParentDefaultHelpArgv(t)) return false; return resolveCliNetworkProxyPolicy(t) === "default"; } /** Bare `openclaw` has no command path, so its launch target decides the TTY rule and proxy routing. */ function resolveBareRootLaunchPolicy(e) { if (e.kind === "remote-gateway-inference") return { ttyMessage: "Remote Gateway inference setup needs an interactive TTY. Re-run `openclaw` in a terminal connected to this Gateway.", startProxy: false }; if (e.kind === "onboarding") return { ttyMessage: e.classic ? "OpenClaw config is invalid. Run `openclaw doctor --fix` before onboarding." : "Onboarding needs an interactive TTY. Use `openclaw onboard --non-interactive --accept-risk ...` for automation.", startProxy: true }; return { ttyMessage: TUI_REQUIRES_TTY, startProxy: e.local }; } function isDebugProxyCaptureEnvEnabled(e = process.env) { return isTruthyEnvValue(e.OPENCLAW_DEBUG_PROXY_ENABLED) || isTruthyEnvValue(e.OPENCLAW_DEBUG_PROXY_REQUIRE); } function shouldBootstrapCliProxyBeforeFastPath(e = process.env) { if (isDebugProxyCaptureEnvEnabled(e)) return true; return PROXY_ENV_KEYS.some((t) => normalizeOptionalString(e[t]) !== void 0); } function formatExcludedPluginCommand(e, t) { return t === e ? `The \`openclaw ${e}\` command is unavailable because \`plugins.allow\` excludes "${e}". Add "${e}" to \`plugins.allow\` if you want that bundled plugin CLI surface.` : `"${e}" is not a plugin; it is a command provided by the "${t}" plugin. Add "${t}" to \`plugins.allow\` instead of "${e}".`; } function resolveMissingPluginCommandMessage(e, t, n) { const r = normalizeLowercaseStringOrEmpty(e); if (!r) return null; const i = Array.isArray(t?.plugins?.allow) && t.plugins.allow.length > 0 ? t.plugins.allow.filter((e) => typeof e === "string").map((e) => normalizeOptionalLowercaseString(e)).filter(Boolean) : []; const a = n?.resolveCommandAliasOwner?.({ command: r, config: t }); const o = a?.pluginId; if (o) { if (i.length > 0 && !i.includes(o)) return formatExcludedPluginCommand(r, o); if (t?.plugins?.entries?.[o]?.enabled === false) return `The \`openclaw ${r}\` command is unavailable because \`plugins.entries.${o}.enabled=false\`. Re-enable that entry if you want the bundled plugin command surface.`; if (a.kind !== "runtime-slash" && a.enabledByDefault !== true && t?.plugins?.entries?.[o]?.enabled !== true) return `The \`openclaw ${r}\` command is provided by the "${o}" plugin, but that bundled plugin is disabled by default. Run \`openclaw plugins enable ${o}\` to enable that CLI surface.`; if (a.kind === "runtime-slash") return `"${r}" is a runtime slash command (/${r}), not a CLI command. It is provided by the "${o}" plugin. ${a.cliCommand ? `Use \`openclaw ${a.cliCommand}\` for related CLI operations, or ` : "Use "}\`/${r}\` in a chat session.`; } if (isReservedNonPluginCommandRoot(r)) return null; const s = n?.resolveToolOwner?.({ toolName: r, config: t }); if (s) { if (t?.plugins?.entries?.[s.pluginId]?.enabled !== false && (i.length === 0 || i.includes(s.pluginId))) { if (s.availability === "manifest-only") return `"${r}" may be provided by the "${s.pluginId}" plugin as an agent tool, not a CLI subcommand. Run \`openclaw --help\` to see available CLI subcommands.`; return `"${r}" is an agent tool available from the "${s.pluginId}" plugin, not a CLI subcommand. Use it from an agent turn (model tool-use), not the CLI. Run \`openclaw --help\` to see available CLI subcommands.`; } } if (i.length > 0 && !i.includes(r)) { if (o && i.includes(o)) return null; const e = n?.resolveCliCommandSurfaceOwner?.({ command: r, config: t }); const a = normalizeOptionalLowercaseString(e); if (!a) return null; if (i.includes(a)) return null; return formatExcludedPluginCommand(r, a); } if (t?.plugins?.entries?.[r]?.enabled === false) return `The \`openclaw ${r}\` command is unavailable because \`plugins.entries.${r}.enabled=false\`. Re-enable that entry if you want the bundled plugin CLI surface.`; return null; } //#endregion //#region src/cli/run-main-proxy.ts async function ensureCliEnvProxyDispatcher() { try { const { hasEnvHttpProxyAgentConfigured: e } = await import("../proxy-env-D3oj3wbx.mjs"); if (!e()) return; const { ensureGlobalUndiciEnvProxyDispatcher: t } = await import("../undici-global-dispatcher-qyMDs7M4.mjs"); t(); } catch {} } async function bootstrapCliProxyCaptureAndDispatcher(e, t) { if (isDebugProxyCaptureEnvEnabled()) { const [{ initializeDebugProxyCaptureAsync: t }, { maybeWarnAboutDebugProxyCoverage: n }] = await e.measure("proxy-imports", () => Promise.all([import("../runtime-B5ujXFJ2.mjs"), import("../coverage-DigCzHe2.mjs")])); await t("cli"); n(void 0, (e) => console.warn(e)); } if (t) await e.measure("proxy-dispatcher", () => ensureCliEnvProxyDispatcher()); } //#endregion //#region src/cli/run-main.ts const UNKNOWN_COMMAND_DISPLAY_LIMIT = 128; function requireInteractiveTty(e) { if (process$1.stdin.isTTY && process$1.stdout.isTTY) return true; console.error(e); process$1.exitCode = 1; return false; } async function tryRunGatewayRunFastPath(e, t) { if (!isGatewayRunFastPathArgv(e)) return false; const [{ Command: n }, { addGatewayRunCommand: r, bootstrapGatewayRun: i }, { VERSION: a }, { emitCliBanner: o }, { defaultRuntime: s }] = await t.measure("gateway-run-imports", () => Promise.all([ import("commander"), import("../run-command-B8z6Egp2.mjs"), import("../version-Cu2zLIq0.mjs"), import("../banner-DRm5GEgU.mjs"), import("../runtime-PcIG_sHE.mjs") ])); const c = resolveGatewayCommandPath(e) ?? ["gateway"]; const l = resolveCliStartupPolicy({ argv: e, commandPath: c, jsonOutputMode: hasJsonOutputFlag(e) }); if (!l.hideBanner) o(a, { argv: e }); const u = new n(); u.name("openclaw"); u.enablePositionalOptions(); u.option("--no-color", "Disable ANSI colors", false); u.exitOverride((e) => { process$1.exitCode = typeof e.exitCode === "number" ? e.exitCode : 1; throw e; }); const beforeRun = (e) => i({ opts: e, runtime: s, commandPath: c, startupPolicy: l, startupTrace: t }); r(r(u.command("gateway").description("Run, inspect, and query the WebSocket Gateway"), { beforeRun }).command("run").description("Run the WebSocket Gateway (foreground)"), { beforeRun }); const d = normalizeRootNoColorArgvForProgram(e, u); try { await t.measure("gateway-run-parse", () => u.parseAsync(d), { timeline: false }); } catch (e) { if (!isCommanderParseExit(e)) throw e; process$1.exitCode = e.exitCode; } return true; } async function resolveBareRootLaunchTarget() { const { readConfigSnapshotForEngineSelection: e } = await import("../config-preflight-snapshot-DXY8QhxC.mjs"); await e(); const { readConfigFileSnapshot: t } = await import("../config/config.js"); const n = await t(); if (await shouldStartLocalOnboarding(n)) return { kind: "onboarding" }; if (!n.valid) return { kind: "onboarding", classic: true }; return resolveConfiguredTuiLaunchTarget(n.config ?? n.sourceConfig, { hasConfiguredGateway: n.sourceConfig.gateway !== void 0 }); } async function resolveConfiguredTuiLaunchTarget(e, t) { const n = await resolveReachableGateway(e, t); if (n.kind !== "unreachable") { const { url: t, remote: r, ...i } = n.gateway; const a = { config: e, gatewayUrl: t, ...r ? { configuredRemote: true } : {}, ...i }; if (n.kind !== "missing-configured-model") return { kind: "tui", local: false, ...a }; return r ? { kind: "remote-gateway-inference", target: a } : { kind: "onboarding" }; } const { listAgentIds: r, resolveAgentEffectiveModelPrimary: i } = await import("../agent-scope-7S_X4gNj.mjs"); if (!r(e).some((t) => i(e, t))) return { kind: "onboarding" }; return { kind: "tui", local: true }; } function toReachableGateway(e, t) { return { url: e.url, remote: e.scope === "remote", ...t.token ? { token: t.token } : {}, ...t.password ? { password: t.password } : {}, ...e.tlsFingerprint ? { tlsFingerprint: e.tlsFingerprint } : {} }; } async function resolveReachableGateway(e, t) { const { targets: n, auth: r } = await resolveGatewayProbePlan(e); if (n.length === 0) return { kind: "unreachable" }; const { probeGatewayConfiguredModel: i } = await import("../onboard-helpers-Cy-Vj-Pl.mjs"); let a; let o; let s; for (const c of n) { if (!isSafeGatewayProbeTarget(c)) continue; const n = toReachableGateway(c, r); if (t.hasConfiguredGateway && !s) s = n; const { remote: l, ...u } = n; const d = await i({ ...u, ...l ? { config: e, originScopedDeviceAuth: true, configuredRemote: true } : {}, ...e.gateway?.remote?.edgeAuth ? { config: e } : {}, ...c.preauthHandshakeTimeoutMs ? { preauthHandshakeTimeoutMs: c.preauthHandshakeTimeoutMs } : {} }); if (d === "configured") return { kind: "configured", gateway: n }; if (d === "missing-configured-model") { a ??= n; continue; } if (d === "reachable-unverified" && !o) o = n; } if (a) return { kind: "missing-configured-model", gateway: a }; if (o) return { kind: "reachable-unverified", gateway: o }; if (s) return { kind: "configured-unreachable", gateway: s }; return { kind: "unreachable" }; } async function resolveGatewayProbePlan(e) { const t = normalizeOptionalString(e.gateway?.remote?.url); if (normalizeOptionalString(e.gateway?.mode) === "remote" && t) try { const { resolveGatewayClientBootstrap: t } = await import("../client-bootstrap-DnfXdX1c.mjs"); const n = await t({ config: e, authPolicy: "probe", modeOverride: "remote", ignoreEnvUrlOverride: true }); return { targets: [{ url: n.url, scope: "remote", ...n.tlsFingerprint ? { tlsFingerprint: n.tlsFingerprint } : {} }], auth: n.auth }; } catch { return { targets: [], auth: {} }; } return resolveLocalGatewayProbeTargets(e); } function isSafeGatewayProbeTarget(e) { if (e.scope === "remote") return isSafeRemoteGatewayProbeUrl(e.url); return isSecureWebSocketUrl(e.url, { allowPrivateWs: process$1.env.OPENCLAW_ALLOW_INSECURE_PRIVATE_WS === "1" }); } function isSafeRemoteGatewayProbeUrl(e) { let t; try { t = new URL(e); } catch { return false; } const n = normalizeWebSocketProtocol(t.protocol); if (n === "wss:") return true; if (n !== "ws:") return false; if (isLoopbackHost(t.hostname.replace(/\.+$/, ""))) return true; return process$1.env.OPENCLAW_ALLOW_INSECURE_PRIVATE_WS === "1" && isSecureWebSocketUrl(e, { allowPrivateWs: true }); } async function resolveLocalGatewayProbeTargets(e) { const [{ resolveControlUiLinks: t }, { resolveGatewayClientBootstrap: n }, { readActiveGatewayLockPort: r }] = await Promise.all([ import("../control-ui-links-BBllpkA0.mjs"), import("../client-bootstrap-DnfXdX1c.mjs"), import("../gateway-lock-C8DzJkpV.mjs") ]); const i = e.gateway; const a = resolveGatewayPort(e); const o = (Boolean(normalizeOptionalString(process$1.env.OPENCLAW_GATEWAY_PORT)) ? void 0 : await r()) ?? a; const s = await n({ config: e, authPolicy: "probe", modeOverride: "local", ignoreEnvUrlOverride: true, localPortOverride: o }); const c = { port: o, basePath: i?.controlUi?.basePath, tlsEnabled: i?.tls?.enabled === true }; const l = { ...s.tlsFingerprint ? { tlsFingerprint: s.tlsFingerprint } : {}, ...s.preauthHandshakeTimeoutMs ? { preauthHandshakeTimeoutMs: s.preauthHandshakeTimeoutMs } : {} }; const u = { ...l, url: s.url, scope: "local-loopback" }; const d = i?.bind; if (d !== "tailnet" && d !== "custom") return { targets: [u], auth: s.auth }; const f = t({ ...c, bind: d, customBindHost: i?.customBindHost }); return { targets: f.wsUrl === s.url ? [u] : [u, { ...l, url: f.wsUrl, scope: "local-configured" }], auth: s.auth }; } function pauseNonTtyStdinForCliExit() { const e = process$1.stdin; if (e.isTTY) return; try { e.pause(); } catch {} } function isCommanderParseExit(e) { if (!e || typeof e !== "object") return false; const t = e; return typeof t.exitCode === "number" && Number.isInteger(t.exitCode) && typeof t.code === "string" && t.code.startsWith("commander."); } function findBuiltInCommandDescriptor(e) { return [...getCoreCliCommandDescriptors(), ...getSubCliEntriesCore()].find((t) => t.name === e); } function resolvesMachineOutput(e, t) { return e.machineOutput?.({ argv: t, stdoutIsTTY: process$1.stdout.isTTY || false }) ?? false; } function resolveBuiltInMachineOutput({ argv: e, primary: t }) { const n = t ? findBuiltInCommandDescriptor(t) : void 0; return n ? resolvesMachineOutput(n, e) : false; } async function resolvePluginMachineOutput(e) { const { primary: t } = resolveCliArgvInvocation(e.argv); if (!t || findBuiltInCommandDescriptor(t)) return false; const { loadPluginCliDescriptors: n } = await import("../cli-registry-loader-CmHrcIQ8.mjs"); const r = (await n({ cfg: e.config, env: process$1.env, primaryCommand: t, session: e.session })).find((e) => e.name === t); const resolveOutput = () => r ? resolvesMachineOutput(r, e.argv) : false; return e.session ? e.session.withCache(resolveOutput) : resolveOutput(); } async function isPluginCliRoot(e) { try { const { resolvePluginCliRootOwnerIds: t } = await import("../cli-registry-loader-CmHrcIQ8.mjs"); const n = await t({ cfg: e.config, env: process$1.env, primaryCommand: e.primary, session: e.session }); return n === null ? null : n.length > 0; } catch { return null; } } function createAllowlistAgnosticCliLookupConfig(e) { if (!Array.isArray(e.plugins?.allow) || e.plugins.allow.length === 0) return e; return { ...e, plugins: { ...e.plugins, allow: [] } }; } async function resolveCliCommandSurfaceOwner(e) { const { resolveManifestCliCommandSurfaceOwner: t } = await import("../manifest-command-aliases.runtime-DSmzeiIu.mjs"); const n = t({ command: e.primary, config: e.config }); if (n) return n; try { const { resolvePluginCliRootOwnerIds: t } = await import("../cli-registry-loader-CmHrcIQ8.mjs"); return (await t({ cfg: createAllowlistAgnosticCliLookupConfig(e.config), env: process$1.env, primaryCommand: e.primary }))?.[0]; } catch { return; } } function resolveUnownedCliPrimaryCandidate(e) { const { primary: t } = resolveCliArgvInvocation(rewriteUpdateFlagArgv(e)); if (!t || t === "help" || isReservedNonPluginCommandRoot(t) || findBuiltInCommandDescriptor(t)) return null; return t; } async function assertCliPrimaryOwned(e) { const t = resolveUnownedCliPrimaryCandidate(e.argv); if (!t) return; if (await isPluginCliRoot({ primary: t, config: e.config, session: e.session }) !== false) return; const n = await resolveExpectedPluginPolicyError({ primary: t, config: e.config }); if (n) throw n; const r = sanitizeTerminalText(t); const i = r.length <= UNKNOWN_COMMAND_DISPLAY_LIMIT ? r : `${truncateUtf16Safe(r, 127)}…`; const { createCliUnknownCommandError: a } = await import("../error-output-CKaItDaC.mjs"); throw a(i, { argv: e.argv, ...i === t ? {} : { commandNames: [] } }); } async function resolveExpectedPluginPolicyError(e) { const { resolveManifestCommandAliasOwner: t, resolveManifestToolOwner: n } = await import("../manifest-command-aliases.runtime-DSmzeiIu.mjs"); const r = await resolveCliCommandSurfaceOwner(e); const i = resolveMissingPluginCommandMessage(e.primary, e.config, { resolveCommandAliasOwner: t, resolveToolOwner: n, resolveCliCommandSurfaceOwner: () => r }); if (!i) return; const { ExpectedCliError: a } = await import("../failure-output-DKniP608.mjs"); return new a({ message: i, humanOutput: i, machineOutput: i }); } async function runCli(e = process$1.argv, t = {}) { const n = t.runtimeRecoveryEnv ?? { ...process$1.env }; const r = normalizeWindowsArgv(e); const i = resolveCliArgvInvocation(r); if (await tryRunUpdateAdmissionBeforeStartup(i)) return; const a = resolveBuiltInMachineOutput(i); const invoke = () => withConsoleLogsRoutedToStderrForJson(r, () => { const run = async (e) => { const o = {}; let s; try { const invokeCommand = () => withGatewayServiceInstallation(o, () => runCliWithPreparedOutputMode(r, { ...t, runtimeRecoveryEnv: n, builtInMachineOutput: a, harnessCleanup: e, serviceInstallation: o, onGatewayResourcesSettled: (e) => { s = e; } })); const i = e?.pluginResources; return await (i ? i.run(invokeCommand) : invokeCommand()); } catch (e) { if (isGatewayRunInvocationArgv(r) && !i.hasHelpOrVersion) { const { handleGatewayStartupMaintenance: t } = await import("../startup-maintenance-BWhzokOu.mjs"); if (await t(e)) return; } throw e; } finally { const t = e?.pluginResources; try { if (s === void 0) await closeCliResources(e); } finally { if (t) await runCliDisposer("plugin-registration-resources", () => t.release()); pauseNonTtyStdinForCliExit(); } } }; const e = isGatewayRunInvocationArgv(r); return withCliPluginInvocation(e, run); }, { machineOutput: a, restoreChanges: true, retainRoutingUntilProcessExit: t.retainConsoleRoutingUntilProcessExit }); const o = resolveCliArgvInvocation(rewriteUpdateFlagArgv(r)); return !o.hasHelpOrVersion && [ "update", "doctor", "proxy" ].includes(o.primary ?? "") ? await withDeferredDebugProxyCapture(invoke) : await invoke(); } async function runCliWithPreparedOutputMode(e, t) { const n = createGatewayDispatchStartupTrace(e, "cli.main"); const r = parseCliProfileArgs(e); if (r.ok && r.profile) applyCliProfileEnv({ profile: r.profile }); const i = resolveCliArgvInvocation(e); let a = false; const installConsoleCapture = async () => { if (a) return; const { enableConsoleCapture: e } = await import("../console-DzWOOvYF.mjs"); e(); a = true; }; const configureStartupTraces = async () => { await configureGatewayStartupTraceConsoleFormatting(n); if (t.additionalStartupTrace) await configureGatewayStartupTraceConsoleFormatting(t.additionalStartupTrace); }; const o = parseCliContainerArgs(e); if (!o.ok) { await installConsoleCapture(); await configureStartupTraces(); throw new Error(o.error); } const s = parseCliProfileArgs(o.argv); const c = o.container ?? normalizeOptionalString(process$1.env.OPENCLAW_CONTAINER) ?? null; const l = !s.ok || c !== null && s.profile !== null; if (!i.hasHelpOrVersion || c !== null || l) await installConsoleCapture(); if (!s.ok) { await configureStartupTraces(); throw new Error(s.error); } if (s.profile) applyCliProfileEnv({ profile: s.profile }); if (c && s.profile) { await configureStartupTraces(); throw new Error("--container cannot be combined with --profile/--dev"); } let u; try { u = maybeRunCliInContainer(e); } catch (e) { await configureStartupTraces(); throw e; } if (u.handled) { await configureStartupTraces(); if (u.exitCode !== 0) process$1.exitCode = u.exitCode; return; } const d = rewriteUpdateFlagArgv(normalizeRootHelpTargetArgv(normalizeRootNoColorArgv(s.argv))); const f = resolveCliArgvInvocation(d); const p = f.hasHelpOrVersion; const m = isGatewayRunInvocationArgv(d); const h = f.commandPath[0] === "database"; const g = !m; n.mark("argv"); const { assertSupportedRuntime: _, isCurrentRuntimeSupported: v } = await import("../runtime-guard-Cecap7VY.mjs"); await _(void 0, void 0, d, true, t.runtimeRecoveryEnv); if (await tryRunGatewayServiceUpdateCapabilityProbe(d)) return; if (!p && (m || f.primary === "worker" || f.primary === "node" && (f.commandPath[1] === "run" || f.commandPath[1] === "worker"))) { const { initializeSqliteRuntime: e } = await import("../sqlite-runtime-initialize-DOIoH5sx.mjs"); await e(); } if (!p && !h && !isAgentExecInvocation(f.commandPath) && shouldLoadCliDotEnv(g)) await n.measure("dotenv", async () => { if (isRemoteAgentDispatchInvocation(d, f.primary)) { const { loadGatewayDispatchCliDotEnv: e } = await import("../gateway-dispatch-dotenv-B1rNiKgh.mjs"); await e(); } else { const { loadCliDotEnv: e } = await import("../dotenv-BqC7eRgR.mjs"); e({ loadGlobalEnv: g }); } }); if (!p) { const { inspectCliGatewayServiceInstallation: e } = await import("../run-main-service-installation-BoGu5pT3.mjs"); t.serviceInstallation.installation = await e(process$1.env); } const { prepareCliDatabaseEngine: y } = await import("../database-engine-selection-CKQdgAU6.mjs"); if (await n.measure("database-engine-selection", () => y(d))) return; let b; if (!p && f.primary === "doctor") { const { prepareDoctorCliStartup: e } = await import("../run-main-doctor-startup-B_bumVdd.mjs"); const n = await e(d, { json: t.builtInMachineOutput }); if (n.handled) return; b = n.preflight; } await configureStartupTraces(); if (!p && m) await n.measure("gateway-run-select-environment", async () => { const [{ selectGatewayRunEnvironment: e }, { defaultRuntime: t }] = await n.measure("gateway-run-select-environment-imports", () => Promise.all([import("../pre-bootstrap-BvgO1zPk.mjs"), import("../runtime-PcIG_sHE.mjs")])); await e({ opts: resolveGatewayRunPreBootstrapOptions(d) ?? {}, runtime: t }); }); normalizeEnv(); if (shouldEnsureCliPath(d)) { const { ensureOpenClawCliOnPath: e } = await import("../path-env-CLu8_afo.mjs"); e(); } const x = d.slice(2).some((e) => e.includes("://")); const S = !p && x ? (await import("../session-ref-DcyWYW82.mjs")).parseBareSessionInvocation(d) : null; let C = null; let w; let T = []; let E = null; let D = null; let O; const getPluginCliSession = async () => { O ??= (await import("../cli-registry-loader-CmHrcIQ8.mjs")).createPluginCliLoadSession(getPluginCache()); return O; }; const k = m; const A = resolveCliStartupPolicy({ argv: d, commandPath: f.commandPath, jsonOutputMode: t.builtInMachineOutput || hasJsonOutputFlag(d), env: process$1.env }); const j = !await v() || f.primary === "update" || f.primary === "doctor"; const readBestEffortCliConfig = async () => { if (!D) D = import("../io-DeTUDO0h.mjs").then(async (e) => { if (j) return e.readSourceConfigBestEffort(); const t = { observe: false, ...k ? { isolateEnv: true } : {}, ...A.validateConfigOnly || m ? { pluginValidation: "core-only" } : { skipPluginValidation: true } }; if (!resolveUnownedCliPrimaryCandidate(d)) return e.readBestEffortConfig(t); const n = await (await getPluginCliSession()).readConfig(() => e.readBestEffortConfigSnapshot(t)); if (n.configDiagnostics) { const { path: e, issues: t } = n.configDiagnostics; throw createInvalidConfigError(e, formatInvalidConfigDetails(t)); } return n.config; }); return await D; }; const uninstallProxySignalHandlers = () => { for (const [e, t] of T) process$1.off(e, t); T = []; }; const stopStartedProxy = () => { if (w) return w; E?.(); E = null; uninstallProxySignalHandlers(); const e = C; C = null; const stop = async () => { if (e) { const { stopProxy: t } = await import("../proxy-lifecycle-DlzTKbbH.mjs"); await t(e); } }; const n = t.harnessCleanup?.pluginResources; w = Promise.resolve().then(() => n ? n.runCleanup(stop) : stop()); return w; }; const killStartedProxy = () => { const e = C; C = null; e?.kill("SIGTERM"); }; const installProxySignalHandlers = () => { if (!C || T.length > 0) return; E = registerSignalExitBarrier(stopStartedProxy); T = [ ["SIGTERM", () => exitAfterSignalExitBarriers(143, "SIGTERM")], ["SIGINT", () => exitAfterSignalExitBarriers(130, "SIGINT")], ["exit", killStartedProxy] ]; for (const [e, t] of T) process$1.once(e, t); }; const replaceStartedProxy = async (e) => { await stopStartedProxy(); const { startProxy: t } = await import("../proxy-lifecycle-DlzTKbbH.mjs"); C = await t(e); w = void 0; installProxySignalHandlers(); }; let M = null; let N = false; if (t.harnessCleanup) t.harnessCleanup.releaseManagedProxy = stopStartedProxy; try { if (!h) await configureCliStartupDiagnostics([n, t.additionalStartupTrace], m ? readBestEffortCliConfig : void 0); if (!p && !S && f.primary && !findBuiltInCommandDescriptor(f.primary)) { const e = await withConsoleLogsRoutedToStderr(readBestEffortCliConfig); if (await withConsoleLogsRoutedToStderr(() => resolvePluginMachineOutput({ argv: d, config: e, session: O }))) { const { routeLogsToStderr: e } = await import("../console-DzWOOvYF.mjs"); e(); } } if (!p && shouldStartProxyForCli(d)) { const e = await withConsoleLogsRoutedToStderr(readBestEffortCliConfig); if (!S) await assertCliPrimaryOwned({ argv: d, config: e, session: O }); await replaceStartedProxy(e?.proxy ?? void 0); } if (!p && m) { const { installGatewayRunRuntimeHooks: e } = await import("../runtime-hooks-DnD9uwQK.mjs"); M = e({ onProcessResourcesSettled: t.onGatewayResourcesSettled, releaseManagedProxy: stopStartedProxy, refreshManagedProxy: replaceStartedProxy }); } if (shouldUseRootHelpFastPath(d)) { const { loadRootHelpRenderOptionsForConfigSensitivePlugins: e } = await import("../root-help-live-config-DxvS2fIz.mjs"); const t = await e(process$1.env); if (!t) { const { outputPrecomputedRootHelpText: e } = await import("../root-help-metadata-BOmAFAGo.mjs"); if (e()) return; } const { outputRootHelp: n } = await import("../root-help-C86Bx-Rp.mjs"); await n(t ?? void 0); return; } if (await tryOutputPrecomputedCommandHelp(d)) return; if (shouldUseSetupOnboardConfigureHelpFastPath(d)) { const { tryOutputSetupOnboardConfigureHelp: e } = await import("../setup-onboard-configure-help-fast-path-Bbrgo58v.mjs"); if (await e(d)) return; } await installConsoleCapture(); if (S) { if (!requireInteractiveTty("OpenClaw TUI needs an interactive TTY. Use `openclaw agent --local ...` for automation.")) return; const { runTuiCliAction: e } = await import("../tui-cli-0Ggc7aKd.mjs"); await e(S.target, S.options); return; } if (resolveUnownedCliPrimaryCandidate(d)) await assertCliPrimaryOwned({ argv: d, config: await readBestEffortCliConfig(), session: O }); const e = shouldHandleBareRoot(d); if (e) await ensureCliEnvProxyDispatcher(); const r = e ? await resolveBareRootLaunchTarget() : null; if (r) { const e = resolveBareRootLaunchPolicy(r); if (!requireInteractiveTty(e.ttyMessage)) return; if (e.startProxy) await replaceStartedProxy((await withConsoleLogsRoutedToStderr(readBestEffortCliConfig))?.proxy ?? void 0); if (r.kind === "remote-gateway-inference") { const { runRemoteGatewayInferenceOnboarding: e } = await import("../onboard-remote-gateway-CnLK8VVu.mjs"); await e(r.target); return; } if (r.kind === "onboarding") { const { setupWizardCommand: e } = await import("../onboard-D2PUTMFG.mjs"); await e(r.classic ? { classic: true } : {}); return; } const { runTui: t } = await import("../tui-CRxv9Fqs.mjs"); await t({ deliver: false, ...r.local ? { local: true } : { config: r.config, boundGateway: { url: r.gatewayUrl, ...r.configuredRemote ? { configuredRemote: true } : {}, ...r.token ? { token: r.token } : {}, ...r.password ? { password: r.password } : {}, ...r.tlsFingerprint ? { tlsFingerprint: r.tlsFingerprint } : {} } } }); return; } const i = !p && shouldStartProxyForCli(d); const a = i && shouldBootstrapCliProxyBeforeFastPath(); if (isGatewayRunFastPathArgv(d)) { const { installUnhandledRejectionHandler: e } = await n.measure("unhandled-rejection-handler-import", () => import("../unhandled-rejections-C3_E5_Ob.mjs")); e(); N = true; } if (!a && await tryRunGatewayRunFastPath(d, n)) return; if (!p && !h) await bootstrapCliProxyCaptureAndDispatcher(n, i); if (a && await tryRunGatewayRunFastPath(d, n)) return; if (!p) { const e = await n.measure("route-import", () => import("../route-Bg4PlyxN.mjs")); if (await n.measure("route", () => t.builtInMachineOutput ? e.tryRouteCli(d, { machineOutput: true }) : e.tryRouteCli(d), { timeline: false })) return; } let o = normalizeGeneratedHelpCommandArgv(d); const s = t.builtInMachineOutput || hasJsonOutputFlag(o); const { createCliProgress: c } = await import("../progress-CNwY7Ykv.mjs"); const l = c({ label: "Loading OpenClaw CLI…", indeterminate: true, delayMs: 0, ...s ? { enabled: false } : {} }); try { const [{ buildProgram: e }, { handleCliUncaughtException: r }, { installUnhandledRejectionHandler: i }] = await n.measure("core-imports", () => Promise.all([ import("../build-program-BiJqaode.mjs"), import("../failure-output-DKniP608.mjs"), import("../unhandled-rejections-C3_E5_Ob.mjs") ])); const a = await n.measure("build-program", () => e({ doctorDatabasePreflight: b, runtimeRecoveryEnv: t.runtimeRecoveryEnv })); await t.harnessCleanup?.pluginResources?.waitForRegistrations(); if (!N) i(); process$1.on("uncaughtException", (e) => { r(e, d); }); const c = resolveCliArgvInvocation(o); const { primary: u } = c; if (u) await n.measure("register-primary", async () => { const { getProgramContext: e } = await import("../program-context-CqZjJR02.mjs"); const t = e(a); if (t) { const { registerCoreCliByName: e } = await import("../command-registry-core-Bta1MMeR.mjs"); await e(a, t, u); } const { registerSubCliByName: n } = await import("../register.subclis-D9pUHFsl.mjs"); await n(a, u, o); }); const f = u !== null && findSubcommand(a, u) !== void 0; if (!shouldSkipPluginCommandRegistration({ argv: o, primary: u, hasBuiltinPrimary: f })) { const e = await n.measure("register-plugin-commands", async () => { const { registerPluginCliCommandsFromValidatedConfig: e } = await import("../cli-Can2BQj3.mjs"); const t = resolveCliStartupPolicy({ argv: o, commandPath: c.commandPath, jsonOutputMode: s }); return await e(a, void 0, void 0, { mode: "lazy", primary: u, skipPluginValidation: t.skipConfigGuard, session: await getPluginCliSession() }); }); if (u && !findSubcommand(a, u)) { const t = await resolveExpectedPluginPolicyError({ primary: u, config: e }); if (t) throw t; } } o = normalizeRootLogLevelArgv(normalizeRootNoColorArgvForProgram(o, a), { shouldPreserveLogLevel: ({ remainingArgs: e, logLevelIndex: t }) => resolveRootOptionRole(a, e, t) !== "root" }); l.done(); let m = false; try { const e = t.harnessCleanup?.pluginResources; await e?.waitForRegistrations(); O?.close(); const parse = () => n.measure("parse", () => a.parseAsync(o), { timeline: false }); await (e ? e.run(parse) : parse()); await e?.waitForRegistrations(); m = p; } catch (e) { if (!isCommanderParseExit(e)) throw e; if (isJsonOutputModeActive(o) && e.exitCode !== 0) throw e; process$1.exitCode = e.exitCode; m = p && e.exitCode === 0; } if (m) requestExitAfterOneShotOutput(); } finally { l.done(); } } finally { O?.close(); M?.(); if (!t.harnessCleanup) await runCliDisposer("managed-proxy", stopStartedProxy); } } //#endregion export { runCli };