UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

874 lines (873 loc) • 41.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { n as isNodeRuntime } from "./runtime-binary-QwVVJ9cA.mjs"; import { r as SUPPORTED_NODE_VERSIONS } from "./node-version-CYJ7qOPD.mjs"; import { h as resolveDefaultSecretProviderAlias } from "./ref-contract-b8L-9DrQ.mjs"; import { _ as resolveSecretInputRef } from "./types.secrets-BmNLLnHp.mjs"; import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { r as parseTcpPortFromArgs } from "./tcp-port-CuNPxuH-.mjs"; import { C as resolveIsNixMode, b as resolveGatewayPort, o as isDefaultInstallIdentity } from "./paths-DAcAg5aV.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs"; import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { n as NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON, r as assertGatewayServiceMutationAllowed } from "./gateway-supervision-C1X-e8qk.mjs"; import { p as sanitizeServiceInspectionError } from "./service-inspection-error-BKgh5HDJ.mjs"; import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs"; import { a as hasGatewayServiceEnvironmentOverride, o as hasGatewayServiceLauncherOverride, s as resolveManagedGatewayServiceCommand, t as assertServiceDefinitionWritable } from "./service-types-DdxELPHF.mjs"; import { l as summarizeGatewayServiceLayout, r as inspectGatewayServiceInstallationDrift, t as gatewayServiceCommandMatchesRoot } from "./service-layout-C5OySMEw.mjs"; import { n as GatewayServiceAuthorityError } from "./service-update-authority-wlK0pAdP.mjs"; import { p as isSystemdUnitActive } from "./systemd-busctl-query-BuQgKtLl.mjs"; import { t as mergeGatewayServiceEnv } from "./service-env-merge-994N__ny.mjs"; import { o as formatGatewayServiceInstallationDrift } from "./shared-cDUnFvXF.mjs"; import { n as readInstallOwner, t as formatInstallOwnerMessage } from "./install-owner-DDPQXcjQ.mjs"; import { f as resolveSystemNodeInfo, i as renderSystemNodeWarning, o as resolveNodeRuntimeInfo } from "./runtime-paths-xW9-a89Z.mjs"; import { d as OPENCLAW_WRAPPER_ENV_KEY, n as resolveGatewayService } from "./service-hQiIzcTo.mjs"; import { b as isLaunchctlNotLoaded, r as removeBootedOutLaunchAgentPlist, v as execLaunchctl } from "./launchd-service-files-BgSRMq9s.mjs"; import { t as withGatewayServiceOperationLock } from "./service-operation-lock-D6q8s2_X.mjs"; import { a as readDaemonRuntimePin, c as withDaemonRuntimePinMigration } from "./runtime-pin-state-DXPlp4E4.mjs"; import { n as inspectGatewayHeapLimit, t as formatGatewayHeapLimitReport } from "./gateway-heap-BLwYd-BN.mjs"; import { t as readGatewayServiceState } from "./service-state-uYnG1mTd.mjs"; import { a as findSystemdGatewayInstallation, s as isSystemUnitActiveAndEnabled } from "./systemd-scope-BRv8e8-N.mjs"; import { o as uninstallUserSystemdGatewayUnit } from "./systemd-lifecycle-yGkIpc48.mjs"; import { c as normalizeServiceEnvKey, d as readManagedServiceEnvKeysFromEnvironment } from "./service-managed-env-BculT5iw.mjs"; import "./systemd-k-QLc2ED.mjs"; import { i as renderGatewayServiceCleanupHints, t as findExtraGatewayServices } from "./inspect-DWWc6709.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { i as resolveGatewayDaemonRuntime } from "./daemon-runtime-agdJw6fb.mjs"; import { t as SERVICE_PROXY_ENV_KEYS } from "./service-env-BbgmtKhw.mjs"; import { a as needsNodeRuntimeMigration, n as auditGatewayServiceConfig, o as readEmbeddedGatewayToken, t as SERVICE_AUDIT_CODES } from "./service-audit-BfaswvZi.mjs"; import { t as resolveGatewayAuthToken } from "./auth-token-resolution-CUaXbu3r.mjs"; import { t as buildGatewayInstallPlan } from "./daemon-install-helpers-DYNaMvoO.mjs"; import { a as isServiceRepairDeferred, i as formatServiceRepairDeferredNote, l as shouldManageGatewayService, r as confirmDoctorServiceRepair, s as resolveServiceRepairPolicy } from "./doctor-service-repair-policy-DAuL0W8-.mjs"; import { n as cleanupLegacyLinuxUserServices, t as classifyLegacyServices } from "./doctor-gateway-legacy-services-BBb-0U5c.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import os from "node:os"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/doctor-gateway-auth-token.ts /** Preserve a recovered credential without overwriting any existing store entry. */ async function preserveGatewayAuthTokenForService(e) { const { listSecretStoreEntries: t, readSecretStoreValue: n, writeSecretStoreEntryForConfigRef: r } = await import("./secret-store-xf4-UqW-.mjs"); const i = { env: e.env }; const a = { kind: "team" }; const o = resolveDefaultSecretProviderAlias(e.cfg, "store", { preferFirstProviderForSource: true }); for (const r of await t({ scope: a, database: i, assertCurrent: e.assertCurrent })) { const t = await n({ scope: a, database: i, name: r.name, assertCurrent: e.assertCurrent }); e.assertCurrent?.(); if (!t.ok) { if (t.error.code === "SECRET_STORE_NOT_FOUND") continue; throw new Error(t.error.message); } if (t.value === e.token) return { ref: { source: "store", provider: o, id: r.name }, reused: true }; } const { stat: s } = await import("node:fs/promises"); const { randomUUID: c } = await import("node:crypto"); const { resolveOpenClawStateSqlitePath: l } = await import("./openclaw-state-db.paths-DiM3pkKt.mjs"); const u = l(e.env); const d = await s(u).catch(ignoreMissingPath); let f; if (d) { const { createVerifiedSqliteSnapshot: t } = await import("./sqlite-snapshot-DGhn22ul.mjs"); e.assertCurrent?.(); ({path: f} = await t({ sourcePath: u, targetPath: `${u}.doctor-gateway-token.${c()}.bak`, preserveRowIds: true })); } return { ref: { source: "store", provider: o, id: await r({ baseName: "OPENCLAW_GATEWAY_TOKEN", value: e.token, updatedBy: "doctor", database: i, assertCurrent: e.assertCurrent }) }, reused: false, backupPath: f }; } /** * Resolves the token a managed gateway service can receive at install/update time. * * Exec SecretRefs are skipped by default because the service installer cannot safely evaluate * arbitrary commands. Configured SecretRefs never fall back to ambient credentials. */ async function resolveGatewayAuthTokenForService(e, t, n = {}) { if (resolveSecretInputRef({ value: e.gateway?.auth?.token, defaults: e.secrets?.defaults }).ref?.source === "exec" && n.allowExecSecretRefs !== true) return { unavailableReason: "gateway.auth.token SecretRef is configured but unavailable because exec SecretRef resolution is disabled." }; const r = await resolveGatewayAuthToken({ cfg: e, env: t, unresolvedReasonStyle: "detailed" }); if (r.token) return { token: r.token }; if (!r.secretRefConfigured) return {}; if (r.unresolvedRefReason?.includes("resolved to an empty value")) return { unavailableReason: r.unresolvedRefReason }; return { unavailableReason: `gateway.auth.token SecretRef is configured but unresolved (${r.unresolvedRefReason ?? "unknown reason"}).` }; } //#endregion //#region src/commands/doctor-service-audit.ts function formatServiceConfigIssues(e) { return e.map(({ message: e, detail: t }) => `- ${e}${t ? ` (${t})` : ""}`); } /** Keep source-checkout and native audit findings in one panel. */ function reportGatewayServiceConfigAudit(e, t, n) { const r = t?.entrypointSourceCheckout ? [`Gateway service entrypoint resolves to a source checkout: ${t.packageRootReal ?? t.packageRoot ?? t.entrypointReal ?? t.entrypoint}.`, `Run \`${formatCliCommand("openclaw gateway install --force")}\` from the intended package install to replace the gateway service definition.`].join("\n") : null; const i = e.issues.some((e) => e.code === SERVICE_AUDIT_CODES.gatewayEntrypointMismatch) ? null : r; if (e.issues.length === 0 && !n) { if (i !== null) note(i, "Gateway service config"); return i; } note([...i !== null ? [i, ""] : [], ...formatServiceConfigIssues(e.issues)].join("\n"), "Gateway service config"); return i; } /** Describe the selected install plan without changing runtime or launcher policy. */ function formatGatewayServiceRepairPreview(e) { const t = []; if (e.missingSystemNode) { const n = e.runtimeIssues.some((e) => e.code === SERVICE_AUDIT_CODES.gatewayRuntimeNode || e.code === SERVICE_AUDIT_CODES.gatewayRuntimeBun); t.push({ checkId: "core/doctor/gateway-service", severity: n ? "error" : "warning", category: n ? "fix-now" : "recommended", message: `No supported system Node is available; this repair retains ${e.plan.programArguments[0]}.`, fixHint: `Install system Node ${SUPPORTED_NODE_VERSIONS} and rerun Doctor to resolve the runtime finding.`, docsUrl: "https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs" }); } if (e.plannedLayout?.entrypointSourceCheckout) t.push({ checkId: "core/doctor/gateway-service", severity: "warning", category: "recommended", message: "This repair retains a source-checkout entrypoint.", fixHint: `Run \`${formatCliCommand("openclaw gateway install --force")}\` from the intended package install to replace it.`, docsUrl: "https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs" }); return { preview: [ `Runtime: ${e.managedDefinition.programArguments[0]} -> ${e.plan.programArguments[0]}`, `Entrypoint: ${e.currentLayout?.entrypoint ?? "not identified"} -> ${e.plannedLayout?.entrypoint ?? "not identified"}`, `PATH: ${e.command.environment?.PATH ?? "not set"} -> ${e.plan.environment?.PATH ?? "not set"}`, ...(e.definitionDrift ?? []).flatMap((e) => e.kind === "outdated" && (e.key === "ExitTimeOut" || e.key === "TimeoutStopSec") ? [`Shutdown budget (${e.key}): ${String(e.current)} -> ${String(e.expected)}`] : []), ...t.map((e) => `Will remain: ${e.message} ${e.fixHint}`) ].join("\n"), unresolvedFindings: t }; } function reportServiceDefinitionDrift(e) { const t = [...(e.definitionDrift ?? []).map((e) => e.message), ...e.definitionDriftError ? [e.definitionDriftError] : []]; if (t.length > 0) note(t.map((e) => `- ${e}`).join("\n"), "Gateway service definition"); } /** Installation repair cannot implicitly approve other service-definition changes. */ function isServiceInstallationOnlyRepair(e) { return !e.definitionDriftError && !e.definitionDrift?.length && e.issues.every((e) => e.code === SERVICE_AUDIT_CODES.gatewayEntrypointMismatch); } function hasRepairableServiceDefinitionDrift(e) { return !e.definitionDriftError && e.definitionDrift?.some((e) => e.kind === "outdated") === true && !e.definitionDrift.some((e) => e.kind === "unknown-edit"); } function isPreservedLaunchdTimeoutWarning(e) { return e.issues.every((e) => e.code === "launchd-stop-timeout") && e.definitionDrift?.some((e) => e.kind === "preserved" && e.key === "ExitTimeOut") === true; } /** Native policy repair must not auto-approve unrelated command or credential changes. */ function isServiceDefinitionOnlyRepair(e) { const t = /* @__PURE__ */ new Set([ SERVICE_AUDIT_CODES.gatewayEgressProxyEnvEmbedded, SERVICE_AUDIT_CODES.systemdAfterNetworkOnline, SERVICE_AUDIT_CODES.systemdWantsNetworkOnline, SERVICE_AUDIT_CODES.systemdRestartSec, SERVICE_AUDIT_CODES.systemdKillModeProcessOrNone, SERVICE_AUDIT_CODES.systemdKillModeControlGroup, SERVICE_AUDIT_CODES.systemdStopTimeout, "launchd-run-at-load", "launchd-keep-alive", "launchd-stop-timeout", "launchd-env-wrapper-outdated" ]); return e.issues.every((e) => t.has(e.code)); } /** The install plan retains pins/wrappers; only a changed, owned Node runtime is repairable. */ async function canRepairRuntime(e, t, n, r, i) { const a = /* @__PURE__ */ new Set([ SERVICE_AUDIT_CODES.gatewayRuntimeNode, SERVICE_AUDIT_CODES.gatewayRuntimeNodeVersionManager, SERVICE_AUDIT_CODES.gatewayRuntimeNodeSystemMissing, SERVICE_AUDIT_CODES.gatewayPathMissing, SERVICE_AUDIT_CODES.gatewayPathMissingDirs, SERVICE_AUDIT_CODES.gatewayPathNonMinimal ]); return !r?.entrypointSourceCheckout && !hasGatewayServiceLauncherOverride(t) && n.runtime === "node" && n.programArguments[0] !== resolveManagedGatewayServiceCommand(t)?.programArguments[0] && e.issues.some((e) => e.code === SERVICE_AUDIT_CODES.gatewayRuntimeNode) && e.issues.every((e) => a.has(e.code)) && !e.definitionDriftError && !e.definitionDrift?.some((e) => e.kind === "unknown-edit" && !(i === "linux" && e.sourcePath && e.sourcePath !== t.sourcePath && t.definitionPaths?.includes(e.sourcePath))) && await gatewayServiceCommandMatchesRoot(r?.packageRootReal, t) === true; } function isOperatorOwnedServiceIssue(e, t, n) { const hasOverride = (e) => hasGatewayServiceEnvironmentOverride(t, e, { environmentValueSources: n }); switch (e.code) { case SERVICE_AUDIT_CODES.gatewayRuntimeNode: return hasGatewayServiceLauncherOverride(t); case SERVICE_AUDIT_CODES.gatewayPathMissing: case SERVICE_AUDIT_CODES.gatewayPathMissingDirs: case SERVICE_AUDIT_CODES.gatewayPathNonMinimal: return hasOverride(["PATH"]); case SERVICE_AUDIT_CODES.gatewayTokenEmbedded: case SERVICE_AUDIT_CODES.gatewayTokenMismatch: case SERVICE_AUDIT_CODES.gatewayTokenDrift: return hasOverride(["OPENCLAW_GATEWAY_TOKEN"]); case SERVICE_AUDIT_CODES.gatewayPasswordEmbedded: return hasOverride(["OPENCLAW_GATEWAY_PASSWORD"]); case SERVICE_AUDIT_CODES.gatewayManagedEnvEmbedded: return hasGatewayServiceEnvironmentOverride(t, e.environmentKeys ?? [], { environmentValueSources: n, normalizeKey: normalizeServiceEnvKey }); case SERVICE_AUDIT_CODES.gatewayEgressProxyEnvEmbedded: return hasOverride(e.environmentKeys ?? []); case SERVICE_AUDIT_CODES.gatewayProxyEnvEmbedded: return hasGatewayServiceEnvironmentOverride(t, (e.environmentKeys ?? []).filter((e) => SERVICE_PROXY_ENV_KEYS.some((t) => t === e)), { ignoreResets: true }); default: return false; } } function reportGatewayServiceFailure(e, t, n) { if (n) n({ checkId: "core/doctor/gateway-service", severity: "error", category: "fix-now", message: e, fixHint: "Run openclaw gateway status --deep from the intended install/profile. Resolve the reported permission or configuration error, then rerun openclaw doctor --fix in an interactive terminal.", docsUrl: "https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs" }); else t.error(e); } function reportUnresolvedGatewayServiceFindings(e, t) { if (!t) { note(e.map((e) => `${e.message} ${e.fixHint}`).join("\n"), "Gateway service findings still unresolved"); return; } for (const n of e) t(n); } function noteDeclinedGatewayServiceRepair(e, t) { if (e) note("Skipped Gateway token preservation and service repair. Rerun `openclaw doctor --fix` in an interactive terminal to approve saving a store SecretRef in gateway.auth.token.", "Gateway service config"); if (t === null) note(`Run \`${formatCliCommand("openclaw gateway install --force")}\` when you want to replace the gateway service definition.`, "Gateway service config"); } //#endregion //#region src/commands/doctor-gateway-installation.ts async function canRepairRunningGatewayDefinition(e) { if ((await e.service.readRuntime(mergeGatewayServiceEnv(e.env, e.command)).catch(() => null))?.status === "running") return true; note(`Gateway native-policy repair requires a running managed service. The existing definition and stop state were preserved; inspect it with \`${formatCliCommand("openclaw gateway status --deep", e.env)}\` before using \`${formatCliCommand("openclaw gateway install --force", e.env)}\`.`, "Gateway service definition"); return false; } /** One native writer retains Doctor custody through publication and recovery. */ async function installDoctorGatewayService(e) { try { const install = async (t = e.maintenance?.assertCurrent) => { const publish = async (n) => { if (e.repair.kind === "definition" && !e.maintenance) { if (!await canRepairRunningGatewayDefinition({ service: e.service, command: e.command, env: e.args.env })) throw new Error("Gateway stopped before native-policy repair; its definition was preserved."); } await e.service.install({ ...e.args, assertCurrent: t, definitionTransaction: n, beforeMutation: e.maintenance?.beforeMutation ?? e.args.beforeMutation }); }; if (e.repair.kind !== "installation" && e.repair.root) { const { reconcileGatewayServiceDefinition: t } = await import("./service-reconciliation-DIY8fLQF.mjs"); await t({ env: e.args.env, root: e.repair.root, command: e.command, expectedCommand: e.args, install: publish, warn: (e) => note(e, "Gateway service definition") }); } else await publish(); }; if (e.repair.kind === "installation") { const t = { service: e.service, command: e.command, activeRoot: e.repair.root, maintenance: e.maintenance, env: e.args.env }; await withGatewayServiceOperationLock(t.env, async (e) => { const assertCurrent = () => { e(); t.maintenance?.assertCurrent(); }; await assertGatewayServiceInstallationRepairAllowed(t); assertCurrent(); await install(assertCurrent); if (process.platform === "win32" && !t.maintenance) await t.service.restart({ env: t.env, stdout: process.stdout, assertCurrent }); }); note("Gateway service installation reconciled with the active CLI.", "Gateway service installation"); } else await install(); } catch (t) { if (t instanceof GatewayServiceAuthorityError || hasCommandProcessCleanupError(t)) throw t; reportGatewayServiceFailure(`Gateway service update failed: ${String(t)}`, e.runtime, e.onFinding); } } /** Doctor consumes the updater's verified ownership; a recorded path alone grants no repair. */ async function assertGatewayServiceInstallationRepairAllowed(e) { const { inspectManagedGatewayServiceBeforeUpdate: t, GATEWAY_SERVICE_INSPECTION_WARNING: n } = await import("./update-command-service-plan-Bc8xWWoh.mjs"); const r = e.maintenance; const i = await readGatewayServiceState(e.service, { env: process.env, requireEffective: true, requireLoadedCommand: true, ...r?.managerUid !== void 0 ? { loadForInspection: { managerUid: r.managerUid, assertCurrent: r.assertCurrent, assertReadCurrent: r.assertReadCurrent } } : {}, validateEnvBeforeStatusRead: (e) => assertGatewayServiceMutationAllowed("repair the gateway service installation", e) }).catch((e) => { throw new Error(`${n} ${sanitizeServiceInspectionError(e).message}`, { cause: e }); }); const a = await t({ state: i, root: e.activeRoot, allowInstallRootChange: true }); r?.assertCurrent(); if (a.kind === "unavailable") throw new Error(a.message); if (!isDeepStrictEqual(i.command, e.command)) throw new Error("Gateway service definition changed during Doctor; rerun doctor to inspect the current installation."); if (a.kind !== "owned" || !a.requiresInstallRootRefresh) throw new Error(`Gateway service installation is controlled by another owner; automatic installation repair was skipped. Inspect it with \`${formatCliCommand("openclaw gateway status --deep", i.env)}\`.`); } const EXECSTART_REPAIR_CODES = /* @__PURE__ */ new Set([SERVICE_AUDIT_CODES.gatewayCommandMissing, SERVICE_AUDIT_CODES.gatewayEntrypointMismatch]); function isExecStartRepairIssue(e) { return EXECSTART_REPAIR_CODES.has(e.code); } function resolveSystemdScopeFromServicePath(e) { const t = e?.replaceAll("\\", "/") ?? ""; return t.startsWith("/etc/systemd/") || t.startsWith("/usr/lib/systemd/") || t.startsWith("/lib/systemd/") ? "system" : "user"; } function resolveSystemdUnitNameFromServicePath(e) { const t = e ? path.posix.basename(e.replaceAll("\\", "/")) : ""; return t.endsWith(".service") ? t : "openclaw-gateway.service"; } async function resolveSystemdServiceRewriteBlock(e, t) { if (process.platform !== "linux" || !t.some(isExecStartRepairIssue)) return; const n = resolveSystemdUnitNameFromServicePath(e.sourcePath); const r = resolveSystemdScopeFromServicePath(e.sourcePath); const i = await isSystemdUnitActive(process.env, n, r); if (!i.ok) return `Could not determine whether gateway service ${n} is active: ${i.error}. Leaving supervisor metadata unchanged. Check \`systemctl${r === "user" ? " --user" : ""} status ${n}\` and rerun doctor.`; if (!i.value) return; t.splice(0, t.length, ...t.filter((e) => !isExecStartRepairIssue(e))); return `Gateway service ${n} is running; skipped command/entrypoint rewrites and leaving supervisor metadata unchanged. Stop the service first or use \`${formatCliCommand("openclaw gateway install --force")}\` when you want to replace the active launcher.`; } //#endregion //#region src/commands/doctor-gateway-runtime-plan.ts /** Builds Doctor service plans while preserving installed runtime and environment intent. */ async function buildExpectedGatewayServicePlan(e) { const t = resolveManagedGatewayServiceCommand(e.command); const n = t?.programArguments[0]; let r = e.runtimePath; if (r === void 0 && !e.pinnedRuntimePath && e.runtime === "node" && !e.serviceInstallEnv["OPENCLAW_WRAPPER"]?.trim() && n && isNodeRuntime(n) && (await resolveNodeRuntimeInfo(n, e.serviceInstallEnv)).status === "supported") r = n; return buildGatewayInstallPlan({ env: e.serviceInstallEnv, port: e.port, runtime: e.runtime, runtimePath: r, pinnedRuntimePath: e.pinnedRuntimePath, existingCommand: e.command, existingEnvironment: t?.environment, existingEnvironmentValueSources: t?.environmentValueSources, warn: (e, t) => note(e, t), config: e.cfg }); } //#endregion //#region src/commands/doctor-gateway-dueling.ts async function maybeResolveDuelingSystemdGatewayScopes(e, t) { if (process.platform !== "linux") return; const n = await findSystemdGatewayInstallation(process.env).catch(() => { note("Could not verify the effective Gateway service identities. Nothing was removed; inspect both units with openclaw gateway status --deep.", "Gateway cleanup needs an owner decision"); return null; }); if (n?.kind !== "dueling") return; const { user: r, system: i } = n; note([ "Both a user-scope and a system-scope OpenClaw gateway unit are installed:", `- user: ${r.unitPath}`, `- system: ${i.unitPath}`, "They bind the same port and will SIGTERM each other in a restart loop." ].join("\n"), "Dueling gateway services detected"); if (!await isSystemUnitActiveAndEnabled(process.env, i.unitName).catch(() => false)) { note([ "Could not verify the system-scope unit is both running and enabled at boot, so the", "user-scope unit may be your working gateway. Not removing anything", "automatically.", "If the system-scope unit is the one you want, activate it and re-run doctor:", `- sudo systemctl enable --now ${i.unitName}`, "If the user-scope unit is the one you want, remove the system unit:", `- sudo systemctl disable --now ${i.unitName} && sudo rm ${i.unitPath}` ].join("\n"), "Gateway cleanup needs an owner decision"); return; } note(["The system-scope unit is the active and boot-enabled supervisor and is", "treated as authoritative; the user-scope unit is the redundant leftover."].join("\n"), "System-scope unit owns the gateway"); const a = resolveServiceRepairPolicy(); if (isServiceRepairDeferred(a)) { note(formatServiceRepairDeferredNote(), "Gateway cleanup skipped"); return; } if (!await confirmDoctorServiceRepair(t, { message: "Remove the redundant user-scope gateway unit and keep the system-scope unit?", initialValue: true }, a)) { const e = renderGatewayServiceCleanupHints(); if (e.length > 0) note(e.map((e) => `- ${e}`).join("\n"), "Cleanup hints"); return; } const o = await findSystemdGatewayInstallation(process.env).catch(() => null); if (o?.kind !== "dueling" || o.user.unitName !== r.unitName || o.user.unitPath !== r.unitPath || o.system.unitName !== i.unitName || o.system.unitPath !== i.unitPath || !await isSystemUnitActiveAndEnabled(process.env, i.unitName).catch(() => false)) { note("Gateway service ownership changed or could not be verified after confirmation. Nothing was removed; inspect both units and run Doctor again.", "Gateway cleanup needs an owner decision"); return; } const s = await uninstallUserSystemdGatewayUnit({ env: process.env, stdout: process.stdout, target: r }).catch((t) => { e.error(`Failed to remove redundant user-scope gateway unit: ${String(t)}`); const n = renderGatewayServiceCleanupHints(); if (n.length > 0) note(n.map((e) => `- ${e}`).join("\n"), "Cleanup hints"); return null; }); if (!s) return; note(s.removed ? `Removed user-scope unit ${s.unitPath}.` : `User-scope unit already absent at ${s.unitPath}.`, "Redundant user gateway removed"); if (!s.disabled) { e.log(`Removed the user-scope unit file, but systemctl was unavailable to stop it. Run: systemctl --user disable --now ${s.unitName} && systemctl --user daemon-reload`); return; } const c = await findSystemdGatewayInstallation(process.env, { requireLoaded: true }).catch(() => null); const l = `Cleanup of ${s.unitName} completed.`; if (c?.kind === "user" || c?.kind === "dueling") e.log(`${l} Another user-scope unit remains at ${c.user.unitPath}. It was not removed. Run openclaw doctor again to inspect it before removal.`); else if (c?.kind === "system" && c.system.unitName === i.unitName && c.system.unitPath === i.unitPath) e.log(`${l} No other matching installed user-scope unit was found.`); else e.log(`${l} Remaining service ownership could not be verified. Run openclaw gateway status --deep and openclaw doctor before any further cleanup.`); } //#endregion //#region src/commands/doctor-gateway-services.ts const DOCTOR_LAUNCHCTL_TIMEOUT_MS = 5e3; const DOCTOR_LAUNCHCTL_CONFIRM_POLL_MS = 100; async function confirmLegacyLaunchdServiceUnloaded(e) { const t = Date.now() + DOCTOR_LAUNCHCTL_TIMEOUT_MS; while (Date.now() < t) { const n = Math.max(1, t - Date.now()); const r = await execLaunchctl(["print", e], Math.min(DOCTOR_LAUNCHCTL_TIMEOUT_MS, n)); if (r.code !== 0) return isLaunchctlNotLoaded(r); const i = Math.min(DOCTOR_LAUNCHCTL_CONFIRM_POLL_MS, t - Date.now()); if (i <= 0) break; await sleep(i); } return false; } async function filterInactiveExtraGatewayServices(e) { if (process.platform !== "linux") return e; const t = []; for (const n of e) { if (n.platform !== "linux" || n.legacy === true) { t.push(n); continue; } const e = await isSystemdUnitActive(process.env, n.label, n.scope); if (!e.ok || e.value) t.push(n); } return t; } async function detectExtraGatewayServiceIssues(e = {}) { if (!isDefaultInstallIdentity(process.env) || !await shouldManageGatewayService()) return { services: [], errors: [] }; const t = await findExtraGatewayServices(process.env, { deep: e.deep }); return { services: await filterInactiveExtraGatewayServices(t.services), errors: t.errors }; } async function cleanupLegacyLaunchdService(e) { const t = typeof process.getuid === "function" ? `gui/${process.getuid()}` : "gui/501"; await execLaunchctl([ "bootout", t, e.plistPath ], DOCTOR_LAUNCHCTL_TIMEOUT_MS); await execLaunchctl(["unload", e.plistPath], DOCTOR_LAUNCHCTL_TIMEOUT_MS); if (!await confirmLegacyLaunchdServiceUnloaded(`${t}/${e.label}`)) return { status: "failed", reason: "launchctl could not confirm unload" }; try { await fs.access(e.plistPath); } catch (e) { if (e.code === "ENOENT") return { status: "removed" }; return { status: "failed", reason: "could not inspect plist" }; } const n = path.join(os.homedir(), ".Trash", `${e.label}-${Date.now()}.plist`); try { const { trashed: t } = await removeBootedOutLaunchAgentPlist(e.plistPath, n); return t ? { status: "removed", destination: n } : { status: "removed" }; } catch { return { status: "failed", reason: "could not move plist" }; } } async function cleanupLegacyDarwinServices(e) { const t = []; const n = []; for (const r of e) { if (!r.sourcePath) { n.push(`${r.label} (missing plist path)`); continue; } const e = await cleanupLegacyLaunchdService({ label: r.label, plistPath: r.sourcePath }); if (e.status === "removed") t.push(e.destination ? `${r.label} -> ${e.destination}` : r.label); else n.push(`${r.label} (${e.reason})`); } return { removed: t, failed: n }; } /** * Audits and optionally rewrites the installed local gateway service configuration. * * The repair preserves managed env sources and avoids Nix/remote installs. * Updater-driven Doctor leaves service publication with update finalization. */ async function maybeRepairGatewayServiceConfig(e, t, n, r, i) { if (!isDefaultInstallIdentity(process.env)) { note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON, "Gateway"); return e; } if (resolveIsNixMode(process.env)) { note("Nix mode detected; skip service updates.", "Gateway"); return e; } if (t === "remote") { note("Gateway mode is remote; skipped local service audit.", "Gateway"); return e; } const a = await resolveOpenClawPackageRoot({ moduleUrl: import.meta.url, argv1: process.argv[1] }); const o = await readInstallOwner(a); if (o) { note(formatInstallOwnerMessage(o), "Gateway runtime"); return e; } const s = resolveServiceRepairPolicy(); const c = isServiceRepairDeferred(s); const l = process.platform; const u = resolveGatewayService(); const d = await u.readCommand(process.env).catch(() => null); if (!d) { const t = await auditGatewayServiceConfig({ env: process.env, command: null, platform: l }); reportServiceDefinitionDrift(t); if (t.issues.length > 0) note(formatServiceConfigIssues(t.issues).join("\n"), "Gateway service config"); return e; } const f = resolveManagedGatewayServiceCommand(d) ?? d; note(formatGatewayHeapLimitReport(inspectGatewayHeapLimit(d.environment?.NODE_OPTIONS, d.programArguments)), "Gateway heap"); const p = f.environment?.[OPENCLAW_WRAPPER_ENV_KEY]?.trim(); const m = await withDaemonRuntimePinMigration(process.env, () => readDaemonRuntimePin({ kind: "gateway", env: process.env }, d)); const h = { ...process.env, ...p && !Object.hasOwn(process.env, "OPENCLAW_WRAPPER") ? { [OPENCLAW_WRAPPER_ENV_KEY]: p } : {} }; const g = normalizeOptionalString(d.environment?.[OPENCLAW_WRAPPER_ENV_KEY]); if (g) note(`Gateway service invokes ${OPENCLAW_WRAPPER_ENV_KEY}: ${g}`, "Gateway"); const _ = await summarizeGatewayServiceLayout(d); const v = await readInstallOwner(_?.packageRootReal ?? _?.packageRoot ?? null); if (v) { note(formatInstallOwnerMessage(v), "Gateway runtime"); return e; } const y = Boolean(resolveSecretInputRef({ value: e.gateway?.auth?.token, defaults: e.secrets?.defaults }).ref); const b = await resolveGatewayAuthTokenForService(e, process.env, { allowExecSecretRefs: i.allowExecSecretRefs === true }); if (b.unavailableReason) note(`Unable to verify gateway service token drift: ${b.unavailableReason}`, "Gateway service config"); const x = y ? void 0 : b.token; const S = resolveGatewayPort(e, process.env); const C = Boolean(h[OPENCLAW_WRAPPER_ENV_KEY]?.trim()); const w = C ? "node" : m.pin?.runtime ?? resolveGatewayDaemonRuntime(f.programArguments); const T = w === "bun" || w === "standalone" ? m.pin?.path ?? f.programArguments[0] : void 0; const E = await buildExpectedGatewayServicePlan({ cfg: e, command: d, serviceInstallEnv: h, port: S, runtime: w, runtimePath: T, pinnedRuntimePath: m.pin?.path }); const D = await summarizeGatewayServiceLayout(E); const O = D?.packageRootReal; const k = O ? await inspectGatewayServiceInstallationDrift(_, O) : void 0; const A = k && e.gateway?.port === void 0 && !process.env.OPENCLAW_GATEWAY_PORT?.trim() ? parseTcpPortFromArgs(d.programArguments) ?? S : S; const j = await auditGatewayServiceConfig({ platform: l, env: process.env, command: d, expectedGatewayToken: x, expectedManagedServiceEnvKeys: readManagedServiceEnvKeysFromEnvironment(E.environment), expectedServicePath: E.environment.PATH, expectedDurableEnvironment: E.environment, expectedPort: A, ...k ? { expectedCommand: E } : {} }); reportServiceDefinitionDrift(j); if (j.runtimeNote) note(j.runtimeNote, "Gateway runtime"); const M = readEmbeddedGatewayToken(d); if (y && M) j.issues.push({ code: SERVICE_AUDIT_CODES.gatewayTokenMismatch, message: "Gateway service OPENCLAW_GATEWAY_TOKEN should be unset when gateway.auth.token is SecretRef-managed", detail: "service token is stale", level: "recommended" }); const N = !C && !m.pin && needsNodeRuntimeMigration(j.issues); const P = N ? await resolveSystemNodeInfo({ env: process.env, platform: l }) : null; const F = P?.status === "supported" ? P.path : null; if (N && !F && w !== "node") note(renderSystemNodeWarning(P) || `System Node ${SUPPORTED_NODE_VERSIONS} not found. Install via Homebrew/apt/choco and rerun doctor to migrate off Bun/version managers.`, "Gateway runtime"); const I = N && F ? await buildExpectedGatewayServicePlan({ cfg: e, command: d, serviceInstallEnv: h, port: A, runtime: "node", runtimePath: F }) : E; const L = I === E ? D : await summarizeGatewayServiceLayout(I); if (L?.entrypointReal && _?.entrypointReal && L.entrypointReal !== _.entrypointReal) j.issues.push({ code: SERVICE_AUDIT_CODES.gatewayEntrypointMismatch, message: "Gateway service entrypoint does not match the current install." + (k ? ` ${formatGatewayServiceInstallationDrift(k, h, { command: d })}` : ""), detail: `${_?.entrypoint} -> ${L?.entrypoint}`, level: "recommended" }); const R = await canRepairRuntime(j, d, I, D, l); const z = !R && !k && Boolean(O) && !D?.entrypointSourceCheckout && hasRepairableServiceDefinitionDrift(j); const B = k ? void 0 : await resolveSystemdServiceRewriteBlock(d, j.issues); if (B) note(B, "Gateway service config"); const V = reportGatewayServiceConfigAudit(j, _, z); j.issues = j.issues.filter((e) => e.repair !== "host"); if (j.issues.length === 0 && !z) return e; if (!z && !k && isPreservedLaunchdTimeoutWarning(j)) return e; if (j.issues.length > 0 && j.issues.every((e) => e.code === SERVICE_AUDIT_CODES.gatewayRuntimeProbeFailed)) return e; const H = j.issues.some((e) => e.level === "aggressive") || k !== void 0 && (j.definitionDriftError !== void 0 || j.definitionDrift?.some((e) => e.kind === "unknown-edit") === true); if (H && !r.shouldForce && !R) note("Custom or unexpected service edits detected. Rerun with --force to overwrite.", "Gateway service config"); if (c) { note(formatServiceRepairDeferredNote(), "Gateway service config"); return e; } if (z && !i.serviceMaintenance && !await canRepairRunningGatewayDefinition({ service: u, command: d, env: h })) return e; if (B) return e; if (l === "linux" && j.issues.some((e) => isExecStartRepairIssue(e) && hasGatewayServiceLauncherOverride(d) || e.code === SERVICE_AUDIT_CODES.gatewayPortMismatch && hasGatewayServiceLauncherOverride(d, { includeWorkingDirectory: false }) || isOperatorOwnedServiceIssue(e, d, E.environmentValueSources))) { const t = resolveSystemdUnitNameFromServicePath(d.sourcePath); const n = `systemctl${resolveSystemdScopeFromServicePath(d.sourcePath) === "user" ? " --user" : ""} cat ${t}`; note(`Gateway service command, working directory, or environment comes from an operator-owned systemd drop-in; rewriting the managed unit cannot repair it. Inspect with \`${n}\`, then update or remove the drop-in and rerun doctor.`, "Gateway service config"); return e; } if (k && O) try { await assertGatewayServiceInstallationRepairAllowed({ service: u, command: d, activeRoot: O, maintenance: i.serviceMaintenance }); } catch (t) { note(String(t), "Gateway service installation"); return e; } const U = x ?? readEmbeddedGatewayToken(f); const W = typeof e.gateway?.auth?.token === "string" ? normalizeOptionalString(e.gateway.auth.token) : void 0; const G = !y && !W && Boolean(U); const { preview: K, unresolvedFindings: q } = formatGatewayServiceRepairPreview({ command: d, managedDefinition: f, plan: I, currentLayout: _, plannedLayout: L, missingSystemNode: N && !F && !R, runtimeIssues: j.issues, definitionDrift: j.definitionDrift }); note(K, "Gateway service repair preview"); if (!await r.confirmRuntimeRepair({ message: G ? "Preserve the Gateway token in the secret store, write its SecretRef to config, and reinstall the service now?" : H && !R ? "Overwrite gateway service config with the repair shown above now?" : "Apply the gateway service repair shown above now?", initialValue: G ? false : H ? r.shouldForce : true, requiresInteractiveConfirmation: G || !(k && isServiceInstallationOnlyRepair(j)) && !R && !(z && isServiceDefinitionOnlyRepair(j)) })) { noteDeclinedGatewayServiceRepair(G, V); return e; } try { for (const e of [mergeGatewayServiceEnv(h, d), I.environment]) { const t = await u.readDefinitionMutationCapability?.({ env: h, environment: e }).catch(() => ({ kind: "unknown", reason: "inspection-failed" })); if (t) assertServiceDefinitionWritable(t); } } catch (t) { reportGatewayServiceFailure(`Gateway service repair blocked: ${String(t)}`, n, i.onFinding); return e; } let J = e; if (G && U) try { const { ref: t, reused: n, backupPath: r } = await preserveGatewayAuthTokenForService({ cfg: e, env: h, token: U, assertCurrent: i.serviceMaintenance?.assertCurrent }); note(n ? `Gateway token already exists in secret store entry "${t.id}"; the store was left unchanged.` : `Saved Gateway token in secret store entry "${t.id}".${r ? ` Backup: ${r}` : ""} If config publication fails, the entry is retained and reused on the next repair.`, "Gateway"); i.serviceMaintenance?.assertCurrent(); J = await i.writeConfig({ ...e, gateway: { ...e.gateway, auth: { ...e.gateway?.auth, mode: e.gateway?.auth?.mode ?? "token", token: t } } }); note("Configured gateway.auth.token as a store SecretRef before reinstalling service.", "Gateway"); } catch (t) { if (t instanceof ConfigWritePostCommitError) throw t; reportGatewayServiceFailure(`Failed to persist gateway.auth.token before service repair: ${String(t)}`, n, i.onFinding); return e; } const Y = await buildExpectedGatewayServicePlan({ cfg: J, command: d, serviceInstallEnv: h, port: A, runtime: N && F ? "node" : w, runtimePath: N && F ? F : T, pinnedRuntimePath: m.pin?.path }); await installDoctorGatewayService({ onFinding: i.onFinding, service: u, command: d, maintenance: i.serviceMaintenance, runtime: n, repair: k && O ? { kind: "installation", root: O } : z && O ? { kind: "definition", root: O } : { kind: "config", ...O && !D?.entrypointSourceCheckout && (R || j.definitionDrift?.some((e) => e.kind === "preserved")) ? { root: O } : {} }, args: { ...Y, runtimePinUpdate: { expected: m, pin: m.pin }, env: h, stdout: process.stdout, warn: (e) => note(e, "Gateway") } }); if (q.length > 0) reportUnresolvedGatewayServiceFindings(q, i.onFinding); return J; } async function maybeScanExtraGatewayServices(e, t, n) { if (!isDefaultInstallIdentity(process.env)) { note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON, "Gateway"); return; } const { services: r, errors: i } = await detectExtraGatewayServiceIssues(e); if (i.length > 0) note(i.map((e) => `- ${e.source}: ${e.message}`).join("\n"), "Gateway service inspection incomplete"); if (r.length === 0) return; note(r.map((e) => `- ${e.label} (${e.scope}, ${e.detail})`).join("\n"), "Other gateway-like services detected"); const a = r.filter((e) => e.legacy === true); if (a.length > 0) { const e = resolveServiceRepairPolicy(); const r = isServiceRepairDeferred(e); if (r) note(formatServiceRepairDeferredNote(), "Legacy gateway cleanup skipped"); if (r ? false : await confirmDoctorServiceRepair(n, { message: "Remove legacy gateway services now?", initialValue: true }, e)) { const e = []; const { darwinUserServices: n, linuxUserServices: r, failed: i } = classifyLegacyServices(a); for (const [a, o] of [[n, () => cleanupLegacyDarwinServices(n)], [r, () => cleanupLegacyLinuxUserServices(r, t)]]) if (a.length > 0) { const t = await o(); e.push(...t.removed); i.push(...t.failed); } if (e.length > 0) note(e.map((e) => `- ${e}`).join("\n"), "Legacy gateway removed"); if (i.length > 0) note(i.map((e) => `- ${e}`).join("\n"), "Legacy gateway cleanup skipped"); } } const o = renderGatewayServiceCleanupHints(r.filter((e) => e.legacy !== true)); if (o.length > 0) note(o.map((e) => `- ${e}`).join("\n"), process.platform === "darwin" ? "Cleanup hints" : "Inspection hints"); note([ "Recommendation: run a single gateway per machine for most setups.", "One gateway supports multiple agents.", "If you need multiple gateways (e.g., a rescue bot on the same host), isolate ports + config/state (see docs: /gateway#multiple-gateways-same-host)." ].join("\n"), "Gateway recommendation"); } //#endregion export { detectExtraGatewayServiceIssues, maybeRepairGatewayServiceConfig, maybeResolveDuelingSystemdGatewayScopes, maybeScanExtraGatewayServices };