openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
35 lines • 25.8 kB
JavaScript
import{s as formatErrorStackWithMessage}from"./error-coercion-B-1Loz4b.mjs";import{r as asOptionalRecord}from"./record-coerce-DwDZngEy.mjs";import{l as resolveGlobalSingleton,n as normalizeLowercaseStringOrEmpty}from"./string-coerce-BBqv4GXj.mjs";import{r as asFiniteNumber}from"./number-coercion-DIhBGkET.mjs";import{u as normalizeUniqueStringEntriesLower}from"./string-normalization-mfgVoo8i.mjs";import{t as isBlockedObjectKey}from"./prototype-keys-DI_O-fr9.mjs";import"./plugin-instance-invocation-D2U32-yV.mjs";import{n as pluginRuntimeProcessManifest,o as runtimeProcessSealedManifest,t as createRuntimeProcessEntrypoints}from"./runtime-process-manifest-B40zGDrA.mjs";import{t as AsyncContext}from"./async-context-BikFC1Fp.mjs";import{n as isTruthyEnvValue}from"./env-BVwgaeaj.mjs";import{AsyncLocalStorage}from"node:async_hooks";import{mkdirSync}from"node:fs";import{basename,dirname}from"node:path";import{fileURLToPath}from"node:url";import{randomBytes,randomUUID}from"node:crypto";import{appendRegularFileSync}from"@openclaw/fs-safe/advanced";import{performance}from"node:perf_hooks";
//!src/infra/diagnostic-event-listener-presence.ts
const listenerPresence=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticEventListenerPresence.v1`),()=>({untrustedInterest:{broadInterestCount:0,eventInterestDeltas:/* @__PURE__ */ new Map},trustedInterest:{broadInterestCount:0,eventInterestDeltas:/* @__PURE__ */ new Map},interestListeners:/* @__PURE__ */ new Map,internalCount:0,trustedCount:0,promptStatsCount:0}));function isInternalDiagnosticEventInterested(e,t,n){return(!e?.include||e.include.includes(t))&&!e?.exclude?.includes(t)&&(!n||!e?.includeTrusted||e.includeTrusted.includes(t))}function hasInternalDiagnosticEventInterest(e,t=false){const n=t?listenerPresence.trustedInterest:listenerPresence.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}
//!src/infra/diagnostic-event-queue-policy.ts
const ASYNC_EVENT={priority:false,publicExcluded:false};const DIAGNOSTIC_EVENT_POLICIES=[{...ASYNC_EVENT,name:`worker.request`},{...ASYNC_EVENT,name:`diagnostic.gc`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.event_loop.sample`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.main_thread.stall`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.http.cancelled`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.rpc`,publicExcluded:true},{...ASYNC_EVENT,name:`sessions.list.baseline.retired`},{...ASYNC_EVENT,name:`sessions.list.retention`,publicExcluded:true},{...ASYNC_EVENT,name:`sessions.projection.retention`,publicExcluded:true},{...ASYNC_EVENT,name:`sessions.event.retention`,publicExcluded:true},{...ASYNC_EVENT,name:`sessions.event.rows.reset`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.ws.event`,publicExcluded:true},{...ASYNC_EVENT,name:`gateway.ws.connections`,publicExcluded:true},{...ASYNC_EVENT,name:`tool.execution.started`},{...ASYNC_EVENT,name:`tool.execution.completed`,priority:true},{...ASYNC_EVENT,name:`tool.execution.error`,priority:true},{...ASYNC_EVENT,name:`tool.execution.blocked`,priority:true},{...ASYNC_EVENT,name:`skill.used`},{...ASYNC_EVENT,name:`exec.process.completed`},{...ASYNC_EVENT,name:`exec.approval.followup_suppressed`},{...ASYNC_EVENT,name:`message.delivery.started`},{...ASYNC_EVENT,name:`message.delivery.completed`},{...ASYNC_EVENT,name:`message.delivery.error`},{...ASYNC_EVENT,name:`talk.event`},{...ASYNC_EVENT,name:`model.call.started`},{...ASYNC_EVENT,name:`model.call.completed`,priority:true},{...ASYNC_EVENT,name:`model.call.error`,priority:true},{...ASYNC_EVENT,name:`model.response.observed`},{...ASYNC_EVENT,name:`run.progress`},{...ASYNC_EVENT,name:`run.execution_phase`},{...ASYNC_EVENT,name:`agent.commentary`},{...ASYNC_EVENT,name:`harness.run.completed`,priority:true},{...ASYNC_EVENT,name:`harness.run.error`,priority:true},{...ASYNC_EVENT,name:`context.assembled`},{...ASYNC_EVENT,name:`log.record`,publicExcluded:true}];const ASYNC_DIAGNOSTIC_EVENT_NAMES=DIAGNOSTIC_EVENT_POLICIES.map(e=>e.name);const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES=DIAGNOSTIC_EVENT_POLICIES.filter(e=>e.priority).map(e=>e.name);const PUBLIC_EXCLUDED_DIAGNOSTIC_EVENT_NAMES=DIAGNOSTIC_EVENT_POLICIES.filter(e=>e.publicExcluded).map(e=>e.name);
//!src/infra/diagnostic-trace-context.ts
const TRACE_ID_RE=/^[0-9a-f]{32}$/;const SPAN_ID_RE=/^[0-9a-f]{16}$/;const TRACE_FLAGS_RE=/^[0-9a-f]{2}$/;const DIAGNOSTIC_TRACE_SCOPE_STATE_KEY=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`);function isNonZeroHex(e){return!/^0+$/.test(e)}const traceContext=new AsyncContext(DIAGNOSTIC_TRACE_SCOPE_STATE_KEY);function isValidDiagnosticTraceId(e){return typeof e===`string`&&TRACE_ID_RE.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e===`string`&&SPAN_ID_RE.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e===`string`&&TRACE_FLAGS_RE.test(e)}function normalizeDiagnosticTraceContext(e){const t=asOptionalRecord(e);if(!t||!isValidDiagnosticTraceId(t.traceId))return;if(t.spanId!==void 0&&!isValidDiagnosticSpanId(t.spanId))return;if(t.parentSpanId!==void 0&&!isValidDiagnosticSpanId(t.parentSpanId))return;if(t.traceFlags!==void 0&&!isValidDiagnosticTraceFlags(t.traceFlags))return;return{traceId:t.traceId,...t.spanId?{spanId:t.spanId}:{},...t.parentSpanId?{parentSpanId:t.parentSpanId}:{},...t.traceFlags?{traceFlags:t.traceFlags}:{}}}function getActiveDiagnosticTraceContext(){return traceContext.getStore()}
//!src/infra/diagnostic-event-snapshot.ts
const immutableSnapshots=/* @__PURE__ */ new WeakSet;function cloneDiagnosticValueForListener(e,t=false){if(immutableSnapshots.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e))){immutableSnapshots.add(e);return Object.freeze(e)}const n=structuredClone(e);if(freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet))immutableSnapshots.add(n);return n}function createDiagnosticValueForListeners(e,t=false){let n;return()=>{if(n)return n;const r=cloneDiagnosticValueForListener(e,t);if(immutableSnapshots.has(r))n=r;return r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!==`object`)return typeof e!==`function`&&typeof e!==`symbol`;if(immutableSnapshots.has(e)||t?.has(e))return true;const n=Object.getPrototypeOf(e);if(!Object.isFrozen(e)||n!==Object.prototype&&n!==Array.prototype&&n!==null)return false;let r=t;return Reflect.ownKeys(e).every(t=>{const n=Object.getOwnPropertyDescriptor(e,t);if(typeof t===`symbol`||!(`value`in n))return false;if(n.value&&typeof n.value===`object`)(r??=/* @__PURE__ */ new WeakSet).add(e);return isImmutableDiagnosticValue(n.value,r)})}function freezeDiagnosticValue(e,t){if(!e||typeof e!==`object`||t.has(e))return true;if(ArrayBuffer.isView(e))return false;t.add(e);const n=Object.getPrototypeOf(e);let r=n===Object.prototype||n===Array.prototype||n===null;for(const n of Object.values(e))if(!freezeDiagnosticValue(n,t))r=false;Object.freeze(e);return r}function enrichDiagnosticEvent(e,t,n=true){const r={};for(const[e,n]of Object.entries(t)){if(isBlockedObjectKey(e))continue;r[e]=n}if(n)r.trace??=getActiveDiagnosticTraceContext();e.seq+=1;r.seq=e.seq;r.ts=Date.now();return r}function captureQueuedDiagnosticEvent(e,t){try{let n=false;let r=false;if(e.privateData||e.trustedListenersOnly){for(const i of t)if(isInternalDiagnosticEventInterested(i,e.event.type,e.metadata.trusted)){n=true;if(i?.includePrivateData!==false){r=true;break}}}if(e.trustedListenersOnly&&!n)return false;e.event=cloneDiagnosticValueForListener(e.event,true);if(e.privateData)try{e.privateData=r?cloneDiagnosticValueForListener(e.privateData):void 0}catch(t){e.privateData=void 0;console.error(`[diagnostic-events] private snapshot error type=${e.event.type}: ${String(t)}`)}return true}catch(t){console.error(`[diagnostic-events] queue snapshot error type=${e.event.type}: ${String(t)}`);return false}}
//!src/infra/diagnostic-model-request-provenance.ts
const CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY=`coreModelRequestLifecycle`;
//!src/infra/diagnostic-otel-listener-provenance.ts
const trustedOtelDiagnosticListeners=/* @__PURE__ */ new WeakSet;function isTrustedOtelDiagnosticListener(e){return trustedOtelDiagnosticListeners.has(e)}
//!src/infra/diagnostic-plugin-usage-provenance.ts
const hostPluginUsageIds=/* @__PURE__ */ new WeakMap;function consumeHostPluginUsageDiagnosticEvent(e){const t=hostPluginUsageIds.get(e);hostPluginUsageIds.delete(e);return t}
//!src/infra/diagnostic-semantic-run-progress-provenance.ts
const CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY=`coreSemanticRunProgress`;const coreSemanticRunProgressEvents=/* @__PURE__ */ new WeakMap;function consumeCoreSemanticRunProgressDiagnosticEvent(e){const t=coreSemanticRunProgressEvents.get(e);coreSemanticRunProgressEvents.delete(e);return t}
//!src/infra/diagnostic-tool-execution-liveness.ts
const TOOL_EXECUTION_LIVENESS_METADATA_KEY=`toolExecutionLiveness`;const state=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){const t=state.events.get(e);state.events.delete(e);return t}
//!src/infra/diagnostic-trace-propagation.ts
const DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`);const tracePropagationState=resolveGlobalSingleton(DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY,()=>({marker:DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}));function hasDiagnosticTracePropagationConsumer(){return tracePropagationState.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){const t=tracePropagationState.activeBridge;if(!t?.prepareEvent)return false;if(!t.shouldPrepareEvent)return true;try{return t.shouldPrepareEvent(e)}catch(e){console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(e)}`);return false}}function prepareDiagnosticTracePropagation(e,t){const n=tracePropagationState.activeBridge;if(!n?.prepareEvent)return;try{n.prepareEvent(e,t)}catch(t){console.error(`[diagnostic-trace-propagation] prepare error type=${e.type} seq=${e.seq}: ${String(t)}`)}}
//!src/agents/usage.ts
const USAGE_COST_COMPONENTS=[`input`,`output`,`cacheRead`,`cacheWrite`];function hasNonzeroUsage(e){if(!e||e.usageReport?.state===`unavailable`)return false;return[e.input,e.output,e.cacheRead,e.cacheWrite,e.contextUsage?.state===`available`?e.contextUsage.promptTokens:void 0,e.contextUsage?.state===`available`?e.contextUsage.totalTokens:void 0,e.reasoningTokens,e.total].some(e=>typeof e===`number`&&Number.isFinite(e)&&e>0)||e.contextUsage?.state===`unavailable`}function hasRecordedUsageCost(e){const t=asOptionalRecord(e);const n=asFiniteNumber(t?.total);return n!==void 0&&n>=0&&(n>0||t?.totalOrigin===`provider-billed`||USAGE_COST_COMPONENTS.some(e=>(asFiniteNumber(t?.[e])??0)!==0))}function hasObservedModelUsage(e){return e?.usageReport!==void 0||hasRecordedUsageCost(e?.cost)||hasNonzeroUsage(e)}
//!src/infra/diagnostic-flags-env.ts
function parseDiagnosticEnvFlags(e){const t=e?.trim()??``;const n=t.toLowerCase();if(!n)return{flags:[],disablesAll:false};if([`0`,`false`,`off`,`none`].includes(n))return{flags:[],disablesAll:true};if([`1`,`true`,`all`,`*`].includes(n))return{flags:[`*`],disablesAll:false};return{flags:t.split(/[,\s]+/),disablesAll:false}}
//!src/infra/diagnostic-flags.ts
const DIAGNOSTICS_ENV=`OPENCLAW_DIAGNOSTICS`;function isDiagnosticFlagEnabled(e,t,n=process.env){const r=t?.diagnostics?.flags??[];const i=parseDiagnosticEnvFlags(n[DIAGNOSTICS_ENV]);const a=i.disablesAll?[]:normalizeUniqueStringEntriesLower([...r,...i.flags]);const o=normalizeLowercaseStringOrEmpty(e);if(!o)return false;for(const e of a){if(e===`*`||e===`all`||e===o)return true;if(e.endsWith(`.*`)&&o===e.slice(0,-2))return true;if(e.endsWith(`*`)&&o.startsWith(e.slice(0,-1)))return true}return false}
//!src/infra/main-thread-stall.ts
const taskState=resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new AsyncLocalStorage}));function runWithMainThreadTask(e,t,n){const r=taskState.observer;return r?r.run(e,t,n):t()}
//!src/infra/diagnostics-timeline.ts
const OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION=`openclaw.diagnostics.v1`;const MAX_PENDING_TIMELINE_BYTES=65536;function modelUsageTimelineAttributes(e){const t={usageState:e?.usageReport?.state??(hasObservedModelUsage(e)?`available`:`unreported`)};for(const n of[`input`,`output`,`cacheRead`,`cacheWrite`,`cacheWrite1h`,`cacheWrite5m`,`reasoningTokens`,`promptTokens`,`total`]){const r=e?.[n];if(r!==void 0)t[n]=r}return t}function recordDiagnosticModelUsageTimeline(e){if(!isDiagnosticsTimelineEnabled())return;const t=e.trace??getActiveDiagnosticTraceContext();emitDiagnosticsTimelineEvent({type:`mark`,name:`model.usage`,provider:e.provider,attributes:{...modelUsageTimelineAttributes({...e.usage,usageReport:e.usageReport}),...e.model?{model:e.model}:{},...e.sessionId?{sessionId:e.sessionId}:{},...t?{traceId:t.traceId}:{},...e.purpose?{purpose:e.purpose}:{},...e.runtimeKind?{runtimeKind:e.runtimeKind}:{},...e.completionId?{completionId:e.completionId}:{},...e.attemptId?{attemptId:e.attemptId}:{},...e.costUsd!==void 0?{costUsd:e.costUsd}:{}}})}const activeDiagnosticsTimelineSpan=new AsyncLocalStorage;const spanObserver=new AsyncLocalStorage;const timelineWriter=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e;let t;let n;let r=false;let i=false;const a=/* @__PURE__ */ new Set;function append(e,t){try{const n=dirname(e.path);if(!a.has(n)){mkdirSync(n,{recursive:true});a.add(n)}appendRegularFileSync({filePath:e.path,content:t})}catch(t){e.failedWrites++;if(!i){i=true;console.warn(`[diagnostics] failed to write timeline event: ${String(t)}`)}}}function flush(){if(n){clearImmediate(n);n=void 0}const e=t;t=void 0;if(e)append(e.capture,e.content)}process.once(`exit`,()=>{r=true;flush()});return{flush,write(i,a,o){if(e?.path!==i){flush();e={path:i,id:randomUUID(),sequence:0,failedWrites:0}}const s=serializeTimelineEvent({...a,attributes:{...a.attributes,captureId:e.id,sequence:++e.sequence,failedWrites:e.failedWrites}},o);const c=Buffer.byteLength(s,`utf8`);if(t&&t.bytes+c>MAX_PENDING_TIMELINE_BYTES)flush();if(r||c>MAX_PENDING_TIMELINE_BYTES){append(e,s);return}if(t){t.content+=s;t.bytes+=c}else t={capture:e,content:s,bytes:c};n??=setImmediate(flush).unref()}}});function isDiagnosticsTimelineEnabled(e={}){const{config:t,env:n=process.env}=e;const r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH;if(typeof r!==`string`||r.trim().length===0)return false;return isDiagnosticFlagEnabled(`timeline`,t,n)||isDiagnosticFlagEnabled(`diagnostics.timeline`,t,n)||isTruthyEnvValue(n.OPENCLAW_DIAGNOSTICS)}function normalizeNumber(e){if(typeof e!==`number`||!Number.isFinite(e))return;return Math.max(0,Math.round(e*1e3)/1e3)}function normalizeAttributes(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e)){if(typeof r===`number`){if(Number.isFinite(r))t[n]=r;continue}if(typeof r===`string`||typeof r===`boolean`||r===null)t[n]=r}return Object.keys(t).length>0?t:void 0}function serializeTimelineEvent(e,t){const n=normalizeAttributes(e.attributes);const r={schemaVersion:OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION,type:e.type,timestamp:e.timestamp??(/* @__PURE__ */ new Date()).toISOString(),name:e.name,...t.OPENCLAW_DIAGNOSTICS_RUN_ID?{runId:t.OPENCLAW_DIAGNOSTICS_RUN_ID}:{},...t.OPENCLAW_DIAGNOSTICS_ENV?{envName:t.OPENCLAW_DIAGNOSTICS_ENV}:{},pid:process.pid,...e.runId?{runId:e.runId}:{},...e.envName?{envName:e.envName}:{},...typeof e.pid===`number`?{pid:e.pid}:{},phase:e.phase||void 0,spanId:e.spanId||void 0,parentSpanId:e.parentSpanId||void 0,durationMs:normalizeNumber(e.durationMs),errorName:e.errorName||void 0,errorMessage:e.errorMessage||void 0,p50Ms:normalizeNumber(e.p50Ms),p95Ms:normalizeNumber(e.p95Ms),p99Ms:normalizeNumber(e.p99Ms),maxMs:normalizeNumber(e.maxMs),activeSpanName:e.activeSpanName||void 0,provider:e.provider||void 0,operation:e.operation||void 0,ok:typeof e.ok===`boolean`?e.ok:void 0,status:normalizeNumber(e.status),command:e.command||void 0,exitCode:e.exitCode,signal:e.signal,attributes:n};return`${JSON.stringify(r)}\n`}function emitDiagnosticsTimelineEvent(e,t={}){const n=t.env??process.env;if(!isDiagnosticsTimelineEnabled(t))return;const r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim();if(!r)return;timelineWriter.write(r,e,n)}
//!src/infra/worker-diagnostic-script.ts
const scriptBasename=e=>basename(e).replace(/\.[cm]?[jt]s$/u,`.js`);const entries=createRuntimeProcessEntrypoints(import.meta.url);const workerScripts=/* @__PURE__ */ new Map;for(const e of Object.values(entries)){const t=scriptBasename(e.distWorkerPath);workerScripts.set(t,t);workerScripts.set(scriptBasename(e.sourceModulePath),t)}for(const e of Object.values(pluginRuntimeProcessManifest)){const t=scriptBasename(e.distWorkerPath);workerScripts.set(t,t);workerScripts.set(scriptBasename(e.package.distWorkerPath),t);workerScripts.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(const e of Object.values(runtimeProcessSealedManifest))for(const[t,n]of e.entries){const e=scriptBasename(`${n}.mjs`);if(!workerScripts.has(e))workerScripts.set(e,scriptBasename(entries[t].distWorkerPath))}const workerScriptNames=new Set(workerScripts.values());function normalizeDiagnosticWorkerScript(e){return typeof e===`string`&&workerScriptNames.has(e)?e:`other`}function workerScriptName(e,t=false){if(t||e instanceof URL&&e.protocol!==`file:`)return`other`;return workerScripts.get(scriptBasename(e instanceof URL?fileURLToPath(e):e))??`other`}
//!src/infra/diagnostic-events.ts
const EMPTY_DIAGNOSTIC_PRIVATE_DATA=Object.freeze({});const MAX_ASYNC_DIAGNOSTIC_EVENTS=1e4;const MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN=100;const DIAGNOSTIC_EVENTS_STATE_KEY=Symbol.for(`openclaw.diagnosticEvents.state.v1`);const ASYNC_DIAGNOSTIC_EVENT_TYPES=new Set(ASYNC_DIAGNOSTIC_EVENT_NAMES);const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES=new Set(PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES);const diagnosticEventsState=resolveGlobalSingleton(DIAGNOSTIC_EVENTS_STATE_KEY,()=>({marker:DIAGNOSTIC_EVENTS_STATE_KEY,enabled:true,seq:0,listeners:/* @__PURE__ */ new Map,trustedListeners:/* @__PURE__ */ new Map,toolExecutionListeners:/* @__PURE__ */ new Set,toolExecutionSeq:0,dispatchDepth:0,asyncQueue:[],asyncDrainScheduled:false,asyncDroppedEvents:0,asyncDroppedTrustedEvents:0,asyncDroppedUntrustedEvents:0,asyncDroppedPriorityEvents:0}));function areDiagnosticsEnabledForProcess(){return diagnosticEventsState.enabled}function dispatchDiagnosticEvent(e,t,n,r,i={}){if(e.dispatchDepth>100){console.error(`[diagnostic-events] recursion guard tripped at depth=${e.dispatchDepth}, dropping type=${t.type}`);return}e.dispatchDepth+=1;try{const a=createDiagnosticValueForListeners(t,true);const o=r&&createDiagnosticValueForListeners(r);if(!i.trustedListenersOnly)for(const[r,i]of e.listeners){if(!isInternalDiagnosticEventInterested(i,t.type,n.trusted))continue;try{r(a(),n)}catch(e){const n=e instanceof Error?formatErrorStackWithMessage(e):String(e);console.error(`[diagnostic-events] listener error type=${t.type} seq=${t.seq}: ${n}`)}}for(const[r,s]of e.trustedListeners){if(!isInternalDiagnosticEventInterested(s,t.type,n.trusted))continue;try{const e=a();const t=isTrustedOtelDiagnosticListener(r);let c=EMPTY_DIAGNOSTIC_PRIVATE_DATA;if(s?.includePrivateData!==false){c=o?.()??EMPTY_DIAGNOSTIC_PRIVATE_DATA;if(t&&(i.hostPluginId||Object.hasOwn(c,`hostPluginId`))){const e={...c,hostPluginId:i.hostPluginId};if(!i.hostPluginId)Reflect.deleteProperty(e,`hostPluginId`);c=Object.freeze(e)}}r(e,n,c)}catch(e){const n=e instanceof Error?formatErrorStackWithMessage(e):String(e);console.error(`[diagnostic-events] trusted listener error type=${t.type} seq=${t.seq}: ${n}`)}}}finally{e.dispatchDepth-=1}}function isPriorityAsyncDiagnosticEvent(e){return e.metadata.trusted&&PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(e.event.type)}function noteAsyncDiagnosticDrop(e,t){e.asyncDroppedEvents+=1;if(t.metadata.trusted)e.asyncDroppedTrustedEvents+=1;else e.asyncDroppedUntrustedEvents+=1;if(isPriorityAsyncDiagnosticEvent(t))e.asyncDroppedPriorityEvents+=1}function makeRoomForPriorityAsyncDiagnosticEvent(e){const t=e.asyncQueue.findIndex(e=>!isPriorityAsyncDiagnosticEvent(e));if(t>=0)return e.asyncQueue.splice(t,1)[0];return e.asyncQueue.shift()}function scheduleAsyncDiagnosticDrain(e){if(e.asyncDrainScheduled)return;e.asyncDrainScheduled=true;setImmediate(()=>{e.asyncDrainScheduled=false;const t=e.asyncQueue.splice(0,MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN);for(const n of t)dispatchDiagnosticEvent(e,n.event,n.metadata,n.privateData,n);if(e.asyncQueue.length>0){scheduleAsyncDiagnosticDrain(e);return}dispatchAsyncDiagnosticDropSummary(e)})}function dispatchAsyncDiagnosticDropSummary(e){if(e.asyncDroppedEvents<=0)return;const t=e.asyncDroppedEvents;const n=e.asyncDroppedTrustedEvents;const r=e.asyncDroppedUntrustedEvents;const i=e.asyncDroppedPriorityEvents;e.asyncDroppedEvents=0;e.asyncDroppedTrustedEvents=0;e.asyncDroppedUntrustedEvents=0;e.asyncDroppedPriorityEvents=0;dispatchDiagnosticEvent(e,enrichDiagnosticEvent(e,{type:`diagnostic.async_queue.dropped`,droppedEvents:t,...n>0?{droppedTrustedEvents:n}:{},...r>0?{droppedUntrustedEvents:r}:{},...i>0?{droppedPriorityEvents:i}:{},queueLength:e.asyncQueue.length,maxQueueLength:MAX_ASYNC_DIAGNOSTIC_EVENTS,drainBatchSize:MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN}),Object.freeze({internal:true,trusted:false}))}function emitDiagnosticEventWithTrust(e,t,n={}){const r=diagnosticEventsState;const i=t&&isToolExecutionEventInput(e)?dispatchTrustedToolExecutionEvent(r,e):void 0;if(!r.enabled)return;if(e.type===`security.event`&&n.allowSecurityEvent!==true)return;const a=hasInternalDiagnosticEventInterest(e.type,t);if(!a&&!(t&&!n.queuedPhase&&hasDiagnosticTracePropagationConsumer())){r.seq+=1;return}let o=enrichDiagnosticEvent(r,i??e,!n.queuedPhase);if(t&&o.type===`diagnostic.gc`){switch(o.kind){case`scavenge`:case`mark_sweep_compact`:case`incremental`:case`weak_processing`:break;default:o.kind=void 0}switch(o.reason){case`none`:case`forced`:case`synchronous_phantom_processing`:case`all_available_garbage`:case`all_external_memory`:case`schedule_idle`:case`construct_retained`:case`other`:break;default:o.reason=`other`}o.thread=o.thread===void 0||o.thread===`main`?`main`:normalizeDiagnosticWorkerScript(o.thread);if(o.thread!==`code-mode-node.worker.js`||typeof o.workerSlot!==`number`||!Number.isInteger(o.workerSlot)||o.workerSlot<1||o.workerSlot>64)o.workerSlot=void 0}const{hostPluginId:s,internal:c=false,privateData:l}=n;const u=n.trustedTraceContext===true;const d=Object.freeze({...c?{internal:true}:{},trusted:t,...n.toolExecutionLiveness?{[TOOL_EXECUTION_LIVENESS_METADATA_KEY]:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{[CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY]:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{[CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY]:n.coreSemanticRunProgress}:{},...u?{trustedTraceContext:u}:{}});const f=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(o);const p=a&&(n.queuedPhase||ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type));if(p){if(r.asyncQueue.length>=MAX_ASYNC_DIAGNOSTIC_EVENTS){if(!t||!PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type)){noteAsyncDiagnosticDrop(r,{event:o,metadata:d,privateData:l,hostPluginId:s});return}const e=makeRoomForPriorityAsyncDiagnosticEvent(r);if(e)noteAsyncDiagnosticDrop(r,e)}const e={event:o,metadata:d,privateData:l,hostPluginId:s};if(!captureQueuedDiagnosticEvent(e,r.trustedListeners.values()))return;o=e.event;r.asyncQueue.push(e)}if(f){if(!p)o=cloneDiagnosticValueForListener(o,true);prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o),d)}if(p)scheduleAsyncDiagnosticDrain(r);else if(a)dispatchDiagnosticEvent(r,o,d,l,{hostPluginId:s})}function isToolExecutionEventInput(e){return e.type===`tool.execution.started`||e.type===`tool.execution.completed`||e.type===`tool.execution.error`||e.type===`tool.execution.blocked`}function dispatchTrustedToolExecutionEvent(e,t){e.toolExecutionSeq+=1;if(e.toolExecutionListeners.size===0)return;let n;try{n=cloneDiagnosticValueForListener({...t,seq:e.toolExecutionSeq,ts:Date.now()},true)}catch(e){console.error(`[diagnostic-events] tool execution clone error type=${t.type}: ${String(e)}`);return}const r=createDiagnosticValueForListeners(n);for(const t of e.toolExecutionListeners)try{t(r())}catch(e){console.error(`[diagnostic-events] tool execution listener error type=${n.type} seq=${n.seq}: ${String(e)}`)}return n}function emitDiagnosticEvent(e){emitDiagnosticEventWithTrust(e,false)}function emitDiagnosticEventWithTrustedTraceContext(e){emitDiagnosticEventWithTrust(e,false,{trustedTraceContext:true})}function emitInternalDiagnosticEvent(e,t){emitDiagnosticEventWithTrust(e,false,{internal:true,privateData:t})}function emitTrustedDiagnosticEvent(e){if(e.type===`model.usage`)recordDiagnosticModelUsageTimeline(e);const t=consumeToolExecutionLivenessDiagnosticEvent(e);const n=consumeHostPluginUsageDiagnosticEvent(e);const r=consumeCoreSemanticRunProgressDiagnosticEvent(e);emitDiagnosticEventWithTrust(e,true,{...t?{toolExecutionLiveness:t}:{},...n?{hostPluginId:n,internal:true}:{},...r?{coreSemanticRunProgress:r}:{}})}export{emitTrustedDiagnosticEvent as a,isDiagnosticFlagEnabled as c,normalizeDiagnosticTraceContext as d,hasInternalDiagnosticEventInterest as f,emitInternalDiagnosticEvent as i,parseDiagnosticEnvFlags as l,emitDiagnosticEvent as n,workerScriptName as o,emitDiagnosticEventWithTrustedTraceContext as r,runWithMainThreadTask as s,areDiagnosticsEnabledForProcess as t,getActiveDiagnosticTraceContext as u};