UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

276 lines (275 loc) • 11 kB
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as writeRuntimeJson, t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as isDiagnosticFlagEnabled } from "./diagnostic-flags-D41PMN4c.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as isConfigReadFailure, n as createConfigReadError } from "./io.invalid-config-DK-BYZ4Y.mjs"; import { n as isGatewaySecretRefUnavailableError } from "./credentials-UDpmcQCV.mjs"; import { n as isRich } from "./theme-BOI0xyRZ.mjs"; import { n as info } from "./globals-CgepmiqE.mjs"; import { t as formatDurationCompact } from "./format-duration-iMnO_MN6.mjs"; import { c as formatGatewayTransportErrorJson, n as buildGatewayProbeConnectionDetails, o as formatGatewayAuthErrorJson, r as callGateway, s as formatGatewayClientRequestErrorJson, 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 listReadOnlyChannelPluginsForConfig } from "./read-only-idsFCBWl.mjs"; import { t as buildChannelAccountBindings } from "./bindings-BGbnqeha.mjs"; import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs"; import { r as withProgress } from "./progress-DZHhZ1Fk.mjs"; import { t as styleHealthChannelLine } from "./health-style-BnzvkZFf.mjs"; import { t as formatExactDuration } from "./format-duration-exact-DIgmHPIY.mjs"; import { t as probeGatewayStatus } from "./probe-De6cOB3j.mjs"; import { t as waitForGatewayDiagnostic } from "./gateway-diagnostic-readiness-D_rhAvsQ.mjs"; import { a as formatHealthChannelLines, n as formatContextEngineHealthLine, r as formatDeliveryQueueHealthLine, t as formatConfigReloadHealthLine } from "./health-format-DfkUmdM_.mjs"; import { n as resolveHealthAccountContext } from "./account-context-CZFa_dD3.mjs"; import { a as GATEWAY_HEALTH_REACHABLE_LINE, c as gatewayConnectErrorWasRateLimited, l as gatewayProbeResultSawGateway, o as buildCredentialsRequiredHealthDiagnostic, s as buildRateLimitedHealthDiagnostic, u as gatewayProbeResultWasRateLimited } from "./gateway-health-auth-diagnostic-XnQcuBP6.mjs"; import { t as logGatewayConnectionDetails } from "./status.gateway-connection-DsZRujZ8.mjs"; //#region src/commands/health.ts const healthLog = createSubsystemLogger("health"); function isGatewayHealthAuthUnavailableError(e) { return isGatewayCredentialsRequiredError(e) || isGatewaySecretRefUnavailableError(e); } async function emitReachableGatewayAuthDiagnostic(e) { const t = gatewayConnectErrorWasRateLimited(e.error); if (!t && !isGatewayHealthAuthUnavailableError(e.error)) return false; let n = t; if (!t) { const t = await buildGatewayProbeConnectionDetails(e); const r = await probeGatewayStatus({ url: t.url, token: e.token, password: e.password, tlsFingerprint: t.tlsFingerprint, preauthHandshakeTimeoutMs: t.preauthHandshakeTimeoutMs, timeoutMs: e.timeoutMs ?? DEFAULT_RESTART_HEALTH_TIMEOUT_MS, config: e.config, json: e.json }); if (!gatewayProbeResultSawGateway(r)) return false; n = gatewayProbeResultWasRateLimited(r); } const r = n ? buildRateLimitedHealthDiagnostic(t ? e.error : void 0) : buildCredentialsRequiredHealthDiagnostic(); if (e.json) writeRuntimeJson(e.runtime, r); else { e.runtime.log(GATEWAY_HEALTH_REACHABLE_LINE); e.runtime.log(r.error.message); } e.runtime.exit(1); return true; } function emitGatewayHealthErrorJson(e, t) { const n = formatGatewayAuthErrorJson(e) ?? formatGatewayClientRequestErrorJson(e) ?? formatGatewayTransportErrorJson(e); if (!n) return false; writeRuntimeJson(t, n); t.exit(1); return true; } function formatEventLoopHealthLine(e) { const t = e.eventLoop; if (!t) return null; return `Gateway event loop: ${t.degraded ? "degraded" : "ok"}${t.degraded && t.degradedSinceMs != null ? ` for ${formatDurationCompact(t.degradedSinceMs) ?? "0s"}` : ""}${t.reasons.length > 0 ? ` reasons=${t.reasons.join(",")}` : ""} max=${Math.round(t.delayMaxMs)}ms p99=${Math.round(t.delayP99Ms)}ms util=${t.utilization} cpu=${t.cpuCoreRatio}`; } async function healthCommand(e, t) { const n = e.config ?? await readNonObservingHealthConfig(); let r; try { const i = await waitForGatewayDiagnostic({ ...e, config: n }, t); if (i === void 0) return; r = await withProgress({ label: "Checking gateway health…", indeterminate: true, enabled: e.json !== true }, async () => await callGateway({ method: "health", params: e.verbose ? { probe: true } : void 0, timeoutMs: i, config: n, token: e.token, password: e.password, sharedStateMode: "read-only", ignoreEnvUrlOverride: e.ignoreEnvUrlOverride, localPortOverride: e.localPortOverride })); } catch (r) { if (await emitReachableGatewayAuthDiagnostic({ ...e, error: r, config: n, runtime: t })) return; if (e.json && emitGatewayHealthErrorJson(r, t)) return; throw r; } if (e.json) writeRuntimeJson(t, r); else { const i = isDiagnosticFlagEnabled("health", n); const a = isRich(); if (e.verbose) { const r = buildGatewayConnectionDetails({ config: n, ignoreEnvUrlOverride: e.ignoreEnvUrlOverride, localPortOverride: e.localPortOverride }); logGatewayConnectionDetails({ runtime: t, info, message: r.message }); } const { buildHealthAgentSummaries: o, resolveHealthAgentOrder: s } = await import("./collector-FojBcyBH.mjs"); const c = s(n); const l = r.defaultAgentId ?? c.defaultAgentId; const u = Array.isArray(r.agents) ? r.agents : []; const d = u.length === 0 && c.ordered.length > 0; const f = buildChannelAccountBindings(n); const p = listReadOnlyChannelPluginsForConfig(n, { includeSetupFallbackPlugins: false }); if (i) { t.log(info("[debug] local channel accounts")); for (const e of p) { const r = e.config.listAccountIds(n); const i = resolveChannelDefaultAccountId({ plugin: e, cfg: n, accountIds: r }); t.log(` ${e.id}: accounts=${r.join(", ") || "(none)"} default=${i}`); for (const i of r) { const { inspectedAccount: r, probeAccount: a, configured: o, diagnostics: s } = await resolveHealthAccountContext({ plugin: e, cfg: n, accountId: i }); const c = asNullableRecord(r ?? a); const l = c && typeof c.tokenSource === "string" ? c.tokenSource : void 0; t.log(` - ${i}: configured=${o ?? "unknown"}${l ? ` tokenSource=${l}` : ""}`); for (const e of s) t.log(` ! ${e}`); } } t.log(info("[debug] bindings map")); for (const [e, n] of f.entries()) { const r = Array.from(n.entries()).map(([e, t]) => `${e}=[${t.join(", ")}]`); t.log(` ${e}: ${r.join(" ")}`); } t.log(info("[debug] gateway channel checks")); for (const [e, n] of Object.entries(r.channels ?? {})) { const r = n.accounts ?? {}; const i = Object.entries(r).map(([e, t]) => { const n = asNullableRecord(t.probe); const r = n ? asNullableRecord(n.bot) : null; return `${e}=${(r && typeof r.username === "string" ? r.username : null) ?? "(no bot)"}`; }); t.log(` ${e}: ${i.join(", ") || "(none)"}`); } } const m = []; for (const e of p) { if ((r.channels?.[e.id])?.linked !== true || !e.status?.logSelfId) continue; const t = l ? f.get(e.id)?.get(l) ?? [] : []; const i = e.config.listAccountIds(n); const a = resolveChannelDefaultAccountId({ plugin: e, cfg: n, accountIds: i }); const o = t[0] ?? a; const s = await resolveHealthAccountContext({ plugin: e, cfg: n, accountId: o }); if (s.probeAccount === void 0 || !s.enabled || s.configured !== true || s.diagnostics.length > 0) continue; m.push({ channelId: e.id, accountId: o, account: s.probeAccount, logSelfId: e.status.logSelfId.bind(e.status) }); } const h = d ? await o(n, c) : u; const g = d && l ? (h.find((e) => e.agentId === l) ?? h[0])?.agentId : l; const _ = e.verbose || !g ? h : h.filter((e) => e.agentId === g); const v = (() => { if (e.verbose) return; const t = _.length > 0 ? _ : h; const n = {}; for (const [e, r] of f.entries()) { const i = [...new Set(t.flatMap((e) => r.get(e.agentId) ?? []))]; if (i.length > 0) n[e] = i; } return Object.keys(n).length > 0 ? n : void 0; })(); const y = formatHealthChannelLines(r, { accountMode: e.verbose ? "all" : "default", accountIdsByChannel: v }); for (const e of y) t.log(styleHealthChannelLine(e, a)); for (const e of [ formatEventLoopHealthLine, formatContextEngineHealthLine, formatDeliveryQueueHealthLine, formatConfigReloadHealthLine ]) { const n = e(r); if (n) t.log(styleHealthChannelLine(n, a)); } for (const { channelId: e, accountId: r, account: i, logSelfId: a } of m) try { a({ account: i, cfg: n, runtime: t, includeChannelPrefix: true }); } catch (t) { const i = { channel: e, accountId: r, error: formatErrorMessage(t) }; if (isDiagnosticFlagEnabled("health", n)) healthLog.info("logSelfId.failed", i); } if (Number.isFinite(r.durationMs)) t.log(info(`Gateway check duration: ${r.durationMs}ms`)); if (h.length > 0) { const e = h.map((e) => e.isDefault ? `${e.agentId} (default)` : e.agentId); t.log(info(`Agents: ${e.join(", ")}`)); } const b = _.map((e) => { const t = e.heartbeat?.everyMs; return `${t ? formatExactDuration(t, "unknown", true) : "disabled"} (${e.agentId})`; }); if (b.length > 0) t.log(info(`Heartbeat interval: ${b.join(", ")}`)); const x = _.length > 0 ? _ : [{ agentId: void 0, sessions: r.sessions }]; for (const { agentId: e, sessions: n } of x) { const r = e ? `Session store (${e})` : "Session store"; t.log(info(`${r}: ${n.path} (${n.count} entries)`)); for (const { key: e, age: r } of n.recent) t.log(`- ${e} (${r === null ? "no activity" : `${Math.round(r / 6e4)}m ago`})`); } } } /** * Runs `healthCommand` inside a host flow (wizard/onboard/doctor). The command's * CLI-style `runtime.exit(1)` diagnostic paths surface as a thrown `ExitError`, * so the host reports the failure and keeps running instead of dying mid-flow. */ async function healthCommandNonExiting(e, t) { await healthCommand(e, { ...t, exit: (e) => { throw new ExitError(e); } }); } async function readNonObservingHealthConfig() { const { readConfigFileSnapshot: e } = await import("./config/config.js"); const t = await e({ observe: false, pluginValidation: "core-only" }); if (isConfigReadFailure(t)) throw createConfigReadError(t); return t.runtimeConfig ?? t.config; } //#endregion export { readNonObservingHealthConfig as a, healthCommandNonExiting as i, emitReachableGatewayAuthDiagnostic as n, healthCommand as r, emitGatewayHealthErrorJson as t };