UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

311 lines (310 loc) • 12.7 kB
import { t as createSubsystemLogger } from "./subsystem-DISldKSB.js"; import { s as loadConfig } from "./io-y3Az_Onx.js"; import { t as emitDiagnosticEvent } from "./diagnostic-events-DLiZiw1x.js"; //#region src/logging/diagnostic-session-state.ts const diagnosticSessionStates = /* @__PURE__ */ new Map(); const SESSION_STATE_TTL_MS = 1800 * 1e3; const SESSION_STATE_PRUNE_INTERVAL_MS = 60 * 1e3; const SESSION_STATE_MAX_ENTRIES = 2e3; let lastSessionPruneAt = 0; function pruneDiagnosticSessionStates(now = Date.now(), force = false) { const shouldPruneForSize = diagnosticSessionStates.size > SESSION_STATE_MAX_ENTRIES; if (!force && !shouldPruneForSize && now - lastSessionPruneAt < SESSION_STATE_PRUNE_INTERVAL_MS) return; lastSessionPruneAt = now; for (const [key, state] of diagnosticSessionStates.entries()) { const ageMs = now - state.lastActivity; if (state.state === "idle" && state.queueDepth <= 0 && ageMs > SESSION_STATE_TTL_MS) diagnosticSessionStates.delete(key); } if (diagnosticSessionStates.size <= SESSION_STATE_MAX_ENTRIES) return; const excess = diagnosticSessionStates.size - SESSION_STATE_MAX_ENTRIES; const ordered = Array.from(diagnosticSessionStates.entries()).toSorted((a, b) => a[1].lastActivity - b[1].lastActivity); for (let i = 0; i < excess; i += 1) { const key = ordered[i]?.[0]; if (!key) break; diagnosticSessionStates.delete(key); } } function resolveSessionKey({ sessionKey, sessionId }) { return sessionKey ?? sessionId ?? "unknown"; } function findStateBySessionId(sessionId) { for (const state of diagnosticSessionStates.values()) if (state.sessionId === sessionId) return state; } function getDiagnosticSessionState(ref) { pruneDiagnosticSessionStates(); const key = resolveSessionKey(ref); const existing = diagnosticSessionStates.get(key) ?? (ref.sessionId && findStateBySessionId(ref.sessionId)); if (existing) { if (ref.sessionId) existing.sessionId = ref.sessionId; if (ref.sessionKey) existing.sessionKey = ref.sessionKey; return existing; } const created = { sessionId: ref.sessionId, sessionKey: ref.sessionKey, lastActivity: Date.now(), state: "idle", queueDepth: 0 }; diagnosticSessionStates.set(key, created); pruneDiagnosticSessionStates(Date.now(), true); return created; } function getDiagnosticSessionStateCountForTest$1() { return diagnosticSessionStates.size; } function resetDiagnosticSessionStateForTest() { diagnosticSessionStates.clear(); lastSessionPruneAt = 0; } //#endregion //#region src/logging/diagnostic.ts const diag = createSubsystemLogger("diagnostic"); const webhookStats = { received: 0, processed: 0, errors: 0, lastReceived: 0 }; let lastActivityAt = 0; const DEFAULT_STUCK_SESSION_WARN_MS = 12e4; const MIN_STUCK_SESSION_WARN_MS = 1e3; const MAX_STUCK_SESSION_WARN_MS = 1440 * 60 * 1e3; let commandPollBackoffRuntimePromise = null; function loadCommandPollBackoffRuntime() { commandPollBackoffRuntimePromise ??= import("./command-poll-backoff.runtime-CFkTcpWy.js"); return commandPollBackoffRuntimePromise; } function markActivity() { lastActivityAt = Date.now(); } function resolveStuckSessionWarnMs(config) { const raw = config?.diagnostics?.stuckSessionWarnMs; if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_STUCK_SESSION_WARN_MS; const rounded = Math.floor(raw); if (rounded < MIN_STUCK_SESSION_WARN_MS || rounded > MAX_STUCK_SESSION_WARN_MS) return DEFAULT_STUCK_SESSION_WARN_MS; return rounded; } function logWebhookReceived(params) { webhookStats.received += 1; webhookStats.lastReceived = Date.now(); if (diag.isEnabled("debug")) diag.debug(`webhook received: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} total=${webhookStats.received}`); emitDiagnosticEvent({ type: "webhook.received", channel: params.channel, updateType: params.updateType, chatId: params.chatId }); markActivity(); } function logWebhookProcessed(params) { webhookStats.processed += 1; if (diag.isEnabled("debug")) diag.debug(`webhook processed: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} duration=${params.durationMs ?? 0}ms processed=${webhookStats.processed}`); emitDiagnosticEvent({ type: "webhook.processed", channel: params.channel, updateType: params.updateType, chatId: params.chatId, durationMs: params.durationMs }); markActivity(); } function logWebhookError(params) { webhookStats.errors += 1; diag.error(`webhook error: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} error="${params.error}" errors=${webhookStats.errors}`); emitDiagnosticEvent({ type: "webhook.error", channel: params.channel, updateType: params.updateType, chatId: params.chatId, error: params.error }); markActivity(); } function logMessageQueued(params) { const state = getDiagnosticSessionState(params); state.queueDepth += 1; state.lastActivity = Date.now(); if (diag.isEnabled("debug")) diag.debug(`message queued: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} source=${params.source} queueDepth=${state.queueDepth} sessionState=${state.state}`); emitDiagnosticEvent({ type: "message.queued", sessionId: state.sessionId, sessionKey: state.sessionKey, channel: params.channel, source: params.source, queueDepth: state.queueDepth }); markActivity(); } function logMessageProcessed(params) { if (params.outcome === "error" ? diag.isEnabled("error") : diag.isEnabled("debug")) { const payload = `message processed: channel=${params.channel} chatId=${params.chatId ?? "unknown"} messageId=${params.messageId ?? "unknown"} sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} outcome=${params.outcome} duration=${params.durationMs ?? 0}ms${params.reason ? ` reason=${params.reason}` : ""}${params.error ? ` error="${params.error}"` : ""}`; if (params.outcome === "error") diag.error(payload); else diag.debug(payload); } emitDiagnosticEvent({ type: "message.processed", channel: params.channel, chatId: params.chatId, messageId: params.messageId, sessionId: params.sessionId, sessionKey: params.sessionKey, durationMs: params.durationMs, outcome: params.outcome, reason: params.reason, error: params.error }); markActivity(); } function logSessionStateChange(params) { const state = getDiagnosticSessionState(params); const isProbeSession = state.sessionId?.startsWith("probe-") ?? false; const prevState = state.state; state.state = params.state; state.lastActivity = Date.now(); if (params.state === "idle") state.queueDepth = Math.max(0, state.queueDepth - 1); if (!isProbeSession && diag.isEnabled("debug")) diag.debug(`session state: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} prev=${prevState} new=${params.state} reason="${params.reason ?? ""}" queueDepth=${state.queueDepth}`); emitDiagnosticEvent({ type: "session.state", sessionId: state.sessionId, sessionKey: state.sessionKey, prevState, state: params.state, reason: params.reason, queueDepth: state.queueDepth }); markActivity(); } function logSessionStuck(params) { const state = getDiagnosticSessionState(params); diag.warn(`stuck session: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} state=${params.state} age=${Math.round(params.ageMs / 1e3)}s queueDepth=${state.queueDepth}`); emitDiagnosticEvent({ type: "session.stuck", sessionId: state.sessionId, sessionKey: state.sessionKey, state: params.state, ageMs: params.ageMs, queueDepth: state.queueDepth }); markActivity(); } function logLaneEnqueue(lane, queueSize) { diag.debug(`lane enqueue: lane=${lane} queueSize=${queueSize}`); emitDiagnosticEvent({ type: "queue.lane.enqueue", lane, queueSize }); markActivity(); } function logLaneDequeue(lane, waitMs, queueSize) { diag.debug(`lane dequeue: lane=${lane} waitMs=${waitMs} queueSize=${queueSize}`); emitDiagnosticEvent({ type: "queue.lane.dequeue", lane, queueSize, waitMs }); markActivity(); } function logRunAttempt(params) { diag.debug(`run attempt: sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} runId=${params.runId} attempt=${params.attempt}`); emitDiagnosticEvent({ type: "run.attempt", sessionId: params.sessionId, sessionKey: params.sessionKey, runId: params.runId, attempt: params.attempt }); markActivity(); } function logToolLoopAction(params) { const payload = `tool loop: sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} tool=${params.toolName} level=${params.level} action=${params.action} detector=${params.detector} count=${params.count}${params.pairedToolName ? ` pairedTool=${params.pairedToolName}` : ""} message="${params.message}"`; if (params.level === "critical") diag.error(payload); else diag.warn(payload); emitDiagnosticEvent({ type: "tool.loop", sessionId: params.sessionId, sessionKey: params.sessionKey, toolName: params.toolName, level: params.level, action: params.action, detector: params.detector, count: params.count, message: params.message, pairedToolName: params.pairedToolName }); markActivity(); } function logActiveRuns() { const activeSessions = Array.from(diagnosticSessionStates.entries()).filter(([, s]) => s.state === "processing").map(([id, s]) => `${id}(q=${s.queueDepth},age=${Math.round((Date.now() - s.lastActivity) / 1e3)}s)`); diag.debug(`active runs: count=${activeSessions.length} sessions=[${activeSessions.join(", ")}]`); markActivity(); } let heartbeatInterval = null; function startDiagnosticHeartbeat(config) { if (heartbeatInterval) return; heartbeatInterval = setInterval(() => { let heartbeatConfig = config; if (!heartbeatConfig) try { heartbeatConfig = loadConfig(); } catch { heartbeatConfig = void 0; } const stuckSessionWarnMs = resolveStuckSessionWarnMs(heartbeatConfig); const now = Date.now(); pruneDiagnosticSessionStates(now, true); const activeCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "processing").length; const waitingCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "waiting").length; const totalQueued = Array.from(diagnosticSessionStates.values()).reduce((sum, s) => sum + s.queueDepth, 0); if (!(lastActivityAt > 0 || webhookStats.received > 0 || activeCount > 0 || waitingCount > 0 || totalQueued > 0)) return; if (now - lastActivityAt > 12e4 && activeCount === 0 && waitingCount === 0) return; diag.debug(`heartbeat: webhooks=${webhookStats.received}/${webhookStats.processed}/${webhookStats.errors} active=${activeCount} waiting=${waitingCount} queued=${totalQueued}`); emitDiagnosticEvent({ type: "diagnostic.heartbeat", webhooks: { received: webhookStats.received, processed: webhookStats.processed, errors: webhookStats.errors }, active: activeCount, waiting: waitingCount, queued: totalQueued }); loadCommandPollBackoffRuntime().then(({ pruneStaleCommandPolls }) => { for (const [, state] of diagnosticSessionStates) pruneStaleCommandPolls(state); }).catch((err) => { diag.debug(`command-poll-backoff prune failed: ${String(err)}`); }); for (const [, state] of diagnosticSessionStates) { const ageMs = now - state.lastActivity; if (state.state === "processing" && ageMs > stuckSessionWarnMs) logSessionStuck({ sessionId: state.sessionId, sessionKey: state.sessionKey, state: state.state, ageMs }); } }, 3e4); heartbeatInterval.unref?.(); } function stopDiagnosticHeartbeat() { if (heartbeatInterval) { clearInterval(heartbeatInterval); heartbeatInterval = null; } } function getDiagnosticSessionStateCountForTest() { return getDiagnosticSessionStateCountForTest$1(); } function resetDiagnosticStateForTest() { resetDiagnosticSessionStateForTest(); webhookStats.received = 0; webhookStats.processed = 0; webhookStats.errors = 0; webhookStats.lastReceived = 0; lastActivityAt = 0; stopDiagnosticHeartbeat(); } //#endregion export { startDiagnosticHeartbeat as _, logLaneEnqueue as a, logRunAttempt as c, logToolLoopAction as d, logWebhookError as f, resolveStuckSessionWarnMs as g, resetDiagnosticStateForTest as h, logLaneDequeue as i, logSessionStateChange as l, logWebhookReceived as m, getDiagnosticSessionStateCountForTest as n, logMessageProcessed as o, logWebhookProcessed as p, logActiveRuns as r, logMessageQueued as s, diag as t, logSessionStuck as u, stopDiagnosticHeartbeat as v, getDiagnosticSessionState as y };