UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,204 lines (1,203 loc) • 42.5 kB
import { g as readStringValue, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs"; import { a as createGatewayEnvSecretRef, l as isValidEnvSecretRefId } from "./ref-contract-b8L-9DrQ.mjs"; import "./types.secrets-BmNLLnHp.mjs"; import { t as canAccess } from "./path-existence-Co7-GyVr.mjs"; import { n as sanitizeTerminalText, r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { a as displayPath } from "./utils-C8YECn2Q.mjs"; import { n as parseTcpPort } from "./tcp-port-CuNPxuH-.mjs"; import { b as resolveGatewayPort, t as CONFIG_PATH } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { A as tryResolveLegacyCompatibilityAgentId, O as tryResolveAmbientOwnerAgentId, y as resolveMutableAgentEntry } from "./agent-scope-config-DmXgFGKP.mjs"; import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs"; import { o as resolvePluginContributionOwners } from "./plugin-registry-contributions-iAw3gSDD.mjs"; import { b as parseIpAddressOrCidr } from "./ip-BUyyYvdK.mjs"; import { a as resolveAgentEffectiveModelPrimary } from "./agent-scope-BwB8YH6y.mjs"; import "./plugin-registry-BrQav-kR.mjs"; import { r as listChatChannels } from "./chat-meta-CsbrDHrF.mjs"; import { l as readConfigFileSnapshotForWrite, t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { a as isLoopbackAddress, d as isTrustedProxyAddress } from "./net-BgRayX-P.mjs"; import "./config-CMA-J084.mjs"; import { r as resolveManifestProviderAuthChoice } from "./provider-auth-choices-BfC_56hU.mjs"; import { n as WizardCancelledError } from "./prompts-CCXo2K24.mjs"; import { t as resolveGatewayStartupTiming } from "./gateway-startup-timing-BGts4IhB.mjs"; import { l as isNonFatalSystemdInstallProbeError } from "./systemd-busctl-query-BuQgKtLl.mjs"; import { r as findTailscaleBinary } from "./tailscale-6NHccc09.mjs"; import { r as t } from "./i18n-AiHKCZaZ.mjs"; import { n as resolveGatewayService, t as describeGatewayServiceRestart } from "./service-hQiIzcTo.mjs"; import { n as isGatewayServiceInstalled } from "./service-state-uYnG1mTd.mjs"; import "./systemd-k-QLc2ED.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { r as resolveGatewayProbeAuthSafeWithSecretInputs } from "./probe-auth-CWenh0cl.mjs"; import { r as resolveLocalControlUiProbeLinks, t as resolveAdvertisedControlUiLinks } from "./control-ui-links-tAtEMm92.mjs"; import { t as randomToken } from "./random-token-Sl4a6KEQ.mjs"; import { a as guardCancel, d as summarizeExistingConfig, f as validateGatewayPasswordInput, n as applyWizardMetadata, p as waitForGatewayReachable, s as normalizeGatewayTokenInput, t as DEFAULT_WORKSPACE, u as probeGatewayReachable } from "./onboard-helpers-I6fwzX78.mjs"; import { a as ensureOnboardingAgentWorkspace, c as resolveOnboardingAgentTarget, i as applyOnboardingWorkspace, n as applyOnboardingPrimaryModel, r as applyOnboardingUtilityModel, t as applyAgentModelDefaults } from "./onboard-agent-target-D7VNwjZB.mjs"; import { d as writeWizardConfigFile } from "./setup.shared-2t79532Q.mjs"; import { r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs"; import { r as withProgress } from "./progress-DZHhZ1Fk.mjs"; import { t as createClackPrompter } from "./clack-prompter-oqVcatgQ.mjs"; import { r as logConfigUpdated } from "./logging-D0RirHBi.mjs"; import { t as describeCodexNativeWebSearch } from "./codex-native-web-search.shared-BYcLEL59.mjs"; import { n as GATEWAY_DAEMON_RUNTIME_OPTIONS } from "./daemon-runtime-agdJw6fb.mjs"; import { n as gatewayInstallErrorHint } from "./daemon-install-helpers-DYNaMvoO.mjs"; import { t as resolveGatewayInstallToken } from "./gateway-install-token-BUEEPvbI.mjs"; import { t as formatWindowsGatewayFirewallGuidance } from "./windows-gateway-firewall-diagnostics-Vu0aahGN.mjs"; import { a as outro, c as select, i as intro, l as text, n as CONFIGURE_WIZARD_SECTIONS, o as parseConfigureWizardSections, r as confirm, s as password, t as CONFIGURE_SECTION_OPTIONS } from "./configure.shared-BGU6WxUW.mjs"; import { i as setupChannels, n as createChannelSetupHooks } from "./channel-setup-CreFIC7D.mjs"; import { n as promptAuthChoiceGrouped } from "./auth-choice-prompt-CxeMwsLJ.mjs"; import { t as applyAuthChoice } from "./auth-choice.apply-DYJ_v1UI.mjs"; import { a as validateGatewayPortInput, i as maybeAddTailnetOriginToControlUiAllowedOrigins, n as TAILSCALE_EXPOSURE_OPTIONS, r as TAILSCALE_MISSING_BIN_NOTE_LINES, t as TAILSCALE_DOCS_LINES } from "./gateway-config-prompts.shared-UvBGR-kv.mjs"; import { n as prepareGatewayServiceInstall, t as resolveGatewaySetupRuntime } from "./gateway-setup-runtime-_1YriGV5.mjs"; import { t as ensureSystemdUserLingerInteractive } from "./systemd-linger-LU0DUv2A.mjs"; import { i as promptModelAllowlist, n as applyModelFallbacksFromSelection, r as promptDefaultModel, t as applyModelAllowlist } from "./model-picker-aGjVXhu3.mjs"; import { t as resolvePreferredProviderForAuthChoice } from "./provider-auth-choice-preference-aJfNppcY.mjs"; import { t as loadStaticManifestCatalogRowsForList } from "./list.manifest-catalog-pvA1E8h-.mjs"; import { t as promptCustomApiConfig } from "./onboard-custom-C2jdjMDq.mjs"; import { o as formatHealthCheckFailure } from "./health-format-DfkUmdM_.mjs"; import { i as healthCommandNonExiting } from "./health-CAgyEE1j.mjs"; import { t as validateDottedDecimalIPv4Input } from "./ipv4--PTE68Cr.mjs"; import { t as promptRemoteGatewayConfig } from "./onboard-remote-CH2jFnnK.mjs"; import { t as setupSkills } from "./onboard-skills-D7xW46qH.mjs"; import path from "node:path"; //#region src/commands/configure.prompts.ts const configurePrompts = { text: async (e) => guardCancel(await text(e), defaultRuntime, 1), password: async (e) => guardCancel(await password(e), defaultRuntime, 1), confirm: async (e) => guardCancel(await confirm(e), defaultRuntime, 1), select: async (e) => guardCancel(await select(e), defaultRuntime, 1) }; //#endregion //#region src/commands/configure.channels.ts const RESERVED_CHANNEL_CONFIG_KEYS = /* @__PURE__ */ new Set(["defaults", "modelByChannel"]); function listConfiguredChannelRemovalChoices(e) { const n = e.channels; if (!n) return []; const r = new Map(listChatChannels().map((e) => [e.id, sanitizeTerminalText(e.label) || formatUnknownChannelRemovalLabel(e.id)])); return Object.keys(n).filter((e) => !RESERVED_CHANNEL_CONFIG_KEYS.has(e)).filter((e) => !isBlockedObjectKey(e)).map((e) => ({ id: e, label: r.get(e) ?? formatUnknownChannelRemovalLabel(e) })).toSorted(compareChannelRemovalChoices); } function formatUnknownChannelRemovalLabel(e) { return sanitizeTerminalText(e) || "<invalid channel key>"; } function compareChannelRemovalChoices(e, n) { return e.label.localeCompare(n.label, void 0, { numeric: true, sensitivity: "base" }) || e.id.localeCompare(n.id, void 0, { numeric: true, sensitivity: "base" }); } async function removeChannelConfigWizard(e) { const n = { ...e }; while (true) { const e = listConfiguredChannelRemovalChoices(n); if (e.length === 0) { note(["No channel config found in openclaw.json.", `Tip: \`${formatCliCommand("openclaw channels status")}\` shows what is configured and enabled.`].join("\n"), "Remove channel"); return n; } const r = await configurePrompts.select({ message: "Remove which channel config?", options: [...e.map((e) => ({ value: { kind: "channel", id: e.id }, label: e.label, hint: "Deletes tokens + settings from config (credentials stay on disk)" })), { value: { kind: "done" }, label: "Done" }] }); if (r.kind === "done") return n; const i = r.id; const a = e.find((e) => e.id === i)?.label ?? i; if (!await configurePrompts.confirm({ message: terminalText`Delete ${a} configuration from ${displayPath(CONFIG_PATH)}?`, initialValue: false })) continue; const o = { ...n.channels }; delete o[i]; if (Object.keys(o).length) n.channels = o; else delete n.channels; note([terminalText`${a} selected for removal from config.`, "Note: credentials/sessions on disk are unchanged."].join("\n"), "Channel removal"); } } //#endregion //#region src/commands/configure.daemon.ts async function maybeInstallDaemon(e) { const n = resolveGatewayService(); let r; try { r = await isGatewayServiceInstalled(n, { env: process.env }); } catch (e) { if (!isNonFatalSystemdInstallProbeError(e)) throw e; r = false; } const i = r ? await configurePrompts.select({ message: "Gateway service already installed", options: [ { value: "restart", label: "Restart" }, { value: "reinstall", label: "Reinstall" }, { value: "skip", label: "Skip" } ] }) : "reinstall"; if (i === "skip") return "skipped"; if (i === "restart") await withProgress({ label: "Gateway service", indeterminate: true, delayMs: 0 }, async (e) => { e.setLabel("Restarting Gateway service…"); const r = await n.restart({ env: process.env, stdout: process.stdout }); e.setLabel(describeGatewayServiceRestart("Gateway", r).progressMessage); }); else { let r = null; const i = await n.readCommand(process.env); const a = await resolveGatewaySetupRuntime({ env: process.env, existingCommand: i, selectRuntime: async (e) => { if (GATEWAY_DAEMON_RUNTIME_OPTIONS.length === 1) return GATEWAY_DAEMON_RUNTIME_OPTIONS[0]?.value ?? e; return await configurePrompts.select({ message: "Gateway service runtime", options: GATEWAY_DAEMON_RUNTIME_OPTIONS, initialValue: e }); } }); await withProgress({ label: "Gateway service", indeterminate: true, delayMs: 0 }, async (o) => { o.setLabel("Preparing Gateway service…"); const s = await captureRuntimeConfigAsyncReader()(); const c = await resolveGatewayInstallToken({ config: s, env: process.env }); for (const e of c.warnings) note(e, "Gateway"); if (c.unavailableReason) { r = [ "Gateway install blocked:", c.unavailableReason, "Fix gateway auth config/token input and rerun configure." ].join(" "); o.setLabel("Gateway service install blocked."); return; } const l = await prepareGatewayServiceInstall({ service: n, selection: a, port: e.port, existingCommand: i, warn: (e, n) => note(e, n), config: s }); o.setLabel("Installing Gateway service…"); try { await l.install(); o.setLabel("Gateway service installed."); } catch (e) { r = formatErrorMessage(e); o.setLabel("Gateway service install failed."); } }); if (r) { note("Gateway service install failed: ".concat(r), "Gateway"); note(gatewayInstallErrorHint(), "Gateway"); return "failed"; } } await ensureSystemdUserLingerInteractive({ runtime: defaultRuntime, prompter: { confirm: configurePrompts.confirm, note }, reason: "Linux installs use a systemd user service. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.", requireConfirm: true }); return "succeeded"; } //#endregion //#region src/commands/configure.gateway-auth.ts function hasConfiguredProviderModels(e, n) { if (!n) return false; if ((e.models?.providers?.[n]?.models?.length ?? 0) > 0) return true; const r = `${n}/`; return Object.keys(e.agents?.defaults?.models ?? {}).some((e) => e.trim().startsWith(r)); } function listConfiguredModelProviders(e) { return Object.entries(e.models?.providers ?? {}).filter(([, e]) => (e.models?.length ?? 0) > 0).map(([e]) => e); } function resolveSingleConfiguredProvider(e) { const n = listConfiguredModelProviders(e); return n.length === 1 ? n[0] : void 0; } function resolveProviderFromModelRef(e) { const n = e?.trim(); const r = n?.indexOf("/") ?? -1; return r > 0 ? n?.slice(0, r) : void 0; } function resolveCanonicalOpenAISelectionForLegacyCodexPrimary(e, n, r) { const i = resolveAgentModelPrimaryValue(resolveMutableAgentEntry(e, n.agentId)?.model ?? e.agents?.defaults?.model); const a = i?.startsWith("codex/") ? i.slice(6).trim() : ""; if (!a) return; const o = `openai/${a}`; return r.find((e) => e.trim() === o); } /** Prompt for model provider credentials and explicit default model policy settings. */ async function promptAuthConfig(e, n, r, i = resolveOnboardingAgentTarget(e)) { let a = e; let o = "skip"; let s; while (true) { o = await promptAuthChoiceGrouped({ prompter: r, includeSkip: true, config: a }); s = o === "skip" ? void 0 : await resolvePreferredProviderForAuthChoice({ choice: o, config: a }); if (o === "custom-api-key") { a = (await promptCustomApiConfig({ prompter: r, runtime: n, config: a, target: i, setAsPrimary: !resolveAgentEffectiveModelPrimary(a, i.agentId) })).config; break; } if (o === "skip") { const e = await promptDefaultModel({ config: a, prompter: r, allowKeep: true, includeProviderPluginSetups: false, loadCatalog: true, browseCatalogOnDemand: true, preferredProvider: s, agentId: i.agentId, agentDir: i.agentDir, workspaceDir: i.workspaceDir, runtime: n }); if (e.config) a = e.config; if (e.model) { a = applyOnboardingPrimaryModel(a, i, e.model); s = resolveProviderFromModelRef(e.model) ?? s; } break; } const e = a; const c = await applyAuthChoice({ authChoice: o, config: a, prompter: r, runtime: n, agentId: i.agentId, agentDir: i.agentDir, setDefaultModel: false, preserveExistingDefaultModel: true }); a = c.config; if (c.utilityModelOverride) return applyOnboardingUtilityModel(a, i, c.utilityModelOverride); if (c.agentModelOverride && !resolveAgentEffectiveModelPrimary(e, i.agentId)) a = applyOnboardingPrimaryModel(a, i, c.agentModelOverride); if (!hasConfiguredProviderModels(a, s)) { const n = e.models?.providers ?? {}; const r = listConfiguredModelProviders(a); const i = r.filter((e) => { const r = n[e]?.models?.length ?? 0; return (a.models?.providers?.[e]?.models?.length ?? 0) > r; }); s = i.length === 1 ? i[0] : s ?? (r.length === 1 ? r[0] : void 0); } if (c.retrySelection) continue; break; } if (o !== "custom-api-key") { const e = a; const n = i.workspaceDir; const c = process.env; let l; const { resolvePluginProviders: u, resolveProviderPluginChoice: d } = await import("./provider-auth-choice.runtime.js"); const f = d({ providers: u({ config: e, workspaceDir: n, env: c, mode: "setup" }), choice: o, manifestChoice: resolveManifestProviderAuthChoice(o, { config: e, workspaceDir: n, env: c, includeUntrustedWorkspacePlugins: false }) }); const p = f?.provider.wizard?.setup; if (!p) l = f?.provider.id ? { provider: f.provider.id } : void 0; else l = { provider: f.provider.id, ...p.modelAllowlist, ...p.modelSelection?.promptWhenAuthChoiceProvided === true ? { loadCatalog: true } : {} }; const m = l?.provider ?? s ?? resolveSingleConfiguredProvider(a); const h = hasConfiguredProviderModels(a, m); const g = Boolean(m && loadStaticManifestCatalogRowsForList({ cfg: a, providerFilter: m }).length > 0); const _ = l?.loadCatalog ?? (h || g); const v = Boolean(m && _ && (l?.loadCatalog === true || h)); const y = await promptModelAllowlist({ config: a, prompter: r, agentId: i.agentId, agentDir: i.agentDir, workspaceDir: i.workspaceDir, env: process.env, allowedKeys: l?.allowedKeys, initialSelections: l?.initialSelections, message: l?.message, preferredProvider: m, providerScopedCatalog: v, loadCatalog: _ }); if (y.models) { const e = y.models; const n = resolveCanonicalOpenAISelectionForLegacyCodexPrimary(a, i, e); if (n) a = applyOnboardingPrimaryModel(a, i, n); a = applyAgentModelDefaults(a, i, (n) => applyModelAllowlist(applyModelFallbacksFromSelection(n, e, { scopeKeys: y.scopeKeys }), e, { scopeKeys: y.scopeKeys })); } } return a; } //#endregion //#region src/commands/configure.gateway-health.ts async function runGatewayHealthCheck(e) { const n = resolveLocalControlUiProbeLinks({ bind: e.cfg.gateway?.bind ?? "loopback", port: e.port, customBindHost: e.cfg.gateway?.customBindHost, basePath: void 0, tlsEnabled: e.cfg.gateway?.tls?.enabled === true }); const r = e.cfg.gateway?.remote?.url?.trim(); const i = e.cfg.gateway?.mode === "remote" ? r : void 0; const a = i ? "remote" : "local"; const o = i ?? n.wsUrl; const s = await resolveGatewayProbeAuthSafeWithSecretInputs({ cfg: e.cfg, env: process.env, mode: a, ...a === "local" ? { localPrecedence: "env-first" } : {} }); if (s.warning) { const e = a === "remote" && Boolean(s.auth.token || s.auth.password); note([ `Could not resolve ${a} gateway SecretRef for health check.`, s.warning, ...e ? ["Continuing with the other configured remote credential."] : ["Health check skipped to avoid falling back to ambient credentials.", `Fix the SecretRef, then run \`${formatCliCommand("openclaw health")}\` again.`] ].join("\n"), "Gateway auth"); if (!e) return "skipped"; } const { token: c, password: l } = s.auth; try { const n = await waitForGatewayReachable({ url: o, ...a === "remote" ? { config: e.cfg, originScopedDeviceAuth: true, configuredRemote: true } : {}, token: c, password: l, ...e.daemonSetupOutcome === "succeeded" ? resolveGatewayStartupTiming() : { deadlineMs: 15e3 } }); if (!n.ok) throw new Error(n.detail ?? `gateway did not become reachable at ${o}`); await healthCommandNonExiting({ json: false, timeoutMs: 1e4, config: e.cfg, token: c, password: l, ...a === "local" ? { localPortOverride: e.port } : { ignoreEnvUrlOverride: true } }, e.runtime); } catch (n) { if (!(n instanceof ExitError)) e.runtime.error(formatHealthCheckFailure(n)); note([ "Docs:", "https://docs.openclaw.ai/gateway/health", "https://docs.openclaw.ai/gateway/troubleshooting" ].join("\n"), "Health check help"); return "failed"; } return "succeeded"; } //#endregion //#region src/commands/configure.gateway.ts async function promptGatewayConfig(e) { const n = await configurePrompts.text({ message: "Gateway port", initialValue: String(resolveGatewayPort(e)), validate: validateGatewayPortInput }); const r = parseTcpPort(n) ?? resolveGatewayPort(e); let i = await configurePrompts.select({ message: "Gateway bind mode", options: [ { value: "loopback", label: "Loopback (Local only)", hint: "Bind to 127.0.0.1 - secure, local-only access" }, { value: "tailnet", label: "Tailnet (Tailscale IP)", hint: "Bind to your Tailscale IP plus local loopback" }, { value: "auto", label: "Auto (Loopback → LAN)", hint: "Prefer loopback; fall back to all interfaces if unavailable" }, { value: "lan", label: "LAN (All interfaces)", hint: "Bind to 0.0.0.0 - accessible from anywhere on your network" }, { value: "custom", label: "Custom IP", hint: "Specific IPv4s also bind 127.0.0.1" } ] }); let a; if (i === "custom") { const e = await configurePrompts.text({ message: "Custom IP address", placeholder: "192.168.1.100", validate: validateDottedDecimalIPv4Input }); a = readStringValue(e); } let o = await configurePrompts.select({ message: "Gateway access protection", options: [ { value: "token", label: "Token (recommended)", hint: "Recommended default" }, { value: "password", label: "Password" }, { value: "trusted-proxy", label: "Trusted Proxy", hint: "Behind reverse proxy (Pomerium, Caddy, Traefik, etc.)" } ], initialValue: "token" }); let s = await configurePrompts.select({ message: "Tailscale exposure", options: [...TAILSCALE_EXPOSURE_OPTIONS] }); let c = null; if (s !== "off") { c = await findTailscaleBinary(); if (!c) note(TAILSCALE_MISSING_BIN_NOTE_LINES.join("\n"), "Tailscale Warning"); note(TAILSCALE_DOCS_LINES.join("\n"), "Tailscale"); } if (o === "trusted-proxy" && s !== "off") { note("Trusted proxy auth is incompatible with Tailscale serve/funnel. Disabling Tailscale.", "Note"); s = "off"; } if (s !== "off" && i !== "loopback") { note("Tailscale requires bind=loopback. Adjusting bind to loopback.", "Note"); i = "loopback"; } if (s === "funnel" && o !== "password") { note("Tailscale funnel requires password auth.", "Note"); o = "password"; } let l; let u; let d; let f; let p = e; if (o === "token") { if (await configurePrompts.select({ message: "Gateway token source", options: [{ value: "plaintext", label: "Generate/store plaintext token", hint: "Default" }, { value: "ref", label: "Use SecretRef", hint: "Store an env-backed reference instead of plaintext" }], initialValue: "plaintext" }) === "ref") { const n = await configurePrompts.text({ message: "Gateway token env var", initialValue: "OPENCLAW_GATEWAY_TOKEN", placeholder: "OPENCLAW_GATEWAY_TOKEN", validate: (e) => { const n = normalizeOptionalString(e) ?? ""; if (!isValidEnvSecretRefId(n)) return "Use an env var name like OPENCLAW_GATEWAY_TOKEN."; if (!process.env[n]?.trim()) return `Environment variable "${n}" is missing or empty in this session.`; } }); const r = normalizeOptionalString(n) ?? ""; l = createGatewayEnvSecretRef(e, r); note(`Validated ${r}. OpenClaw will store a token SecretRef.`, "Gateway token"); } else { const e = await configurePrompts.password({ message: "Gateway token (blank to generate)" }); l = normalizeGatewayTokenInput(e) || randomToken(); } } if (o === "password") { const e = await configurePrompts.password({ message: "Gateway password", validate: validateGatewayPasswordInput }); u = normalizeOptionalString(e) ?? ""; } if (o === "trusted-proxy") { note([ "Trusted proxy mode: OpenClaw trusts user identity from a reverse proxy.", "The proxy must authenticate users and pass identity via headers.", "Only requests from specified proxy IPs will be trusted.", "", "Common use cases: Pomerium, Caddy + OAuth, Traefik + forward auth", "Docs: https://docs.openclaw.ai/gateway/trusted-proxy-auth" ].join("\n"), "Trusted Proxy Auth"); const n = await configurePrompts.text({ message: "Header containing user identity", placeholder: "x-forwarded-user", initialValue: "x-forwarded-user", validate: (e) => e?.trim() ? void 0 : "User header is required" }); const r = await configurePrompts.text({ message: "Required headers (comma-separated, optional)", placeholder: "x-forwarded-proto,x-forwarded-host" }); const i = r ? normalizeStringEntries(r.split(",")) : []; const a = await configurePrompts.text({ message: "Allowed users (comma-separated, blank = all authenticated users)", placeholder: "nick@example.com,admin@company.com" }); const o = a ? normalizeStringEntries(a.split(",")) : []; const s = await configurePrompts.text({ message: "Trusted proxy IPs (comma-separated)", placeholder: "10.0.1.10,192.168.1.5", validate: (e) => (e ?? "").split(",").every((e) => parseIpAddressOrCidr(e)) ? void 0 : "Enter comma-separated IPv4 or IPv6 addresses or CIDR ranges (e.g. 10.0.0.1, ::1, 10.0.0.0/24); no empty entries." }); f = normalizeStringEntries(s.split(",")); const c = e.gateway?.auth?.mode === "trusted-proxy" ? e.gateway.auth.trustedProxy : void 0; let l = c?.allowLoopback; if (f.some((e) => { return [ parseIpAddressOrCidr(e)?.[0].toString(), "127.0.0.1", "::1" ].some((n) => isLoopbackAddress(n) && isTrustedProxyAddress(n, [e])); })) { const e = t("wizard.gateway.trustedProxyLoopbackTitle"); note(t("wizard.gateway.trustedProxyLoopbackWarning"), e); l = await configurePrompts.confirm({ message: t("wizard.gateway.trustedProxyAllowLoopback"), initialValue: l === true }) || void 0; if (!l) note(t("wizard.gateway.trustedProxyLoopbackRefused"), e); } d = { ...c, userHeader: normalizeOptionalString(n) ?? "", requiredHeaders: i.length > 0 ? i : void 0, allowUsers: o.length > 0 ? o : void 0, allowLoopback: l }; } const m = { ...p.gateway?.auth, mode: o }; delete m.token; delete m.password; delete m.trustedProxy; if (o === "token") m.token = l; else if (o === "password" && u) m.password = u; else if (o === "trusted-proxy") m.trustedProxy = d; p = { ...p, gateway: { ...p.gateway, mode: "local", port: r, bind: i, auth: m, ...a && { customBindHost: a }, ...f && { trustedProxies: f }, tailscale: { ...p.gateway?.tailscale, mode: s } } }; p = await maybeAddTailnetOriginToControlUiAllowedOrigins({ config: p, tailscaleMode: s, tailscaleBin: c }); return { config: p, port: r }; } //#endregion //#region src/commands/configure.wizard.ts const GATEWAY_HINT_PROBE_TIMEOUT_MS = 300; async function promptWebToolsConfig(e, n) { const r = e.tools?.web?.search; const i = e.tools?.web?.fetch; const { isCodexNativeWebSearchRelevant: a } = await import("./codex-native-web-search-DsH_nVtI.mjs"); const o = resolvePluginContributionOwners({ config: e, contribution: "contracts", matches: "webSearchProviders" }).length > 0; note([ "Web search lets your agent look things up online using the `web_search` tool.", "Codex-capable models can use native Codex web search.", "Other models use a separate web search provider, which you can configure here.", "Docs: https://docs.openclaw.ai/tools/web" ].join("\n"), "Web search"); const s = await configurePrompts.confirm({ message: "Enable the web_search tool?", initialValue: r?.enabled ?? o }); let c = { ...r, enabled: s }; let l = e; if (s) { const i = await a({ config: e }); let o = true; if (i) { note([ "Codex-capable models can use native Codex web search instead of a separate provider.", "Other models need a separate web search provider.", "If you do not choose one, OpenClaw can select a provider from available credentials; otherwise other models may not have web search.", ...describeCodexNativeWebSearch(e) ? [describeCodexNativeWebSearch(e)] : [] ].join("\n"), "Codex native search"); const n = await configurePrompts.confirm({ message: "Enable native Codex web search for Codex-capable models?", initialValue: r?.openaiCodex?.enabled === true }); const i = n ? await configurePrompts.select({ message: "Native Codex web search mode", options: [{ value: "cached", label: "cached (recommended)", hint: "Uses cached web content" }, { value: "live", label: "live", hint: "Allows live external web access" }], initialValue: r?.openaiCodex?.mode ?? "cached" }) : void 0; c = { ...c, openaiCodex: { ...r?.openaiCodex, enabled: n, ...n ? { mode: i } : {} } }; if (n) o = await configurePrompts.confirm({ message: r?.provider ? terminalText`Change the separate web search provider (currently ${r.provider})?` : "Also configure a separate web search provider for other models?", initialValue: Boolean(r?.provider) }); } if (o) { const { resolveSearchProviderOptions: i, runSearchSetupFlow: a } = await import("./search-setup-BUgcR-Xv.mjs"); if (i(e).length === 0) { note([ "No web search providers are currently available under this plugin policy.", "Enable plugins or remove deny rules, then rerun configure.", "Docs: https://docs.openclaw.ai/tools/web" ].join("\n"), "Web search"); if (c.openaiCodex?.enabled !== true) c = { ...r, enabled: false }; } else { l = (await a(l, defaultRuntime, n, { preserveDisabledSearchState: false })).config; const e = l.tools?.web?.search; c = { ...e, enabled: e?.enabled ?? (e?.provider ? true : r?.enabled), openaiCodex: { ...r?.openaiCodex, ...c.openaiCodex } }; } } } note(["`web_fetch` is a separate tool for reading a specific URL.", "It does not require an API key and works independently of web search providers, including Codex."].join("\n"), "Web fetch"); const u = await configurePrompts.confirm({ message: "Enable the web_fetch tool?", initialValue: i?.enabled ?? true }); const d = { ...l.tools?.web?.fetch, enabled: u }; return { ...l, tools: { ...l.tools, web: { ...l.tools?.web, search: c, fetch: d } } }; } /** Run the configure wizard, optionally limited to selected sections. */ async function runConfigureWizard(e) { try { intro("OpenClaw configure"); const n = createClackPrompter(); const r = await readConfigFileSnapshotForWrite(); const i = r.snapshot; const a = { ...r.writeOptions.assertConfigPathForWrite ? { assertConfigPathForWrite: r.writeOptions.assertConfigPathForWrite } : {}, expectedConfigPath: r.writeOptions.expectedConfigPath, ownedConfigPathForWrite: r.writeOptions.ownedConfigPathForWrite }; const o = i.hash; const s = i.valid ? i.sourceConfig ?? i.config : {}; if (i.exists) { const e = i.valid ? "Existing config detected" : "Invalid config"; note(summarizeExistingConfig(s), e); if (!i.valid && i.issues.length > 0) note([ ...i.issues.map((e) => terminalText`- ${e.path}: ${e.message}`), "", "Docs: https://docs.openclaw.ai/gateway/configuration" ].join("\n"), "Config issues"); if (!i.valid) { outro(`Config invalid. Run \`${formatCliCommand("openclaw doctor --fix")}\` to apply supported repairs, then re-run configure.`); defaultRuntime.exit(1); return; } } const c = e.sections; const l = !c || c.includes("gateway") || c.includes("daemon") || c.includes("health"); const promptGatewayRunMode = async () => { const e = `ws://127.0.0.1:${resolveGatewayPort(s)}`; const n = normalizeOptionalString(s.gateway?.remote?.url) ?? ""; const r = (async () => { const n = await resolveGatewayProbeAuthSafeWithSecretInputs({ cfg: s, env: process.env, mode: "local", localPrecedence: "env-first" }); if (n.warning) return { ok: false, authUnavailable: true }; return probeGatewayReachable({ url: e, token: n.auth.token, password: n.auth.password, timeoutMs: GATEWAY_HINT_PROBE_TIMEOUT_MS }); })(); const i = n ? (async () => { const e = await resolveGatewayProbeAuthSafeWithSecretInputs({ cfg: s, env: process.env, mode: "remote" }); return probeGatewayReachable({ url: n, config: s, originScopedDeviceAuth: true, configuredRemote: true, token: e.auth.token, ...e.auth.password ? { password: e.auth.password } : {}, timeoutMs: GATEWAY_HINT_PROBE_TIMEOUT_MS }); })() : Promise.resolve(null); const [a, o] = await Promise.all([r, i]); return await configurePrompts.select({ message: "Where will the Gateway run?", options: [{ value: "local", label: "Local (this machine)", hint: a.ok ? `Gateway reachable (${e})` : "authUnavailable" in a ? `Gateway auth unavailable; check skipped (${e})` : `No gateway detected (${e})` }, { value: "remote", label: "Remote (info-only)", hint: !n ? "No remote URL configured yet" : o?.ok ? terminalText`Gateway reachable (${n})` : terminalText`Configured but unreachable (${n})` }] }); }; const u = l ? await promptGatewayRunMode() : "local"; const d = l || s.gateway?.mode !== "remote" ? u : "remote"; const f = !l; if (l && u === "remote") { let e = await promptRemoteGatewayConfig(s, n); e = applyWizardMetadata(e, { command: "configure", mode: d }); e = (await writeWizardConfigFile(e, { mergeBase: s, ...o !== void 0 ? { baseHash: o } : {}, writeOptions: a })).nextConfig; logConfigUpdated(defaultRuntime); if (c?.includes("health")) { const n = await runGatewayHealthCheck({ cfg: e, runtime: defaultRuntime, port: resolveGatewayPort(e) }); outro(n === "succeeded" ? "Remote gateway configured and health check completed." : n === "failed" ? "Remote gateway configured, but health check failed." : "Remote gateway configured; health check skipped."); } else outro("Remote gateway configured."); return; } let p = { ...s }; let m = structuredClone(s); let h = l && p.gateway?.mode !== "local"; if (h) p = { ...p, gateway: { ...p.gateway, mode: "local" } }; let g; const resolveSetupTarget = async () => { g ??= p.agents?.ownership === "explicit" ? tryResolveAmbientOwnerAgentId(p) : tryResolveLegacyCompatibilityAgentId(p); const e = listAgentIds(p); if (!g && e.length > 1) g = await configurePrompts.select({ message: "Which agent do you want to configure?", options: e.map((e) => ({ value: e, label: e })) }); return resolveOnboardingAgentTarget(p, g); }; let _ = resolveGatewayPort(s); let v = false; let y; let b; const x = createChannelSetupHooks({ runtime: defaultRuntime }); const persistPendingConfig = async () => { if (!h) return; p = applyWizardMetadata(p, { command: "configure", mode: d }); const e = await writeWizardConfigFile(p, { mergeBase: m, writeOptions: a }); m = structuredClone(e.nextConfig); await x.runPostWriteHooks(e.path); p = e.nextConfig; h = false; v = true; logConfigUpdated(defaultRuntime); }; const configureWorkspace = async () => { const e = await resolveSetupTarget(); const n = await configurePrompts.text({ message: "Workspace directory", initialValue: e.workspaceDir }); const r = resolveUserPath(normalizeOptionalString(n ?? "") || DEFAULT_WORKSPACE); if (!i.exists) { const e = [ "MEMORY.md", "memory", ".git" ].map((e) => path.join(r, e)); if ((await Promise.all(e.map((e) => canAccess(e)))).some(Boolean)) note([terminalText`Existing workspace detected at ${r}`, "Existing files are preserved. Missing templates may be created, never overwritten."].join("\n"), "Existing workspace"); } p = applyOnboardingWorkspace(p, e, r); await ensureOnboardingAgentWorkspace(await resolveSetupTarget(), defaultRuntime, { skipBootstrap: Boolean(p.agents?.defaults?.skipBootstrap), skipOptionalBootstrapFiles: p.agents?.defaults?.skipOptionalBootstrapFiles }); }; const configureChannelsSection = async () => { if (await configurePrompts.select({ message: "Channel setup", options: [{ value: "configure", label: "Add or update channels", hint: "Configure accounts and disable unselected accounts" }, { value: "remove", label: "Remove channel config", hint: "Delete channel tokens/settings from openclaw.json" }], initialValue: "configure" }) === "configure") { const e = await resolveSetupTarget(); p = await setupChannels(p, defaultRuntime, n, { workspaceDir: e.workspaceDir, allowDisable: true, allowIMessageInstall: true, allowSignalInstall: true, deferStatusUntilSelection: true, skipConfirm: true, skipStatusNote: true, onPostWriteHook: x.onPostWriteHook }); } else p = await removeChannelConfigWizard(p); }; let S = false; const C = { workspace: configureWorkspace, model: async () => { p = await promptAuthConfig(p, defaultRuntime, n, await resolveSetupTarget()); }, web: async () => { p = await promptWebToolsConfig(p, n); }, memory: async () => { const { runMemorySetupFlow: e } = await import("./memory-setup-DtjVmk2o.mjs"); p = await e(p, n, { agentDir: (await resolveSetupTarget()).agentDir }); }, gateway: async () => { const e = await promptGatewayConfig(p); p = e.config; _ = e.port; S = true; }, channels: configureChannelsSection, plugins: async () => { const { configurePluginConfig: e } = await import("./setup.plugin-config-DET2y6Lk.mjs"); p = await e({ config: p, prompter: n, workspaceDir: (await resolveSetupTarget()).workspaceDir }); }, skills: async () => { p = await setupSkills(p, (await resolveSetupTarget()).workspaceDir, defaultRuntime, n); }, daemon: async () => { if (!S) { const e = await configurePrompts.text({ message: "Gateway port for service install", initialValue: String(_), validate: validateGatewayPortInput }); _ = parseTcpPort(e) ?? _; } y = await maybeInstallDaemon({ port: _ }); }, health: async () => { b = await runGatewayHealthCheck({ cfg: p, runtime: defaultRuntime, port: _, daemonSetupOutcome: y }); } }; if (c) { if (c.length === 0) { outro("No configuration changes selected."); return; } for (const { value: e } of CONFIGURE_SECTION_OPTIONS) { if (e === "daemon" || e === "health" || !c.includes(e)) continue; const n = p; await C[e](); h ||= e !== "memory" || p !== n; } await persistPendingConfig(); for (const e of ["daemon", "health"]) if (c.includes(e)) await C[e](); } else { let e = false; while (true) { const n = await configurePrompts.select({ message: "What do you want to configure?", options: [...CONFIGURE_SECTION_OPTIONS, { value: "__continue", label: e ? "Done" : "Skip for now" }], initialValue: CONFIGURE_SECTION_OPTIONS[0]?.value }); if (n === "__continue") break; e = true; if (n === "daemon" || n === "health") await persistPendingConfig(); const r = p; await C[n](); if (n !== "daemon" && n !== "health") { h ||= n !== "memory" || p !== r; await persistPendingConfig(); } } if (!e) { if (h) { await persistPendingConfig(); outro("Gateway mode set to local."); return; } outro("No configuration changes selected."); return; } } const w = [...y === "failed" ? ["daemon setup"] : [], ...b === "failed" ? ["health check"] : []]; let T = v ? "Configuration updated." : "No configuration changes selected."; if (w.length > 0) T = `${v ? "Configuration updated" : "Configuration unchanged"}, but ${w.join(" and ")} failed.`; else if (!v && b) T = `Health check ${b === "succeeded" ? "completed" : "skipped"}.`; else if (!v && y) T = `Daemon setup ${y === "succeeded" ? "completed" : "skipped"}.`; if (f) { const e = normalizeOptionalString(p.gateway?.remote?.url); if (e) note([ "Remote Gateway:", e, "Docs: https://docs.openclaw.ai/gateway/remote" ].join("\n"), "Gateway"); outro(T); return; } const E = p.gateway?.bind ?? "loopback"; const D = { bind: E, port: _, customBindHost: p.gateway?.customBindHost, basePath: p.gateway?.controlUi?.basePath, tlsEnabled: p.gateway?.tls?.enabled === true }; const O = await resolveAdvertisedControlUiLinks(D); const k = resolveLocalControlUiProbeLinks(D); const A = await resolveGatewayProbeAuthSafeWithSecretInputs({ cfg: p, env: process.env, mode: "local", localPrecedence: "env-first" }); const j = y === "succeeded" ? waitForGatewayReachable : probeGatewayReachable; let M = A.warning ? { ok: false, detail: "auth unavailable; check skipped" } : await j({ ...y === "succeeded" ? resolveGatewayStartupTiming() : {}, url: k.wsUrl, token: A.auth.token, password: A.auth.password }); if (!M.ok && !A.warning && s.gateway?.auth?.password) { const e = await resolveGatewayProbeAuthSafeWithSecretInputs({ cfg: s, env: process.env, mode: "local", localPrecedence: "env-first" }); if (!e.warning && e.auth.password && A.auth.password !== e.auth.password) M = await probeGatewayReachable({ url: k.wsUrl, token: A.auth.token, password: e.auth.password }); } const N = A.warning ? "Gateway: auth unavailable (check skipped)" : M.ok ? "Gateway: reachable" : terminalText`Gateway: not detected${M.detail ? ` (${M.detail})` : ""}`; const P = formatWindowsGatewayFirewallGuidance({ bind: E }); note([ terminalText`Web UI: ${O.httpUrl}`, terminalText`Gateway WS: ${O.wsUrl}`, N, ...P, "Docs: https://docs.openclaw.ai/web/control-ui" ].join("\n"), "Control UI"); outro(T); } catch (e) { if (e instanceof WizardCancelledError) { defaultRuntime.exit(1); return; } throw e; } } //#endregion //#region src/commands/configure.commands.ts /** * Non-interactive config subcommands surfaced when the wizard cannot run. * Mirrors the real `openclaw config <sub>` surface so the message only ever * points users at commands that exist (see `src/cli/config-cli.ts`). */ const CONFIGURE_NON_TTY_HINT = [ "Interactive configuration requires an interactive terminal (TTY).", "For non-interactive setup, use these subcommands instead:", ` ${formatCliCommand("openclaw config set <path> <value>")} write a config entry`, ` ${formatCliCommand("openclaw config get <path>")} read a config entry`, ` ${formatCliCommand("openclaw config patch")} apply a JSON patch`, ` ${formatCliCommand("openclaw config validate")} validate configuration` ].join("\n"); /** Parse `--section` input and run the requested configure wizard sections. */ async function configureCommandFromSectionsArg(e) { const { sections: n, invalid: r } = parseConfigureWizardSections(e); if (r.length > 0) { defaultRuntime.error(terminalText`Invalid --section: ${r.map((e) => e || "\"\"").join(", ")}. Expected one of: ${CONFIGURE_WIZARD_SECTIONS.join(", ")}. Run ${formatCliCommand("openclaw configure")} without --section to use the full wizard.`); defaultRuntime.exit(1); return; } if (!isTerminalInteractive()) { defaultRuntime.error(CONFIGURE_NON_TTY_HINT); defaultRuntime.exit(1); return; } await runConfigureWizard(n.length > 0 ? { sections: n } : {}); } //#endregion export { configureCommandFromSectionsArg };