openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
441 lines (440 loc) • 18 kB
JavaScript
import { d as resolveGatewayLaunchAgentLabel, h as resolveGatewaySystemdServiceName, v as resolveNodeLaunchAgentLabel } from "./constants-BZisy3jr.mjs";
import { t as ExitError } from "./runtime-B-SLYP-m.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { b as resolveGatewayPort, o as isDefaultInstallIdentity } from "./paths-DAcAg5aV.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { a as getResolvedLoggerFileTarget } from "./logger-1QDNfT7Y.mjs";
import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs";
import { n as NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON } from "./gateway-supervision-C1X-e8qk.mjs";
import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { g as resolveGatewayBindHost, v as resolveGatewayRequiredListenHosts } from "./net-BgRayX-P.mjs";
import "./config-CMA-J084.mjs";
import { r as isWSLEnv, t as isWSL } from "./wsl-I_VtUW9p.mjs";
import { i as readGatewayRestartHandoffSync, n as formatGatewayRestartHandoffDiagnostic } from "./restart-handoff-Cby-pPDg.mjs";
import { l as summarizeGatewayServiceLayout } from "./service-layout-C5OySMEw.mjs";
import { a as isSystemdCgroupHygieneRisk, o as isSystemdStartLimitHit, r as getSystemdCgroupHygieneSummary } from "./service-runtime-BHR12N-P.mjs";
import { l as classifySystemdUnavailableDetail } from "./systemd-user-transport-BwOKajKM.mjs";
import { a as buildGatewayRuntimeRecoveryHints, i as renderSystemdUnavailableHints, r as isSystemdUnavailableDetail, t as formatRuntimeStatus } from "./runtime-format-7s5oelVT.mjs";
import { n as readInstallOwner, t as formatInstallOwnerMessage } from "./install-owner-DDPQXcjQ.mjs";
import { n as resolveGatewayService, t as describeGatewayServiceRestart } from "./service-hQiIzcTo.mjs";
import { i as isLaunchAgentLoaded, s as launchAgentPlistExists } from "./launchd-runtime-DS9pQoDc.mjs";
import { a as repairLaunchAgentBootstrap } from "./launchd-BlyjKZEQ.mjs";
import { a as isExpectedGatewayListeners, r as formatPortDiagnostics } from "./ports-format-BBqs9qRU.mjs";
import { n as inspectPortUsage, t as inspectPortConnections } from "./ports-inspect-DjJ_TGZf.mjs";
import { t as readGatewayServiceState } from "./service-state-uYnG1mTd.mjs";
import { n as findSystemGatewayServices } from "./inspect-DWWc6709.mjs";
import { t as note } from "./note-CnLgHvug.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 { n as readLastGatewayErrorLine } from "./diagnostics-D2709GiO.mjs";
import { n as prepareGatewayServiceInstall, t as resolveGatewaySetupRuntime } from "./gateway-setup-runtime-_1YriGV5.mjs";
import { i as formatGatewayClosedDiagnostic, o as formatHealthCheckFailure, s as formatHealthDiagnosticNote } from "./health-format-DfkUmdM_.mjs";
import { i as healthCommandNonExiting } from "./health-CAgyEE1j.mjs";
import { a as isServiceRepairDeferred, i as formatServiceRepairDeferredNote, l as shouldManageGatewayService, r as confirmDoctorServiceRepair, s as resolveServiceRepairPolicy, t as SERVICE_REPAIR_POLICY_ENV } from "./doctor-service-repair-policy-DAuL0W8-.mjs";
//#region src/commands/doctor-format.ts
function buildGatewayRuntimeHints(e, t = {}) {
const n = [];
if (!e) return n;
const r = t.platform ?? process.platform;
const i = t.env ?? process.env;
const a = (() => {
try {
return getResolvedLoggerFileTarget().file;
} catch {
return null;
}
})();
const o = a ? [`File logs: ${a}`] : [];
const s = e.inspectionFailure?.detail ?? e.detail;
if (r === "linux" && isSystemdUnavailableDetail(s)) return [...renderSystemdUnavailableHints({
wsl: isWSLEnv(i),
kind: classifySystemdUnavailableDetail(s),
env: i
}), ...o];
if (e.cachedLabel && r === "darwin") {
const e = resolveGatewayLaunchAgentLabel(i.OPENCLAW_PROFILE);
n.push(`LaunchAgent label cached but plist missing. Clear with: launchctl bootout gui/$UID/${e}`);
n.push(`Then reinstall: ${formatCliCommand("openclaw gateway install", i)}`);
}
if (e.missingUnit) {
n.push(`Service not installed. Run: ${formatCliCommand("openclaw gateway install", i)}`);
n.push(...o);
return n;
}
const c = e.missingGuiSession && r === "darwin";
const l = r === "win32" && e.state === "Disabled";
if (c || l || e.status === "stopped") {
if (!c && r === "linux" && isSystemdStartLimitHit(e)) n.push("systemd stopped restarting the gateway after repeated crashes.", `Recover with: ${formatCliCommand("openclaw gateway restart", i)}, then inspect logs if it keeps crashing.`);
else if (!c && !l) n.push("Service is loaded but not running (likely exited immediately).");
n.push(...buildGatewayRuntimeRecoveryHints({
kind: c ? "gui-session" : l ? "disabled-task" : "stopped",
restartCommand: formatCliCommand("openclaw gateway restart", i),
logFile: a,
platform: r,
env: i,
systemd: e.systemd
}));
if (c) return n;
}
if (r === "linux" && isSystemdCgroupHygieneRisk(e.systemd)) {
const t = quoteCliArg(e.systemd?.unit ?? `${resolveGatewaySystemdServiceName(i.OPENCLAW_PROFILE)}.service`);
const r = e.systemd?.scope === "system";
const a = getSystemdCgroupHygieneSummary(e.systemd);
if (a) n.push(`Systemd cgroup hygiene looks elevated: ${a}.`, "This usually means old helper or browser processes may still be attached to the gateway service.", `Run: systemctl ${r ? "--system" : "--user"} show ${t} -p KillMode -p TasksCurrent -p MemoryCurrent -p MainPID`, `Run: systemd-cgls ${r ? "--unit" : "--user-unit"} ${t}`, `After reviewing service settings, run: ${formatCliCommand("openclaw gateway restart", i)}`);
}
return n;
}
//#endregion
//#region src/commands/doctor-gateway-daemon-flow.ts
function noteGatewayRuntime(e, t) {
const n = formatRuntimeStatus(e);
const r = buildGatewayRuntimeHints(e, {
platform: process.platform,
env: t
});
const i = n ? [`Runtime: ${n}`, ...r] : r;
if (i.length > 0) note(i.join("\n"), "Gateway");
}
async function maybeRepairLaunchAgentBootstrap(e) {
if (process.platform !== "darwin" || !await launchAgentPlistExists(e.env) || await isLaunchAgentLoaded({ env: e.env })) return { status: "skipped" };
note("LaunchAgent is installed but not loaded in launchd.", `${e.title} LaunchAgent`);
if (e.serviceRepairDeferred) {
note(formatServiceRepairDeferredNote(), `${e.title} LaunchAgent`);
return { status: "not-loaded" };
}
if (!await confirmDoctorServiceRepair(e.prompter, {
message: `Repair ${e.title} LaunchAgent bootstrap now?`,
initialValue: true
})) return { status: "not-loaded" };
e.runtime.log(`Bootstrapping ${e.title} LaunchAgent...`);
const t = await repairLaunchAgentBootstrap({ env: e.env });
if (!t.ok) {
if (t.status === "system-launchdaemon-conflict" || t.status === "system-launchdaemon-unverifiable") return {
status: "system-launchdaemon-blocked",
detail: t.detail
};
if (t.status === "gui-session-unavailable") return {
status: "gui-session-unavailable",
detail: t.detail
};
e.runtime.error(`${e.title} LaunchAgent bootstrap failed: ${t.detail ?? "unknown error"}`);
return { status: "not-loaded" };
}
if (!await isLaunchAgentLoaded({ env: e.env })) {
e.runtime.error(`${e.title} LaunchAgent still not loaded after repair.`);
return { status: "not-loaded" };
}
note(`${e.title} LaunchAgent repaired.`, `${e.title} LaunchAgent`);
return { status: "repaired" };
}
function renderBlockingSystemGatewayServices(e) {
return [
"System-level OpenClaw gateway service detected while the user gateway service is not installed.",
...e.map((e) => `- ${e.label} (${e.detail})`),
"OpenClaw will not install a second user-level gateway service automatically.",
"Run `openclaw gateway status --deep` or `openclaw doctor --deep` to inspect duplicate services.",
`Set ${SERVICE_REPAIR_POLICY_ENV}=external if a system supervisor owns the gateway lifecycle.`
].join("\n");
}
function renderEstablishedGatewayConnections(e) {
return [
"Established Gateway TCP clients detected:",
...e.slice(0, 8).map((e) => {
return `- ${e.pid ? `pid=${e.pid}` : "pid=?"} ${e.direction}${e.command ? ` ${e.command}` : ""}${e.address ? ` ${e.address}` : ""}${e.commandLine ? ` cmd=${e.commandLine}` : ""}`;
}),
...e.length > 8 ? [`- ... ${e.length - 8} more connection(s)`] : [],
"If logs show protocol mismatch after rollback, stop stale OpenClaw client processes listed here and rerun doctor."
].join("\n");
}
async function maybeReportEstablishedGatewayClients(e, t, n) {
if (!t) return;
const r = n ?? resolveGatewayPort(e, process.env);
const i = (await inspectPortConnections(r).catch(() => null))?.connections.filter(({ direction: e }) => e !== "server");
if (i?.length) note(renderEstablishedGatewayConnections(i), "Gateway clients");
}
async function noteGatewayPortDiagnostics(e, t) {
const n = resolveGatewayPort(e, process.env);
const r = await resolveGatewayBindHost(e.gateway?.bind ?? "loopback", e.gateway?.customBindHost);
const i = await inspectPortUsage(n, { probeHosts: resolveGatewayRequiredListenHosts(r) });
await maybeReportEstablishedGatewayClients(e, t, n);
const a = i.status === "busy" && !isExpectedGatewayListeners(i.listeners, i.port);
if (a) note(formatPortDiagnostics(i).join("\n"), "Gateway port");
return a;
}
async function noteGatewayServiceInspectionFailure(e) {
const t = [`Gateway service status could not be determined: ${e.detail}`];
const n = process.platform === "linux" && classifySystemdUnavailableDetail(e.detail);
if (n) t.push(...renderSystemdUnavailableHints({
wsl: await isWSL(),
kind: n
}));
t.push(`Run ${formatCliCommand("openclaw gateway status --deep")} and retry doctor.`);
note(t.join("\n"), "Gateway");
}
/**
* Repairs or diagnoses the local gateway service after the health check fails.
*
* Remote gateway mode is only diagnosed; local mode may bootstrap launchd, install missing
* services, report port conflicts, or restart unhealthy supervision when policy allows.
*/
async function maybeRepairGatewayDaemon(e) {
if (!isDefaultInstallIdentity(process.env)) {
note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON, "Gateway");
return;
}
if (e.cfg.gateway?.mode === "remote") return;
if (e.healthOk) {
if (process.platform === "linux" && await shouldManageGatewayService()) {
const e = (await readGatewayServiceState(resolveGatewayService(), { env: process.env })).runtime?.systemd?.startRefusal;
if (e) note(e.message, "Gateway");
}
await maybeReportEstablishedGatewayClients(e.cfg, e.options.deep ?? false);
return;
}
const t = await resolveOpenClawPackageRoot({
moduleUrl: import.meta.url,
argv1: process.argv[1]
});
const n = await readInstallOwner(t);
if (n) {
await noteGatewayPortDiagnostics(e.cfg, e.options.deep ?? false);
note(formatInstallOwnerMessage(n), "Gateway");
return;
}
if (!await shouldManageGatewayService()) {
await noteGatewayPortDiagnostics(e.cfg, e.options.deep ?? false);
note(formatServiceRepairDeferredNote(), "Gateway");
return;
}
const r = resolveServiceRepairPolicy();
const i = isServiceRepairDeferred(r);
const a = resolveGatewayService();
const restartGatewayService = async () => {
try {
return await a.restart({
env: process.env,
stdout: process.stdout
});
} catch (e) {
const t = e instanceof Error ? e.message : String(e);
note(`Gateway service restart failed: ${t}`, "Gateway");
return null;
}
};
const o = process.platform === "darwin";
const s = await readGatewayServiceState(a, { env: process.env });
const c = await summarizeGatewayServiceLayout(s.command);
const l = await readInstallOwner(c?.packageRootReal ?? c?.packageRoot ?? null);
if (l) {
await noteGatewayPortDiagnostics(e.cfg, e.options.deep ?? false);
note(formatInstallOwnerMessage(l), "Gateway");
return;
}
const u = s.runtime?.systemd?.startRefusal;
if (u) {
note(u.message, "Gateway");
return;
}
if (s.loadState.status === "unknown") {
if (a.unsupportedReason) note(a.unsupportedReason, "Gateway");
else await noteGatewayServiceInspectionFailure(s.loadState);
return;
}
let d = s.loadState.status === "loaded";
let f = s.runtime;
const p = s.env;
if (e.options.deep) {
const e = readGatewayRestartHandoffSync(p);
if (e) note(formatGatewayRestartHandoffDiagnostic(e), "Gateway");
}
if (o) {
const t = f?.missingGuiSession ? {
status: "gui-session-unavailable",
detail: f.detail ?? ""
} : await maybeRepairLaunchAgentBootstrap({
env: process.env,
title: "Gateway",
runtime: e.runtime,
prompter: e.prompter,
serviceRepairDeferred: i
});
await maybeRepairLaunchAgentBootstrap({
env: {
...process.env,
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(process.env.OPENCLAW_PROFILE)
},
title: "Node",
runtime: e.runtime,
prompter: e.prompter,
serviceRepairDeferred: i
});
if (t.status === "not-loaded") return;
if (t.status === "system-launchdaemon-blocked") {
note(t.detail, "Gateway");
return;
}
if (t.status === "gui-session-unavailable") f = {
status: "unknown",
detail: t.detail || f?.detail,
missingGuiSession: true
};
if (t.status === "repaired") {
const e = await readGatewayServiceState(a, { env: process.env });
if (e.loadState.status === "unknown") {
await noteGatewayServiceInspectionFailure(e.loadState);
return;
}
d = e.loadState.status === "loaded";
f = e.runtime;
}
}
if (o && f?.systemLaunchDaemon) {
noteGatewayRuntime(f, process.env);
return;
}
if (!await noteGatewayPortDiagnostics(e.cfg, e.options.deep ?? false) && d && f?.status === "running") {
const e = await readLastGatewayErrorLine(process.env);
if (e) note(`Recent Gateway log error (may be from an earlier run): ${e}`, "Gateway");
}
if (!d) {
if (o && (f?.missingGuiSession || f?.cachedLabel || f?.systemLaunchDaemon)) {
noteGatewayRuntime(f, process.env);
return;
}
note("Gateway service not installed.", "Gateway");
if (process.platform === "linux") {
const e = await findSystemGatewayServices();
if (e.length > 0) {
note(renderBlockingSystemGatewayServices(e), "Gateway");
return;
}
}
if (i) {
note(formatServiceRepairDeferredNote(), "Gateway");
return;
}
if (!await confirmDoctorServiceRepair(e.prompter, {
message: "Install gateway service now?",
initialValue: true,
requiresInteractiveConfirmation: true
}, r)) {
note(`Run ${formatCliCommand("openclaw gateway install")} when you want to install the gateway service.`, "Gateway");
return;
}
const t = await resolveGatewaySetupRuntime({
env: process.env,
existingCommand: s.command,
selectRuntime: (t) => e.prompter.select({
message: "Gateway service runtime",
options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
initialValue: t
}, t)
});
const n = await resolveGatewayInstallToken({
config: e.cfg,
env: process.env
});
for (const e of n.warnings) note(e, "Gateway");
if (n.unavailableReason) {
note([
"Gateway service install aborted.",
n.unavailableReason,
"Fix gateway auth config/token input and rerun doctor."
].join("\n"), "Gateway");
return;
}
const c = resolveGatewayPort(e.cfg, process.env);
const l = await prepareGatewayServiceInstall({
service: a,
selection: t,
port: c,
existingCommand: s.command,
warn: (e, t) => note(e, t),
config: e.cfg
});
try {
await l.install();
} catch (e) {
note(`Gateway service install failed: ${String(e)}`, "Gateway");
note(gatewayInstallErrorHint(), "Gateway");
}
return;
}
noteGatewayRuntime(f, p);
if (f?.status !== "running") {
if (e.healthSkipped && f?.status !== "stopped") return;
if (i) {
note(formatServiceRepairDeferredNote(), "Gateway");
return;
}
if (await confirmDoctorServiceRepair(e.prompter, {
message: "Start gateway service now?",
initialValue: true
}, r)) {
if (process.platform === "win32" && f?.state === "Disabled") {
try {
await a.start({
env: p,
stdout: process.stdout
});
} catch (e) {
const t = e instanceof Error ? e.message : String(e);
note(`Gateway service start failed: ${t}`, "Gateway");
}
return;
}
const e = await restartGatewayService();
if (!e) return;
const t = describeGatewayServiceRestart("Gateway", e);
if (!t.scheduled) await sleep(1500);
else note(t.message, "Gateway");
}
}
if (process.platform === "darwin") {
const e = resolveGatewayLaunchAgentLabel(process.env.OPENCLAW_PROFILE);
note(`LaunchAgent loaded; stopping requires "${formatCliCommand("openclaw gateway stop")}" or launchctl bootout gui/$UID/${e}.`, "Gateway");
}
if (f?.status !== "running" || e.healthSkipped) return;
if (i) {
note(formatServiceRepairDeferredNote(), "Gateway");
return;
}
if (readGatewayRestartHandoffSync(p)) try {
await healthCommandNonExiting({
json: false,
config: e.cfg
}, e.runtime);
note("Preserving the recent Gateway restart; skipping restart prompt.", "Gateway");
return;
} catch {}
if (e.options.nonInteractive === true) return;
if (await confirmDoctorServiceRepair(e.prompter, {
message: "Restart gateway service now?",
initialValue: false
}, r)) {
const t = await restartGatewayService();
if (!t) return;
const n = describeGatewayServiceRestart("Gateway", t);
if (n.scheduled) {
note(n.message, "Gateway");
return;
}
try {
await healthCommandNonExiting({
json: false,
config: e.cfg
}, e.runtime);
} catch (t) {
if (t instanceof ExitError) return;
const n = formatGatewayClosedDiagnostic(t);
if (n) {
note(n, "Gateway");
note(formatHealthDiagnosticNote(e.gatewayDetailsMessage), "Gateway connection");
} else e.runtime.error(formatHealthCheckFailure(t));
}
}
}
//#endregion
export { maybeRepairGatewayDaemon };