UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 13.5 kB
import{E as parseStrictNonNegativeInteger}from"./number-coercion-B3CfI447.mjs";import{h as onInternalDiagnosticEvent}from"./diagnostic-events-BYBrlAdF.mjs"; //!src/infra/diagnostic-process-types.ts const DIAGNOSTIC_WORKER_RETAINED_STRUCTURES=[`catalog-config`,`catalog-source`,`catalog-entries`,`catalog-index`,`catalog-pricing`,`catalog-request`,`catalog-metadata`,`catalog-static`,`catalog-remote`,`catalog-auth`];const DIAGNOSTIC_MEMORY_PRESSURE_METRICS=[`thresholdBytes`,`limitBytes`,`usedBytes`,`workerThreadId`,`rssGrowthBytes`,`windowMs`];function isMemoryPressureReason(e){return e===`rss_threshold`||e===`heap_threshold`||e===`worker_heap_threshold`||e===`process_memory_threshold`||e===`rss_growth`} //!src/logging/diagnostic-stability-query.ts const DEFAULT_DIAGNOSTIC_STABILITY_CAPACITY=1e3;const DEFAULT_DIAGNOSTIC_STABILITY_LIMIT=50;const MAX_DIAGNOSTIC_STABILITY_LIMIT=DEFAULT_DIAGNOSTIC_STABILITY_CAPACITY;function parseOptionalNonNegativeInteger(e,t){if(e===void 0||e===null)return;if(typeof e===`string`){if(!/^\d+$/.test(e))throw new Error(`${t} must be a non-negative integer`)}const n=parseStrictNonNegativeInteger(e);if(n===void 0)throw new Error(`${t} must be a non-negative integer`);return n}function parseOptionalType(e){if(e===void 0||e===null)return;if(typeof e!==`string`||e.trim()===``)throw new Error(`type must be a non-empty string`);return e.trim()}function normalizeLimit(e,t=DEFAULT_DIAGNOSTIC_STABILITY_LIMIT){const n=parseOptionalNonNegativeInteger(e,`limit`);if(n===void 0)return t;if(n<1||n>1e3)throw new Error(`limit must be between 1 and ${MAX_DIAGNOSTIC_STABILITY_LIMIT}`);return n}function normalizeDiagnosticStabilityQuery(e={},t){return{limit:normalizeLimit(e.limit,t?.defaultLimit),type:parseOptionalType(e.type),sinceSeq:parseOptionalNonNegativeInteger(e.sinceSeq,`sinceSeq`)}} //!src/logging/diagnostic-stability.ts const MAX_DIAGNOSTIC_EXPORTER_STATES=16;const LIVENESS_EVENT_LOOP_DELAY_WARN_MS=1e3;const SAFE_REASON_CODE=/^[A-Za-z0-9_.:-]{1,120}$/u;const SAFE_EXPORTER_CODE=/^[A-Za-z0-9_-]{1,120}$/u;function createState(e=DEFAULT_DIAGNOSTIC_STABILITY_CAPACITY){return{records:Array.from({length:e}),capacity:e,nextIndex:0,count:0,dropped:0,exporterSeq:0,exporterRecords:/* @__PURE__ */ new Map,exporterDropped:0,unsubscribe:null}}function getDiagnosticStabilityState(){const e=globalThis;e[`__openclawDiagnosticStabilityState`]??=createState();return e[`__openclawDiagnosticStabilityState`]}function copyReasonCode(e){if(typeof e!==`string`||!SAFE_REASON_CODE.test(e))return;return e}function copyExporterCode(e){return typeof e===`string`&&SAFE_EXPORTER_CODE.test(e)?e:void 0}function isDiagnosticExporterSignal(e){return e===`traces`||e===`metrics`||e===`logs`}function isDiagnosticExporterStatus(e){return e===`started`||e===`failure`||e===`recovered`||e===`dropped`}function assignReasonCode(e,t){const n=copyReasonCode(t);if(n)e.reason=n}function resolveDiagnosticLivenessRecordLevel(e){const t=e.waiting>0||e.queued>0;const n=(e.eventLoopDelayP99Ms??0)>=LIVENESS_EVENT_LOOP_DELAY_WARN_MS;return e.degradedSinceMs!==void 0||t||e.active>0&&n?`warning`:`info`}function sanitizeDiagnosticEvent(e){const t={seq:e.seq,ts:e.ts,type:e.type};const copy=(e,...n)=>{for(const r of n)t[r]=e[r]};switch(e.type){case`model.usage`:copy(e,`channel`,`provider`,`model`);t.usage={...e.usage};t.context=e.context?{...e.context}:void 0;copy(e,`costUsd`,`durationMs`);break;case`webhook.received`:case`webhook.error`:t.channel=e.channel;break;case`webhook.processed`:copy(e,`channel`,`durationMs`);break;case`message.queued`:copy(e,`channel`,`source`,`queueDepth`);break;case`message.received`:case`message.dispatch.started`:copy(e,`channel`,`source`);break;case`message.dispatch.completed`:copy(e,`channel`,`source`,`durationMs`,`outcome`);assignReasonCode(t,e.reason);break;case`message.processed`:copy(e,`channel`,`durationMs`,`outcome`);assignReasonCode(t,e.reason);break;case`message.delivery.started`:case`message.delivery.completed`:case`message.delivery.error`:copy(e,`channel`,`deliveryKind`);if(e.type!==`message.delivery.started`){t.durationMs=e.durationMs;if(e.type===`message.delivery.completed`){t.resultCount=e.resultCount;t.outcome=`completed`}else{t.outcome=`error`;assignReasonCode(t,e.errorCategory)}}break;case`talk.event`:copy(e,`talkEventType`,`mode`,`transport`,`brain`,`provider`,`final`,`durationMs`);t.bytes=e.byteLength;break;case`session.state`:t.outcome=e.state;assignReasonCode(t,e.reason);t.queueDepth=e.queueDepth;break;case`session.long_running`:case`session.stalled`:case`session.stuck`:t.outcome=e.state;if(e.type===`session.stuck`)t.level=`warning`;assignReasonCode(t,e.reason);copy(e,`ageMs`,`queueDepth`);if(e.activeWorkKind)t.activeWorkKind=e.activeWorkKind;if(e.activeToolName)t.toolName=e.activeToolName;break;case`session.recovery.requested`:t.outcome=e.state;t.action=e.allowActiveAbort?`abort`:`recover`;copy(e,`ageMs`,`queueDepth`);if(e.activeWorkKind)t.activeWorkKind=e.activeWorkKind;assignReasonCode(t,e.reason);break;case`session.recovery.completed`:t.outcome=e.status;copy(e,`action`,`ageMs`,`queueDepth`);t.count=e.released;if(e.activeWorkKind)t.activeWorkKind=e.activeWorkKind;assignReasonCode(t,e.outcomeReason??e.reason);break;case`session.turn.created`:t.source=e.agentId;t.channel=e.channel;t.outcome=e.trigger;break;case`queue.lane.enqueue`:case`queue.lane.dequeue`:t.source=e.lane;t.queueSize=e.queueSize;if(e.type===`queue.lane.dequeue`)t.waitMs=e.waitMs;break;case`run.attempt`:t.count=e.attempt;break;case`run.progress`:assignReasonCode(t,e.reason);break;case`run.execution_phase`:copy(e,`phase`,`provider`,`model`);t.toolName=e.tool;break;case`context.assembled`:copy(e,`channel`,`provider`,`model`);t.count=e.messageCount;t.bytes=e.promptChars;t.context=e.contextTokenBudget!==void 0?{limit:e.contextTokenBudget}:void 0;break;case`diagnostic.heartbeat`:t.webhooks={...e.webhooks};copy(e,`active`,`waiting`,`queued`);break;case`diagnostic.liveness.warning`:t.level=resolveDiagnosticLivenessRecordLevel(e);t.durationMs=e.degradedSinceMs??e.intervalMs;t.count=e.reasons.length;assignReasonCode(t,e.reasons[0]);copy(e,`eventLoopDelayP99Ms`,`eventLoopDelayMaxMs`,`eventLoopUtilization`,`cpuCoreRatio`,`active`,`waiting`,`queued`,`phase`);if(e.activeWorkLabels?.length)t.source=e.activeWorkLabels[0];else if(e.queuedWorkLabels?.length)t.source=e.queuedWorkLabels[0];break;case`diagnostic.phase.completed`:t.phase=e.name;copy(e,`durationMs`,`cpuCoreRatio`);break;case`tool.loop`:copy(e,`toolName`,`level`,`action`,`detector`,`count`,`pairedToolName`);break;case`tool.execution.started`:case`tool.execution.completed`:case`tool.execution.error`:case`tool.execution.blocked`:t.toolName=e.toolName;t.source=e.toolSource;t.pluginId=e.toolOwner;if(e.type===`tool.execution.completed`||e.type===`tool.execution.error`)t.durationMs=e.durationMs;if(e.type===`tool.execution.error`){if(e.terminalReason)t.outcome=e.terminalReason;assignReasonCode(t,e.errorCategory)}else if(e.type===`tool.execution.blocked`){t.outcome=`blocked`;assignReasonCode(t,e.deniedReason)}break;case`skill.used`:t.toolName=e.toolName;t.source=e.skillSource;t.action=e.activation;t.target=e.skillName;break;case`exec.process.completed`:copy(e,`target`,`mode`,`outcome`,`durationMs`,`commandLength`,`exitCode`,`timedOut`,`failureKind`);assignReasonCode(t,e.failureKind);break;case`exec.approval.followup_suppressed`:copy(e,`approvalId`,`phase`);assignReasonCode(t,e.reason);break;case`run.started`:case`run.completed`:copy(e,`provider`,`model`,`channel`);if(e.type===`run.completed`){copy(e,`durationMs`,`outcome`);assignReasonCode(t,e.errorCategory)}break;case`harness.run.started`:case`harness.run.completed`:case`harness.run.error`:t.source=e.harnessId;copy(e,`pluginId`,`provider`,`model`,`channel`);if(e.type!==`harness.run.started`){t.durationMs=e.durationMs;if(e.type===`harness.run.completed`){t.outcome=e.outcome;t.count=e.itemLifecycle?.completedCount}else{t.outcome=`error`;t.action=e.phase;assignReasonCode(t,e.errorCategory)}}break;case`model.call.started`:case`model.call.completed`:case`model.call.error`:copy(e,`provider`,`model`);if(e.type!==`model.call.started`){copy(e,`durationMs`,`timeToFirstByteMs`,`providerProcessingMs`,`providerWaitEstimateMs`);t.requestBytes=e.requestPayloadBytes;t.responseBytes=e.responseStreamBytes;if(e.type===`model.call.error`){t.failureKind=e.failureKind;t.memory=e.memory?{...e.memory}:void 0;assignReasonCode(t,e.errorCategory)}}break;case`security.event`:t.source=e.category;copy(e,`action`,`outcome`);t.level=e.severity;t.target=e.target?.name??e.target?.kind;assignReasonCode(t,e.reason??e.policy?.reason);break;case`diagnostic.memory.sample`:t.memory={...e.memory};break;case`diagnostic.memory.pressure`:t.level=e.level;assignReasonCode(t,e.reason);t.memory={...e.memory};copy(e,...DIAGNOSTIC_MEMORY_PRESSURE_METRICS);break;case`payload.large`:copy(e,`surface`,`action`,`bytes`,`limitBytes`,`count`,`channel`,`pluginId`);assignReasonCode(t,e.reason);break;case`diagnostic.async_queue.dropped`:copy(e,`droppedEvents`,`droppedTrustedEvents`,`droppedUntrustedEvents`,`droppedPriorityEvents`,`queueLength`,`maxQueueLength`,`drainBatchSize`);break;case`model.failover`:t.provider=e.fromProvider;t.model=e.fromModel;assignReasonCode(t,e.reason)}return t}function appendRecord(e){const t=getDiagnosticStabilityState();t.records[t.nextIndex]=e;t.nextIndex=(t.nextIndex+1)%t.capacity;if(t.count<t.capacity){t.count+=1;return}t.dropped+=1}function upsertExporterRecord(e){const t=getDiagnosticStabilityState();const n=`${e.source}\u0000${e.target??`unknown`}\u0000${e.transport??`unknown`}`;if(e.outcome===`dropped`){t.exporterRecords.delete(n);return}const r=t.exporterRecords.get(n);if(!e.mode&&r?.mode)e.mode=r.mode;if(!t.exporterRecords.has(n)&&t.exporterRecords.size>=MAX_DIAGNOSTIC_EXPORTER_STATES){const e=t.exporterRecords.keys().next().value;if(e!==void 0){t.exporterRecords.delete(e);t.exporterDropped+=1}}t.exporterRecords.delete(n);t.exporterRecords.set(n,e)}function recordDiagnosticExporterHealth(e,t){const n=copyExporterCode(e);if(!n||!isDiagnosticExporterSignal(t.signal)||!isDiagnosticExporterStatus(t.status))return;const r=getDiagnosticStabilityState();r.exporterSeq+=1;const i={seq:r.exporterSeq,ts:Date.now(),type:`telemetry.exporter`,source:n,target:t.signal,outcome:t.status};const a=copyExporterCode(t.transport);if(a)i.transport=a;if(t.endpointMode===`configured`||t.endpointMode===`default_endpoint`)i.mode=t.endpointMode;const o=copyReasonCode(t.errorCategory);if(o)i.errorCategory=o;assignReasonCode(i,t.reason??t.errorCategory);upsertExporterRecord(i)}function listRecords(){const e=getDiagnosticStabilityState();const t=[];const n=e.count<e.capacity?0:e.nextIndex;for(let r=0;r<e.count;r+=1){const i=e.records[(n+r)%e.capacity];if(i!==void 0)t.push(i)}return t}function summarizeRecords(e){const t={};let n;let r;let i;let a=0;const o={count:0,rejected:0,truncated:0,chunked:0,bySurface:{}};for(const s of e){t[s.type]=(t[s.type]??0)+1;if(s.memory){n=s.memory;r=r===void 0?s.memory.rssBytes:Math.max(r,s.memory.rssBytes);i=i===void 0?s.memory.heapUsedBytes:Math.max(i,s.memory.heapUsedBytes)}if(s.type===`diagnostic.memory.pressure`)a+=1;if(s.type===`payload.large`){o.count+=1;if(s.action===`rejected`)o.rejected+=1;else if(s.action===`truncated`)o.truncated+=1;else if(s.action===`chunked`)o.chunked+=1;const e=s.surface??`unknown`;o.bySurface[e]=(o.bySurface[e]??0)+1}}return{byType:t,...n||a>0?{memory:{latest:n,maxRssBytes:r,maxHeapUsedBytes:i,pressureCount:a}}:{},...o.count>0?{payloadLarge:o}:{}}}function selectRecords(e,t){const{limit:n,type:r,sinceSeq:i}=normalizeDiagnosticStabilityQuery(t);const a=e.filter(e=>{if(r&&e.type!==r)return false;if(i!==void 0&&e.seq<=i)return false;return true});return{filtered:a,events:a.slice(Math.max(0,a.length-n))}}function startDiagnosticStabilityRecorder(){const e=getDiagnosticStabilityState();if(e.unsubscribe)return;e.unsubscribe=onInternalDiagnosticEvent(e=>appendRecord(sanitizeDiagnosticEvent(e)),{includePromptStats:false,includeTrusted:[`model.call.started`,`model.call.completed`,`model.call.error`],exclude:[`log.record`,`telemetry.exporter`,`gateway.rpc`,`gateway.event_loop.sample`,`gateway.http.cancelled`,`diagnostic.gc`,`diagnostic.child_process.spawn`,`worker.request`,`secret.egress`,`tool.catalog`]})}function stopDiagnosticStabilityRecorder(){const e=getDiagnosticStabilityState();e.unsubscribe?.();e.unsubscribe=null}function getDiagnosticStabilitySnapshot(e){const t=getDiagnosticStabilityState();const n=e?.type===`telemetry.exporter`;const{filtered:r,events:i}=selectRecords(n?[...t.exporterRecords.values()].toSorted((e,t)=>e.seq-t.seq):listRecords(),e);return{generatedAt:(/* @__PURE__ */ new Date()).toISOString(),capacity:n?MAX_DIAGNOSTIC_EXPORTER_STATES:t.capacity,count:r.length,dropped:n?t.exporterDropped:t.dropped,firstSeq:r[0]?.seq,lastSeq:r.at(-1)?.seq,events:i,summary:summarizeRecords(r)}}function selectDiagnosticStabilitySnapshot(e,t){const{filtered:n,events:r}=selectRecords(e.events,t);return{...e,count:n.length,firstSeq:n[0]?.seq,lastSeq:n.at(-1)?.seq,events:r,summary:summarizeRecords(n)}}export{stopDiagnosticStabilityRecorder as a,DIAGNOSTIC_MEMORY_PRESSURE_METRICS as c,startDiagnosticStabilityRecorder as i,DIAGNOSTIC_WORKER_RETAINED_STRUCTURES as l,recordDiagnosticExporterHealth as n,MAX_DIAGNOSTIC_STABILITY_LIMIT as o,selectDiagnosticStabilitySnapshot as r,normalizeDiagnosticStabilityQuery as s,getDiagnosticStabilitySnapshot as t,isMemoryPressureReason as u};