openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 26.3 kB
JavaScript
import{c as e,m as t,n}from"./git-operation.worker-map-size-CypexNQj.mjs";import{d as r,f as i,u as a}from"./git-operation.worker-home-dir-DUQkhCrS.mjs";import{r as o}from"./git-operation.worker-record-coerce-BUlpHiHI.mjs";import{i as s,n as c,t as l}from"./git-operation.worker-runtime-process-manifest-BlrvoYG_.mjs";import{mkdirSync as u}from"node:fs";import{basename as d,dirname as f}from"node:path";import{appendRegularFileSync as p}from"@openclaw/fs-safe/advanced";import{randomUUID as m}from"node:crypto";import{AsyncLocalStorage as h,AsyncResource as ee}from"node:async_hooks";import"node:perf_hooks";import{fileURLToPath as te}from"node:url";function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new ee(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}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 normalizeUniqueStringEntriesLower(e){return uniqueStrings(normalizeStringEntriesLower(e?[...e]:void 0))}const g=a(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?g.trustedInterest:g.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}a(Symbol.for(`openclaw.pluginSourceAcquisitionFailures`),()=>/* @__PURE__ */ new WeakSet),a(Symbol.for(`openclaw.pluginSourcePreparationOperations`),()=>/* @__PURE__ */ new WeakSet),a(Symbol.for(`openclaw.pluginInventoryRetiredError`),()=>class extends Error{constructor(){super(`Plugin inventory has retired; begin a new plugin operation.`),this.name=`PluginInventoryRetiredError`}}),a(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 ne=a(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 re=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 re(e)}const _=a(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new h;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)}}});_.invocation;const v=_.getFrame;_.runFrame;const y={priority:!1,publicExcluded:!1},b=[{...y,name:`worker.request`},{...y,name:`diagnostic.gc`,publicExcluded:!0},{...y,name:`gateway.event_loop.sample`,publicExcluded:!0},{...y,name:`gateway.main_thread.stall`,publicExcluded:!0},{...y,name:`gateway.http.cancelled`,publicExcluded:!0},{...y,name:`gateway.rpc`,publicExcluded:!0},{...y,name:`sessions.list.baseline.retired`},{...y,name:`sessions.list.retention`,publicExcluded:!0},{...y,name:`sessions.projection.retention`,publicExcluded:!0},{...y,name:`sessions.event.retention`,publicExcluded:!0},{...y,name:`sessions.event.rows.reset`,publicExcluded:!0},{...y,name:`gateway.ws.event`,publicExcluded:!0},{...y,name:`gateway.ws.connections`,publicExcluded:!0},{...y,name:`tool.execution.started`},{...y,name:`tool.execution.completed`,priority:!0},{...y,name:`tool.execution.error`,priority:!0},{...y,name:`tool.execution.blocked`,priority:!0},{...y,name:`skill.used`},{...y,name:`exec.process.completed`},{...y,name:`exec.approval.followup_suppressed`},{...y,name:`message.delivery.started`},{...y,name:`message.delivery.completed`},{...y,name:`message.delivery.error`},{...y,name:`talk.event`},{...y,name:`model.call.started`},{...y,name:`model.call.completed`,priority:!0},{...y,name:`model.call.error`,priority:!0},{...y,name:`model.response.observed`},{...y,name:`run.progress`},{...y,name:`run.execution_phase`},{...y,name:`agent.commentary`},{...y,name:`harness.run.completed`,priority:!0},{...y,name:`harness.run.error`,priority:!0},{...y,name:`context.assembled`},{...y,name:`log.record`,publicExcluded:!0}],ie=b.map(e=>e.name),x=b.filter(e=>e.priority).map(e=>e.name);b.filter(e=>e.publicExcluded).map(e=>e.name);const S=a(Symbol.for(`openclaw.asyncContext`),()=>new h);var AsyncContext=class{constructor(e){this.key=e}getStore(){return S.getStore()?.[this.key]}run(e,t){let n=S.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};S.enterWith(i);try{return t()}finally{let e=S.getStore();S.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){S.enterWith({...S.getStore(),[this.key]:e})}};const C=/^[0-9a-f]{32}$/,w=/^[0-9a-f]{16}$/,T=/^[0-9a-f]{2}$/,E=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`);function isNonZeroHex(e){return!/^0+$/.test(e)}const D=new AsyncContext(E);function isValidDiagnosticTraceId(e){return typeof e==`string`&&C.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&w.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&T.test(e)}function normalizeDiagnosticTraceContext(e){let t=o(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 freezeDiagnosticTraceContext(e){return Object.freeze({traceId:e.traceId,...e.spanId?{spanId:e.spanId}:{},...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.traceFlags?{traceFlags:e.traceFlags}:{}})}function getActiveDiagnosticTraceContext(){return D.getStore()}function runWithDiagnosticTraceContext(e,t){return runWithAsyncStore(D,e===void 0?void 0:freezeDiagnosticTraceContext(e),t)}const O=/* @__PURE__ */ new WeakSet;function cloneDiagnosticValueForListener(e,t=!1){if(O.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return O.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&O.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return O.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(O.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,r=!0){let i={};for(let[e,r]of Object.entries(t))n(e)||(i[e]=r);return r&&(i.trace??=getActiveDiagnosticTraceContext()),e.seq+=1,i.seq=e.seq,i.ts=Date.now(),i}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 k=/* @__PURE__ */ new WeakSet;function isTrustedOtelDiagnosticListener(e){return k.has(e)}const A=/* @__PURE__ */ new WeakMap;function consumeHostPluginUsageDiagnosticEvent(e){let t=A.get(e);return A.delete(e),t}const j=/* @__PURE__ */ new WeakMap;function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=j.get(e);return j.delete(e),t}const M=a(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=M.events.get(e);return M.events.delete(e),t}const N=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),P=a(N,()=>({marker:N,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}));function hasDiagnosticTracePropagationConsumer(){return P.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=P.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=P.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 ae=[`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 n=o(e),r=t(n?.total);return r!==void 0&&r>=0&&(r>0||n?.totalOrigin===`provider-billed`||ae.some(e=>(t(n?.[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 F=[`true`,`1`,`yes`,`on`],oe=[`false`,`0`,`no`,`off`];function asBoolean(e){return typeof e==`boolean`?e:void 0}function parseBooleanValue(e,t={}){let n=asBoolean(e);if(n!==void 0)return n;let r=i(e);if(r){if((t.truthy??F).includes(r))return!0;if((t.falsy??oe).includes(r))return!1}}const I=a(Symbol.for(`openclaw.processEnvironmentKey`),()=>({key:{},aliases:new WeakSet([process.env])}));function resolveEnvironmentKey(e){return e===void 0||e===process.env||I.aliases.has(e)?I.key:e}function captureEnvironmentKey(e=process.env){let t=resolveEnvironmentKey(e);return t===I.key&&I.aliases.add(e),t}const L=`OPENCLAW_FS_SAFE_NATIVE_MODE`,R=[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`],z=[...R,`FS_SAFE_PYTHON`,`OPENCLAW_FS_SAFE_PYTHON`,`OPENCLAW_PINNED_PYTHON`,`OPENCLAW_PINNED_WRITE_PYTHON`],B=/* @__PURE__ */ new WeakMap;let V=!1;function nativeModeIsValid(e){let t=e?.trim().toLowerCase()??``;return/^(?:0|false|off|never|1|true|on|auto|required|require)$/u.test(t)}function currentFallback(e){let t=B.get(resolveEnvironmentKey(e));return t&&e[t.key]===t.value?t:void 0}function fsSafeEnvInput(e){let t=currentFallback(e);if(!t)return e;let n={...e,[t.key]:t.previous};return t.existed||delete n[t.key],n}function clearFsSafeEnvFallback(e){let t=currentFallback(e);B.delete(resolveEnvironmentKey(e)),t&&(t.existed?e[t.key]=t.previous:delete e[t.key])}function normalizeFsSafeNativeEnv(e=process.env){clearFsSafeEnvFallback(e);let t=z.filter(t=>e[t]!==void 0);if(t.length&&e===process.env&&!V&&(V=!0,process.emitWarning(`${t.join(`, `)} is deprecated. OpenClaw maps legacy mode values to native mode only when neither FS_SAFE_NATIVE_MODE nor OPENCLAW_FS_SAFE_NATIVE_MODE selects a mode. Replace Python mode variables with native mode variables; interpreter path settings are ignored.`,{code:`FS_SAFE_PYTHON_DEPRECATED`,type:`DeprecationWarning`})),nativeModeIsValid(e.FS_SAFE_NATIVE_MODE)||nativeModeIsValid(e[L]))return;let n=R.map(t=>e[t]).find(e=>e!==void 0);if(n===void 0)return;let r=Object.keys(e),i=!r.includes(L)&&Object.hasOwn(e,L)?r.find(e=>e.toUpperCase()===L)??L:L,a=Object.hasOwn(e,i),o=e[i];e[i]=n,B.set(captureEnvironmentKey(e),{key:i,value:n,previous:o,existed:a})}function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}const H=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`),U=H?a(Symbol.for(`openclaw.detachedAsyncContext`),()=>new H.AsyncResource(`openclaw.detached-async-context`)):void 0;function runInDetachedAsyncContext(e){return U?U.runInAsyncScope(e):e()}const W=a(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new h}));function runWithMainThreadTask(e,t,n){let r=W.observer;return r?r.run(e,t,n):t()}const G=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 h,new h;const K=a(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,i=!1,a=/* @__PURE__ */ new Set;function append(e,t){try{let n=f(e.path);a.has(n)||(u(n,{recursive:!0}),a.add(n)),p({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>G&&flush(),r||c>G?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&&K.write(r,e,n)}const scriptBasename=e=>d(e).replace(/\.[cm]?[jt]s$/u,`.js`),q=l(import.meta.url),J=/* @__PURE__ */ new Map;for(let e of Object.values(q)){let t=scriptBasename(e.distWorkerPath);J.set(t,t),J.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(c)){let t=scriptBasename(e.distWorkerPath);J.set(t,t),J.set(scriptBasename(e.package.distWorkerPath),t),J.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(s))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);J.has(e)||J.set(e,scriptBasename(q[t].distWorkerPath))}const se=new Set(J.values());function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&se.has(e)?e:`other`}function workerScriptName(e,t=!1){return t||e instanceof URL&&e.protocol!==`file:`?`other`:J.get(scriptBasename(e instanceof URL?te(e):e))??`other`}const Y=Object.freeze({}),X=1e4,Z=Symbol.for(`openclaw.diagnosticEvents.state.v1`),ce=new Set(ie),Q=new Set(x),$=a(Z,()=>({marker:Z,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 $.enabled}function dispatchDiagnosticEvent(t,n,r,i,a={}){if(t.dispatchDepth>100)console.error(`[diagnostic-events] recursion guard tripped at depth=${t.dispatchDepth}, dropping type=${n.type}`);else{t.dispatchDepth+=1;try{let o=createDiagnosticValueForListeners(n,!0),s=i&&createDiagnosticValueForListeners(i);if(!a.trustedListenersOnly){for(let[i,a]of t.listeners)if(isInternalDiagnosticEventInterested(a,n.type,r.trusted))try{i(o(),r)}catch(t){let r=t instanceof Error?e(t):String(t);console.error(`[diagnostic-events] listener error type=${n.type} seq=${n.seq}: ${r}`)}}for(let[i,c]of t.trustedListeners)if(isInternalDiagnosticEventInterested(c,n.type,r.trusted))try{let e=o(),t=isTrustedOtelDiagnosticListener(i),n=Y;if(c?.includePrivateData!==!1&&(n=s?.()??Y,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(t){let r=t instanceof Error?e(t):String(t);console.error(`[diagnostic-events] trusted listener error type=${n.type} seq=${n.seq}: ${r}`)}}finally{--t.dispatchDepth}}}function isPriorityAsyncDiagnosticEvent(e){return e.metadata.trusted&&Q.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:X,drainBatchSize:100}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=$,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`:normalizeDiagnosticWorkerScript(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:c=!1,privateData:l}=n,u=n.trustedTraceContext===!0,d=Object.freeze({...c?{internal:!0}:{},trusted:t,...n.toolExecutionLiveness?{toolExecutionLiveness:n.toolExecutionLiveness}:{},...n.coreModelRequestLifecycle?{coreModelRequestLifecycle:n.coreModelRequestLifecycle}:{},...n.coreSemanticRunProgress?{coreSemanticRunProgress:n.coreSemanticRunProgress}:{},...u?{trustedTraceContext:u}:{}}),f=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(o),p=a&&(n.queuedPhase||ce.has(o.type));if(p){if(r.asyncQueue.length>=X){if(!t||!Q.has(o.type)){noteAsyncDiagnosticDrop(r,{event:o,metadata:d,privateData:l,hostPluginId:s});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&¬eAsyncDiagnosticDrop(r,e)}let e={event:o,metadata:d,privateData:l,hostPluginId:s};if(!captureQueuedDiagnosticEvent(e,r.trustedListeners.values()))return;o=e.event,r.asyncQueue.push(e)}f&&(p||(o=cloneDiagnosticValueForListener(o,!0)),prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o),d)),p?scheduleAsyncDiagnosticDrain(r):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){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 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{AsyncContext as _,workerScriptName as a,hasInternalDiagnosticEventInterest as b,fsSafeEnvInput as c,resolveEnvironmentKey as d,isDiagnosticFlagEnabled as f,runWithDiagnosticTraceContext as g,normalizeDiagnosticTraceContext as h,emitTrustedDiagnosticEvent as i,normalizeFsSafeNativeEnv as l,getActiveDiagnosticTraceContext as m,emitDiagnosticEvent as n,runWithMainThreadTask as o,parseDiagnosticEnvFlags as p,emitDiagnosticEventWithTrustedTraceContext as r,runInDetachedAsyncContext as s,areDiagnosticsEnabledForProcess as t,captureEnvironmentKey as u,v,runWithAsyncStore as x,ne as y};