openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
401 lines (400 loc) • 20.9 kB
JavaScript
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { i as formatMissingChildRuntimeWarning } from "./child-runtime-viability-DFyU3D5D.mjs";
import { g as redactSecretDegradationReason, l as formatSecretDegradationRetryHint } from "./runtime-degraded-state-BSnwk5PQ.mjs";
import { o as isLoopbackGatewayUrl } from "./net-BgRayX-P.mjs";
import { s as readMissingScopeError } from "./gateway-error-details-B69XiHdh.mjs";
import { n as isGatewaySecretRefUnavailableError } from "./credentials-UDpmcQCV.mjs";
import { n as GatewayProtocolRequestTimeoutError } from "./protocol-request-CsClAJsG.mjs";
import { i as formatDurationSeconds } from "./format-duration-iMnO_MN6.mjs";
import { n as formatGatewayCrash } from "./gateway-crash-D22VnCOp.mjs";
import { n as buildGatewayProbeConnectionDetails, r as callGateway, t as buildGatewayConnectionDetails, u as isGatewayCredentialsRequiredError } from "./call-DVCK1deJ.mjs";
import { r as DEFAULT_RESTART_HEALTH_TIMEOUT_MS } from "./restart-health.constants-BJKsCEH8.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { t as scrubDoctorErrorMessage } from "./doctor-error-message-BWgd1c6H.mjs";
import { l as readGatewayRecentCrashesAsync, s as readGatewayLastInstallationReplacementAsync } from "./gateway-boot-lifecycle-CkLg5ugv.mjs";
import { t as probeGatewayStatus } from "./probe-De6cOB3j.mjs";
import { i as inspectInstalledGatewayStatePaths, r as compareCliGatewayStateDirs, t as GATEWAY_SERVICE_PATHS_UNVERIFIED } from "./state-dir-gateway-check-cUOyUbQ1.mjs";
import { t as collectChannelStatusIssues } from "./channels-status-issues-DbdoQjaU.mjs";
import { t as waitForGatewayDiagnostic } from "./gateway-diagnostic-readiness-D_rhAvsQ.mjs";
import { i as formatGatewayClosedDiagnostic, o as formatHealthCheckFailure, s as formatHealthDiagnosticNote } from "./health-format-DfkUmdM_.mjs";
import { c as gatewayConnectErrorWasRateLimited, i as GATEWAY_HEALTH_RATE_LIMITED_TITLE, l as gatewayProbeResultSawGateway, n as GATEWAY_HEALTH_CREDENTIALS_REQUIRED_TITLE, r as GATEWAY_HEALTH_RATE_LIMITED_MESSAGE, t as GATEWAY_HEALTH_CREDENTIALS_REQUIRED_MESSAGE, u as gatewayProbeResultWasRateLimited } from "./gateway-health-auth-diagnostic-XnQcuBP6.mjs";
import { o as isServiceRepairExternallyManaged } from "./doctor-service-repair-policy-DAuL0W8-.mjs";
import { t as hasActiveGatewayExecCredential } from "./doctor-gateway-exec-credential-n80b7QiI.mjs";
import { t as formatSqliteWalHealthWarning } from "./sqlite-wal-health-cnXK1aTP.mjs";
import { t as formatTelemetryExporterSummary } from "./telemetry-exporter-summary-DA3oxWwE.mjs";
//#region src/commands/doctor-gateway-health.ts
const DOCTOR_SECRET_OWNER_ID_MAX_CHARS = 96;
const DOCTOR_SECRET_OWNER_PATH_MAX_CHARS = 120;
const DOCTOR_SECRET_OWNER_VISIBLE_PATHS = 3;
function safeDoctorSecretOwnerText(e, t) {
const n = sanitizeTerminalText(redactSensitiveUrlLikeString(e));
return n.length <= t ? n : `${truncateUtf16Safe(n, t - 1)}…`;
}
/** Projects Gateway-owned secret degradation into the shared bounded Doctor display shape. */
function projectDoctorSecretRuntimeDegradations(e) {
const t = (e.degradedSecretOwners ?? []).map((e) => {
const t = safeDoctorSecretOwnerText(e.ownerId, DOCTOR_SECRET_OWNER_ID_MAX_CHARS);
const n = `${e.ownerKind}:${t}`;
const r = e.paths.slice(0, DOCTOR_SECRET_OWNER_VISIBLE_PATHS).map((e) => safeDoctorSecretOwnerText(e, DOCTOR_SECRET_OWNER_PATH_MAX_CHARS));
const i = e.paths.length - r.length;
const a = r.join(", ") + (i > 0 ? ` (+${i} paths omitted)` : "");
return {
message: `${e.degradationState ?? "cold"} ${n} (${a || "no affected paths reported"}): ${redactSecretDegradationReason(e.reason)}`,
path: r[0] ?? "gateway",
target: n,
retryHint: formatSecretDegradationRetryHint(e.reason)
};
});
if (e.secretEgressProxy?.state !== "degraded") return t;
return [...t, {
message: "Secret egress proxy: " + safeDoctorSecretOwnerText(e.secretEgressProxy.message ?? "TLS certificate preparation unavailable. Check Gateway logs.", 512),
path: "secrets.egressProxy.enabled",
target: "capability:secret-egress-proxy",
retryHint: "Correct the reported certificate or clock problem before retrying the request."
}];
}
function formatGatewayHealthDiagnostic(e) {
const t = e instanceof Error ? e.message : String(e);
return scrubDoctorErrorMessage(sanitizeTerminalText(redactSensitiveUrlLikeString(t)));
}
function gatewayCrashFinding(e) {
const t = Date.now();
const n = e.filter((e) => t - e.detectedAtMs <= 864e5);
const r = e.filter((e) => t - e.detectedAtMs <= 6048e5);
const i = n.length ? n : r.length >= 3 ? r : [];
return i.length ? [{
checkId: "core/doctor/gateway-health",
severity: "warning",
category: "fix-now",
message: `Gateway ended unexpectedly ${i.length} time(s):\n${i.map((e) => `${new Date(e.detectedAtMs).toISOString()}: ${formatGatewayHealthDiagnostic(formatGatewayCrash(e))}`).join("\n")}`,
path: "gateway",
fixHint: "Inspect `openclaw gateway status` and Gateway or supervisor logs for the recorded exits. A healthy successor does not erase a previous crash.",
docsUrl: "https://docs.openclaw.ai/gateway/restart-recovery#unexpected-exits"
}] : [];
}
async function readLocalGatewayCrashFindings(e, t) {
if (e.gateway?.mode === "remote") return [];
try {
return gatewayCrashFinding(await readGatewayRecentCrashesAsync(t));
} catch (e) {
return [{
checkId: "core/doctor/gateway-health",
severity: "warning",
message: `Gateway crash history unavailable: ${formatGatewayHealthDiagnostic(e)}`,
fixHint: "Inspect `openclaw gateway status --deep` using the same profile and account."
}];
}
}
async function readLocalInstallationReplacement(e, t) {
if (e.gateway?.mode === "remote") return;
try {
const e = await readGatewayLastInstallationReplacementAsync(t);
return e ? {
severity: "info",
message: `Previous installation replacement (${new Date(e.completedAtMs).toISOString()}): ${formatGatewayHealthDiagnostic(e.reason)}`
} : void 0;
} catch (e) {
return {
severity: "warning",
message: `Previous installation replacement unavailable: ${formatGatewayHealthDiagnostic(e)}`
};
}
}
async function collectGatewayHealthFindings(e) {
const t = e.cfg.gateway?.mode === "remote" ? "remote" : "local";
const n = t === "remote" ? "gateway.remote.url" : "gateway.mode";
const r = await readLocalInstallationReplacement(e.cfg, e.env);
const i = r ? [{
checkId: "core/doctor/gateway-health",
...r,
category: "historical",
fixHint: "No action needed if the current Gateway is healthy. This records the previous installation replacement.",
docsUrl: "https://docs.openclaw.ai/cli/doctor/recovery",
path: "gateway.mode"
}] : [];
i.push(...await readLocalGatewayCrashFindings(e.cfg, e.env));
let a;
const warning = (e, r) => ({
checkId: "core/doctor/gateway-health",
severity: "warning",
message: e,
path: a || t === "remote" ? n : "gateway",
...a ? { target: formatGatewayHealthDiagnostic(a.url) } : {},
fixHint: r
});
try {
a = await buildGatewayProbeConnectionDetails({
config: e.cfg,
configPath: e.configPath
});
if (e.allowExecSecretRefs !== true && await hasActiveGatewayExecCredential({
cfg: e.cfg,
env: e.env,
targetUrl: a.url
})) return [...i, warning("Authenticated Gateway health inspection was intentionally skipped because an active credential uses an exec SecretRef.", "Rerun `openclaw doctor --lint --only core/doctor/gateway-health --allow-exec` to permit configured secret execution.")];
const n = await callGateway({
method: "status",
params: { includeChannelSummary: false },
timeoutMs: 3e3,
sharedStateMode: "read-only",
config: e.cfg,
configPath: e.configPath,
tlsFingerprint: a.tlsFingerprint,
preauthHandshakeTimeoutMs: a.preauthHandshakeTimeoutMs
});
const r = projectDoctorSecretRuntimeDegradations(n).map((e) => ({
checkId: "core/doctor/gateway-health",
severity: "warning",
message: `Secret runtime degradation: ${e.message}`,
path: e.path,
target: e.target,
fixHint: `Retry: ${e.retryHint}`
}));
if (t === "remote") r.push(...gatewayCrashFinding(n.recentCrashes ?? []));
const o = formatSqliteWalHealthWarning(n.sqliteWal);
if (n.modelReasoningWarning) r.push(warning(formatGatewayHealthDiagnostic(n.modelReasoningWarning), "Set reasoning: true on the configured model, or choose a non-thinking model."));
if (o) r.push(warning(`SQLite WAL: ${o}`, "Inspect openclaw status --deep output."));
if (n.installationReplacementWarning) r.push(warning(formatGatewayHealthDiagnostic(n.installationReplacementWarning), "Wait for the service manager to restart the Gateway; for a foreground Gateway, run `openclaw gateway run` again after it exits."));
return [...i, ...r];
} catch (e) {
if (!a) return [...i, warning(`Gateway health inspection could not be prepared: ${formatGatewayHealthDiagnostic(e)}`, "Fix Gateway connection configuration, then rerun `openclaw doctor --lint --only core/doctor/gateway-health`.")];
const n = gatewayConnectErrorWasRateLimited(e) ? {
message: GATEWAY_HEALTH_RATE_LIMITED_MESSAGE,
fixHint: "Wait for the temporary authentication lockout to expire, then rerun doctor."
} : isGatewayHealthAuthUnavailableError(e) ? {
message: "Gateway status could not be inspected because this CLI has no usable token/password or paired device token for read-scope RPCs.",
fixHint: "Configure the Gateway token/password or pair this device, then rerun the selected health check."
} : {
message: `Gateway status could not be inspected: ${formatGatewayHealthDiagnostic(e)}`,
fixHint: t === "remote" ? "Verify the remote Gateway URL, network path, TLS settings, and credentials." : "Inspect the service with `openclaw gateway status --deep`, or run `openclaw doctor` for guided checks."
};
return [...i, warning(n.message, n.fixHint)];
}
}
function isGatewayCallTimeout(e) {
return /^gateway timeout after \d+ms(?:\n|$)/.test(e);
}
function isGatewayHealthAuthUnavailableError(e) {
return isGatewayCredentialsRequiredError(e) || isGatewaySecretRefUnavailableError(e) || readMissingScopeError(e) !== null;
}
function noteGatewayStateDirectory(e, t) {
if (!e.stateDir) return;
const n = compareCliGatewayStateDirs({
cliStateDir: resolveStateDir(process.env),
cliConfigPath: resolveConfigPath(process.env),
gatewayStateDir: e.stateDir,
gatewayConfigPath: e.configPath,
source: t,
mode: "warn"
});
if (n.kind === "warn") note(`${n.message}\nAfter moving or renaming the state directory, the running Gateway still uses the paths it started with. A full restart is required: \`openclaw gateway restart\` (not a reload). Then rerun \`openclaw doctor\`.\nRun plugin inspection and doctor --fix with the Gateway's OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH. To change the managed service, run \`openclaw gateway install --force\` from the intended profile and review operator-owned service overrides.`, "Gateway state directory mismatch");
}
async function noteInstalledGatewayStateDirectory(e, t) {
if (e.gateway?.mode === "remote" || isServiceRepairExternallyManaged()) return;
try {
if (!isLoopbackGatewayUrl(buildGatewayConnectionDetails({ config: e }).url)) return;
const n = await inspectInstalledGatewayStatePaths(Math.min(t, 3e3));
if (n.kind === "known") noteGatewayStateDirectory(n, "installed Gateway service");
else if (n.kind === "unknown") note(GATEWAY_SERVICE_PATHS_UNVERIFIED, "Gateway state directory");
} catch {
note(GATEWAY_SERVICE_PATHS_UNVERIFIED, "Gateway state directory");
}
}
/**
* Probes gateway status and reports user-facing connection/auth/channel warnings.
*
* A credentials-required gateway still counts as healthy but unauthenticated when the preauth
* probe confirms the server is reachable.
*/
async function checkGatewayHealth(e) {
const report = (t, n, r = "fix-now", i = "Run openclaw gateway status --deep using the same profile and account, inspect the reported startup errors, then rerun Doctor.") => {
if (e.onFinding) e.onFinding({
checkId: "core/doctor/gateway-health",
severity: r === "historical" ? "info" : "warning",
category: r,
message: `${n}: ${t}`,
fixHint: i,
docsUrl: "https://docs.openclaw.ai/cli/doctor/checks#gateway-and-service-repairs"
});
else note(t, n);
};
const t = await readLocalInstallationReplacement(e.cfg);
if (t) report(t.message, "Previous Gateway installation replacement", "historical", "No action needed if the current Gateway is healthy. This records a completed installation replacement.");
for (const t of await readLocalGatewayCrashFindings(e.cfg)) report(t.message, "Gateway crashes", t.category, t.fixHint);
const { bindAgentToolGatewayRequest: n } = await import("./in-process-gateway-uUYBiTqp.mjs");
const r = n({ hostedOnly: true });
const i = DEFAULT_RESTART_HEALTH_TIMEOUT_MS;
let a = false;
let o;
let s;
try {
const t = await waitForGatewayDiagnostic({
config: e.cfg,
timeoutMs: i,
serviceMode: isServiceRepairExternallyManaged() ? "external" : "native"
}, e.runtime);
if (t === void 0) return {
healthOk: true,
authenticated: false
};
const n = performance.now();
o = await callGateway({
method: "status",
params: { includeChannelSummary: false },
timeoutMs: t,
sharedStateMode: "read-only",
config: e.cfg,
onHelloOk: ({ snapshot: e }) => {
s = e;
noteGatewayStateDirectory(e, "live Gateway");
}
});
const c = performance.now() - n;
const l = Math.ceil(c) + 1e3;
const u = Math.min(3e4, Math.max(i, 5e3 + l, Math.ceil(c * 3)));
const d = Math.max(1, u - l);
const slowDiagnosticNote = (e) => `Gateway answered status in ${formatDurationSeconds(c)}; ${e} diagnostics did not finish within ${formatDurationSeconds(u)}. The host may be slow; this does not mark the Gateway unhealthy.`;
a = true;
if (e.cfg.gateway?.mode === "remote") for (const e of gatewayCrashFinding(o.recentCrashes ?? [])) report(e.message, "Gateway crashes", e.category, e.fixHint);
const f = o?.runtimeVersion?.trim();
if (f && f !== VERSION) note([
`This command is OpenClaw ${VERSION}; the running Gateway is OpenClaw ${f}.`,
"Check `openclaw --version`, `which openclaw`, and `openclaw gateway status --deep`.",
"If this mismatch is unexpected, update PATH so `openclaw` points to the version you want, or reinstall the Gateway service from that same OpenClaw install."
].join("\n"), "OpenClaw version mismatch");
const noteWarning = (e, t) => {
if (e) report(sanitizeTerminalText(e), t);
};
noteWarning(o.startupMigrationWarning, "Startup migration warnings");
const p = formatSqliteWalHealthWarning(o.sqliteWal);
if (p) report(p, "SQLite WAL");
noteWarning(o.modelReasoningWarning, "Model reasoning");
noteWarning(o.childRuntime ? formatMissingChildRuntimeWarning(o.childRuntime) : void 0, "Gateway runtime");
noteWarning(o.installationReplacementWarning, "Installation replaced");
const m = projectDoctorSecretRuntimeDegradations(o);
if (m.length > 0) report(m.map((e) => `- ${e.message}\n Retry: ${e.retryHint}`).join("\n"), "Secret runtime degradation");
if (o.degradedPlugins && o.degradedPlugins.length > 0) report(o.degradedPlugins.map((e) => `- ${e.pluginId} (${e.diagnostic.reason}): ${e.diagnostic.detail}`).join("\n"), "Plugins configured unavailable");
const [h, g] = await Promise.allSettled([callGateway({
method: "channels.status",
params: {
probe: true,
timeoutMs: d
},
timeoutMs: u,
sharedStateMode: "read-only",
config: e.cfg
}), r({
method: "diagnostics.stability",
params: {
type: "telemetry.exporter",
limit: 1e3
},
timeoutMs: u,
sharedStateMode: "read-only",
config: e.cfg
})]);
if (h.status === "fulfilled") {
const e = collectChannelStatusIssues(h.value);
if (e.length > 0) report(e.map((e) => `- ${e.channel} ${e.accountId}: ${e.message}${e.fix ? ` (${e.fix})` : ""}`).join("\n"), "Channel warnings");
} else report([isGatewayCallTimeout(formatErrorMessage(h.reason)) ? slowDiagnosticNote("channel") : `Channel status check failed: ${sanitizeTerminalText(formatErrorMessage(h.reason))}`, `Retry: ${formatCliCommand("openclaw channels status --probe")}`].join("\n"), "Channel warnings", "recommended", "Rerun openclaw channels status --probe to inspect channel readiness; the Gateway answered status successfully.");
if (g.status === "fulfilled") {
const e = formatTelemetryExporterSummary(g.value);
if (e) {
if (e.status === "ok") note(e.lines.join("\n"), e.title);
else report(e.lines.join("\n"), e.title, "recommended", "Inspect openclaw gateway stability --type telemetry.exporter if you use telemetry export; this does not establish a Gateway failure.");
}
} else report([g.reason instanceof GatewayProtocolRequestTimeoutError || isGatewayCallTimeout(formatErrorMessage(g.reason)) ? slowDiagnosticNote("exporter") : `Exporter diagnostics failed: ${sanitizeTerminalText(formatErrorMessage(g.reason))}`, `Retry: ${formatCliCommand("openclaw gateway stability --type telemetry.exporter")}`].join("\n"), "Telemetry exporters", "recommended", "Rerun openclaw gateway stability --type telemetry.exporter if you use telemetry export; the Gateway answered status successfully.");
return {
healthOk: a,
authenticated: true,
status: o
};
} catch (t) {
if (!s?.stateDir) await noteInstalledGatewayStateDirectory(e.cfg, i);
if (gatewayConnectErrorWasRateLimited(t)) {
report(GATEWAY_HEALTH_RATE_LIMITED_MESSAGE, GATEWAY_HEALTH_RATE_LIMITED_TITLE, "recommended", "Wait for the temporary authentication lockout to expire, then rerun Doctor. The Gateway was reachable; its authenticated health remains unverified.");
return {
healthOk: true,
authenticated: false
};
}
if (isGatewayHealthAuthUnavailableError(t)) {
const t = await buildGatewayProbeConnectionDetails({ config: e.cfg });
const n = await probeGatewayStatus({
url: t.url,
timeoutMs: i,
tlsFingerprint: t.tlsFingerprint,
preauthHandshakeTimeoutMs: t.preauthHandshakeTimeoutMs,
config: e.cfg,
json: true
});
if (gatewayProbeResultSawGateway(n)) {
if (gatewayProbeResultWasRateLimited(n)) report(GATEWAY_HEALTH_RATE_LIMITED_MESSAGE, GATEWAY_HEALTH_RATE_LIMITED_TITLE, "recommended", "Wait for the temporary authentication lockout to expire, then rerun Doctor. The Gateway was reachable; its authenticated health remains unverified.");
else report(GATEWAY_HEALTH_CREDENTIALS_REQUIRED_MESSAGE, GATEWAY_HEALTH_CREDENTIALS_REQUIRED_TITLE, "fix-now", "Configure the Gateway token/password or pair this device, then rerun Doctor to verify authenticated health.");
a = true;
return {
healthOk: a,
authenticated: false
};
}
}
const n = formatGatewayClosedDiagnostic(t);
if (n) {
const t = buildGatewayConnectionDetails({ config: e.cfg });
report(n, "Gateway");
report(formatHealthDiagnosticNote(t.message), "Gateway connection");
} else if (e.onFinding) report(formatHealthCheckFailure(t), "Gateway health check failed");
else e.runtime.error(formatHealthCheckFailure(t));
}
return {
healthOk: a,
authenticated: false,
status: o
};
}
/** Probes gateway memory readiness without forcing deep embedding checks. */
async function probeGatewayMemoryStatus(e) {
const { bindAgentToolGatewayRequest: t } = await import("./in-process-gateway-uUYBiTqp.mjs");
const n = t({ hostedOnly: true });
try {
const t = await n({
method: "doctor.memory.status",
params: { probe: false },
timeoutMs: 8e3,
sharedStateMode: "read-only",
config: e.cfg
});
if (t.health) return {
checked: true,
ready: t.health.status === "ready",
error: t.health.status === "ready" ? void 0 : t.health.message ?? `memory provider health is ${t.health.status}`,
skipped: false
};
const r = t.embedding.checked !== false;
return {
checked: r,
ready: t.embedding.ok,
error: t.embedding.error,
...t.embeddingRuntime ? { runtimeFacts: t.embeddingRuntime } : {},
skipped: !r
};
} catch (e) {
const t = formatErrorMessage(e);
const n = isGatewayCallTimeout(t);
return {
checked: !n,
ready: false,
error: `gateway memory check ${n ? "timed out" : "unavailable"}: ${t}`,
skipped: false
};
}
}
//#endregion
export { checkGatewayHealth, collectGatewayHealthFindings, probeGatewayMemoryStatus };