UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 41.6 kB
import{n as e}from"./logger-file.worker-global-singleton-Bzg0kLPt.mjs";import{_ as t,a as n,c as r,i,l as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"./logger-file.worker-logger-file-io-NE_bW-lu.mjs";import{b as p,d as m,i as ee,l as te,r as ne,u as re,v as h,y as g}from"./logger-file.worker-sealed-runtime-registry-CXVqyWuw.mjs";import{a as ie,c as ae,f as oe,i as _,l as v,m as y,n as se,p as ce,t as le}from"./logger-file.worker-redact-CIQa-nVB.mjs";import{isMainThread as ue}from"node:worker_threads";import{AsyncLocalStorage as b,AsyncResource as de}from"node:async_hooks";import{createHash as fe,randomUUID as pe}from"node:crypto";import me,{mkdirSync as he}from"node:fs";import ge from"node:os";import x,{dirname as _e}from"node:path";import"node:util";import"node:perf_hooks";import{appendRegularFileSync as ve}from"@openclaw/fs-safe/advanced";import{Logger as ye}from"tslog";function enterAsyncStore(e,t){return this.enterWith(e),t()}function runWithAsyncStore(e,t,n){return e.getStore()===t?n():new de(`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 be=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?be.trustedInterest:be.untrustedInterest;return n.broadInterestCount+(n.eventInterestDeltas.get(e)??0)>0}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 xe=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 Se=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 Se(e)}const S=e(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new b;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)}}});S.invocation;const Ce=S.getFrame;S.runFrame;const C={priority:!1,publicExcluded:!1},w=[{...C,name:`worker.request`},{...C,name:`diagnostic.gc`,publicExcluded:!0},{...C,name:`gateway.event_loop.sample`,publicExcluded:!0},{...C,name:`gateway.main_thread.stall`,publicExcluded:!0},{...C,name:`gateway.http.cancelled`,publicExcluded:!0},{...C,name:`gateway.rpc`,publicExcluded:!0},{...C,name:`sessions.list.baseline.retired`},{...C,name:`sessions.list.retention`,publicExcluded:!0},{...C,name:`sessions.projection.retention`,publicExcluded:!0},{...C,name:`sessions.event.retention`,publicExcluded:!0},{...C,name:`sessions.event.rows.reset`,publicExcluded:!0},{...C,name:`gateway.ws.event`,publicExcluded:!0},{...C,name:`gateway.ws.connections`,publicExcluded:!0},{...C,name:`tool.execution.started`},{...C,name:`tool.execution.completed`,priority:!0},{...C,name:`tool.execution.error`,priority:!0},{...C,name:`tool.execution.blocked`,priority:!0},{...C,name:`skill.used`},{...C,name:`exec.process.completed`},{...C,name:`exec.approval.followup_suppressed`},{...C,name:`message.delivery.started`},{...C,name:`message.delivery.completed`},{...C,name:`message.delivery.error`},{...C,name:`talk.event`},{...C,name:`model.call.started`},{...C,name:`model.call.completed`,priority:!0},{...C,name:`model.call.error`,priority:!0},{...C,name:`model.response.observed`},{...C,name:`run.progress`},{...C,name:`run.execution_phase`},{...C,name:`agent.commentary`},{...C,name:`harness.run.completed`,priority:!0},{...C,name:`harness.run.error`,priority:!0},{...C,name:`context.assembled`},{...C,name:`log.record`,publicExcluded:!0}],we=w.map(e=>e.name),Te=w.filter(e=>e.priority).map(e=>e.name);w.filter(e=>e.publicExcluded).map(e=>e.name);const Ee=/^[0-9a-f]{32}$/,De=/^[0-9a-f]{16}$/,Oe=/^[0-9a-f]{2}$/,ke=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`);function isNonZeroHex(e){return!/^0+$/.test(e)}const Ae=new c(ke);function isValidDiagnosticTraceId(e){return typeof e==`string`&&Ee.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&De.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&Oe.test(e)}function normalizeDiagnosticTraceContext(e){let t=g(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 Ae.getStore()}const T=/* @__PURE__ */ new WeakSet;function cloneDiagnosticValueForListener(e,t=!1){if(T.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return T.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&T.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return T.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(T.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))oe(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 je=/* @__PURE__ */ new WeakSet;function isTrustedOtelDiagnosticListener(e){return je.has(e)}const E=/* @__PURE__ */ new WeakMap;function consumeHostPluginUsageDiagnosticEvent(e){let t=E.get(e);return E.delete(e),t}const D=/* @__PURE__ */ new WeakMap;function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=D.get(e);return D.delete(e),t}const O=e(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new c(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=O.events.get(e);return O.events.delete(e),t}const k=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),A=e(k,()=>({marker:k,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}));function hasDiagnosticTracePropagationConsumer(){return A.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=A.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=A.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 Me=[`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=g(e),n=y(t?.total);return n!==void 0&&n>=0&&(n>0||t?.totalOrigin===`provider-billed`||Me.some(e=>(y(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 r=t?.diagnostics?.flags??[],i=parseDiagnosticEnvFlags(n.OPENCLAW_DIAGNOSTICS),a=i.disablesAll?[]:normalizeUniqueStringEntriesLower([...r,...i.flags]),o=te(e);if(!o)return!1;for(let e of a)if(e===`*`||e===`all`||e===o||e.endsWith(`.*`)&&o===e.slice(0,-2)||e.endsWith(`*`)&&o.startsWith(e.slice(0,-1)))return!0;return!1}const Ne=[`true`,`1`,`yes`,`on`],Pe=[`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=re(e);if(r){if((t.truthy??Ne).includes(r))return!0;if((t.falsy??Pe).includes(r))return!1}}e(Symbol.for(`openclaw.processEnvironmentKey`),()=>({key:{},aliases:new WeakSet([process.env])}));function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}const j=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 b,new b;const Fe=e(Symbol.for(`openclaw.diagnosticsTimelineWriter`),()=>{let e,t,n,r=!1,i=!1,a=/* @__PURE__ */ new Set;function append(e,t){try{let n=_e(e.path);a.has(n)||(he(n,{recursive:!0}),a.add(n)),ve({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:pe(),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>j&&flush(),r||c>j?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&&Fe.write(r,e,n)}const M=Object.freeze({}),N=1e4,P=Symbol.for(`openclaw.diagnosticEvents.state.v1`),Ie=new Set(we),Le=new Set(Te),Re=e(P,()=>({marker:P,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 Re.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=M;if(c?.includePrivateData!==!1&&(n=s?.()??M,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&&Le.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:N,drainBatchSize:100}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=Re,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`:f(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}:{}}),p=t&&!n.queuedPhase&&shouldPrepareDiagnosticTracePropagation(o),m=a&&(n.queuedPhase||Ie.has(o.type));if(m){if(r.asyncQueue.length>=N){if(!t||!Le.has(o.type)){noteAsyncDiagnosticDrop(r,{event:o,metadata:d,privateData:l,hostPluginId:s});return}let e=makeRoomForPriorityAsyncDiagnosticEvent(r);e&&noteAsyncDiagnosticDrop(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)}p&&(m||(o=cloneDiagnosticValueForListener(o,!0)),prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o),d)),m?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}:{}})}const ze=/* @__PURE__ */ new Map,Be=/* @__PURE__ */ new Map;let Ve,F;function isValidTimeZone(e){let t=ze.get(e);if(t!==void 0)return t;let n;try{new Intl.DateTimeFormat(`en`,{timeZone:e}).format(),n=!0}catch{n=!1}return ze.set(e,n),n}function resolveEffectiveTimeZone(e){let t=e??process.env.TZ;return t&&isValidTimeZone(t)?t:Ve??=Intl.DateTimeFormat().resolvedOptions().timeZone}function getTimestampParts(e,t){let n=resolveEffectiveTimeZone(t),r=Math.floor(e.getTime()/1e3);if(F?.second===r&&F.timeZone===n)return F.parts;let i=Be.get(n);i||(i=new Intl.DateTimeFormat(`en`,{timeZone:n,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1,fractionalSecondDigits:3,timeZoneName:`longOffset`}),Be.set(n,i));let a={};for(let t of i.formatToParts(e))a[t.type]=t.value;return F={second:r,timeZone:n,parts:a},a}function formatTimestamp(e,t){let n=t?.style??`medium`,r=getTimestampParts(e,t?.timeZone),i=r.timeZoneName??`GMT`,a=i===`GMT`?`+00:00`:i.slice(3),o=String(e.getUTCMilliseconds()).padStart(3,`0`);switch(n){case`short`:return`${r.hour}:${r.minute}:${r.second}${a}`;case`medium`:return`${r.hour}:${r.minute}:${r.second}.${o}${a}`;case`long`:return`${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}.${o}${a}`}throw Error(`Unsupported timestamp style`)}function formatJsonConsoleLine(e){let t={...e.meta,time:formatTimestamp(/* @__PURE__ */ new Date,{style:`long`}),level:e.level,...e.subsystem?{subsystem:e.subsystem}:{},message:e.message};return JSON.stringify(le(t))}function formatConsoleDiagnosticLine(e){return(h.overrideSettings?.consoleStyle??v()?.consoleStyle)===`json`?formatJsonConsoleLine(e):e.message}function writeConsoleDiagnosticWarning(e){process.stderr.write(`${formatConsoleDiagnosticLine({level:`warn`,message:e})}\n`)}const He=[`silent`,`fatal`,`error`,`warn`,`info`,`debug`,`trace`],Ue={trace:1,debug:2,info:3,warn:4,error:5,fatal:6,silent:1/0};function tryParseLogLevel(e){if(typeof e!=`string`)return;let t=e.trim();return He.includes(t)?t:void 0}function normalizeLogLevel(e,t=`info`){return tryParseLogLevel(e)??t}function levelToMinLevel(e){return Ue[e]}function isLogLevelEnabled(e,t){return e!==`silent`&&t!==`silent`&&levelToMinLevel(e)>=levelToMinLevel(t)}function resolveEnvLogLevelOverride(){let e=m(process.env.OPENCLAW_LOG_LEVEL)??``;if(!e){h.invalidEnvLogLevelValue=null;return}let t=tryParseLogLevel(e);if(t)return h.invalidEnvLogLevelValue=null,t;h.invalidEnvLogLevelValue!==e&&(h.invalidEnvLogLevelValue=e,writeConsoleDiagnosticWarning(`[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${ie(e)}" (allowed: ${He.join(`|`)}).`))}function readParsedField(e,t,n){for(let r of typeof t==`string`?[t]:t){let t=n(e[r]);if(t!==void 0)return t}}const I=e(Symbol.for(`openclaw.processExitCleanup`),()=>({}));function detachEmptyGroup(e){e.pending.size>0||(I.lastGroup===e&&(I.lastGroup=void 0),process.removeListener(`exit`,e.dispatch))}function registerProcessExitCleanup(e){let t={close:e},n=I.lastGroup;if(!n||process.listeners(`exit`).at(-1)!==n.dispatch){let e=/* @__PURE__ */ new Set([t]),r={pending:e,dispatch:()=>{let t=[...e];e.clear(),detachEmptyGroup(r);for(let e of t)try{e.close()}catch{}}};process.on(`exit`,r.dispatch),I.lastGroup=n=r}else n.pending.add(t);let r=n;return()=>{r.pending.delete(t),detachEmptyGroup(r)}}function createLazyPromiseLoader(e,t={}){let n,createPromise=()=>{let r=Promise.resolve().then(e);return t.cacheRejections!==!0&&r.catch(()=>{n===r&&(n=void 0)}),r};return{load(){return n??=createPromise(),n},peek(){return n},clear(){n=void 0}}}function createLazyRuntimeSurface(e,t){let n=createLazyPromiseLoader(()=>e().then(t),{cacheRejections:!0});return Object.assign(n.load,{peek:n.peek,clear:n.clear})}function createLazyRuntimeModule(e){return createLazyRuntimeSurface(e,e=>e)}function createLazyRuntimeNamedExport(e,t){return createLazyRuntimeSurface(e,e=>e[t])}const We=createLazyRuntimeNamedExport(()=>import(`./logger-file.worker-logger-file-worker-BbVvJ_Ga.mjs`).then(e=>e.t),`runFileLogIOInWorker`);async function runFileLogIO(e){return ue?(await We())(e,()=>Y.flush()):await d(e)}function resolveTarget(e,t=!1){let n=e.defaultRoot;if(!n)return t?e.file:Promise.resolve(e.file);if(n.directory!==void 0){let r=x.join(n.directory,e.file);return t?r:Promise.resolve(r)}if(t){let t=l(e.file,n.options);return n.directory=x.dirname(t),t}return(n.resolution??=runFileLogIO({type:`resolveDefault`,file:e.file,root:n.options}).then(e=>n.directory=x.dirname(e)).catch(e=>{throw n.resolution=void 0,e})).then(t=>x.join(t,e.file))}function prepareTarget(e,t){if(e.prepared)return t?void 0:Promise.resolve();if(t)try{o(resolveTarget(e,!0),e.rolling),e.prepared=!0}catch{}else return e.ready??=resolveTarget(e).then(t=>runFileLogIO({type:`prepare`,file:t,rolling:e.rolling})).then(()=>{e.prepared=!0}).catch(()=>{e.ready=void 0})}let L=[],R=0,z=null,B=0,V=0,H=null,U=null,W=null,G=!1,Ge=!1;const K=/* @__PURE__ */ new Map,q=/* @__PURE__ */ new Set;let J=!1;function getCurrentLogFileBytesSync(e){try{return me.statSync(e).size}catch{return 0}}function buildDroppedMarker(e,t){let n=/* @__PURE__ */ new Date,r=`[openclaw] file log queue overflow; dropped ${t} oldest record${t===1?``:`s`}`,i={0:r,_meta:{date:n,hostname:e.hostname,logLevelName:`WARN`,name:`openclaw`},time:formatTimestamp(n,{style:`long`}),hostname:e.hostname,message:r,dropped:t};return{...e,payload:`${JSON.stringify(i)}\n`}}function writeFileTransportWarning(e,t){try{let n=`${formatConsoleDiagnosticLine({level:`warn`,message:_(e)})}\n`;return t?me.writeSync(process.stderr.fd,n):process.stderr.write(n),!0}catch{return!1}}function warnAboutRotationFailure(e,t){K.get(e.file)!==e.maxFileBytes&&(K.set(e.file,e.maxFileBytes),writeFileTransportWarning(`[openclaw] log file rotation failed; continuing writes file=${e.file} maxFileBytes=${e.maxFileBytes}`,t))}function warnAboutAppendFailure(e,t){if(q.has(e.file))return;let n=q.size>=64;n&&J||writeFileTransportWarning(n?`[openclaw] log file append failure diagnostics saturated; suppressing new file targets`:`[openclaw] log file append failed; records dropped; check that the path is a writable regular file; file=${e.file}`,t)&&(n?J=!0:q.add(e.file))}function clearAppendFailure(e){q.delete(e.file)&&(J=!1)}function claimQueuedEntries(){let e=R===0?L:[...L.slice(R),...L.slice(0,R)];return L=[],R=0,V>0&&H&&e.unshift(buildDroppedMarker(H,V)),V=0,H=null,e}function prepareWrite(e,t,n,r,i){let a=Buffer.byteLength(e.payload,`utf8`),o=i+1;if(n)return{payload:e.payload,payloadBytes:a,nextIndex:o};let s=[e.payload];for(;o<r.length;o+=1){let n=r[o];if(!n||n.file!==e.file||n.maxFileBytes!==e.maxFileBytes||n.targetPreparation!==e.targetPreparation)break;let i=Buffer.byteLength(n.payload,`utf8`);if(a+i>65536||t+a+i>e.maxFileBytes)break;s.push(n.payload),a+=i}return{payload:s.join(``),payloadBytes:a,nextIndex:o}}async function writeEntries(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){if(G)return;let r=e[n];if(!r)return;let i;try{i=r.targetPreparation?await resolveTarget(r.targetPreparation):r.file}catch{warnAboutAppendFailure(r,!1),r.payload=``,B=++n;continue}r.targetPreparation&&await prepareTarget(r.targetPreparation,!1);let a=t.get(i);if(!a){if(a={bytes:await runFileLogIO({type:`size`,file:i}).catch(()=>0)},G)return;t.set(i,a)}let o=a.bytes>0&&a.bytes+Buffer.byteLength(r.payload)>r.maxFileBytes,s=prepareWrite(r,o?0:a.bytes,!1,e,n);B=s.nextIndex;try{let e=await runFileLogIO({type:`append`,file:i,payload:s.payload,rotate:o});e.rotation===`rotated`?(a.bytes=0,K.delete(r.file)):e.rotation===`failed`&&warnAboutRotationFailure(r,!1),e.appended?(a.bytes+=s.payloadBytes,clearAppendFailure(r)):warnAboutAppendFailure(r,!1)}catch{t.delete(i),warnAboutAppendFailure(r,!1)}finally{for(let t of e.slice(n,s.nextIndex))t.payload=``;n=s.nextIndex}}}function writeEntriesSync(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){let r=e[n];if(!r)return;let a;try{a=r.targetPreparation?resolveTarget(r.targetPreparation,!0):r.file}catch{warnAboutAppendFailure(r,!0),r.payload=``,n++;continue}let o=t.get(a);o||(o={bytes:getCurrentLogFileBytesSync(a)},t.set(a,o)),r.targetPreparation&&prepareTarget(r.targetPreparation,!0),o.bytes>0&&o.bytes+Buffer.byteLength(r.payload)>r.maxFileBytes&&(i(a)?(o.bytes=0,K.delete(r.file)):warnAboutRotationFailure(r,!0));let s=prepareWrite(r,o.bytes,!0,e,n);try{ve({filePath:a,content:s.payload}),o.bytes+=s.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!0)}r.payload=``,n=s.nextIndex}}async function runFlushLoop(){for(;;){if(G)return;let e=claimQueuedEntries();if(e.length===0)return;z=e,B=0,await writeEntries(e),z=null,B=0}}function startFlush(){if(W||G)return;let e=runFlushLoop().catch(()=>void 0);W=e,e.then(()=>{W=null,(L.length>0||V>0)&&scheduleFlush()})}function scheduleFlush(){U||W||G||(U=setImmediate(()=>{U=null,startFlush()}))}function handleProcessBeforeExit(){flushFileLogQueue()}function handleProcessExit(){G=!0,drainFileLogQueueSync()}function installProcessHooks(){Ge||(Ge=!0,process.on(`beforeExit`,handleProcessBeforeExit),registerProcessExitCleanup(handleProcessExit))}function enqueueFileLog(e){if(G)writeEntriesSync([e]);else{if(installProcessHooks(),L.length>=4096){let t=L[R];t&&(t.payload=``,H??=t,V+=1),L[R]=e,R=(R+1)%L.length}else L.push(e);scheduleFlush()}}async function flushFileLogQueue(){for(;;){U&&=(clearImmediate(U),null),!W&&(L.length>0||V>0)&&startFlush();let e=W;if(!e)return;await e}}function drainFileLogQueueSync(){U&&=(clearImmediate(U),null);let e=z?z.slice(B):[];z=null,B=0,e.push(...claimQueuedEntries()),writeEntriesSync(e)}const Y=e(Symbol.for(`openclaw.fileLogTransport`),()=>(process.env.VITEST!==`true`&&installProcessHooks(),{prepareTarget:(e,t,n=!1)=>({file:e,rolling:t,prepared:!1,...n?{defaultRoot:typeof n==`boolean`?{options:{stateDir:ne()}}:n}:{}}),resolveTarget,drainSync:drainFileLogQueueSync,enqueue:enqueueFileLog,flush:flushFileLogQueue})),X=/^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u;function encodeLogProfileSegment(e){let t=``;for(let n of e)/^[a-z0-9]$/u.test(n)?t+=n:n===`-`?t+=`--`:n===`_`?t+=`-0`:/^[A-Z]$/u.test(n)?t+=`-1${n.toLowerCase()}`:t+=`-2${n.codePointAt(0)?.toString(16)??`0`}-`;return t}function resolveLogProfileSegment(){let e=process.env.OPENCLAW_PROFILE?.trim();if(!e||e.toLowerCase()==="default")return null;let t=encodeLogProfileSegment(e);return t.length<=220?t:`-3${fe(`sha256`).update(e).digest(`hex`)}`}function resolveDefaultRollingLogFileName(){let e=/* @__PURE__ */ new Date,t=resolveLogProfileSegment(),i=t?`-${t}`:``;return`${n}${i}-${r(e)}${s}`}function isLegacyRollingLogFilePath(e){let t=x.basename(e);return t===`openclaw-YYYY-MM-DD.log`||X.exec(t)?.[1]===`openclaw`}function resolveRollingLogFilePathForDate(e,t){let i=X.exec(x.basename(e));return i?x.join(x.dirname(e),`${i[1]}-${r(t)}${s}`):isLegacyRollingLogFilePath(e)?x.join(x.dirname(e),`${n}-${r(t)}${s}`):e}function isSameRollingLogFileFamily(e,t){let n=X.exec(x.basename(e)),r=X.exec(x.basename(t));return!!(n&&r&&n[1]===r[1])}const Ke=`${a}/openclaw.log`,Z=104857600;let Q=null;const $=/^[A-Za-z0-9_.:-]{1,64}$/u;function clampLogText(e,t){return e.length>t?`${ce(e,t)}...(truncated)`:e}function sanitizeDiagnosticLogText(e,t){return clampLogText(_(clampLogText(e,t)),t)}function normalizeDiagnosticLogName(e){if(!e||e.trim().startsWith(`{`))return;let t=sanitizeDiagnosticLogText(e.trim(),120);return $.test(t)?t:void 0}function assignDiagnosticLogAttribute(e,t,n,r){if(t.count>=32)return;let i=n.trim();if(oe(i)||_(i)!==i||!$.test(i))return;let a;if(typeof r==`string`)a=sanitizeDiagnosticLogText(r,2048);else if(typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))a=r;else return;e[i]=a,t.count+=1}function addDiagnosticLogAttributesFrom(e,t,n){if(n)for(let r in n){if(t.count>=32)break;Object.hasOwn(n,r)&&r!==`trace`&&assignDiagnosticLogAttribute(e,t,r,n[r])}}function isPlainLogRecordObject(e){if(!p(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function extractTraceContext(e){return normalizeDiagnosticTraceContext(e)??normalizeDiagnosticTraceContext(g(e)?.trace)}function getSortedNumericLogEntries(e){return Object.entries(e).filter(([e])=>/^\d+$/.test(e)).toSorted((e,t)=>Number(e[0])-Number(t[0]))}function normalizeFileLogContextValue(e){if(typeof e==`string`){let t=e.trim();return t?clampLogText(t,512):void 0}if(typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function readFirstContextString(e,t){for(let n of e){let e=n?readParsedField(n,t,normalizeFileLogContextValue):void 0;if(e)return e}}function resolveLogHostname(){if(Q)return Q;let e=ge.hostname().trim();return e?(Q=e,e):`unknown`}function withResolvedLogMetaHostname(e,t){return p(e)?{...e,hostname:t}:e}function extractLogBindingPrefix(e){if(typeof e[0]==`string`&&e[0].length<=8192&&e[0].trim().startsWith(`{`))try{let t=JSON.parse(e[0]);if(p(t))return{bindings:t,args:e.slice(1)}}catch{}return{args:e}}function resolveLogTraceContext(e,t){for(let n of[e,...t]){let e=extractTraceContext(n);if(e)return{trace:e,trustedTraceContext:!1}}let n=getActiveDiagnosticTraceContext();return n?{trace:n,trustedTraceContext:!0}:{trustedTraceContext:!1}}function prepareFileLogRecord(e){let t=getSortedNumericLogEntries(e),{bindings:n,args:r}=extractLogBindingPrefix(t.map(([,e])=>e)),{trace:i}=resolveLogTraceContext(n,r),a=isPlainLogRecordObject(r[0])?r[0]:void 0,o=[a,n,e],s=a&&typeof a.message!=`string`?1:0,c=t.slice(t.length-r.length+s).map(([e,t])=>{let n={key:e,json:t!=null&&![`string`,`number`,`boolean`,`bigint`].includes(typeof t)&&!(t instanceof Error)&&!(isPlainLogRecordObject(t)&&typeof t.message==`string`)};return typeof t==`number`&&!Number.isFinite(t)&&(n.primitiveText=String(t)),n}),l=readFirstContextString(o,[`agent_id`,`agentId`]),u=readFirstContextString(o,[`session_id`,`sessionId`,`sessionKey`]),d=readFirstContextString(o,[`channel`,`messageProvider`]);return{fields:{hostname:resolveLogHostname(),...l?{agent_id:l}:{},...u?{session_id:u}:{},...d?{channel:d}:{},...i},messageParts:c}}function buildDiagnosticLogRecord(e){let t=e._meta,{bindings:n,args:r}=extractLogBindingPrefix(getSortedNumericLogEntries(e).map(([,e])=>e)),{trace:i,trustedTraceContext:a}=resolveLogTraceContext(n,r),o=r[0],s=isPlainLogRecordObject(o)?o:void 0;s&&r.shift();let c=``;r.length>0&&typeof r[r.length-1]==`string`?c=sanitizeDiagnosticLogText(String(r.pop()),4096):r.length===1&&(typeof r[0]==`number`||typeof r[0]==`boolean`)&&(c=String(r[0]),r.length=0),c||=`log`;let l=Object.create(null),u={count:0};addDiagnosticLogAttributesFrom(l,u,n),addDiagnosticLogAttributesFrom(l,u,s);let d={};if(t?.path?.fileLine){let e=Number(t.path.fileLine);Number.isFinite(e)&&(d.line=e)}t?.path?.method&&(d.functionName=sanitizeDiagnosticLogText(t.path.method,120));let f=normalizeDiagnosticLogName(t?.name),p=t?.parentNames?.map(normalizeDiagnosticLogName).filter(e=>!!e);return{event:{type:`log.record`,level:t?.logLevelName??`INFO`,message:c,...f?{loggerName:f}:{},...p?.length?{loggerParents:p}:{},...Object.keys(l).length>0?{attributes:l}:{},...Object.keys(d).length>0?{code:d}:{},...i?{trace:i}:{}},trustedTraceContext:a}}function attachDiagnosticEventTransport(e){e.attachTransport({format:()=>``,write:e=>{if(areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`log.record`))try{let t=buildDiagnosticLogRecord(se(e));(t.trustedTraceContext?emitDiagnosticEventWithTrustedTraceContext:emitDiagnosticEvent)(t.event)}catch{}}})}function canUseSilentVitestFileLogFastPath(e){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`&&!e&&!h.overrideSettings}function resolveDefaultActiveLogFile(){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG===`1`?x.join(process.cwd(),`.artifacts`,`test-logs`,`${n}-vitest-${process.pid}-${r(/* @__PURE__ */ new Date)}${s}`):resolveDefaultRollingLogFileName()}function resolveSettings(){if(!u())return{level:`silent`,file:Ke,maxFileBytes:Z,rolling:!1};let e=resolveEnvLogLevelOverride();if(canUseSilentVitestFileLogFastPath(e))return{level:`silent`,file:resolveDefaultRollingLogFileName(),maxFileBytes:Z,rolling:!0,defaultRoot:!0};let t=h.overrideSettings??v(),n=process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`?`silent`:`info`,r=normalizeLogLevel(t?.level,n),i=e??r,a=!t?.file||isLegacyRollingLogFilePath(t.file);return{level:i,file:resolveActiveLogFileWithMode(t?.file??resolveDefaultActiveLogFile(),a),maxFileBytes:resolveMaxLogFileBytes(t?.maxFileBytes),rolling:a,defaultRoot:!t?.file&&(process.env.VITEST!==`true`||process.env.OPENCLAW_TEST_FILE_LOG!==`1`)}}function getRuntimeFileTarget(e){let t=resolveActiveLogFileWithMode(e.file,e.rolling);return e.target?.file!==t&&(e.target=Y.prepareTarget(t,e.rolling,e.target?.defaultRoot??e.defaultRoot)),e.target}async function getResolvedLoggerFileTarget(){let e=getRuntimeFileTarget(getRuntimeSettings());return{file:await Y.resolveTarget(e),rolling:e.rolling}}function getRuntimeSettings(){let e=h.cachedSettings??resolveSettings();return h.cachedSettings=e,e}function isFileLogLevelEnabled(e){return isLogLevelEnabled(e,getRuntimeSettings().level)}function inheritLogLevel(e,t){let resolveLevel=t;Object.defineProperty(e.settings,"minLevel",{configurable:!0,enumerable:!0,get:()=>resolveLevel(),set:e=>{resolveLevel=()=>e}})}var RuntimeLogger=class extends ye{getSubLogger(e,t){let n=e?.minLevel??this.settings.minLevel,r=super.getSubLogger({...e,minLevel:n===1/0?levelToMinLevel(`fatal`):n},t);return e?.minLevel==null?inheritLogLevel(r,()=>this.settings.minLevel):n===1/0&&(r.settings.minLevel=n),r}};function initializeLoggerSourceMapPolicy(){typeof process<`u`&&process.env&&(process.env.TSLOG_SOURCE_MAPS??=`off`)}function buildLogger(){initializeLoggerSourceMapPolicy();let e=new RuntimeLogger({name:`openclaw`,mask:{keys:[]},meta:{property:`_meta`},minLevel:levelToMinLevel(`fatal`),type:`hidden`});return inheritLogLevel(e,()=>levelToMinLevel(getRuntimeSettings().level)),e.attachTransport({format:()=>``,write:e=>{try{let t=getRuntimeSettings();if(t.level===`silent`)return;let n=getRuntimeFileTarget(t),r=formatTimestamp(e.date??/* @__PURE__ */ new Date,{style:`long`}),{fields:i,messageParts:a}=prepareFileLogRecord(e),o=ae({...e,_meta:withResolvedLogMetaHostname(e._meta,i.hostname),time:r,...i},a);Y.enqueue({file:n.file,targetPreparation:n,hostname:i.hostname,maxFileBytes:t.maxFileBytes,payload:`${o}\n`})}catch{}}}),attachDiagnosticEventTransport(e),e}function resolveMaxLogFileBytes(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):Z}function getLogger(){let e=h.cachedLogger;if(e)return e;getRuntimeSettings();let t=buildLogger();return h.cachedLogger=t,t}function getChildLogger(e,t){let n=getLogger(),r=e?JSON.stringify(e):void 0;return n.getSubLogger({name:r,prefix:e?[r??``]:[],...t?.level?{minLevel:levelToMinLevel(t.level)}:{}})}function resolveActiveLogFileWithMode(e,t){let n=ee(e);return t?resolveRollingLogFilePathForDate(n,/* @__PURE__ */ new Date):n}export{xe as _,createLazyRuntimeModule as a,isLogLevelEnabled as c,formatTimestamp as d,areDiagnosticsEnabledForProcess as f,Ce as g,parseDiagnosticEnvFlags as h,isSameRollingLogFileFamily as i,normalizeLogLevel as l,isDiagnosticFlagEnabled as m,getResolvedLoggerFileTarget as n,registerProcessExitCleanup as o,emitTrustedDiagnosticEvent as p,isFileLogLevelEnabled as r,resolveEnvLogLevelOverride as s,getChildLogger as t,formatJsonConsoleLine as u,hasInternalDiagnosticEventInterest as v,runWithAsyncStore as y};