openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
418 lines (417 loc) • 15.6 kB
JavaScript
import { n as asNullableObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { d as redactToolPayloadTextWithConfig } from "./redact-Mj7pppxC.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { l as trackAsyncWork } from "./async-work-scope-BXagjUap.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { n as listAgentEntries } from "./agent-roster-t1ooUdXp.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { A as tryResolveLegacyCompatibilityAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as isDiagnosticFlagEnabled } from "./diagnostic-flags-D41PMN4c.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as awaitWithinDeadline, r as scheduleAbsoluteDeadline, t as ABSOLUTE_DEADLINE_EXPIRED } from "./absolute-deadline-kK4DcdPs.mjs";
import { t as createPermitPool } from "./permit-pool-DR3Z0pxU.mjs";
import { f as degradedPluginMatchesRoot, g as listActiveDegradedPlugins, y as toPublicPluginVerificationDiagnostic } from "./discovery-availability-DtlJ7XvT.mjs";
import "./legacy.default-agent-owner-DpmHgK0A.mjs";
import { l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs";
import { a as resolveChannelHealthState, n as DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS, t as DEFAULT_CHANNEL_CONNECT_GRACE_MS } from "./channel-health-policy-Czg3cLcH.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 { s as redactChannelStatusSummaryBaseUrl } from "./account-snapshot-fields-B0Zypjh2.mjs";
import { a as resolveUnavailableChannelAccountSnapshot } from "./account-state-CG07Qq4V.mjs";
import { n as buildChannelAccountSnapshotFromInspection, r as buildChannelAccountSnapshotFromRuntime } from "./account-summary-RVgW5Dlx.mjs";
import { t as buildChannelAccountSnapshotFromAccount } from "./status-Dia8exqk.mjs";
import { n as resolveHealthAccountContext, t as buildNonSensitiveProbeFailure } from "./account-context-CZFa_dD3.mjs";
import { n as readHeartbeatSummaryForStatus, r as readHeartbeatSummarySnapshot, t as projectHeartbeatSummary } from "./heartbeat-summary-snapshot-aOWhn0vZ.mjs";
import { n as listPluginServiceHealthFailures } from "./service-health-DfPDhkdd.mjs";
import { n as captureDeliveryQueueHealthContext, r as buildContextEngineHealthSummary, t as buildDeliveryQueueHealthSummary } from "./delivery-queue-CQ5qiz5A.mjs";
//#region src/gateway/health/collector.ts
const HEALTH_COLLECTION_TIMEOUT_MS = 7e3;
const monotonicNow = () => performance.now();
const HEALTH_PROBE_CONCURRENCY = 5;
const HEALTH_RECENT_SESSION_LIMIT = 5;
const healthLog = createSubsystemLogger("health");
const debugHealth = (e, t, n) => {
if (isDiagnosticFlagEnabled("health", e)) healthLog.info(t, n);
};
function resolveHealthAgentOrder(e) {
const t = tryResolveLegacyCompatibilityAgentId(e);
const n = listAgentEntries(e);
const r = /* @__PURE__ */ new Set();
const i = [];
for (const e of n) {
if (typeof e.id !== "string" || !e.id.trim()) continue;
const t = normalizeAgentId(e.id);
if (r.has(t)) continue;
r.add(t);
i.push({
id: t,
name: typeof e.name === "string" ? e.name : void 0
});
}
if (t && !r.has(t)) i.unshift({ id: t });
return {
defaultAgentId: t,
ordered: i
};
}
function projectHealthSessions(e, t) {
const n = t.recent.map(({ sessionKey: e, entry: t }) => ({
key: e,
updatedAt: t.updatedAt || null,
age: t.updatedAt ? Date.now() - t.updatedAt : null
}));
return {
path: e,
count: t.count,
recent: n
};
}
/** Shares one bounded session snapshot across every configured agent in this collection. */
async function buildHealthAgentSummaries(e, t, n) {
return (await prepareHealthAgentSummaries(e, t, n)).publish().agents;
}
async function prepareHealthAgentSummaries(e, { defaultAgentId: t, ordered: n }, r, i) {
const { prepareStatusSessionStores: a } = await import("./session-stores-CtrjpypN.mjs");
const { isTransientSqliteError: o } = await import("./unhandled-rejections-C3_E5_Ob.mjs");
const s = await readHeartbeatSummaryForStatus(() => i?.readHeartbeatSummary?.(e) ?? readHeartbeatSummarySnapshot(e, i?.storePath));
const c = new Map(s.jobs.toReversed().map((e) => [e.agentId, e]));
const l = await a(e, n, HEALTH_RECENT_SESSION_LIMIT, {
projection: r,
fallbackToUnscopedStore: true,
recoverReadError(e) {
if (!o(e)) throw e;
return {
count: 0,
recent: [],
byAgent: /* @__PURE__ */ new Map()
};
}
});
return { publish() {
const r = l.publish();
const i = t && !r.byAgent.some(({ agent: e }) => e.id === t) ? r.byAgent[0]?.agent.id : t;
const a = r.byAgent.map(({ agent: e, ...t }) => ({
agentId: e.id,
name: e.name,
isDefault: e.id === i,
heartbeat: projectHeartbeatSummary(c.get(e.id), s.selectionWarning),
sessions: projectHealthSessions(t.path, t)
}));
return {
agents: a,
sessions: (a.find((e) => e.isDefault) ?? a[0])?.sessions ?? projectHealthSessions(r.paths[0] ?? resolveSessionStorePathCore(e.session?.store, { agentId: t ?? n[0]?.id }), r)
};
} };
}
function buildPluginHealthSummary(e) {
function projectError(t, n) {
return {
...n,
activationSource: t?.activationSource,
activationReason: t?.activationReason,
error: truncateUtf16Safe(redactToolPayloadTextWithConfig(n.error, e.logging), 1e3)
};
}
const t = getActivePluginRegistry();
const n = listActiveDegradedPlugins();
const r = n.map(({ pluginId: e, state: t, diagnostic: n }) => ({
id: e,
state: t,
diagnostic: toPublicPluginVerificationDiagnostic(n)
})).sort((e, t) => e.id.localeCompare(t.id));
const i = (t?.plugins ?? []).filter((e) => e.status === "loaded").map((e) => e.id).sort((e, t) => e.localeCompare(t));
const a = (t?.plugins ?? []).filter((e) => e.status === "error" && !n.some((t) => e.id === t.pluginId && e.failurePhase === "validation" && e.activationReason === `configured-unavailable: ${t.diagnostic.reason}` && Boolean(e.rootDir) && degradedPluginMatchesRoot(t, e.rootDir ?? ""))).map((e) => projectError(e, {
id: e.id,
origin: e.origin,
activated: e.activated === true,
error: e.error ?? "unknown plugin load error",
...e.failurePhase ? { failurePhase: e.failurePhase } : {}
}));
const o = t ? listPluginServiceHealthFailures(t).map((e) => projectError(t.plugins.find((t) => t.id === e.pluginId), {
id: e.pluginId,
origin: e.origin,
activated: true,
failurePhase: "service",
error: `service ${e.serviceId}: ${e.error}`
})) : [];
const s = [...a, ...o].sort((e, t) => e.id.localeCompare(t.id) || e.error.localeCompare(t.error));
if (i.length === 0 && s.length === 0 && r.length === 0) return;
return {
loaded: i,
errors: s,
unavailable: r
};
}
const healthOperationPermits = createPermitPool(HEALTH_PROBE_CONCURRENCY);
function buildHealthTimeoutRecord(e) {
const t = `health collection timed out after ${HEALTH_COLLECTION_TIMEOUT_MS}ms`;
return {
accountId: e,
lastError: t,
probe: {
timedOut: true,
error: t
}
};
}
function resolveHealthProbeTimeoutMs(e) {
return Math.max(1, Math.floor(e - performance.now()));
}
async function buildHealthAccountRecord(e) {
const timedOut = () => e.deadlineFallback.record;
const t = e.runtimeSnapshot?.channelAccounts[e.plugin.id]?.[e.accountId];
const n = t ?? (e.accountId === e.defaultAccountId ? e.runtimeSnapshot?.channels[e.plugin.id] : void 0);
const r = e.runtimeOnly && t ? buildChannelAccountSnapshotFromRuntime(t) : void 0;
const i = resolveUnavailableChannelAccountSnapshot(e.cfg, {
channelId: e.plugin.id,
accountId: e.accountId,
runtime: r ?? n
});
if (i) return i;
if (r) {
const t = resolveChannelHealthState(r, {
channelId: e.plugin.id,
now: Date.now(),
staleEventThresholdMs: DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,
channelConnectGraceMs: DEFAULT_CHANNEL_CONNECT_GRACE_MS
});
return {
...r,
...t !== void 0 ? { healthState: t } : {}
};
}
const { probeAccount: a, inspectedAccount: o, enabled: s, configured: c, diagnostics: l } = await resolveHealthAccountContext({
plugin: e.plugin,
cfg: e.cfg,
accountId: e.accountId
});
if (performance.now() >= e.deadlineAtMs) return timedOut();
if (l.length > 0) debugHealth(e.cfg, "account.diagnostics", {
channel: e.plugin.id,
accountId: e.accountId,
diagnostics: l
});
let u;
let d = null;
if (a !== void 0 && s && c === true && e.probe && e.plugin.status?.probeAccount) {
try {
u = await e.plugin.status.probeAccount({
account: a,
timeoutMs: resolveHealthProbeTimeoutMs(e.deadlineAtMs),
cfg: e.cfg
});
} catch (e) {
u = {
ok: false,
error: formatErrorMessage(e)
};
}
d = Date.now();
}
const f = buildNonSensitiveProbeFailure(e.plugin.id, u);
const p = e.includeSensitive ? u : f;
const m = asNullableObjectRecord(p);
if (m?.ok === false && m.timedOut !== true) e.deadlineFallback.record = {
accountId: e.accountId,
probe: p,
...typeof m.error === "string" ? { lastError: m.error } : {}
};
if (performance.now() >= e.deadlineAtMs) return timedOut();
const h = asNullableObjectRecord(asNullableObjectRecord(u)?.bot);
if (h?.username) debugHealth(e.cfg, "probe.bot", {
channel: e.plugin.id,
accountId: e.accountId,
username: h.username
});
const g = a === void 0 ? buildChannelAccountSnapshotFromInspection({
account: o,
accountId: e.accountId,
runtime: n,
probe: p
}) : await buildChannelAccountSnapshotFromAccount({
plugin: e.plugin,
cfg: e.cfg,
accountId: e.accountId,
account: a,
runtime: n,
probe: p,
enabledFallback: s,
configuredFallback: c
});
if (performance.now() >= e.deadlineAtMs) return timedOut();
if (d) g.lastProbeAt = d;
const _ = resolveChannelHealthState(g, {
channelId: e.plugin.id,
now: Date.now(),
staleEventThresholdMs: DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,
channelConnectGraceMs: DEFAULT_CHANNEL_CONNECT_GRACE_MS
});
if (_ !== void 0) g.healthState = _;
const v = a !== void 0 && e.plugin.status?.buildChannelSummary ? await e.plugin.status.buildChannelSummary({
account: a,
cfg: e.cfg,
defaultAccountId: e.accountId,
snapshot: g
}) : void 0;
if (performance.now() >= e.deadlineAtMs) return timedOut();
const y = redactChannelStatusSummaryBaseUrl(v && typeof v === "object" ? {
...g,
...v
} : {
...g,
accountId: e.accountId
});
if (y.configured === void 0 && a !== void 0) y.configured = c;
if (e.includeSensitive && y.probe === void 0 && u !== void 0) y.probe = u;
if (!e.includeSensitive) {
const t = buildNonSensitiveProbeFailure(e.plugin.id, y.probe) ?? f;
if (t) y.probe = t;
else delete y.probe;
}
if (y.lastProbeAt === void 0 && d) y.lastProbeAt = d;
y.accountId = e.accountId;
return y;
}
async function runHealthAccountWithinDeadline(e) {
const t = { record: buildHealthTimeoutRecord(e.accountId) };
const n = trackAsyncWork(async () => {
const n = new AbortController();
const r = scheduleAbsoluteDeadline(e.deadlineAtMs, () => n.abort(), monotonicNow, { unref: true });
const i = await healthOperationPermits.acquire({ signal: n.signal });
r();
if (!i) return t.record;
try {
return await buildHealthAccountRecord({
...e,
deadlineFallback: t
});
} finally {
i();
}
});
const r = await awaitWithinDeadline(() => n, e.deadlineAtMs, monotonicNow);
return r === ABSOLUTE_DEADLINE_EXPIRED ? t.record : r;
}
/** Collects the gateway-owned health snapshot for an explicit trust audience. */
async function collectGatewayHealthSnapshot(e) {
const t = captureDeliveryQueueHealthContext();
const n = performance.now();
const r = n + HEALTH_COLLECTION_TIMEOUT_MS;
const i = await readRuntimeHealthConfig();
const { defaultAgentId: a, ordered: o } = resolveHealthAgentOrder(i);
const s = buildChannelAccountBindings(i);
const c = await prepareHealthAgentSummaries(i, {
defaultAgentId: a,
ordered: o
}, e.sessionRowProjection, e.cronState);
const l = e.audience === "admin";
const u = {};
const d = listReadOnlyChannelPluginsForConfig(i, {
includeSetupFallbackPlugins: false,
includePersistedAuthState: false
});
const f = d.map((e) => e.id);
const p = {};
const m = d.map((t) => {
p[t.id] = t.meta.label ?? t.id;
const n = t.config.listAccountIds(i);
const r = resolveChannelDefaultAccountId({
plugin: t,
cfg: i,
accountIds: n
});
const o = a ? s.get(t.id)?.get(a) ?? [] : [];
const c = o[0] ?? r;
const l = Array.from(new Set(Array.from(s.get(t.id)?.values() ?? []).flat()));
const u = Array.from(new Set([
c,
r,
...n,
...l,
...Object.keys(e.runtimeSnapshot?.channelAccounts[t.id] ?? {})
].filter((e) => e && e.trim())));
debugHealth(i, "channel", {
id: t.id,
accountIds: n,
defaultAccountId: r,
boundAccounts: o,
preferredAccountId: c,
accountIdsToProbe: u
});
return {
plugin: t,
defaultAccountId: r,
preferredAccountId: c,
accountIds: u,
configuredAccountIds: new Set(n),
accountSummaries: {}
};
});
const h = m.flatMap((e) => e.accountIds.map((t) => ({
plan: e,
accountId: t
})));
const { results: g } = await runTasksWithConcurrency({
tasks: h.map(({ plan: t, accountId: n }) => async () => ({
plan: t,
accountId: n,
record: await runHealthAccountWithinDeadline({
plugin: t.plugin,
cfg: i,
accountId: n,
defaultAccountId: t.defaultAccountId,
includeSensitive: l,
probe: e.probe,
deadlineAtMs: r,
runtimeSnapshot: e.runtimeSnapshot,
runtimeOnly: !t.configuredAccountIds.has(n)
})
})),
limit: e.probe ? HEALTH_PROBE_CONCURRENCY : 1,
throwOnError: true
});
for (const e of g) if (e) e.plan.accountSummaries[e.accountId] = e.record;
for (const e of m) {
const t = e.accountSummaries[e.preferredAccountId] ?? e.accountSummaries[e.defaultAccountId] ?? e.accountSummaries[e.accountIds[0] ?? e.preferredAccountId] ?? e.accountSummaries[expectDefined(Object.keys(e.accountSummaries)[0], "object.keys(account summaries) entry at 0")];
if (t) u[e.plugin.id] = {
...t,
accounts: e.accountSummaries
};
}
const _ = buildPluginHealthSummary(i);
const v = await buildContextEngineHealthSummary();
const y = await buildDeliveryQueueHealthSummary(t);
const { agents: b, sessions: x } = c.publish();
const S = b.find((e) => e.isDefault) ?? b[0];
const C = b.find((e) => e.heartbeat.enabled) ?? S;
const w = C?.heartbeat.everyMs ? Math.round(C.heartbeat.everyMs / 1e3) : 0;
return {
ok: true,
ts: Date.now(),
durationMs: Math.floor(performance.now() - n),
...e.eventLoop ? { eventLoop: e.eventLoop } : {},
..._ ? { plugins: _ } : {},
...v ? { contextEngines: v } : {},
...y ? { deliveryQueues: y } : {},
...e.configReloadHotReloadStatus ? { configReload: { hotReloadStatus: e.configReloadHotReloadStatus } } : {},
channels: u,
channelOrder: f,
channelLabels: p,
heartbeatSeconds: w,
...a && S ? { defaultAgentId: S.agentId } : {},
agents: b,
sessions: x
};
}
async function readRuntimeHealthConfig() {
const { getRuntimeConfig: e } = await import("./config/config.js");
return e();
}
//#endregion
export { buildHealthAgentSummaries, collectGatewayHealthSnapshot, resolveHealthAgentOrder };