UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 23.1 kB
import{i as e}from"./fs-safe-copy.worker-global-singleton-DIJgobpU.mjs";import"./fs-safe-copy.worker-fs-safe-env-DlxNGTI7.mjs";import{o as t}from"./fs-safe-copy.worker-error-coercion-AIKMMQJR.mjs";import{g as n,m as r,r as i}from"./fs-safe-copy.worker-number-coercion-1FVMw2ic.mjs";import{r as a}from"./fs-safe-copy.worker-record-coerce-BUlpHiHI.mjs";import{t as o}from"./fs-safe-copy.worker-src-DQ9uH8Sw.mjs";import{i as s,t as c}from"./fs-safe-copy.worker-worker-diagnostic-script-C6p7spUr.mjs";import{mkdirSync as l}from"node:fs";import{dirname as u}from"node:path";import{appendRegularFileSync as d}from"@openclaw/fs-safe/advanced";import{AsyncLocalStorage as f,AsyncResource as p}from"node:async_hooks";import{randomUUID as m}from"node:crypto";import"node:perf_hooks";function normalizeStringEntries(e){return(e??[]).map(e=>String(e).trim()).filter(Boolean)}function normalizeStringEntriesLower(e){return normalizeStringEntries(e).map(e=>e.toLowerCase())}function uniqueValues(e){return[...new Set(e)]}function uniqueStrings(e){return uniqueValues(e)}function normalizeUniqueStringEntries(e){return uniqueStrings(normalizeStringEntries(e?[...e]:void 0))}function normalizeUniqueStringEntriesLower(e){return uniqueStrings(normalizeStringEntriesLower(e?[...e]:void 0))}const h=e(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=!1){let n=t?h.trustedInterest:h.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new p(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}e(Symbol.for(`openclaw.pluginSourceAcquisitionFailures`),()=>/* @__PURE__ */ new WeakSet),e(Symbol.for(`openclaw.pluginSourcePreparationOperations`),()=>/* @__PURE__ */ new WeakSet),e(Symbol.for(`openclaw.pluginInventoryRetiredError`),()=>class extends Error{constructor(){super(`Plugin inventory has retired; begin a new plugin operation.`),this.name=`PluginInventoryRetiredError`}}),e(Symbol.for(`openclaw.pluginSourceRecoveryUnavailableError`),()=>class extends Error{constructor(e){super(`Captured plugin source is missing; its previous code cannot be recovered.`,{cause:e}),this.name=`PluginSourceRecoveryUnavailableError`}});const g=e(Symbol.for(`openclaw.pluginInstanceDrainTimeoutError`),()=>class extends Error{constructor(e,t,n,r){super(e,n),this.settled=t,this.forcedRetirement=r,this.name=`PluginInstanceDrainTimeoutError`}});var _=class InvocationFrame{constructor(e,t=e.invocation){this.retentionOwner=e.retentionOwner,this.invocation=t,this.metadataScope=e.metadataScope,this.cacheScope=e.cacheScope,this.sourceCaptureStorage=e.sourceCaptureStorage}get runtimePluginId(){}get canUseInteractiveStateReadCapacity(){return!1}withScopes(e){return new InvocationFrame(e)}};function createPluginExecutionFrame(e,t){return t?t.withScopes(e):new _(e)}const v=e(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new f;return{invocation:{getStore(){return e.getStore()?.invocation},run(t,n){let r=e.getStore();return r?.invocation===t?n():runWithAsyncStore(e,createPluginExecutionFrame({...r,invocation:t},r),n)},exit(t){let n=e.getStore();return n?.invocation?runWithAsyncStore(e,n.withScopes({...n,invocation:void 0}),t):t()}},getFrame(){return e.getStore()},runFrame(t,n){return runWithAsyncStore(e,t,n)}}});v.invocation;const y=v.getFrame;v.runFrame;const b={priority:!1,publicExcluded:!1},x=[{...b,name:`worker.request`},{...b,name:`diagnostic.gc`,publicExcluded:!0},{...b,name:`gateway.event_loop.sample`,publicExcluded:!0},{...b,name:`gateway.main_thread.stall`,publicExcluded:!0},{...b,name:`gateway.http.cancelled`,publicExcluded:!0},{...b,name:`gateway.rpc`,publicExcluded:!0},{...b,name:`sessions.list.baseline.retired`},{...b,name:`sessions.list.retention`,publicExcluded:!0},{...b,name:`sessions.projection.retention`,publicExcluded:!0},{...b,name:`sessions.event.retention`,publicExcluded:!0},{...b,name:`sessions.event.rows.reset`,publicExcluded:!0},{...b,name:`gateway.ws.event`,publicExcluded:!0},{...b,name:`gateway.ws.connections`,publicExcluded:!0},{...b,name:`tool.execution.started`},{...b,name:`tool.execution.completed`,priority:!0},{...b,name:`tool.execution.error`,priority:!0},{...b,name:`tool.execution.blocked`,priority:!0},{...b,name:`skill.used`},{...b,name:`exec.process.completed`},{...b,name:`exec.approval.followup_suppressed`},{...b,name:`message.delivery.started`},{...b,name:`message.delivery.completed`},{...b,name:`message.delivery.error`},{...b,name:`talk.event`},{...b,name:`model.call.started`},{...b,name:`model.call.completed`,priority:!0},{...b,name:`model.call.error`,priority:!0},{...b,name:`model.response.observed`},{...b,name:`run.progress`},{...b,name:`run.execution_phase`},{...b,name:`agent.commentary`},{...b,name:`harness.run.completed`,priority:!0},{...b,name:`harness.run.error`,priority:!0},{...b,name:`context.assembled`},{...b,name:`log.record`,publicExcluded:!0}],S=x.map(e=>e.name),C=x.filter(e=>e.priority).map(e=>e.name);x.filter(e=>e.publicExcluded).map(e=>e.name);const w=/^[0-9a-f]{32}$/,T=/^[0-9a-f]{16}$/,E=/^[0-9a-f]{2}$/,D=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`);function isNonZeroHex(e){return!/^0+$/.test(e)}const O=new s(D);function isValidDiagnosticTraceId(e){return typeof e==`string`&&w.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&T.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&E.test(e)}function normalizeDiagnosticTraceContext(e){let t=a(e);if(t&&isValidDiagnosticTraceId(t.traceId)&&(t.spanId===void 0||isValidDiagnosticSpanId(t.spanId))&&(t.parentSpanId===void 0||isValidDiagnosticSpanId(t.parentSpanId))&&(t.traceFlags===void 0||isValidDiagnosticTraceFlags(t.traceFlags)))return{traceId:t.traceId,...t.spanId?{spanId:t.spanId}:{},...t.parentSpanId?{parentSpanId:t.parentSpanId}:{},...t.traceFlags?{traceFlags:t.traceFlags}:{}}}function getActiveDiagnosticTraceContext(){return O.getStore()}const k=/* @__PURE__ */ new WeakSet;function cloneDiagnosticValueForListener(e,t=!1){if(k.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return k.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&k.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return k.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(k.has(e)||t?.has(e))return!0;let n=Object.getPrototypeOf(e);if(!Object.isFrozen(e)||n!==Object.prototype&&n!==Array.prototype&&n!==null)return!1;let r=t;return Reflect.ownKeys(e).every(t=>{let n=Object.getOwnPropertyDescriptor(e,t);return typeof t==`symbol`||!(`value`in n)?!1:(n.value&&typeof n.value==`object`&&(r??=/* @__PURE__ */ new WeakSet).add(e),isImmutableDiagnosticValue(n.value,r))})}function freezeDiagnosticValue(e,t){if(!e||typeof e!=`object`||t.has(e))return!0;if(ArrayBuffer.isView(e))return!1;t.add(e);let n=Object.getPrototypeOf(e),r=n===Object.prototype||n===Array.prototype||n===null;for(let n of Object.values(e))freezeDiagnosticValue(n,t)||(r=!1);return Object.freeze(e),r}function enrichDiagnosticEvent(e,t,n=!0){let r={};for(let[e,n]of Object.entries(t))o(e)||(r[e]=n);return n&&(r.trace??=getActiveDiagnosticTraceContext()),e.seq+=1,r.seq=e.seq,r.ts=Date.now(),r}function captureQueuedDiagnosticEvent(e,t){try{let n=!1,r=!1;if(e.privateData||e.trustedListenersOnly){for(let i of t)if(isInternalDiagnosticEventInterested(i,e.event.type,e.metadata.trusted)&&(n=!0,i?.includePrivateData!==!1)){r=!0;break}}if(e.trustedListenersOnly&&!n)return!1;if(e.event=cloneDiagnosticValueForListener(e.event,!0),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!0}catch(t){return console.error(`[diagnostic-events] queue snapshot error type=${e.event.type}: ${String(t)}`),!1}}const A=/* @__PURE__ */ new WeakSet;function isTrustedOtelDiagnosticListener(e){return A.has(e)}const j=/* @__PURE__ */ new WeakMap;function consumeHostPluginUsageDiagnosticEvent(e){let t=j.get(e);return j.delete(e),t}const M=/* @__PURE__ */ new WeakMap;function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=M.get(e);return M.delete(e),t}const N=e(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new s(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=N.events.get(e);return N.events.delete(e),t}const P=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),F=e(P,()=>({marker:P,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}));function hasDiagnosticTracePropagationConsumer(){return F.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=F.activeBridge;if(!t?.prepareEvent)return!1;if(!t.shouldPrepareEvent)return!0;try{return t.shouldPrepareEvent(e)}catch(e){return console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(e)}`),!1}}function prepareDiagnosticTracePropagation(e,t){let n=F.activeBridge;if(n?.prepareEvent)try{n.prepareEvent(e,t)}catch(t){console.error(`[diagnostic-trace-propagation] prepare error type=${e.type} seq=${e.seq}: ${String(t)}`)}}const I=[`input`,`output`,`cacheRead`,`cacheWrite`];function hasNonzeroUsage(e){return!e||e.usageReport?.state===`unavailable`?!1:[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){let t=a(e),n=i(t?.total);return n!==void 0&&n>=0&&(n>0||t?.totalOrigin===`provider-billed`||I.some(e=>(i(t?.[e])??0)!==0))}function hasObservedModelUsage(e){return e?.usageReport!==void 0||hasRecordedUsageCost(e?.cost)||hasNonzeroUsage(e)}function parseDiagnosticEnvFlags(e){let t=e?.trim()??``,n=t.toLowerCase();return n?[`0`,`false`,`off`,`none`].includes(n)?{flags:[],disablesAll:!0}:[`1`,`true`,`all`,`*`].includes(n)?{flags:[`*`],disablesAll:!1}:{flags:t.split(/[,\s]+/),disablesAll:!1}:{flags:[],disablesAll:!1}}function isDiagnosticFlagEnabled(e,t,n=process.env){let i=t?.diagnostics?.flags??[],a=parseDiagnosticEnvFlags(n.OPENCLAW_DIAGNOSTICS),o=a.disablesAll?[]:normalizeUniqueStringEntriesLower([...i,...a.flags]),s=r(e);if(!s)return!1;for(let e of o)if(e===`*`||e===`all`||e===s||e.endsWith(`.*`)&&s===e.slice(0,-2)||e.endsWith(`*`)&&s.startsWith(e.slice(0,-1)))return!0;return!1}const L=[`true`,`1`,`yes`,`on`],R=[`false`,`0`,`no`,`off`];function asBoolean(e){return typeof e==`boolean`?e:void 0}function parseBooleanValue(e,t={}){let r=asBoolean(e);if(r!==void 0)return r;let i=n(e);if(i){if((t.truthy??L).includes(i))return!0;if((t.falsy??R).includes(i))return!1}}const z=[[`ZAI_API_KEY`,`Z_AI_API_KEY`]];function normalizeZaiEnv(e=process.env){!e.ZAI_API_KEY?.trim()&&e.Z_AI_API_KEY?.trim()&&(e.ZAI_API_KEY=e.Z_AI_API_KEY)}function expandEnvNormalizationKeys(e){let t=/* @__PURE__ */ new Set;for(let n of e)for(let e of resolveEnvNormalizationKeys(n))t.add(e);return t}function resolveEnvNormalizationKeys(e){let t=process.platform===`win32`?e.toUpperCase():e;return z.find(e=>e.some(e=>e===t))??[t]}function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}const B=65536;function modelUsageTimelineAttributes(e){let t={usageState:e?.usageReport?.state??(hasObservedModelUsage(e)?`available`:`unreported`)};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`,`cacheWrite1h`,`cacheWrite5m`,`reasoningTokens`,`promptTokens`,`total`]){let r=e?.[n];r!==void 0&&(t[n]=r)}return t}function recordDiagnosticModelUsageTimeline(e){if(!isDiagnosticsTimelineEnabled())return;let 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}}})}new f,new f;const V=e(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,i=!1,a=/* @__PURE__ */ new Set;function append(e,t){try{let n=u(e.path);a.has(n)||(l(n,{recursive:!0}),a.add(n)),d({filePath:e.path,content:t})}catch(t){e.failedWrites++,i||(i=!0,console.warn(`[diagnostics] failed to write timeline event: ${String(t)}`))}}function flush(){n&&=(clearImmediate(n),void 0);let e=t;t=void 0,e&&append(e.capture,e.content)}return process.once(`exit`,()=>{r=!0,flush()}),{flush,write(i,a,o){e?.path!==i&&(flush(),e={path:i,id:m(),sequence:0,failedWrites:0});let s=serializeTimelineEvent({...a,attributes:{...a.attributes,captureId:e.id,sequence:++e.sequence,failedWrites:e.failedWrites}},o),c=Buffer.byteLength(s,`utf8`);t&&t.bytes+c>B&&flush(),r||c>B?append(e,s):(t?(t.content+=s,t.bytes+=c):t={capture:e,content:s,bytes:c},n??=setImmediate(flush).unref())}}});function isDiagnosticsTimelineEnabled(e={}){let{config:t,env:n=process.env}=e,r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH;return typeof r!=`string`||r.trim().length===0?!1:isDiagnosticFlagEnabled(`timeline`,t,n)||isDiagnosticFlagEnabled(`diagnostics.timeline`,t,n)||isTruthyEnvValue(n.OPENCLAW_DIAGNOSTICS)}function normalizeNumber(e){if(typeof e==`number`&&Number.isFinite(e))return Math.max(0,Math.round(e*1e3)/1e3)}function normalizeAttributes(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))typeof r==`number`?Number.isFinite(r)&&(t[n]=r):(typeof r==`string`||typeof r==`boolean`||r===null)&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function serializeTimelineEvent(e,t){let n=normalizeAttributes(e.attributes),r={schemaVersion:`openclaw.diagnostics.v1`,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={}){let n=t.env??process.env;if(!isDiagnosticsTimelineEnabled(t))return;let r=n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim();r&&V.write(r,e,n)}const H=Object.freeze({}),U=1e4,W=Symbol.for(`openclaw.diagnosticEvents.state.v1`),G=new Set(S),K=new Set(C),q=e(W,()=>({marker:W,enabled:!0,seq:0,listeners:/* @__PURE__ */ new Map,trustedListeners:/* @__PURE__ */ new Map,toolExecutionListeners:/* @__PURE__ */ new Set,toolExecutionSeq:0,dispatchDepth:0,asyncQueue:[],asyncDrainScheduled:!1,asyncDroppedEvents:0,asyncDroppedTrustedEvents:0,asyncDroppedUntrustedEvents:0,asyncDroppedPriorityEvents:0}));function areDiagnosticsEnabledForProcess(){return q.enabled}function dispatchDiagnosticEvent(e,n,r,i,a={}){if(e.dispatchDepth>100)console.error(`[diagnostic-events] recursion guard tripped at depth=${e.dispatchDepth}, dropping type=${n.type}`);else{e.dispatchDepth+=1;try{let o=createDiagnosticValueForListeners(n,!0),s=i&&createDiagnosticValueForListeners(i);if(!a.trustedListenersOnly){for(let[i,a]of e.listeners)if(isInternalDiagnosticEventInterested(a,n.type,r.trusted))try{i(o(),r)}catch(e){let r=e instanceof Error?t(e):String(e);console.error(`[diagnostic-events] listener error type=${n.type} seq=${n.seq}: ${r}`)}}for(let[i,c]of e.trustedListeners)if(isInternalDiagnosticEventInterested(c,n.type,r.trusted))try{let e=o(),t=isTrustedOtelDiagnosticListener(i),n=H;if(c?.includePrivateData!==!1&&(n=s?.()??H,t&&(a.hostPluginId||Object.hasOwn(n,`hostPluginId`)))){let e={...n,hostPluginId:a.hostPluginId};a.hostPluginId||Reflect.deleteProperty(e,`hostPluginId`),n=Object.freeze(e)}i(e,r,n)}catch(e){let r=e instanceof Error?t(e):String(e);console.error(`[diagnostic-events] trusted listener error type=${n.type} seq=${n.seq}: ${r}`)}}finally{--e.dispatchDepth}}}function isPriorityAsyncDiagnosticEvent(e){return e.metadata.trusted&&K.has(e.event.type)}function noteAsyncDiagnosticDrop(e,t){e.asyncDroppedEvents+=1,t.metadata.trusted?e.asyncDroppedTrustedEvents+=1:e.asyncDroppedUntrustedEvents+=1,isPriorityAsyncDiagnosticEvent(t)&&(e.asyncDroppedPriorityEvents+=1)}function makeRoomForPriorityAsyncDiagnosticEvent(e){let t=e.asyncQueue.findIndex(e=>!isPriorityAsyncDiagnosticEvent(e));return t>=0?e.asyncQueue.splice(t,1)[0]:e.asyncQueue.shift()}function scheduleAsyncDiagnosticDrain(e){e.asyncDrainScheduled||(e.asyncDrainScheduled=!0,setImmediate(()=>{e.asyncDrainScheduled=!1;let t=e.asyncQueue.splice(0,100);for(let n of t)dispatchDiagnosticEvent(e,n.event,n.metadata,n.privateData,n);e.asyncQueue.length>0?scheduleAsyncDiagnosticDrain(e):dispatchAsyncDiagnosticDropSummary(e)}))}function dispatchAsyncDiagnosticDropSummary(e){if(e.asyncDroppedEvents<=0)return;let t=e.asyncDroppedEvents,n=e.asyncDroppedTrustedEvents,r=e.asyncDroppedUntrustedEvents,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:U,drainBatchSize:100}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=q,i=t&&isToolExecutionEventInput(e)?dispatchTrustedToolExecutionEvent(r,e):void 0;if(!r.enabled||e.type===`security.event`&&n.allowSecurityEvent!==!0)return;let 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`:c(o.thread),(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)}let{hostPluginId:s,internal:l=!1,privateData:u}=n,d=n.trustedTraceContext===!0,f=Object.freeze({...l?{internal:!0}:{},trusted:t,...n.toolExecutionLiveness?{toolExecutionLiveness:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{coreModelRequestLifecycle:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{coreSemanticRunProgress:n.coreSemanticRunProgress}:{},...d?{trustedTraceContext:d}:{}}),p=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(o),m=a&&(n.queuedPhase||G.has(o.type));if(m){if(r.asyncQueue.length>=U){if(!t||!K.has(o.type)){noteAsyncDiagnosticDrop(r,{event:o,metadata:f,privateData:u,hostPluginId:s});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&&noteAsyncDiagnosticDrop(r,e)}let e={event:o,metadata:f,privateData:u,hostPluginId:s};if(!captureQueuedDiagnosticEvent(e,r.trustedListeners.values()))return;o=e.event,r.asyncQueue.push(e)}p&&(m||(o=cloneDiagnosticValueForListener(o,!0)),prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o),f)),m?scheduleAsyncDiagnosticDrain(r):a&&dispatchDiagnosticEvent(r,o,f,u,{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){if(e.toolExecutionSeq+=1,e.toolExecutionListeners.size===0)return;let n;try{n=cloneDiagnosticValueForListener({...t,seq:e.toolExecutionSeq,ts:Date.now()},!0)}catch(e){console.error(`[diagnostic-events] tool execution clone error type=${t.type}: ${String(e)}`);return}let r=createDiagnosticValueForListeners(n);for(let 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,!1)}function emitDiagnosticEventWithTrustedTraceContext(e){emitDiagnosticEventWithTrust(e,!1,{trustedTraceContext:!0})}function emitInternalDiagnosticEvent(e,t){emitDiagnosticEventWithTrust(e,!1,{internal:!0,privateData:t})}function emitTrustedDiagnosticEvent(e){e.type===`model.usage`&&recordDiagnosticModelUsageTimeline(e);let t=consumeToolExecutionLivenessDiagnosticEvent(e),n=consumeHostPluginUsageDiagnosticEvent(e),r=consumeCoreSemanticRunProgressDiagnosticEvent(e);emitDiagnosticEventWithTrust(e,!0,{...t?{toolExecutionLiveness:t}:{},...n?{hostPluginId:n,internal:!0}:{},...r?{coreSemanticRunProgress:r}:{}})}export{runWithAsyncStore as _,emitTrustedDiagnosticEvent as a,normalizeUniqueStringEntries as b,normalizeZaiEnv as c,isDiagnosticFlagEnabled as d,parseDiagnosticEnvFlags as f,g,y as h,emitInternalDiagnosticEvent as i,resolveEnvNormalizationKeys as l,normalizeDiagnosticTraceContext as m,emitDiagnosticEvent as n,expandEnvNormalizationKeys as o,getActiveDiagnosticTraceContext as p,emitDiagnosticEventWithTrustedTraceContext as r,isTruthyEnvValue as s,areDiagnosticsEnabledForProcess as t,parseBooleanValue as u,hasInternalDiagnosticEventInterest as v,normalizeStringEntries as y};