openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 9.25 kB
JavaScript
import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as writeRuntimeJson,t as ExitError}from"./runtime-DIcLIHcp.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as isDiagnosticFlagEnabled}from"./diagnostic-flags-BdHquTqD.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{a as isConfigReadFailure,n as createConfigReadError}from"./io.invalid-config-B2POcxOa.mjs";import{n as isRich}from"./theme-DS2CtI9X.mjs";import{n as info}from"./globals-l9I53ZKA.mjs";import{n as isGatewaySecretRefUnavailableError}from"./credentials-BL-kavyD.mjs";import{t as formatDurationCompact}from"./format-duration-CDAHVcL7.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-CVqWsTxX.mjs";import{r as DEFAULT_RESTART_HEALTH_TIMEOUT_MS}from"./restart-health.constants-BS7LeiAV.mjs";import{n as listReadOnlyChannelPluginsForConfigAsync}from"./read-only-B-Uv2t8Q.mjs";import{t as buildChannelAccountBindings}from"./bindings-B5mteQei.mjs";import{i as resolveChannelDefaultAccountId}from"./helpers-1A2j6LGz.mjs";import{r as withProgress}from"./progress-BcNIavn6.mjs";import{t as styleHealthChannelLine}from"./health-style-DjfyD30O.mjs";import{t as formatExactDuration}from"./format-duration-exact-Dmb7bay7.mjs";import{t as probeGatewayStatus}from"./probe-Bu5oNkoG.mjs";import{t as waitForGatewayDiagnostic}from"./gateway-diagnostic-readiness-CO4yE-qj.mjs";import{a as formatHealthChannelLines,n as formatContextEngineHealthLine,r as formatDeliveryQueueHealthLine,t as formatConfigReloadHealthLine}from"./health-format-DElePmik.mjs";import{n as resolveHealthAccountContext}from"./account-context-XWGQuu-s.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-C6fOEjo5.mjs";import{t as logGatewayConnectionDetails}from"./status.gateway-connection-4Ak2O_Y4.mjs";
//!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)try{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,signal:e.signal});if(!gatewayProbeResultSawGateway(r))return false;n=gatewayProbeResultWasRateLimited(r)}catch(t){if(e.signal?.aborted)return true;throw t}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,signal:e.signal}))}catch(r){if(e.signal?.aborted)return;if(await emitReachableGatewayAuthDiagnostic({...e,error:r,config:n,runtime:t}))return;if(e.json&&emitGatewayHealthErrorJson(r,t))return;throw r}if(e.signal?.aborted)return;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-DuJbkjfJ.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=await listReadOnlyChannelPluginsForConfigAsync(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`})`)}}}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}export{readNonObservingHealthConfig as a,healthCommandNonExiting as i,emitReachableGatewayAuthDiagnostic as n,healthCommand as r,emitGatewayHealthErrorJson as t};