openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
17 lines • 36.2 kB
JavaScript
import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{m as setTrackedWorkerGcObserver,p as sampleTrackedWorkerMemory}from"./worker-cpu-Cmr50ooq.mjs";import{n as getWorkerMessageMetrics}from"./worker-message-metrics-CdbgV0zo.mjs";import{r as createLazyRuntimeModule}from"./lazy-runtime-Ds6M7vp4.mjs";import{t as isValidAgentId}from"./agent-id-cOfqmfln.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{I as hasInternalDiagnosticEventInterest,o as emitInternalDiagnosticEvent,p as isDiagnosticsEnabled,t as areDiagnosticsEnabledForProcess}from"./diagnostic-events-BYBrlAdF.mjs";import{D as runWithDiagnosticTraceContext}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as emitChildProcessSpawnSample}from"./spawn-diagnostics-C-LTFiNq.mjs";import{n as getOldGenerationAfterGcBytes,r as observeGcSamples}from"./gc-observer-DBlUOKf8.mjs";import{a as getRuntimeConfigSnapshot,h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{_ as retireDiagnosticSessionObservations,a as logMessageQueuedWithBacklogPolicy,c as diagnosticSessionStates,d as isIncognitoDiagnosticSession,g as resolveDiagnosticSessionKey,l as getDiagnosticSessionState,n as getLastDiagnosticActivityAt,p as pruneDiagnosticSessionStates,s as markDiagnosticActivity,t as diagnosticLogger,u as isDiagnosticSessionStateCurrent,v as touchDiagnosticSessionState}from"./diagnostic-runtime-QyRFQxNU.mjs";import{v as resolveActiveEmbeddedRunRecoveryBlocker}from"./run-state-Bd0P0LYH.mjs";import"./config-DkZ8y8Gv.mjs";import{r as resolveCompactionTimeoutMs}from"./compaction-safety-timeout-BnvorGSI.mjs";import{d as stopDiagnosticRunActivityTracking,i as getDiagnosticSessionActivitySnapshot,u as startDiagnosticRunActivityTracking,x as captureDiagnosticSessionOperation}from"./diagnostic-run-activity-D_NQZV7c.mjs";import{i as roundDiagnosticMetric,n as getRecentDiagnosticPhases,t as getCurrentDiagnosticPhase}from"./diagnostic-phase-D91Teuec.mjs";import{n as getSessionRowSelectionMetrics}from"./gateway-work-metrics-KYjPT23f.mjs";import{t as truncateDiagnosticContent}from"./diagnostic-content-mVivdxeb.mjs";import{n as resolveDiagnosticModelContentCapturePolicy}from"./diagnostic-llm-content-BlP6pSYe.mjs";import{t as formatAdmissionDiagnostics}from"./command-lane-diagnostics-CwUrYCdn.mjs";import{n as prepareCronJobNameResolver}from"./job-name-0qKdfoCl.mjs";import{a as stopDiagnosticStabilityRecorder,i as startDiagnosticStabilityRecorder}from"./diagnostic-stability-BwUZ9fX3.mjs";import{a as uninstallDiagnosticStabilityFatalHook,n as installDiagnosticStabilityFatalHook}from"./diagnostic-stability-bundle-BVFlI2lH.mjs";import fs from"node:fs/promises";import{totalmem}from"node:os";import{getHeapSpaceStatistics,getHeapStatistics}from"node:v8";import{channel}from"node:diagnostics_channel";import{monitorEventLoopDelay,performance as performance$1}from"node:perf_hooks";
//!src/logging/diagnostic-gc.ts
let stopObserver;function stopDiagnosticGcObserver(){stopObserver?.();stopObserver=void 0;setTrackedWorkerGcObserver(void 0)}function reconcileDiagnosticGcObserver(){if(!areDiagnosticsEnabledForProcess()||!hasInternalDiagnosticEventInterest(`diagnostic.gc`)){stopDiagnosticGcObserver();return}setTrackedWorkerGcObserver(publishGcSamples);stopObserver??=observeGcSamples(e=>publishGcSamples(e,`main`))}function publishGcSamples(e,t,n){if(!areDiagnosticsEnabledForProcess()||!hasInternalDiagnosticEventInterest(`diagnostic.gc`))return;runWithDiagnosticTraceContext(void 0,()=>{for(const r of e)emitInternalDiagnosticEvent({type:`diagnostic.gc`,...r,thread:t,workerSlot:n})})}
//!src/logging/diagnostic-liveness.ts
const DEFAULT_LIVENESS_EVENT_LOOP_DELAY_WARN_MS=1e3;const DEFAULT_LIVENESS_EVENT_LOOP_UTILIZATION_WARN=.95;const DEFAULT_LIVENESS_CPU_CORE_RATIO_WARN=.9;const DEFAULT_LIVENESS_WARN_COOLDOWN_MS=12e4;let diagnosticLivenessMonitor=null;let lastDiagnosticLivenessWallAt=0;let lastDiagnosticLivenessCpuUsage=null;let lastDiagnosticLivenessEventLoopUtilization=null;let lastDiagnosticLivenessEventAt=0;let lastDiagnosticLivenessWarnAt=0;function nanosecondsToMilliseconds(e){return roundDiagnosticMetric(e/1e6,1)}function startDiagnosticLivenessSampler(){lastDiagnosticLivenessWallAt=Date.now();lastDiagnosticLivenessCpuUsage=process.cpuUsage();lastDiagnosticLivenessEventLoopUtilization=performance$1.eventLoopUtilization();lastDiagnosticLivenessEventAt=0;lastDiagnosticLivenessWarnAt=0;if(diagnosticLivenessMonitor){diagnosticLivenessMonitor.reset();return}try{diagnosticLivenessMonitor=monitorEventLoopDelay({resolution:20});diagnosticLivenessMonitor.enable();diagnosticLivenessMonitor.reset()}catch(e){diagnosticLivenessMonitor=null;diagnosticLogger.debug(`diagnostic liveness monitor unavailable: ${String(e)}`)}}function stopDiagnosticLivenessSampler(){diagnosticLivenessMonitor?.disable();diagnosticLivenessMonitor=null;lastDiagnosticLivenessWallAt=0;lastDiagnosticLivenessCpuUsage=null;lastDiagnosticLivenessEventLoopUtilization=null;lastDiagnosticLivenessEventAt=0;lastDiagnosticLivenessWarnAt=0}function sampleDiagnosticLiveness(e){if(!diagnosticLivenessMonitor||!lastDiagnosticLivenessCpuUsage||!lastDiagnosticLivenessEventLoopUtilization||lastDiagnosticLivenessWallAt<=0){startDiagnosticLivenessSampler();return null}const t=Math.max(1,e-lastDiagnosticLivenessWallAt);const n=process.cpuUsage(lastDiagnosticLivenessCpuUsage);const r=performance$1.eventLoopUtilization();const i=performance$1.eventLoopUtilization(r,lastDiagnosticLivenessEventLoopUtilization).utilization;const a=nanosecondsToMilliseconds(diagnosticLivenessMonitor.percentile(99));const o=nanosecondsToMilliseconds(diagnosticLivenessMonitor.max);diagnosticLivenessMonitor.reset();lastDiagnosticLivenessWallAt=e;lastDiagnosticLivenessCpuUsage=process.cpuUsage();lastDiagnosticLivenessEventLoopUtilization=r;const s=roundDiagnosticMetric(n.user/1e3,1);const c=roundDiagnosticMetric(n.system/1e3,1);const l=roundDiagnosticMetric(s+c,1);const u=roundDiagnosticMetric(l/t,3);const d=roundDiagnosticMetric(i,3);const f=[];if(a>=1e3||o>=1e3)f.push(`event_loop_delay`);if(d>=DEFAULT_LIVENESS_EVENT_LOOP_UTILIZATION_WARN)f.push(`event_loop_utilization`);if(u>=DEFAULT_LIVENESS_CPU_CORE_RATIO_WARN)f.push(`cpu`);if(f.length===0)return null;return{reasons:f,intervalMs:t,eventLoopDelayP99Ms:a,eventLoopDelayMaxMs:o,eventLoopUtilization:d,cpuUserMs:s,cpuSystemMs:c,cpuTotalMs:l,cpuCoreRatio:u}}function shouldEmitDiagnosticLivenessEvent(e){if(lastDiagnosticLivenessEventAt>0&&e-lastDiagnosticLivenessEventAt<DEFAULT_LIVENESS_WARN_COOLDOWN_MS)return false;lastDiagnosticLivenessEventAt=e;return true}function shouldEmitDiagnosticLivenessWarning(e,t){if(!t)return false;if(lastDiagnosticLivenessWarnAt>0&&e-lastDiagnosticLivenessWarnAt<DEFAULT_LIVENESS_WARN_COOLDOWN_MS)return false;lastDiagnosticLivenessWarnAt=e;return true}
//!src/logging/diagnostic-memory.ts
const WARNING_RATIO=.8;const CRITICAL_RATIO=.9;const DEFAULT_PRESSURE_REPEAT_MS=3e5;const BYTE_UNITS=[`B`,`KiB`,`MiB`,`GiB`,`TiB`];const memoryPressure=channel(`openclaw.memory.critical`);let defaultHeapSizeLimitBytes;const DEFAULT_PROCESS_MEMORY_LIMIT_BYTES=process.constrainedMemory();const DEFAULT_PHYSICAL_MEMORY_BYTES=totalmem();const DEFAULT_IS_BUN_RUNTIME=typeof process.versions.bun===`string`;const log=createSubsystemLogger(`gateway`).child(`diagnostics/memory`);const lastPressureAtByKey=/* @__PURE__ */ new Map;async function readProcessFootprint(){const e={};try{const t=await fs.readFile(`/proc/self/status`,`utf8`);for(const[n,r]of[[`RssAnon`,`anonymousRssBytes`],[`VmSwap`,`anonymousSwapBytes`]]){const i=t.match(new RegExp(`^${n}:\\s+(\\d+)\\s+kB$`,`m`))?.[1];if(i!==void 0)e[r]=Number(i)*1024}}catch{}return e}function createDiagnosticMemorySampler(e){let t=false;return(n,r)=>{if(r?.emitMemorySample){r.emitMemorySample({emitSample:n});return}const i=n&&process.platform===`linux`;const a=performance.now();const o=emitDiagnosticMemorySample({emitSample:n&&!i});if(!i||t)return;t=true;const s=Math.round(process.uptime()*1e3);readProcessFootprint().then(n=>{t=false;if(e()){const e=Math.round(performance.now()-a);publishMemorySample({...o,...n,workerHeaps:o.workerHeaps?.map(t=>t.sampleAgeMs===void 0?t:Object.assign({},t,{sampleAgeMs:t.sampleAgeMs+e}))},s)}})}}function publishMemorySample(e,t){emitInternalDiagnosticEvent({type:`diagnostic.memory.sample`,memory:{...e,heapSpaces:DEFAULT_IS_BUN_RUNTIME?void 0:getHeapSpaceStatistics()},uptimeMs:t})}function isPositiveMemoryLimit(e){return typeof e===`number`&&Number.isFinite(e)&&e>0}function normalizeMemoryUsage(e,t){return{rssBytes:e.rss,heapTotalBytes:e.heapTotal,heapUsedBytes:e.heapUsed,externalBytes:e.external,arrayBuffersBytes:e.arrayBuffers,...t?{...sampleTrackedWorkerMemory(),workerMessages:getWorkerMessageMetrics(),sessionRowSelections:getSessionRowSelectionMetrics()}:{}}}function pickPressure(e,t,n,r,i){const a=[{reason:`heap_threshold`,usedBytes:e.heapUsedBytes,limitBytes:t,warning:r?.heapUsedWarningBytes,critical:r?.heapUsedCriticalBytes},...(e.workerHeaps??[]).map(e=>({reason:`worker_heap_threshold`,usedBytes:e.heapUsed,limitBytes:e.heapSizeLimitBytes,workerThreadId:e.threadId,warning:void 0,critical:void 0})),{reason:`rss_threshold`,usedBytes:e.rssBytes,limitBytes:n,warning:r?.rssWarningBytes,critical:r?.rssCriticalBytes},...i?[{reason:`process_memory_threshold`,...i}]:[]];for(const[t,n]of[[`critical`,CRITICAL_RATIO],[`warning`,WARNING_RATIO]])for(const{reason:r,usedBytes:i,limitBytes:o,workerThreadId:s,...c}of a){const a=c[t]??(isPositiveMemoryLimit(o)?Math.floor(o*n):void 0);if(isPositiveMemoryLimit(a)&&i>=a)return{level:t,reason:r,memory:e,usedBytes:i,limitBytes:o,thresholdBytes:a,workerThreadId:s}}return null}function shouldEmitPressure(e,t,n){const r=`${e.level}:${e.reason}`;const i=lastPressureAtByKey.get(r);if(i!==void 0&&t-i<n)return false;lastPressureAtByKey.set(r,t);return true}function formatOptionalPressureMetric(e,t){return typeof t===`number`&&Number.isFinite(t)?` ${e}=${t}`:``}function formatScaledNumber(e){return(e>=10?e.toFixed(1):e.toFixed(2)).replace(/\.0+$/u,``).replace(/(\.\d*[1-9])0$/u,`$1`)}function formatReadableBytes(e){if(typeof e!==`number`||!Number.isFinite(e)||e<0)return;let t=e;let n=0;while(t>=1024&&n<BYTE_UNITS.length-1){t/=1024;n++}return n===0?`${Math.round(t)} ${BYTE_UNITS[n]}`:`${formatScaledNumber(t)} ${BYTE_UNITS[n]}`}function formatPressureSummary(e){const t=Number.isFinite(e.usedBytes)?`${formatScaledNumber(e.usedBytes/e.thresholdBytes*100)}%`:void 0;return[`rss=${formatReadableBytes(e.memory.rssBytes)}`,`heap=${formatReadableBytes(e.memory.heapUsedBytes)}`,`threshold=${formatReadableBytes(e.thresholdBytes)}`,`thresholdRatio=${t}`,e.limitBytes!==void 0?`limit=${formatReadableBytes(e.limitBytes)}`:``,`used=${formatReadableBytes(e.usedBytes)}`].filter(e=>Boolean(e)).join(` `)}function logMemoryPressure(e){const t=e.level===`critical`?`nextStep=run openclaw gateway diagnostics export, inspect an existing bundle with openclaw gateway stability --bundle latest, or sample allocations with openclaw gateway call diagnostics.heapProfile --timeout 30000.`:`nextStep=run openclaw gateway status --deep and openclaw gateway diagnostics export; restart gateway if pressure persists`;const n=`memory pressure: level=${e.level} reason=${e.reason} ${formatPressureSummary(e)} rssBytes=${e.memory.rssBytes} heapUsedBytes=${e.memory.heapUsedBytes} externalBytes=${e.memory.externalBytes} arrayBuffersBytes=${e.memory.arrayBuffersBytes}`+formatOptionalPressureMetric(`workerHeapTotalBytes`,e.memory.workerHeapTotalBytes)+formatOptionalPressureMetric(`workerHeapUsedBytes`,e.memory.workerHeapUsedBytes)+formatOptionalPressureMetric(`workerExternalBytes`,e.memory.workerExternalBytes)+formatOptionalPressureMetric(`workerArrayBuffersBytes`,e.memory.workerArrayBuffersBytes)+formatOptionalPressureMetric(`workerCount`,e.memory.workerCount)+formatOptionalPressureMetric(`postgresBridgeCount`,e.memory.postgresBridgeCount)+formatOptionalPressureMetric(`postgresPoolSelfRootCount`,e.memory.postgresPoolSelfRootCount)+formatOptionalPressureMetric(`workerHeapSampledCount`,e.memory.workerHeapSampledCount)+formatOptionalPressureMetric(`workerArrayBuffersSampledCount`,e.memory.workerArrayBuffersSampledCount)+(e.memory.workerMemoryCoverage?` workerMemoryCoverage=${e.memory.workerMemoryCoverage} workerMemoryScope=direct`:``)+(e.memory.workerMemoryMissing?.length?` workerMemoryMissing=${JSON.stringify(e.memory.workerMemoryMissing.slice(0,5))}`:``)+(e.memory.workerHeaps?.length?` workerHeaps=${JSON.stringify(e.memory.workerHeaps.toSorted((e,t)=>t.heapUsed+(t.external??0)-e.heapUsed-(e.external??0)).slice(0,5))}`:``)+formatOptionalPressureMetric(`thresholdBytes`,e.thresholdBytes)+formatOptionalPressureMetric(`limitBytes`,e.limitBytes)+formatOptionalPressureMetric(`usedBytes`,e.usedBytes)+formatOptionalPressureMetric(`workerThreadId`,e.workerThreadId)+(e.memory.workerCount?` workerLimitScope=js-heap-only; external/ArrayBuffers are not capped; nested worker heaps are not included.`:``)+` ${t}`;log.warn(n)}function emitDiagnosticMemorySample(e,t=true){const n=e?.now??Date.now();const r=normalizeMemoryUsage(e?.memoryUsage??process.memoryUsage(),t);const i=e?.isBunRuntime??DEFAULT_IS_BUN_RUNTIME;const a=i?void 0:e?.heapSizeLimitBytes??(defaultHeapSizeLimitBytes??=getHeapStatistics().heap_size_limit);const o=e?.processMemoryLimitBytes??DEFAULT_PROCESS_MEMORY_LIMIT_BYTES;const s=e?.physicalMemoryBytes??DEFAULT_PHYSICAL_MEMORY_BYTES;const c=[o,s].filter(isPositiveMemoryLimit);const l=!i&&process.platform===`linux`&&isPositiveMemoryLimit(o)&&isPositiveMemoryLimit(s)&&o<s?process.availableMemory():void 0;const u=l!==void 0&&Number.isFinite(l)&&l>=0&&l<=o?{usedBytes:o-l,limitBytes:o}:void 0;const d=c.length?Math.min(...c):void 0;const f=t&&e?.emitSample!==false;r.heapSizeLimitBytes=a;r.oldGenerationAfterGcBytes=i?void 0:getOldGenerationAfterGcBytes();if(f)publishMemorySample(r,e?.uptimeMs??Math.round(process.uptime()*1e3));const p=pickPressure(r,a,d,e?.thresholds,u);if(p?.level===`critical`||u&&u.usedBytes>=Math.floor(u.limitBytes*WARNING_RATIO))memoryPressure.publish(p?.level===`critical`);if(t&&p&&shouldEmitPressure(p,n,e?.thresholds?.pressureRepeatMs??DEFAULT_PRESSURE_REPEAT_MS)){emitInternalDiagnosticEvent({type:`diagnostic.memory.pressure`,...p});logMemoryPressure(p)}return r}
//!src/logging/diagnostic-message-content.ts
function emitMessageProcessedDiagnosticEvent(e){const t=resolveDiagnosticModelContentCapturePolicy(getRuntimeConfigSnapshot());const n=t.inputMessages||t.outputMessages?{...t.inputMessages&&e.userPrompt!==void 0?{userPrompt:truncateDiagnosticContent(e.userPrompt)}:{},...t.outputMessages&&e.finalResponse!==void 0?{finalResponse:truncateDiagnosticContent(e.finalResponse)}:{}}:void 0;const r=n!==void 0&&Object.keys(n).length>0;const{userPrompt:i,finalResponse:a,...o}=e;emitInternalDiagnosticEvent({type:`message.processed`,...o},r?{messageContent:n}:void 0)}
//!src/logging/diagnostic-session-attention.ts
function classifySessionAttention(e){const longRunning=t=>({eventType:`session.long_running`,reason:t,classification:`long_running`,activeWorkKind:e.activity.activeWorkKind});const stalled=(t,n=`stalled_agent_run`)=>({eventType:`session.stalled`,reason:t,classification:n,activeWorkKind:e.activity.activeWorkKind});if(e.activity.activeRetryWaitDeadlineAtMs!==void 0&&Date.now()<e.activity.activeRetryWaitDeadlineAtMs)return longRunning(`provider_retry_wait`);if(e.runtimeOwnsLiveness)return longRunning(`runtime_owned_wait`);if(e.activity.activeWorkKind){const t=e.activity.lastProgressAgeMs??0;if(e.activity.hasActiveEmbeddedRun===true&&typeof e.stuckSessionAbortMs===`number`&&(e.activity.repeatedRequestNoProgressAgeMs??0)>=e.stuckSessionAbortMs)return stalled(`repeated_model_requests_without_progress`);if(e.state===`idle`&&e.queueDepth>0&&e.activity.hasActiveEmbeddedRun!==true&&t>e.staleMs)return{eventType:`session.stuck`,reason:`queued_work_without_active_run`,classification:`stale_session_state`};if(e.activity.activeWorkKind===`tool_call`&&(e.activity.activeToolAgeMs??0)>e.staleMs&&t>e.staleMs){if(e.activity.activeToolDeadlineAtMs!==void 0&&Date.now()<e.activity.activeToolDeadlineAtMs)return longRunning(`tool_execution_wait`);return stalled(`blocked_tool_call`,`blocked_tool_call`)}if(e.queueDepth>0&&e.activity.activeWorkKind===`embedded_run`&&isTerminalDiagnosticProgressReason(e.activity.lastProgressReason))return stalled(`queued_behind_terminal_active_work`);if(e.activity.activeWorkKind===`model_call`&&e.activity.hasActiveEmbeddedRun===true&&t>e.staleMs){if(typeof e.stuckSessionAbortMs===`number`&&t>=e.stuckSessionAbortMs)return stalled(`active_work_without_progress`);return longRunning(`active_model_call_without_progress`)}if(t>e.staleMs)return stalled(`active_work_without_progress`);return longRunning(e.queueDepth>0?`queued_behind_active_work`:`active_work`)}return{eventType:`session.stuck`,reason:e.queueDepth>0?`queued_work_without_active_run`:`stale_session_state`,classification:`stale_session_state`}}function isTerminalDiagnosticProgressReason(e){if(!e)return false;return e===`run:completed`||e===`embedded_run:ended`||e.includes(`response.completed`)||e.includes(`rawResponseItem/completed`)||e.includes(`raw_response_item.completed`)||e.includes(`output_item.done`)}function formatSessionActivityLogFields(e){const t=[];if(e.admission)t.push(formatAdmissionDiagnostics(e.admission));if(e.lastProgressReason)t.push(`lastProgress=${e.lastProgressReason}`);if(e.lastProgressAgeMs!==void 0)t.push(`lastProgressAge=${Math.round(e.lastProgressAgeMs/1e3)}s`);if(e.activeToolName)t.push(`activeTool=${e.activeToolName}`);if(e.activeToolCallId)t.push(`activeToolCallId=${e.activeToolCallId}`);if(e.activeToolAgeMs!==void 0)t.push(`activeToolAge=${Math.round(e.activeToolAgeMs/1e3)}s`);if(e.repeatedRequestNoProgressAgeMs!==void 0)t.push(`repeatedRequestNoProgressAge=${Math.round(e.repeatedRequestNoProgressAgeMs/1e3)}s`);if(isTerminalDiagnosticProgressReason(e.lastProgressReason))t.push(`terminalProgressStale=true`);return t.join(` `)}
//!src/logging/diagnostic-session-context.ts
async function withSessionDiagnosticContext(e,t){const n=e.sessionKey?.trim();const r=parseAgentSessionKey(n);if(!n||!r||!isValidAgentId(r.agentId)||isIncognitoSessionKey(n)){t({});return}const[i,a,...o]=r.rest.split(`:`);const s=o.indexOf(`run`);const c=i===`cron`&&a?{cronJobId:a,cronRunId:s>=0?o[s+1]:void 0}:{};if(c.cronJobId)try{c.cronJobName=(await prepareCronJobNameResolver([c.cronJobId]))(c.cronJobId)}catch{}t(c)}function formatSessionDiagnosticFields(e){const quote=e=>{const t=e.replace(/\s+/g,` `).trim();return`"${(t.length>140?`${truncateUtf16Safe(t,137)}...`:t).replace(/["\\]/g,`\\$&`)}"`};return[e.cronJobId?`cronJobId=${e.cronJobId}`:``,e.cronRunId?`cronRunId=${e.cronRunId}`:``,e.cronJobName?`cronJob=${quote(e.cronJobName)}`:``].filter(Boolean).join(` `)}function logWithSessionDiagnosticContext(e){if(!areDiagnosticsEnabledForProcess()||!diagnosticLogger.isEnabled(e.level))return;return withSessionDiagnosticContext(e,t=>{diagnosticLogger[e.level](e.format(formatSessionDiagnosticFields(t)))})}
//!src/logging/diagnostic-session-recovery-coordinator.ts
function requestStuckSessionRecovery(e){const t=e.request.operation;if(!t&&e.classification.eventType!==`session.stuck`)return;const n=t?.watchdog.decide();if(n&&n.action!==`stop`&&n.action!==`expire_cleanup`)return;const r={...e.request,operation:t,allowActiveAbort:n?.action===`stop`,classification:e.classification};const i={sessionId:r.sessionId,sessionKey:r.sessionKey,state:r.expectedState??`processing`,stateGeneration:r.stateGeneration,ageMs:r.ageMs,queueDepth:r.queueDepth};emitInternalDiagnosticEvent({type:`session.recovery.requested`,...i,reason:n?.reason??`stale_session_state`,activeWorkKind:e.classification.activeWorkKind,allowActiveAbort:r.allowActiveAbort});const complete=e=>{if(!e)return;emitInternalDiagnosticEvent({type:`session.recovery.completed`,...i,activeWorkKind:e.activeWorkKind,status:e.status,action:e.action,outcomeReason:`reason`in e?e.reason:void 0,released:`released`in e?e.released||void 0:void 0,stale:t?!t.watchdog.snapshot().current:!isDiagnosticSessionStateCurrent({...r,generation:r.stateGeneration,state:r.expectedState})})};const failed=e=>complete({status:`failed`,action:`none`,reason:`exception`,error:String(e),sessionId:r.sessionId,sessionKey:r.sessionKey});try{Promise.resolve(e.recover(r)).then(complete,failed)}catch(e){failed(e)}}
//!src/logging/diagnostic.ts
const webhookStats={received:0,processed:0,errors:0};const DEFAULT_STUCK_SESSION_WARN_MS=12e4;const MIN_STALLED_EMBEDDED_RUN_ABORT_MS=3e5;const STALLED_EMBEDDED_RUN_ABORT_WARN_MULTIPLIER=3;const RECENT_DIAGNOSTIC_ACTIVITY_MS=12e4;const DIAGNOSTIC_HEARTBEAT_INTERVAL_MS=3e4;const MEMORY_PRESSURE_INTERVAL_MS=1e3;const loadStuckSessionRecoveryRuntime=createLazyRuntimeModule(()=>import(`./diagnostic-stuck-session-recovery.runtime-tDMSOlvX.mjs`));const loadCommandPollBackoffRuntime=createLazyRuntimeModule(()=>import(`./command-poll-backoff.runtime-CKtApx5I.mjs`));async function recoverStuckSession(e){const t=isIncognitoDiagnosticSession(e);return loadStuckSessionRecoveryRuntime().then(({recoverStuckDiagnosticSession:t})=>t(e)).catch(n=>{if(!t)diagnosticLogger.warn(`stuck session recovery unavailable: ${String(n)}`);return{status:`failed`,action:`none`,reason:`exception`,sessionId:e.sessionId,sessionKey:e.sessionKey,error:String(n)}})}function pushLimitedDiagnosticLabel(e,t,n){const r=t.sessionKey??t.sessionId??`unknown`;const i=Math.round(Math.max(0,n-t.lastActivity)/1e3);const a=getDiagnosticSessionActivitySnapshot({sessionId:t.sessionId,sessionKey:t.sessionKey},n);if(e.length>=5)return;const o=a.activeWorkKind?`/${a.activeWorkKind}`:``;const s=a.lastProgressReason?` last=${a.lastProgressReason}`:``;e.push(`${r}(${t.state}${o},q=${t.queueDepth},age=${i}s${s})`)}function resolveDiagnosticQueuedBacklog(e){return Math.max(0,e.queueDepth-(e.state===`processing`&&e.activeQueuedTurn?1:0))}function getDiagnosticWorkSnapshot(e=Date.now()){let t=0;let n=0;let r=0;const i=[];const a=[];const o=[];for(const s of diagnosticSessionStates.values()){if(s.state===`processing`){t+=1;pushLimitedDiagnosticLabel(i,s,e)}else if(s.state===`waiting`){n+=1;pushLimitedDiagnosticLabel(a,s,e)}const c=resolveDiagnosticQueuedBacklog(s);if(c>0)pushLimitedDiagnosticLabel(o,s,e);r+=c}return{activeCount:t,waitingCount:n,queuedCount:r,activeLabels:i,waitingLabels:a,queuedLabels:o}}function hasOpenDiagnosticWork(e){return e.activeCount>0||e.waitingCount>0||e.queuedCount>0}function hasRecentDiagnosticActivity(e){const t=getLastDiagnosticActivityAt();return t>0&&e-t<=RECENT_DIAGNOSTIC_ACTIVITY_MS}function formatOptionalDiagnosticMetric(e){return e===void 0?`unknown`:String(e)}function emitDiagnosticLivenessWarning(e,t,n){const r=getCurrentDiagnosticPhase();const i=getRecentDiagnosticPhases(n-Math.max(0,e.intervalMs));const a=formatRecentDiagnosticPhases(i);const o=formatDiagnosticWorkLabels(t);const s=`liveness warning: reasons=${e.reasons.join(`,`)} interval=${Math.round(e.intervalMs/1e3)}s${e.degradedSinceMs===void 0?``:` degradedFor=${Math.round(e.degradedSinceMs/1e3)}s`} eventLoopDelayP99Ms=${formatOptionalDiagnosticMetric(e.eventLoopDelayP99Ms)} eventLoopDelayMaxMs=${formatOptionalDiagnosticMetric(e.eventLoopDelayMaxMs)} eventLoopUtilization=${formatOptionalDiagnosticMetric(e.eventLoopUtilization)} cpuCoreRatio=${formatOptionalDiagnosticMetric(e.cpuCoreRatio)} active=${t.activeCount} waiting=${t.waitingCount} queued=${t.queuedCount}${r?` phase=${r}`:``}${a?` recentPhases=${a}`:``}${o?` work=[${o}]`:``}`;const c=t.waitingCount>0||t.queuedCount>0;const l=e.degradedSinceMs!==void 0;const u=(e.eventLoopDelayP99Ms??0)>=DEFAULT_LIVENESS_EVENT_LOOP_DELAY_WARN_MS;if(l||c||hasOpenDiagnosticWork(t)&&u)diagnosticLogger.warn(s);else diagnosticLogger.debug(s);emitInternalDiagnosticEvent({type:`diagnostic.liveness.warning`,reasons:e.reasons,intervalMs:e.intervalMs,degradedSinceMs:e.degradedSinceMs,eventLoopDelayP99Ms:e.eventLoopDelayP99Ms,eventLoopDelayMaxMs:e.eventLoopDelayMaxMs,eventLoopUtilization:e.eventLoopUtilization,cpuUserMs:e.cpuUserMs,cpuSystemMs:e.cpuSystemMs,cpuTotalMs:e.cpuTotalMs,cpuCoreRatio:e.cpuCoreRatio,active:t.activeCount,waiting:t.waitingCount,queued:t.queuedCount,phase:r,recentPhases:i,activeWorkLabels:t.activeLabels,waitingWorkLabels:t.waitingLabels,queuedWorkLabels:t.queuedLabels});markDiagnosticActivity()}function formatRecentDiagnosticPhases(e){return e.map(e=>`${e.name}:${Math.round(e.durationMs??0)}ms`).join(`,`)}function formatDiagnosticWorkLabels(e){return[e.activeLabels.length>0?`active=${e.activeLabels.join(`|`)}`:``,e.waitingLabels.length>0?`waiting=${e.waitingLabels.join(`|`)}`:``,e.queuedLabels.length>0?`queued=${e.queuedLabels.join(`|`)}`:``].filter(Boolean).join(` `)}function resolveStuckSessionAbortMs(e){return Math.max(MIN_STALLED_EMBEDDED_RUN_ABORT_MS,e*STALLED_EMBEDDED_RUN_ABORT_WARN_MULTIPLIER)}function logWebhookReceived(e){if(!areDiagnosticsEnabledForProcess())return;webhookStats.received+=1;emitInternalDiagnosticEvent({type:`webhook.received`,channel:e.channel,updateType:e.updateType,chatId:e.chatId});markDiagnosticActivity()}function logWebhookProcessed(e){if(!areDiagnosticsEnabledForProcess())return;webhookStats.processed+=1;emitInternalDiagnosticEvent({type:`webhook.processed`,channel:e.channel,updateType:e.updateType,chatId:e.chatId,durationMs:e.durationMs});markDiagnosticActivity()}function logWebhookError(e){if(!areDiagnosticsEnabledForProcess())return;webhookStats.errors+=1;diagnosticLogger.error(`webhook error: channel=${e.channel} type=${e.updateType??`unknown`} chatId=${e.chatId??`unknown`} error="${e.error}" errors=${webhookStats.errors}`);emitInternalDiagnosticEvent({type:`webhook.error`,channel:e.channel,updateType:e.updateType,chatId:e.chatId,error:e.error});markDiagnosticActivity()}function logMessageQueued(e){logMessageQueuedWithBacklogPolicy(e,true)}function logMessageReceived(e){if(!areDiagnosticsEnabledForProcess())return;emitInternalDiagnosticEvent({type:`message.received`,sessionId:e.sessionId,sessionKey:e.sessionKey,channel:e.channel,messageId:e.messageId,chatId:e.chatId,source:e.source});markDiagnosticActivity()}function logMessageDispatchStarted(e){if(!areDiagnosticsEnabledForProcess())return;emitInternalDiagnosticEvent({type:`message.dispatch.started`,sessionId:e.sessionId,sessionKey:e.sessionKey,channel:e.channel,source:e.source});markDiagnosticActivity()}function logMessageDispatchCompleted(e){if(!areDiagnosticsEnabledForProcess())return;const t=e.outcome===`error`?`error`:`debug`;if(!isIncognitoDiagnosticSession(e)&&diagnosticLogger.isEnabled(t)){const n=`message dispatch completed: channel=${e.channel??`unknown`} sessionId=${e.sessionId??`unknown`} sessionKey=${e.sessionKey??`unknown`} source=${e.source} outcome=${e.outcome} duration=${e.durationMs}ms${e.reason?` reason=${e.reason}`:``}${e.error?` error="${e.error}"`:``}`;diagnosticLogger[t](n)}emitInternalDiagnosticEvent({type:`message.dispatch.completed`,sessionId:e.sessionId,sessionKey:resolveDiagnosticSessionKey(e),channel:e.channel,source:e.source,durationMs:e.durationMs,outcome:e.outcome,reason:e.reason,error:e.error});markDiagnosticActivity()}function logMessageProcessed(e){if(!areDiagnosticsEnabledForProcess())return;const t=e.outcome===`error`?`error`:`debug`;if(!isIncognitoDiagnosticSession(e)&&diagnosticLogger.isEnabled(t)){const n=`message processed: channel=${e.channel} chatId=${e.chatId??`unknown`} messageId=${e.messageId??`unknown`} sessionId=${e.sessionId??`unknown`} sessionKey=${e.sessionKey??`unknown`} outcome=${e.outcome} duration=${e.durationMs??0}ms${e.reason?` reason=${e.reason}`:``}${e.error?` error="${e.error}"`:``}`;diagnosticLogger[t](n)}emitMessageProcessedDiagnosticEvent({...e,sessionKey:resolveDiagnosticSessionKey(e)});markDiagnosticActivity()}function logSessionTurnCreated(e){if(!areDiagnosticsEnabledForProcess())return;emitInternalDiagnosticEvent({type:`session.turn.created`,runId:e.runId,sessionId:e.sessionId,sessionKey:e.sessionKey,agentId:e.agentId,channel:e.channel,trigger:e.trigger});markDiagnosticActivity()}function markDiagnosticSessionProgress(e){if(!areDiagnosticsEnabledForProcess())return;touchDiagnosticSessionState(getDiagnosticSessionState(e));markDiagnosticActivity()}let heartbeatJob;let memoryPressureJob;let detachHeartbeatOwner;let lastDiagnosticHeartbeatTickAt;let updateHeartbeatOptions;function stopDiagnosticObservations(){stopDiagnosticGcObserver();lastDiagnosticHeartbeatTickAt=void 0;stopDiagnosticRunActivityTracking();retireDiagnosticSessionObservations();stopDiagnosticLivenessSampler();stopDiagnosticStabilityRecorder();uninstallDiagnosticStabilityFatalHook()}function startGatewayDiagnosticHeartbeat(e,t,n){if(e.signal.aborted)return;if(heartbeatJob){updateHeartbeatOptions?.(t,n);return}let r=t;let i=n;let a=false;let o=false;let s=0;const reconcileObservations=()=>{if(!areDiagnosticsEnabledForProcess()||!isDiagnosticsEnabled(r)){if(a){stopDiagnosticObservations();a=false;o=false}return false}if(!a){startDiagnosticRunActivityTracking();startDiagnosticStabilityRecorder();installDiagnosticStabilityFatalHook();lastDiagnosticHeartbeatTickAt=e.now();s=i?.startupGraceMs!=null&&i.startupGraceMs>0?e.now()+i.startupGraceMs:0;a=true}const t=!i?.sampleLiveness;if(t!==o){if(t)startDiagnosticLivenessSampler();else stopDiagnosticLivenessSampler();o=t}reconcileDiagnosticGcObserver();return true};updateHeartbeatOptions=(e,t)=>{r=e;i=t;reconcileObservations()};reconcileObservations();const c=createDiagnosticMemorySampler(()=>!e.signal.aborted&&heartbeatJob===l&&a);const tick=()=>{if(e.signal.aborted||heartbeatJob!==l)return;if(!reconcileObservations())return;emitChildProcessSpawnSample();let t=r;if(!t)try{t=(i?.getConfig??readRuntimeConfig)()}catch{t=void 0}const n=i?.testTimings?.stuckSessionWarnMs??DEFAULT_STUCK_SESSION_WARN_MS;const a=i?.testTimings?.stuckSessionAbortMs??resolveStuckSessionAbortMs(n);const o=resolveCompactionTimeoutMs(t);const u=e.now();const d=lastDiagnosticHeartbeatTickAt===void 0?0:u-lastDiagnosticHeartbeatTickAt;lastDiagnosticHeartbeatTickAt=u;const f=Math.max(0,d-DIAGNOSTIC_HEARTBEAT_INTERVAL_MS);const p=s>0&&u<s;const m=u-f;const h=f>=DEFAULT_LIVENESS_EVENT_LOOP_DELAY_WARN_MS;if(h&&!p)diagnosticLogger.warn(`liveness heartbeat delayed: overdue=${Math.round(f)}ms elapsed=${Math.round(d)}ms; deferring recovery decisions`);pruneDiagnosticSessionStates(u,true);const g=getDiagnosticWorkSnapshot(u);const _=(i?.sampleLiveness??sampleDiagnosticLiveness)(u,g);const v=p?null:_;const y=v!==null&&shouldEmitDiagnosticLivenessEvent(u);const b=v!==null&&shouldEmitDiagnosticLivenessWarning(u,hasOpenDiagnosticWork(g));const x=y||b;const S=x||hasRecentDiagnosticActivity(u)||hasOpenDiagnosticWork(g);c(S,i);if(!S)return;if(x&&v)emitDiagnosticLivenessWarning(v,g,u);emitInternalDiagnosticEvent({type:`diagnostic.heartbeat`,webhooks:{received:webhookStats.received,processed:webhookStats.processed,errors:webhookStats.errors},active:g.activeCount,waiting:g.waitingCount,queued:g.queuedCount});loadCommandPollBackoffRuntime().then(({pruneStaleCommandPolls:e})=>{for(const[,t]of diagnosticSessionStates)e(t)}).catch(e=>{diagnosticLogger.debug(`command-poll-backoff prune failed: ${String(e)}`)});for(const[,e]of diagnosticSessionStates){const t={sessionId:e.sessionId,sessionKey:e.sessionKey,sessionFile:e.sessionFile,expectedState:e.state,stateGeneration:e.generation??0,queueDepth:resolveDiagnosticQueuedBacklog(e)};const r=m-e.lastActivity;const s=t.sessionId?resolveActiveEmbeddedRunRecoveryBlocker(t.sessionId):void 0;if(s===`stale_session_state`||!isDiagnosticSessionStateCurrent({...t,state:t.expectedState,generation:t.stateGeneration}))continue;const c=captureDiagnosticSessionOperation(t);const l=getDiagnosticSessionActivitySnapshot(t,m);const u=t.expectedState===`idle`&&t.queueDepth>0&&(l.activeWorkKind!==void 0||l.hasActiveEmbeddedRun===true)&&(l.lastProgressAgeMs??0)>n;const d=l.activeWorkKind?l.lastProgressAgeMs??0:0;const f=u?l.lastProgressAgeMs??r:Math.max(r,l.repeatedRequestNoProgressAgeMs??0,d);if(t.expectedState===`processing`&&f>n||u){function logSessionAttention(){if(!areDiagnosticsEnabledForProcess())return;const r=t.queueDepth;const i=classifySessionAttention({state:t.expectedState,queueDepth:r,activity:l,staleMs:n,stuckSessionAbortMs:a,runtimeOwnsLiveness:s===`runtime_owned_wait`});const o=i.eventType===`session.stuck`?`lastStuckWarnAgeMs`:i.eventType===`session.long_running`?`lastLongRunningWarnAgeMs`:void 0;if(o){const t=e[o];const r=t===void 0?n:Math.max(t+n,t*2);if(f<r)return i;e[o]=f}const u=i.eventType===`session.stuck`?`stuck session`:`long-running session`;if(i.eventType!==`session.stalled`&&!isIncognitoDiagnosticSession(e))logWithSessionDiagnosticContext({level:i.eventType===`session.long_running`&&r<=0?`debug`:`warn`,sessionKey:t.sessionKey,format:e=>{const n=[formatSessionActivityLogFields(l),e].filter(Boolean).join(` `);return`${u}: sessionId=${t.sessionId??`unknown`} sessionKey=${t.sessionKey??`unknown`} state=${t.expectedState} age=${Math.round(f/1e3)}s queueDepth=${r} reason=${i.reason} classification=${i.classification}${i.activeWorkKind?` activeWorkKind=${i.activeWorkKind}`:``}${n?` ${n}`:``} recovery=${c?`controller_owned`:`state_reconciliation`}`}});const d=isTerminalDiagnosticProgressReason(l.lastProgressReason);const p={sessionId:t.sessionId,sessionKey:t.sessionKey,state:t.expectedState,ageMs:f,queueDepth:r,reason:i.reason,...i.activeWorkKind?{activeWorkKind:i.activeWorkKind}:{},...l.lastProgressAgeMs!==void 0?{lastProgressAgeMs:l.lastProgressAgeMs}:{},...l.lastProgressReason?{lastProgressReason:l.lastProgressReason}:{},...l.activeToolName?{activeToolName:l.activeToolName}:{},...l.activeToolCallId?{activeToolCallId:l.activeToolCallId}:{},...l.activeToolAgeMs!==void 0?{activeToolAgeMs:l.activeToolAgeMs}:{},...l.repeatedRequestNoProgressAgeMs!==void 0?{repeatedRequestNoProgressAgeMs:l.repeatedRequestNoProgressAgeMs}:{},...d?{terminalProgressStale:true}:{}};if(i.eventType===`session.long_running`)emitInternalDiagnosticEvent({type:`session.long_running`,...p,classification:`long_running`});else if(i.eventType===`session.stalled`)emitInternalDiagnosticEvent({type:`session.stalled`,...p,classification:i.classification});else emitInternalDiagnosticEvent({type:`session.stuck`,...p,classification:`stale_session_state`});markDiagnosticActivity();return i}const r=logSessionAttention();if(!r||h)continue;requestStuckSessionRecovery({recover:i?.recoverStuckSession??recoverStuckSession,classification:r,request:{...t,ageMs:f,operation:c,staleActiveProgressAbortMs:a,...r.reason===`repeated_model_requests_without_progress`?{repeatedRequestNoProgressAbortMs:a}:{},compactionSafetyTimeoutMs:o}})}}};const l=e.schedule({id:`diagnostic-heartbeat`,atMs:e.now()+DIAGNOSTIC_HEARTBEAT_INTERVAL_MS,everyMs:DIAGNOSTIC_HEARTBEAT_INTERVAL_MS,phase:`maintenance`,run:tick});heartbeatJob=l;memoryPressureJob=e.schedule({id:`diagnostic-memory-pressure`,atMs:e.now()+MEMORY_PRESSURE_INTERVAL_MS,everyMs:MEMORY_PRESSURE_INTERVAL_MS,run:()=>{if(!e.signal.aborted&&heartbeatJob===l)emitDiagnosticMemorySample(void 0,false)}});const stopOwnedHeartbeat=()=>{if(heartbeatJob===l)stopGatewayDiagnosticHeartbeat()};e.signal.addEventListener(`abort`,stopOwnedHeartbeat,{once:true});detachHeartbeatOwner=()=>e.signal.removeEventListener(`abort`,stopOwnedHeartbeat);if(e.signal.aborted)stopOwnedHeartbeat()}function stopGatewayDiagnosticHeartbeat(){detachHeartbeatOwner?.();detachHeartbeatOwner=void 0;heartbeatJob?.cancel();heartbeatJob=void 0;memoryPressureJob?.cancel();memoryPressureJob=void 0;updateHeartbeatOptions=void 0;stopDiagnosticObservations()}export{logMessageReceived as a,logWebhookProcessed as c,startGatewayDiagnosticHeartbeat as d,stopGatewayDiagnosticHeartbeat as f,logMessageQueued as i,logWebhookReceived as l,logMessageDispatchStarted as n,logSessionTurnCreated as o,logMessageProcessed as r,logWebhookError as s,logMessageDispatchCompleted as t,markDiagnosticSessionProgress as u};