UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

447 lines (446 loc) • 17.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { n as isNodeRuntime } from "./runtime-binary-QwVVJ9cA.mjs"; import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs"; import { r as SUPPORTED_NODE_VERSIONS } from "./node-version-CYJ7qOPD.mjs"; import { t as resolveNodeStartupTlsEnvironment } from "./node-startup-env-DXFeSgmy.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { i as isMissingPathError, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { n as parseTcpPort } from "./tcp-port-CuNPxuH-.mjs"; import { b as resolveGatewayPort } from "./paths-DAcAg5aV.mjs"; import { n as isDangerousHostEnvOverrideVarName, o as normalizeEnvVarKey, r as isDangerousHostEnvVarName } from "./host-env-security-BrTYS4pH.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs"; import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs"; import { y as resolveFutureConfigActionBlock } from "./config-env-vars-ByeGN-9N.mjs"; import { o as ServiceStartRefusalError, p as sanitizeServiceInspectionError } from "./service-inspection-error-BKgh5HDJ.mjs"; import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { g as resolveGatewayBindHost, s as isLoopbackHost, t as defaultGatewayBindMode } from "./net-BgRayX-P.mjs"; import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import { r as resolveGatewayAuth } from "./auth-resolve-C6_i-P4T.mjs"; import "./auth-dV1bLOjr.mjs"; import { s as resolveManagedGatewayServiceCommand, t as assertServiceDefinitionWritable } from "./service-types-DdxELPHF.mjs"; import { i as assertGatewayServiceUpdateCurrent, o as isUpdateOwnedGatewayServiceCommand } from "./service-update-authority-wlK0pAdP.mjs"; import { l as isNonFatalSystemdInstallProbeError } from "./systemd-busctl-query-BuQgKtLl.mjs"; import { t as mergeGatewayServiceEnv } from "./service-env-merge-994N__ny.mjs"; import { _ as installDaemonServiceAndEmit, d as resolveDaemonInstallBlockMessage, h as buildDaemonServiceSnapshot, n as createDaemonInstallActionContext } from "./shared-cDUnFvXF.mjs"; import { r as omitSecretEgressProxyEnvironment } from "./environment-DkQljHwc.mjs"; import { l as resolvePreferredNodePath, s as resolvePinnedDaemonRuntimePath, u as resolveRecordedDaemonRuntime } from "./runtime-paths-xW9-a89Z.mjs"; import { d as OPENCLAW_WRAPPER_ENV_KEY, h as resolveOpenClawWrapperPath, n as resolveGatewayService } from "./service-hQiIzcTo.mjs"; import { c as withDaemonRuntimePinMigration, o as readDaemonRuntimePinForInstall } from "./runtime-pin-state-DXPlp4E4.mjs"; import { n as formatInvalidPortOption, t as formatInvalidConfigPort } from "./error-format-O7EzXfiI.mjs"; import { i as resolveGatewayDaemonRuntime, r as isGatewayDaemonRuntime } from "./daemon-runtime-agdJw6fb.mjs"; import { n as resolveRestoreServiceCli, t as assertExpectedRuntimePin } from "./install-restore-cli-BRi0_SdX.mjs"; import { o as readEmbeddedGatewayToken } from "./service-audit-BfaswvZi.mjs"; import { t as buildGatewayInstallPlan } from "./daemon-install-helpers-DYNaMvoO.mjs"; import { t as resolveGatewayInstallToken } from "./gateway-install-token-BUEEPvbI.mjs"; import { t as reconcileGatewayServiceDefinition } from "./service-reconciliation-DTmAjAgt.mjs"; import { constants } from "node:fs"; import fs$1 from "node:fs/promises"; //#region src/cli/daemon-cli/install.ts /** Merge safe existing service environment into the current install invocation environment. */ function mergeInstallInvocationEnv(e) { const t = process.platform; const normalizeInstallEnvKey = (e) => t === "win32" ? e.toUpperCase() : e; const n = {}; for (const [r, i] of Object.entries(omitSecretEgressProxyEnvironment(e.env, t))) { const e = normalizeEnvVarKey(r, { portable: true }); if (!e || isDangerousHostEnvVarName(e)) continue; n[normalizeInstallEnvKey(e)] = i; } if (!e.existingServiceEnv || Object.keys(e.existingServiceEnv).length === 0) return n; const r = {}; for (const [t, n] of Object.entries(e.existingServiceEnv)) { const e = normalizeEnvVarKey(t, { portable: true }); if (!e) continue; const i = e.toUpperCase(); if (i === "OPENCLAW_WRAPPER") { const e = n.trim(); if (e) r[normalizeInstallEnvKey(i)] = e; continue; } if (i === "HOME" || i === "PATH" || i === "TMPDIR" || i === "HOMEBREW_PREFIX" || i.startsWith("OPENCLAW_")) continue; if (isDangerousHostEnvVarName(e) || isDangerousHostEnvOverrideVarName(e) && i !== "NODE_EXTRA_CA_CERTS") continue; const a = n.trim(); if (!a) continue; r[normalizeInstallEnvKey(e)] = a; } return { ...r, ...n }; } /** Install or refresh the managed Gateway service. */ async function runDaemonInstall(e) { let t; const { json: n, stdout: r, warnings: i, warn: a, emit: o, emitMessage: s, fail: c } = createDaemonInstallActionContext(e.json, () => t); const l = resolveDaemonInstallBlockMessage("gateway"); if (l) { c(l); return; } const u = resolveGatewayService(); let d; try { d = await u.readCommand(process.env, { requireEffective: true, allowMissingDefinition: true }); } catch (e) { const t = sanitizeServiceInspectionError(e).message; c(e instanceof ServiceStartRefusalError ? `SERVICE_DEFINITION_UNKNOWN: ${t}` : t); return; } let f; try { f = await u.isLoaded({ env: process.env }); } catch (e) { if (!isNonFatalSystemdInstallProbeError(e)) { c(`Gateway service check failed: ${String(e)}`); return; } f = false; } const p = resolveManagedGatewayServiceCommand(d); const m = p?.environment; const h = mergeInstallInvocationEnv({ env: process.env, existingServiceEnv: m }); let g; try { g = await withDaemonRuntimePinMigration(h, () => readDaemonRuntimePinForInstall({ kind: "gateway", env: h }, d, e.runtime !== void 0 || e.runtimePath !== void 0)); } catch (e) { c(`Runtime pin inspection failed: ${String(e)}`); return; } if (e.expectedRuntimePin !== void 0) try { assertExpectedRuntimePin(e.expectedRuntimePin, g, "Gateway"); } catch (e) { c(e instanceof Error ? e.message : String(e)); return; } let _; let v; if (e.restoreServiceCli !== void 0) try { ({serviceCli: _, runtimePath: v} = await resolveRestoreServiceCli(e.restoreServiceCli, e, h)); } catch (e) { c(e instanceof Error ? e.message : String(e)); return; } if (e.expectedRuntimePin !== void 0) { const { ensureConfigReady: e } = await import("./config-guard-fnQ2CTuK.mjs"); await e({ runtime: defaultRuntime, commandPath: ["gateway", "install"], suppressDoctorStdout: n }); } let y = e.runtimePath ?? (e.runtime ? void 0 : g.pin?.path); const b = mergeGatewayServiceEnv(process.env, d); const assertWritable = async () => { try { for (const e of [b, h]) { const t = await u.readDefinitionMutationCapability?.({ env: process.env, environment: e }).catch(() => ({ kind: "unknown", reason: "inspection-failed" })); if (t) assertServiceDefinitionWritable(t); } return true; } catch (e) { c(`Gateway install blocked: ${String(e)}`); return false; } }; if ((e.force || !f) && !await assertWritable()) return; let { snapshot: x, writeOptions: S } = await readConfigFileSnapshotForWrite(); const C = resolveFutureConfigActionBlock({ action: "install or rewrite the gateway service", snapshot: x }); if (C) { c(`Gateway install blocked: ${C.message}`, C.hints); return; } let w = x.valid ? x.sourceConfig : x.config; const T = parseTcpPort(e.port); if (e.port !== void 0 && T === null) { c(formatInvalidPortOption("--port")); return; } const E = T ?? resolveGatewayPort(w); if (!Number.isFinite(E) || E <= 0 || E > 65535) { c(formatInvalidConfigPort("gateway.port")); return; } const D = e.runtime || g.pin?.runtime || resolveGatewayDaemonRuntime([y ?? ""]); if (!isGatewayDaemonRuntime(D)) { c("Invalid --runtime (use \"node\", \"bun\", or \"standalone\")"); return; } let O = D; let k; if (e.wrapper !== void 0) { try { k = await resolveOpenClawWrapperPath(e.wrapper); } catch (e) { c(`Invalid --wrapper: ${String(e)}`); return; } if (!k) { c("Invalid --wrapper"); return; } } if (!k) try { k = await resolveOpenClawWrapperPath(h[OPENCLAW_WRAPPER_ENV_KEY]); } catch (e) { c(`Invalid ${OPENCLAW_WRAPPER_ENV_KEY}: ${String(e)}`); return; } let A; try { if (!k || e.runtimePath !== void 0) y = await resolvePinnedDaemonRuntimePath(y, O, h); A = k ? void 0 : y ?? v; } catch (e) { c(`Invalid runtime pin: ${String(e)}; reinstall with an explicit --runtime or --runtime-path to replace the saved runtime pin.`); return; } const j = w.gateway?.bind ?? defaultGatewayBindMode(w.gateway?.tailscale?.mode ?? "off"); const M = await resolveGatewayBindHost(j, w.gateway?.customBindHost); function formatNoAuthNonLoopbackInstallBlock() { const e = resolveGatewayAuth({ authConfig: w.gateway?.auth, env: h, tailscaleMode: w.gateway?.tailscale?.mode ?? "off" }); const t = j === "tailnet" || !isLoopbackHost(M); if (e.mode !== "none" || !t) return; const n = [`${j === "tailnet" && isLoopbackHost(M) ? `gateway.bind=tailnet currently resolves to ${M} but can later resolve to a Tailnet interface` : `gateway.bind=${j} resolves to ${M}`}, but gateway.auth.mode=none disables Gateway auth.`]; const r = normalizeOptionalString(e.token) ? "token" : normalizeOptionalString(e.password) ? "password" : void 0; if (r) n.push(`This config already has gateway.auth.${r}; run ${formatCliCommand(`openclaw config set gateway.auth.mode ${r}`)} and then rerun ${formatCliCommand("openclaw gateway install --force")}.`); else n.push(`Configure token/password auth, use trusted-proxy auth, or set ${formatCliCommand("openclaw config set gateway.bind loopback")} before installing the managed service.`); return n.join(" "); } const N = formatNoAuthNonLoopbackInstallBlock(); if (N) { c(`Gateway install blocked: ${N}`); return; } let P; const F = p?.programArguments[0]; const I = O === "node" && !k && !A && (e.runtime === void 0 || isNodeRuntime(F ?? "")) ? await resolveRecordedDaemonRuntime(F, h) : void 0; if (I?.status === "supported" && e.runtime === void 0) { O = I.runtime; A = I.path; } if (I?.runtime === "node") { if (I.status !== "probe-failed" && I.capabilityError) a(I.capabilityError); const t = I.status === "probe-failed" && await fs$1.access(I.path, constants.X_OK).then(() => false, (e) => isMissingPathError(e) || hasErrnoCode(e, "EACCES")) ? `missing Gateway service Node (${I.path})` : I.status === "unsupported" ? `unsupported Gateway service Node ${I.version} (${I.path})` : void 0; if (t) { try { A = await resolvePreferredNodePath({ env: h, runtime: "node", preferCurrentExecPath: true }); } catch (e) { c(`Gateway runtime selection failed: ${String(e)}`); return; } if (!A) { c(`No supported Node runtime is available. Install Node ${SUPPORTED_NODE_VERSIONS}, then rerun openclaw gateway install.`); return; } P = `Replacing ${t} with ${A}; refreshing the install.`; } else if (I.status === "probe-failed" && !e.force) { c(`${I.error.message} Reinstall with: ${formatCliCommand("openclaw gateway install --force")}.`); return; } } const buildInstallPlan = (t) => buildGatewayInstallPlan({ allowUnconfigured: e.allowUnconfigured, env: h, port: E, runtime: O, runtimePath: A, pinnedRuntimePath: y, wrapperPath: k, serviceCli: _, existingCommand: d, existingEnvironment: m, existingEnvironmentValueSources: p?.environmentValueSources, config: w, ...t }); if (f && !e.force) { async function getGatewayServiceAutoRefreshMessage() { const t = e.allowUnconfigured; const n = process.env; const r = e.runtime !== void 0 || e.runtimePath !== void 0; try { const e = resolveManagedGatewayServiceCommand(d); if (!e) return d ? void 0 : "Gateway service definition is missing; refreshing the install."; if (r) return "Gateway runtime selection changed; refreshing the install."; const i = createLazyPromise(() => buildInstallPlan({ warn: () => void 0 })); const a = e.programArguments.includes("--allow-unconfigured"); if (a || t) { if (a !== (await i()).programArguments.includes("--allow-unconfigured")) return "Gateway service start-mode argument differs from the current install plan; refreshing the install."; } const o = readEmbeddedGatewayToken(e); if (o) { const e = await i(); if (o !== normalizeOptionalString(e.environment.OPENCLAW_GATEWAY_TOKEN)) return "Gateway service OPENCLAW_GATEWAY_TOKEN differs from the current install plan; refreshing the install."; } if (Boolean(k || normalizeOptionalString(h["OPENCLAW_WRAPPER"])) || y) { const t = await i(); if (t.programArguments.join("\0") !== e.programArguments.join("\0")) return "Gateway service command differs from the current runtime/wrapper install plan; refreshing the install."; if (normalizeOptionalString(t.environment["OPENCLAW_WRAPPER"]) !== normalizeOptionalString(e.environment?.["OPENCLAW_WRAPPER"])) return `Gateway service ${OPENCLAW_WRAPPER_ENV_KEY} differs from the current wrapper install plan; refreshing the install.`; } const s = e.programArguments[0]?.trim(); if (!s) return; const c = e.environment ?? {}; const l = c.NODE_EXTRA_CA_CERTS?.trim(); if (l && !resolveNodeStartupTlsEnvironment({ env: c, execPath: s }).NODE_EXTRA_CA_CERTS) return "Gateway service trusts the outdated macOS CA bundle; refreshing the install."; const u = resolveNodeStartupTlsEnvironment({ env: { ...n, ...c, NODE_EXTRA_CA_CERTS: void 0 }, execPath: s, includeDarwinDefaults: false }).NODE_EXTRA_CA_CERTS; if (!u) return; if (l !== u) return "Gateway service is missing the nvm TLS CA bundle; refreshing the install."; return; } catch { return; } } P ??= await getGatewayServiceAutoRefreshMessage(); if (P) { if (!await assertWritable()) return; } } if (P) a(P); if (x.valid && w.gateway?.mode === void 0) { const e = x.sourceConfig ?? x.config; await replaceConfigFile({ sourceConfig: { ...e, gateway: { ...e.gateway, mode: "local" } }, snapshot: x, writeOptions: { baseSnapshot: x, ...S, ...isUpdateOwnedGatewayServiceCommand() ? { assertCurrent: () => { S.assertCurrent?.(); assertGatewayServiceUpdateCurrent(); } } : {}, skipRuntimeSnapshotRefresh: true }, afterWrite: { mode: "auto" } }); const t = await readConfigFileSnapshotForWrite(); x = t.snapshot; S = t.writeOptions; w = x.valid ? x.sourceConfig : x.config; a("No gateway.mode found. Set gateway.mode=local for managed gateway install."); } if (f && !e.force && !P) { s({ ok: true, result: "already-installed", message: `Gateway service already ${u.loadedText}.`, service: buildDaemonServiceSnapshot(u, f) }); if (!n) defaultRuntime.log(`Reinstall with: ${formatCliCommand("openclaw gateway install --force")}`); return; } const L = await resolveGatewayInstallToken({ config: w, env: h, explicitToken: e.token, generateIfMissing: { snapshot: x, writeOptions: S } }); if (L.unavailableReason) { c(`Gateway install blocked: ${L.unavailableReason}`); return; } for (const e of L.warnings) a(e); const { programArguments: R, workingDirectory: z, environment: B, environmentValueSources: V } = await buildInstallPlan({ runtimeExplicit: e.runtime !== void 0 || e.runtimePath !== void 0, warn: a }); const install = async (t) => { await u.install({ runtimePinUpdate: { expected: g, pin: y ? { runtime: O, path: y } : void 0, ...e.expectedRuntimePin !== void 0 ? { requireDefinitionMatch: true, ...!_ && g.definition !== void 0 ? { requireRunning: true } : {} } : {} }, env: h, stdout: r, warn: a, programArguments: R, workingDirectory: z, environment: B, environmentValueSources: V, definitionTransaction: t }); }; const H = `Gateway service installed. Runtime readiness has not been checked; startup may still be in progress. Check with ${formatCliCommand("openclaw gateway status")} and ${formatCliCommand("openclaw health")}.`; await installDaemonServiceAndEmit({ serviceNoun: "Gateway", service: u, successMessage: H, onVerified: async () => { if (!n) defaultRuntime.log(H); }, warnings: i, emit: o, fail: c, install: async () => { if (isUpdateOwnedGatewayServiceCommand() || isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS)) t = await reconcileGatewayServiceDefinition({ env: h, root: await resolveOpenClawPackageRoot({ moduleUrl: import.meta.url }) ?? void 0, command: d, expectedCommand: { programArguments: R, workingDirectory: z, environment: B, environmentValueSources: V }, install, warn: a }); else await install(); } }); } //#endregion export { runDaemonInstall as n, mergeInstallInvocationEnv as t };