UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

589 lines (588 loc) • 23 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { o as writeRuntimeJson, r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { i as redactSecrets } from "./redact-Mj7pppxC.mjs"; import { a as createGatewayEnvSecretRef } from "./ref-contract-b8L-9DrQ.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./utils-C8YECn2Q.mjs"; import { b as resolveGatewayPort, s as isDefaultStateDir } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as listAgentEntries } from "./agent-roster-t1ooUdXp.mjs"; import "./agent-scope-config-DmXgFGKP.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as resolveCanonicalConfiguredSecretInputWithFallback } from "./resolve-configured-secret-input-string-CzTHGWPa.mjs"; import { t as withOpenClawStateLease } from "./openclaw-state-lease-Cn13CM0c.mjs"; import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { o as withPluginLifecycleLease } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { t as resolveGatewayStartupTiming } from "./gateway-startup-timing-BGts4IhB.mjs"; import { t as gatewayCredentialScope } from "./gateway-origin-scope-SP9yyLnR.mjs"; import { n as preserveGatewaySshRemotePort } from "./connection-details-BWzGtdxz.mjs"; import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs"; import { r as resolveLocalControlUiProbeLinks } from "./control-ui-links-tAtEMm92.mjs"; import { n as applyWizardMetadata, p as waitForGatewayReachable, t as DEFAULT_WORKSPACE, u as probeGatewayReachable } from "./onboard-helpers-I6fwzX78.mjs"; import { a as ensureOnboardingAgentWorkspace, c as resolveOnboardingAgentTarget, l as resolveOnboardingSetupTarget } from "./onboard-agent-target-D7VNwjZB.mjs"; import { t as enableDefaultOnboardingInternalHooks } from "./onboard-hooks-PtiyNF0u.mjs"; import { t as createNonInteractiveLoggingPrompter } from "./non-interactive-prompter-DfC9Cfxv.mjs"; import { r as logConfigUpdated } from "./logging-D0RirHBi.mjs"; import { t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-agdJw6fb.mjs"; import { t as resolveGatewayAuthToken } from "./auth-token-resolution-CUaXbu3r.mjs"; import { n as applySkipBootstrapConfig, r as resolveOnboardingWorkspaceConflict, t as applyLocalSetupWorkspaceConfig } from "./onboard-config-6HrUmKtD.mjs"; import { u as withSetupMigrationTargetLock } from "./setup.migration-snapshot-Brz-tpao.mjs"; import { t as rejectOnboardingOption } from "./onboard-options-CrkNjPND.mjs"; import { t as applyNonInteractiveGatewayConfig } from "./gateway-config-CKjXrNgc.mjs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/onboard-non-interactive/config-write.ts /** Commits a non-interactive onboard config update with pending plugin records handled first. */ async function commitNonInteractiveOnboardConfig(e) { const { writeWizardConfigFile: t } = await import("./setup.shared-D5wOOEt0.mjs"); return (await t(e.nextConfig, { mergeBase: e.baseConfig, allowConfigSizeDrop: e.reset === true, ...e.baseHash !== void 0 ? { baseHash: e.baseHash } : {} })).nextConfig; } //#endregion //#region src/commands/onboard-non-interactive/local.ts function formatGatewayRuntimeSummary(e) { const t = e?.service; if (!t?.runtimeStatus) return; const n = [t.runtimeStatus]; if (typeof t.pid === "number") n.push(`pid ${t.pid}`); if (t.state) n.push(`state ${t.state}`); if (typeof t.lastExitStatus === "number") n.push(`last exit ${t.lastExitStatus}`); if (t.lastExitReason) n.push(`reason ${t.lastExitReason}`); return n.join(", "); } function classifyGatewayHealthFailure(e) { const t = e.detail ?? ""; const n = /\b(?:econnrefused|connection refused|connect refused)\b/i.test(t); const r = e.diagnostics?.lastGatewayError ?? ""; const i = `${t}\n${r}`; if (/\b(?:unauthorized|forbidden|invalid token|invalid password|auth mismatch)\b/i.test(i)) return "auth-mismatch"; if (/\b(?:runtime[- ]deps?|runtime dependencies|cannot find (?:module|package)|(?:err_)?module_not_found|sqlite-vec|loadextension)\b/i.test(i)) return "module-missing"; if (e.diagnostics?.service?.loadState.status === "not-loaded" && n) return "service-missing"; const a = e.diagnostics?.service?.runtimeStatus; if (a && a !== "running" && a !== "active" && n) return "service-stopped"; if (r.trim()) return "startup-blocked"; if (n) return "not-listening"; } function recoveryHintForGatewayHealthFailure(e) { switch (e) { case "auth-mismatch": case "module-missing": return `Fix: run \`${formatCliCommand("openclaw doctor --fix")}\`.`; case "service-missing": return `Fix: run \`${formatCliCommand("openclaw gateway install --force")}\`.`; case "service-stopped": return `Fix: run \`${formatCliCommand("openclaw gateway restart")}\`.`; case "startup-blocked": return `Fix: run \`${formatCliCommand("openclaw gateway status --deep")}\`.`; case "not-listening": return `Fix: start \`${formatCliCommand("openclaw gateway run")}\`, or run \`${formatCliCommand("openclaw gateway restart")}\` for a managed gateway.`; default: return; } } function logNonInteractiveOnboardingFailure(e) { const t = classifyGatewayHealthFailure({ detail: e.detail, diagnostics: e.diagnostics }); const n = e.hints?.filter(Boolean) ?? []; const r = n.some((e) => e.startsWith("Fix:")) ? void 0 : recoveryHintForGatewayHealthFailure(t); const i = [...r ? [r] : [], ...n]; const a = redactSecrets({ message: e.message, detail: e.detail, hints: i, gateway: e.gateway, daemonInstall: e.daemonInstall, daemonRuntime: e.daemonRuntime, diagnostics: e.diagnostics }); const o = formatGatewayRuntimeSummary(a.diagnostics); const s = a.diagnostics?.service; const c = s ? s.loadState.status === "loaded" ? s.loadedText : s.loadState.status.replace("-", " ") : void 0; if (e.opts.json) { writeRuntimeJson(e.runtime, { ...formatCliJsonFailure(a.message), mode: e.mode, phase: e.phase, message: a.message, classification: t, detail: a.detail, gateway: a.gateway, installDaemon: Boolean(e.installDaemon), daemonInstall: a.daemonInstall, daemonRuntime: a.daemonRuntime, diagnostics: a.diagnostics, hints: a.hints.length > 0 ? a.hints : void 0 }); return; } const l = [ a.message, t ? `Classification: ${t}` : void 0, a.detail ? `Last check: ${a.detail}` : void 0, s ? `Service: ${s.label} (${c})` : void 0, o ? `Runtime: ${o}` : void 0, a.diagnostics?.lastGatewayError ? `Recent Gateway log error (may be from an earlier run): ${a.diagnostics.lastGatewayError}` : void 0, a.diagnostics?.inspectError ? `Diagnostics warning: ${a.diagnostics.inspectError}` : void 0, a.hints.length > 0 ? a.hints.join("\n") : void 0 ].filter(Boolean).join("\n"); if (e.informational) e.runtime.log(l); else e.runtime.error(l); } async function collectGatewayHealthFailureDiagnostics() { const e = {}; try { const { readGatewayServiceState: t, resolveGatewayService: n } = await import("./service-D5ZNJZsc.mjs"); const r = n(); const i = await t(r, { env: process.env }); const a = i.runtime; const o = i.loadState.status === "unknown" ? null : i.loadState.status === "loaded"; e.service = { label: r.label, loaded: o, loadState: i.loadState, loadedText: r.loadedText, runtimeStatus: a?.status, state: a?.state, pid: a?.pid, lastExitStatus: a?.lastExitStatus, lastExitReason: a?.lastExitReason }; } catch (t) { e.inspectError = `service diagnostics failed: ${String(t)}`; } try { const { readLastGatewayErrorLine: t } = await import("./diagnostics-NS6J5vya.mjs"); e.lastGatewayError = await t(process.env) ?? void 0; } catch (t) { e.inspectError = e.inspectError ? `${e.inspectError}; log diagnostics failed: ${String(t)}` : `log diagnostics failed: ${String(t)}`; } return e.service || e.lastGatewayError || e.inspectError ? e : void 0; } /** Resolves the auth material used by the post-setup gateway health probe. */ async function resolveGatewayHealthProbeAuth(e) { if (e.gateway?.auth?.mode === "password" || e.gateway?.auth?.mode === "trusted-proxy") { const t = await resolveCanonicalConfiguredSecretInputWithFallback({ config: e, env: process.env, value: e.gateway.auth.password, path: "gateway.auth.password", unresolvedReasonStyle: "detailed", readFallback: () => process.env.OPENCLAW_GATEWAY_PASSWORD }); return { password: t.value, unresolvedRefReason: t.unresolvedRefReason }; } const t = await resolveGatewayAuthToken({ cfg: e, env: process.env, unresolvedReasonStyle: "detailed" }); const n = {}; if (t.token) n.token = t.token; if (t.unresolvedRefReason) n.unresolvedRefReason = t.unresolvedRefReason; return n; } /** Runs local non-interactive setup from config mutation through health verification. */ async function runNonInteractiveLocalSetup(e) { const { opts: t, runtime: n, baseConfig: r, sourceConfigBeforeMigrations: i, baseHash: a } = e; const o = "local"; const s = isDefaultStateDir(process.env) ? DEFAULT_WORKSPACE : path.join(resolveStateDir(process.env), "workspace"); const c = resolveUserPath((t.workspace?.trim() || r.agents?.defaults?.workspace?.trim() || process.env.OPENCLAW_WORKSPACE_DIR?.trim() || s).trim()); const l = listAgentEntries(i).length > 0; if (t.team && l) { rejectOnboardingOption(t, n, "An agent roster already exists. Use `openclaw agents team create` to add a team."); return; } const u = t.agentName ?? (t.team ? "coordinator" : "main"); const d = resolveOnboardingWorkspaceConflict(i, c); const f = d?.currentWorkspaceDir ?? c; if (d) n.error([ "Warning: existing agents keep their current workspace during non-interactive onboarding.", `Current workspace: ${d.currentWorkspaceDir}`, `Requested workspace: ${d.requestedWorkspaceDir}`, `Run \`${formatCliCommand("openclaw onboard --classic")}\` to confirm moving the existing agent fleet.` ].join("\n")); let p = applyLocalSetupWorkspaceConfig(r, c, { allowWorkspaceChange: !l && !d }); if (t.skipBootstrap) p = applySkipBootstrapConfig(p); const m = resolveOnboardingSetupTarget(p, !l && (t.agentName || t.team) ? { name: u, workspaceDir: t.team ? path.join(f, normalizeAgentId(u)) : f } : void 0); const h = t.authChoice ? void 0 : (await import("./auth-choice-inference-Ck9ySLSG.mjs")).inferAuthChoiceFromFlags(t, { config: p, workspaceDir: m.workspaceDir, env: process.env }); if (!t.authChoice && h && h.matches.length > 1) { const e = [ "Multiple API key flags were provided for non-interactive setup.", "Use a single provider flag or pass --auth-choice explicitly.", `Flags: ${h.matches.map((e) => e.label).join(", ")}` ].join("\n"); rejectOnboardingOption(t, n, e); return; } const g = t.authChoice ?? h?.choice ?? "skip"; const _ = await applyNonInteractiveGatewayConfig({ nextConfig: p, opts: t, runtime: n, defaultPort: resolveGatewayPort(r) }); if (!_) return; p = _.nextConfig; if (!t.skipSkills) p = { ...p, skills: { ...p.skills, install: { ...p.skills?.install, nodeManager: t.nodeManager ?? p.skills?.install?.nodeManager ?? "npm" } } }; if (g !== "skip") { const { repairAuthProfileMigration: e } = await import("./auth-profile-repair-B0I6-wjp.mjs"); const i = await e({ cfg: p, prompter: { shouldRepair: true, confirmAutoFix: async () => true } }); p = i.config; for (const e of [...i.storeChanges, ...i.changes]) n.log(e); for (const e of i.warnings) n.error(`Warning: ${e}`); const { applyNonInteractiveAuthChoice: a } = await import("./auth-choice-Bw8J0bsy.mjs"); const o = await a({ nextConfig: p, authChoice: g, opts: t, runtime: n, baseConfig: r, target: m }); if (!o) return; p = o; } if (!t.skipHooks) p = enableDefaultOnboardingInternalHooks(p); const { ensureOnboardingAgent: v } = await import("./onboard-agent-GWdAerUe.mjs"); const y = await v({ config: p, workspace: f, baseConfig: r, firstAgent: { name: u, ...t.team ? { team: true } : {} }, expectedConfigHash: a ?? null }); for (const e of y.sessionMigrationWarnings ?? []) n.log(`Warning: ${e}`); p = applyLocalSetupWorkspaceConfig(y.config, c); const b = y.configHash ?? a; if (t.skipBootstrap) p = applySkipBootstrapConfig(p); const x = resolveOnboardingAgentTarget(p, y.agentId); await ensureOnboardingAgentWorkspace(x, n, { skipBootstrap: Boolean(p.agents?.defaults?.skipBootstrap), skipOptionalBootstrapFiles: p.agents?.defaults?.skipOptionalBootstrapFiles }); p = applyWizardMetadata(p, { command: "onboard", mode: o }); p = await commitNonInteractiveOnboardConfig({ nextConfig: p, baseConfig: y.configBase, baseHash: b, reset: t.reset }); logConfigUpdated(n); const { initializeFreshDaemonRuntimePinMigration: S } = await import("./state-migrations.daemon-runtime-pins-D86JRnHq.mjs"); S(process.env); const C = t.daemonRuntime ?? "node"; let w; let T = false; if (t.installDaemon) { const { installGatewayDaemonNonInteractive: e } = await import("./daemon-install-hn_BQtOV.mjs"); const r = await e({ nextConfig: p, opts: t, runtime: n, port: _.port }); w = { requested: true, installed: r.installed, ...!r.installed ? { skippedReason: r.skippedReason } : {} }; if (!r.installed) { logNonInteractiveOnboardingFailure({ opts: t, runtime: n, mode: o, phase: "daemon-install", message: r.skippedReason === "systemd-user-unavailable" ? "Gateway service install is unavailable because systemd user services are not reachable in this Linux session." : "Gateway service install did not complete successfully.", installDaemon: true, daemonInstall: w, daemonRuntime: C, hints: r.skippedReason === "systemd-user-unavailable" ? ["Fix: rerun without `--install-daemon` for one-shot setup, or enable a working user-systemd session and retry.", "If your auth profile uses env-backed refs, keep those env vars set in the shell that runs `openclaw gateway run` or `openclaw agent --local`."] : [`Run \`${formatCliCommand("openclaw gateway status --deep")}\` for more detail.`] }); n.exit(1); return; } } if (!t.skipHealth) { const { healthCommandNonExiting: e } = await import("./health-DfcXdtuz.mjs"); const r = resolveLocalControlUiProbeLinks({ bind: _.bind, port: _.port, customBindHost: p.gateway?.customBindHost, basePath: void 0, tlsEnabled: p.gateway?.tls?.enabled === true }); const i = { opts: t, runtime: n, mode: o, phase: "gateway-health", gateway: { wsUrl: r.wsUrl, httpUrl: r.httpUrl }, installDaemon: Boolean(t.installDaemon), daemonInstall: w, daemonRuntime: t.installDaemon ? C : void 0 }; const a = t.installDaemon ? resolveGatewayStartupTiming() : { deadlineMs: 15e3 }; const s = await resolveGatewayHealthProbeAuth(p); const c = { url: r.wsUrl, token: s.token, password: s.password }; const l = t.installDaemon === false ? await probeGatewayReachable(c) : await waitForGatewayReachable({ ...c, ...a }); if (!l.ok) { const e = [l.detail, s.unresolvedRefReason].filter(Boolean).join("\n") || void 0; const a = t.installDaemon ? await collectGatewayHealthFailureDiagnostics() : void 0; const o = t.installDaemon === false && classifyGatewayHealthFailure({ detail: e, diagnostics: a }) === "not-listening"; if (o && !t.json) n.log("Setup complete; gateway was not installed or started because daemon installation was explicitly skipped."); if (!o || !t.json) logNonInteractiveOnboardingFailure({ ...i, message: `Gateway did not become reachable at ${r.wsUrl}.`, detail: e, diagnostics: a, hints: !t.installDaemon ? [ "Non-interactive local setup only waits for an already-running gateway unless you pass `--install-daemon` to `openclaw onboard`.", `Fix: start \`${formatCliCommand("openclaw gateway run")}\`, re-run \`${formatCliCommand("openclaw onboard --install-daemon")}\`, or use \`${formatCliCommand("openclaw onboard --skip-health")}\`.`, process.platform === "win32" ? "Native Windows managed gateway install tries Scheduled Tasks first and falls back to a per-user Startup-folder login item when task creation is denied." : void 0 ].filter((e) => Boolean(e)) : [`Run \`${formatCliCommand("openclaw gateway status --deep")}\` for more detail.`], informational: o }); if (!o) { n.exit(1); return; } T = true; } else { const a = []; const o = t.json ? { ...n, log: (...e) => { a.push(e.map(String).join(" ")); } } : n; try { await e({ json: false, timeoutMs: t.installDaemon && process.platform === "win32" ? 9e4 : 1e4, config: p, localPortOverride: _.port, token: s.token, password: s.password }, o); } catch (e) { const t = e instanceof ExitError ? a.join("\n") || void 0 : formatErrorMessage(e); logNonInteractiveOnboardingFailure({ ...i, message: `Gateway is reachable at ${r.wsUrl}, but the health check failed.`, detail: t, hints: [`Run \`${formatCliCommand("openclaw health")}\` for full diagnostics.`] }); n.exit(1); return; } } } if (t.json) writeRuntimeJson(n, { ok: true, mode: o, workspace: x.workspaceDir, authChoice: g, gateway: { port: _.port, bind: _.bind, authMode: _.authMode, tailscaleMode: _.tailscaleMode, ...T ? { reachable: false } : {} }, installDaemon: Boolean(t.installDaemon), daemonInstall: w, daemonRuntime: t.installDaemon ? C : void 0, skipSkills: Boolean(t.skipSkills), skipHealth: Boolean(t.skipHealth) }); if (!t.json) n.log(`Tip: run \`${formatCliCommand("openclaw configure --section web")}\` to store your Brave API key for web_search. Docs: https://docs.openclaw.ai/tools/web`); } //#endregion //#region src/commands/onboard-non-interactive.ts function isMigrationImport(e) { return Boolean(e.importFrom || e.importSource || e.importSecrets || e.flow === "import"); } async function runNonInteractiveSetupExclusive(e, t) { const n = await readConfigFileSnapshot(); if (n.exists && !n.valid) { rejectOnboardingOption(e, t, `Config invalid. Run \`${formatCliCommand("openclaw doctor --fix")}\` to apply supported repairs, then re-run setup.`); return; } const r = n.valid && n.exists ? n.sourceConfig ?? n.config : {}; const i = e.mode ?? "local"; if (isMigrationImport(e)) { /** Runs a setup migration import with non-interactive prompt failures. */ const n = e.importFrom?.trim(); if (!n) { rejectOnboardingOption(e, t, `--import-from is required for non-interactive migration import. Run ${formatCliCommand("openclaw migrate list")} to choose a provider.`); return; } const { detectSetupMigrationSources: i, runSetupMigrationImport: a } = await import("./setup.migration-import-ZmDRZ1Wd.mjs"); const o = await i({ config: r, runtime: t }); const readValidSnapshot = async () => { const e = await readConfigFileSnapshot(); if (!e.valid) throw new Error("Migration target config became invalid. Run `openclaw doctor --fix` to apply supported repairs."); return e; }; const s = await a({ opts: { ...e, importFrom: n, nonInteractive: true }, baseConfig: r, ...o, prompter: createNonInteractiveLoggingPrompter(t, (e) => `Non-interactive migration import needs explicit flags before prompting: ${e}`), runtime: t, async readConfigFile() { const e = await readValidSnapshot(); return e.exists ? e.sourceConfig ?? e.config : {}; }, async commitConfigFile(e, n) { const r = await readValidSnapshot(); const i = r.exists ? r.sourceConfig ?? r.config : {}; if (!isDeepStrictEqual(i, n)) throw new ConfigMutationConflictError("config changed during migration promotion"); const a = await replaceConfigFile({ sourceConfig: e, snapshot: r, ...r.hash !== void 0 ? { baseHash: r.hash } : {}, writeOptions: { allowConfigSizeDrop: true } }); logConfigUpdated(t); return a.nextConfig; } }); if (s.kind === "back") throw new Error("Non-interactive migration import cannot navigate back."); await s.acknowledgePromotion?.(); return; } if (i === "remote") { const a = normalizeOptionalString(e.remoteUrl); const o = normalizeOptionalString(e.remoteToken); const s = normalizeOptionalString(e.remotePassword); const c = r.gateway?.remote; const l = gatewayCredentialScope(c?.url ?? "") !== gatewayCredentialScope(a ?? "") ? {} : { ...c, ...preserveGatewaySshRemotePort(r, a) }; if (o) delete l.password; if (s) delete l.token; const u = { ...l, url: a }; if (o) u.token = e.secretInputMode === "ref" ? createGatewayEnvSecretRef(r, "OPENCLAW_GATEWAY_TOKEN") : o; if (s) u.password = e.secretInputMode === "ref" ? createGatewayEnvSecretRef(r, "OPENCLAW_GATEWAY_PASSWORD") : s; let d = { ...r, gateway: { ...r.gateway, mode: "remote", remote: u } }; if (e.skipBootstrap) d = applySkipBootstrapConfig(d); d = applyWizardMetadata(d, { command: "onboard", mode: i }); await commitNonInteractiveOnboardConfig({ nextConfig: d, baseConfig: r, baseHash: n.hash, reset: e.reset }); logConfigUpdated(t); const f = { mode: i, remoteUrl: a, auth: d.gateway?.remote?.token ? "token" : d.gateway?.remote?.password ? ["pass", "word"].join("") : "none" }; if (e.json) writeRuntimeJson(t, f); else { t.log(`Remote gateway: ${a}`); t.log(`Auth: ${f.auth}`); t.log(`Tip: run \`${formatCliCommand("openclaw configure --section web")}\` to store your Brave API key for web_search. Docs: https://docs.openclaw.ai/tools/web`); } return; } await runNonInteractiveLocalSetup({ opts: e, runtime: t, baseConfig: r, sourceConfigBeforeMigrations: n.sourceConfigBeforeMigrations ?? {}, baseHash: n.hash }); } async function runNonInteractiveSetup(e, t = defaultRuntime) { await withSetupMigrationTargetLock(resolveStateDir(), async () => { if (isMigrationImport(e)) { await runNonInteractiveSetupExclusive(e, t); return; } await withOpenClawStateLease({ scope: "core:onboarding", key: "global", database: { scope: "shared" }, leaseMs: 3e5, waitMs: 6e5, leaseLabel: "non-interactive onboarding lease", operationLabel: "onboarding.non-interactive.lease" }, () => withPluginLifecycleLease({}, () => runNonInteractiveSetupExclusive(e, t))); }); } //#endregion export { runNonInteractiveSetup };