UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

17 lines • 158 kB
import{n as e,t}from"./git-operation.worker-record-coerce-B9rMjEA7.mjs";import{a as n,i as r,o as i,t as a}from"./git-operation.worker-src-D09IpTfC.mjs";import"./git-operation.worker-path-guards-B3dt-SRh.mjs";import{createRequire as o}from"node:module";import{AsyncLocalStorage as s,AsyncResource as c}from"node:async_hooks";import l from"node:fs/promises";import u,{basename as d,dirname as f}from"node:path";import"node:util";import{Chalk as p}from"chalk";import{createHash as m,randomUUID as h}from"node:crypto";import g,{mkdirSync as _}from"node:fs";import{performance as ee}from"node:perf_hooks";import{appendRegularFile as te,appendRegularFileSync as v,canUseRootFileOpen as ne,openRootFileSync as re}from"@openclaw/fs-safe/advanced";import{fileURLToPath as ie}from"node:url";import"@openclaw/fs-safe/errors";import{hasNodeErrorCode as ae,hasNodeErrorCode as oe,isNotFoundPathError as se,isPathInside as ce}from"@openclaw/fs-safe/path";import y from"node:os";import{channel as le}from"node:diagnostics_channel";import{isMainThread as ue,threadId as de}from"node:worker_threads";import{Logger as fe}from"tslog";var pe=Object.defineProperty,__exportAll=(e,t)=>{let n={};for(var r in e)pe(n,r,{get:e[r],enumerable:!0});return t||pe(n,Symbol.toStringTag,{value:`Module`}),n};const me=Symbol.for(`openclaw.provider-auth-persistence-error`);function isProviderAuthPersistenceError(e){try{return me in e&&e[me]===!0}catch{return!1}}function isErrorObject(e){try{return e instanceof Error||Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function isAggregateErrorObject(e){try{if(e instanceof AggregateError)return!0;for(let t=Object.getPrototypeOf(e);t;t=Object.getPrototypeOf(t)){let e=Object.getOwnPropertyDescriptor(t,`constructor`)?.value;if(typeof e==`function`&&e.name===`AggregateError`)return!0}}catch{}return!1}function readProperty(e,t){try{return e[t]}catch{return}}function readErrorText(e,t){let n=readProperty(e,t);return typeof n==`string`?n:void 0}function formatStatusAndCode(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return;try{if(Object.keys(e).some(e=>e!==`status`&&e!==`code`))return}catch{}let t=readProperty(e,`status`),n=readProperty(e,`code`);if(t!==void 0||n!==void 0)return`status=${typeof t==`string`||typeof t==`number`?String(t):`unknown`} code=${typeof n==`string`||typeof n==`number`?String(n):`unknown`}`}function stringifyUnknown(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)return String(e);try{let t=JSON.stringify(e);if(t!==void 0)return t}catch{}try{return Object.prototype.toString.call(e)}catch{return`Unknown error`}}function readErrorCauses(e){if(!isErrorObject(e))return[];let t=readProperty(e,`cause`),n=isAggregateErrorObject(e)?readProperty(e,`errors`):void 0,r=isProviderAuthPersistenceError(e)?[readProperty(e,`persistenceError`),readProperty(e,`cleanupError`)]:[],i=readErrorText(e,`name`)===`SuppressedError`?[readProperty(e,`error`),readProperty(e,`suppressed`)].map(e=>e??String(e)):[];return[...r,t||void 0,...Array.isArray(n)?n:[],...i]}function formatErrorMessage(e,t={}){let n;if(isErrorObject(e)){n=readErrorText(e,`message`)||readErrorText(e,`name`)||`Error`;let r=/* @__PURE__ */ new Set([n]),appendCauseMessage=e=>{e&&!r.has(e)&&(n+=` | ${e}`,r.add(e))};if(t.includeCode){let t=readProperty(e,`code`);(typeof t==`string`||typeof t==`number`)&&appendCauseMessage(String(t))}let i=collectErrorGraphCandidates(e,readErrorCauses);for(let e of i.slice(1))if(isErrorObject(e)){let t=readErrorText(e,`message`);t&&n.includes(t)?r.add(t):appendCauseMessage(t);let i=readProperty(e,`code`);(typeof i==`string`||typeof i==`number`)&&appendCauseMessage(String(i))}else appendCauseMessage(typeof e==`string`?e:formatStatusAndCode(e)??stringifyUnknown(e))}else n=formatStatusAndCode(e)??stringifyUnknown(e);return t.redact?t.redact(n):n}function formatErrorStackWithMessage(e){let t=readErrorText(e,`name`)||`Error`,n=readErrorText(e,`message`)??``,r=readProperty(e,`stack`);if(typeof r!=`string`||!r)return n||t;if(!n||r.includes(n))return r;let i=`${t}: ${n}`,a=r.indexOf(`
`),o=a<0?r:r.slice(0,a);return o===t?i+r.slice(o.length):`${i}\n${r}`}function toErrorObject(e,t){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);let n=Error(t,{cause:e});return(typeof e==`object`&&e||typeof e==`function`)&&Object.assign(n,e),n}function extractErrorCode(e){if(!e||typeof e!=`object`)return;let t=readProperty(e,`code`);return typeof t==`string`||typeof t==`number`?String(t):void 0}function collectErrorGraphCandidates(e,t){if(e==null)return[];let n=[e],r=(/* @__PURE__ */ new Set()).add(e);for(let e of n)if(e&&typeof e==`object`&&t)for(let i of t(e))i!=null&&!r.has(i)&&(r.add(i),n.push(i));return n}function collectNestedErrorCandidates(e){return collectErrorGraphCandidates(e,e=>{let t=[readProperty(e,`cause`),readProperty(e,`reason`),readProperty(e,`original`),readProperty(e,`error`),readProperty(e,`suppressed`),readProperty(e,`data`)],n=readProperty(e,`errors`);return Array.isArray(n)&&t.push(...n),t})}const he=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]];RegExp(`[${he.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),(()=>{let e=Math.max(...he.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,n]of he.entries())for(let[r,i]of n)t.fill(e+1,r,i+1);return t})();function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}function normalizeNullableString(e){return typeof e==`string`&&e.trim()||null}function normalizeOptionalString(e){return normalizeNullableString(e)??void 0}function normalizeOptionalLowercaseString(e){return normalizeOptionalString(e)?.toLowerCase()}function normalizeLowercaseStringOrEmpty(e){return normalizeOptionalLowercaseString(e)??``}function asFiniteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function asPositiveFiniteNumber(e){let t=asFiniteNumber(e);return t&&t>0?t:void 0}const ge=2147e6;function clampTimerTimeoutMs(e,t=1){let n=asFiniteNumber(e);if(n!==void 0)return Math.min(Math.max(Math.floor(n),Math.max(1,Math.floor(t))),ge)}function clampPositiveTimerTimeoutMs(e){let t=asFiniteNumber(e);if(!(t===void 0||t<=0))return clampTimerTimeoutMs(t)}function resolveTimerTimeoutMs(e,t,n=1){let r=asFiniteNumber(e)??asFiniteNumber(t),i=Math.max(0,Math.floor(n));return r===void 0?i:Math.min(Math.max(Math.floor(r),i),ge)}function resolveIntegerOption(e,t,n={}){let r=asFiniteNumber(e)??t,i=Math.floor(r),a=n.min===void 0?i:Math.max(n.min,i);return n.max===void 0?a:Math.min(n.max,a)}function resolveOptionalIntegerOption(e,t={}){if(typeof e==`number`&&Number.isFinite(e))return resolveIntegerOption(e,e,t)}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))}function isHighSurrogate(e){return e>=55296&&e<=56319}function isLowSurrogate(e){return e>=56320&&e<=57343}function sliceUtf16Safe(e,t,n){let r=e.length,i=t<0?Math.max(r+t,0):Math.min(t,r),a=n===void 0?r:n<0?Math.max(r+n,0):Math.min(n,r);return a<=i?``:(i>0&&i<r&&isLowSurrogate(e.charCodeAt(i))&&isHighSurrogate(e.charCodeAt(i-1))&&(i+=1),a>0&&a<r&&isHighSurrogate(e.charCodeAt(a-1))&&isLowSurrogate(e.charCodeAt(a))&&--a,e.slice(i,a))}function truncateUtf16Safe(e,t){let n=Math.max(0,Math.floor(t));return e.length<=n?e:sliceUtf16Safe(e,0,n)}function isVerbose(){return!1}const _e=Symbol.for(`openclaw.globalSingletonLifecycleResets`);function resolveGlobalSingletonResetRegistry(){let e=globalThis,t=e[_e];if(t instanceof Map)return t;let n=/* @__PURE__ */ new Map;return e[_e]=n,n}function resolveGlobalSingleton(e,t,n,r=`close-and-restart`){let i=globalThis,a;return Object.hasOwn(i,e)?a=i[e]:(a=t(),i[e]=a),n&&resolveGlobalSingletonResetRegistry().set(e,{lifecycle:r,reset:()=>n(a)}),a}function resolveGlobalMap(e,t,n){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Map,typeof t==`string`?e=>e.clear():t,typeof t==`string`?t:n)}function resolveGlobalSet(e,t){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Set,e=>e.clear(),t)}const ve=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=!1){let n=t?ve.trustedInterest:ve.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 c(`OpenClawAsyncStore`).runInAsyncScope(enterAsyncStore,e,t,n)}var ye=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(){}withScopes(e){return new InvocationFrame(e)}};function createPluginExecutionFrame(e,t){return t?t.withScopes(e):new ye(e)}const be=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceInvocation`),()=>{let e=new s;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)}}});be.invocation;const xe=be.getFrame;be.runFrame;const b={priority:!1,publicExcluded:!1},Se=[{...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.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}],Ce=Se.map(e=>e.name),we=Se.filter(e=>e.priority).map(e=>e.name);Se.filter(e=>e.publicExcluded).map(e=>e.name);const x=resolveGlobalSingleton(Symbol.for(`openclaw.asyncContext`),()=>new s);var AsyncContext=class{constructor(e){this.key=e}getStore(){return x.getStore()?.[this.key]}run(e,t){let n=x.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};x.enterWith(i);try{return t()}finally{let e=x.getStore();x.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){x.enterWith({...x.getStore(),[this.key]:e})}};const Te=/^[0-9a-f]{32}$/,Ee=/^[0-9a-f]{16}$/,De=/^[0-9a-f]{2}$/,Oe=Symbol.for(`openclaw.diagnosticTraceScope.state.v1`);function isNonZeroHex(e){return!/^0+$/.test(e)}const ke=new AsyncContext(Oe);function isValidDiagnosticTraceId(e){return typeof e==`string`&&Te.test(e)&&isNonZeroHex(e)}function isValidDiagnosticSpanId(e){return typeof e==`string`&&Ee.test(e)&&isNonZeroHex(e)}function isValidDiagnosticTraceFlags(e){return typeof e==`string`&&De.test(e)}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 ke.getStore()}function runWithDiagnosticTraceContext(e,t){return runWithAsyncStore(ke,e===void 0?void 0:freezeDiagnosticTraceContext(e),t)}const Ae=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]);function isBlockedObjectKey(e){return Ae.has(e)}const S=/* @__PURE__ */ new WeakSet;function cloneDiagnosticValueForListener(e,t=!1){if(S.has(e))return e;if(t&&Object.getOwnPropertySymbols(e).length===0&&Object.values(e).every(e=>isImmutableDiagnosticValue(e)))return S.add(e),Object.freeze(e);let n=structuredClone(e);return freezeDiagnosticValue(n,/* @__PURE__ */ new WeakSet)&&S.add(n),n}function createDiagnosticValueForListeners(e,t=!1){let n;return()=>{if(n)return n;let r=cloneDiagnosticValueForListener(e,t);return S.has(r)&&(n=r),r}}function isImmutableDiagnosticValue(e,t){if(!e||typeof e!=`object`)return typeof e!=`function`&&typeof e!=`symbol`;if(S.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))isBlockedObjectKey(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 Me=/* @__PURE__ */ new WeakMap;function consumeHostPluginUsageDiagnosticEvent(e){let t=Me.get(e);return Me.delete(e),t}const Ne=/* @__PURE__ */ new WeakMap;function consumeCoreSemanticRunProgressDiagnosticEvent(e){let t=Ne.get(e);return Ne.delete(e),t}const Pe=resolveGlobalSingleton(Symbol.for(`openclaw.diagnosticToolExecutionLiveness`),()=>({context:new AsyncContext(Symbol(`toolExecutionDeadline`)),events:/* @__PURE__ */ new WeakMap}));function consumeToolExecutionLivenessDiagnosticEvent(e){let t=Pe.events.get(e);return Pe.events.delete(e),t}const Fe=Symbol.for(`openclaw.diagnosticTracePropagation.state.v1`),Ie=resolveGlobalSingleton(Fe,()=>({marker:Fe,bridges:/* @__PURE__ */ new Set,activeBridge:void 0}));function hasDiagnosticTracePropagationConsumer(){return Ie.activeBridge?.prepareEvent!==void 0}function shouldPrepareDiagnosticTracePropagation(e){let t=Ie.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=Ie.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 Le=[`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=t(e),r=asFiniteNumber(n?.total);return r!==void 0&&r>=0&&(r>0||n?.totalOrigin===`provider-billed`||Le.some(e=>(asFiniteNumber(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 r=t?.diagnostics?.flags??[],i=parseDiagnosticEnvFlags(n.OPENCLAW_DIAGNOSTICS),a=i.disablesAll?[]:normalizeUniqueStringEntriesLower([...r,...i.flags]),o=normalizeLowercaseStringOrEmpty(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 Re=[`true`,`1`,`yes`,`on`],ze=[`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=normalizeOptionalLowercaseString(e);if(r){if((t.truthy??Re).includes(r))return!0;if((t.falsy??ze).includes(r))return!1}}function isTruthyEnvValue(e){return parseBooleanValue(e)===!0}const Be=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`),Ve=Be?resolveGlobalSingleton(Symbol.for(`openclaw.detachedAsyncContext`),()=>new Be.AsyncResource(`openclaw.detached-async-context`)):void 0;function runInDetachedAsyncContext(e){return Ve?Ve.runInAsyncScope(e):e()}const He=resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new s}));function runWithMainThreadTask(e,t,n){let r=He.observer;return r?r.run(e,t,n):t()}const Ue=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 s,new s;const We=resolveGlobalSingleton(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)||(_(n,{recursive:!0}),a.add(n)),v({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:h(),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>Ue&&flush(),r||c>Ue?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&&We.write(r,e,n)}const Ge={managedHandoff:{ownerSource:`src/infra/update-managed-service-handoff-sealed.ts`,entries:[[`postgresBridge`,`managedHandoffPostgresBridge`]]},worker:{ownerSource:`src/worker/worker-deploy-runtime.ts`,entries:[[`clientCredentials`,`client-credential.worker`],[`codeModeNode`,`code-mode-node.worker`],[`stateRead`,`openclaw-state-read.worker`],[`workerNativeLifecycle`,`worker-native-lifecycle.worker`],[`fileToolPlanning`,`file-tool-planning.worker`],[`fileToolRead`,`file-tool-read.worker`],[`gatewayStateOwnerHeartbeat`,`gateway-state-owner-heartbeat.worker`],[`githubExec`,`github-exec-launcher`],[`imageProcessor`,`image-processor.worker`],[`serviceChildRelay`,`service-child-relay`],[`sqliteSourceRevision`,`sqlite-source-revision.worker`],[`sqliteStore`,`sqlite-store.worker`],[`sharedStateStore`,`sqlite-store.worker`]]},serviceChildRelay:{ownerSource:`src/process/supervisor/service-child-relay.ts`,entries:[[`serviceChildGroupAnchor`,`service-child-group-anchor`]]}},scriptBasename=e=>d(e).replace(/\.[cm]?[jt]s$/u,`.js`),Ke=n(import.meta.url),C=/* @__PURE__ */ new Map;for(let e of Object.values(Ke)){let t=scriptBasename(e.distWorkerPath);C.set(t,t),C.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(i)){let t=scriptBasename(e.distWorkerPath);C.set(t,t),C.set(scriptBasename(e.package.distWorkerPath),t),C.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(Ge))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);C.has(e)||C.set(e,scriptBasename(Ke[t].distWorkerPath))}const qe=new Set(C.values());function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&qe.has(e)?e:`other`}function workerScriptName(e,t=!1){return t||e instanceof URL&&e.protocol!==`file:`?`other`:C.get(scriptBasename(e instanceof URL?ie(e):e))??`other`}const Je=Object.freeze({}),Ye=1e4,Xe=Symbol.for(`openclaw.diagnosticEvents.state.v1`),Ze=new Set(Ce),Qe=new Set(we),$e=resolveGlobalSingleton(Xe,()=>({marker:Xe,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 $e.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}`);else{e.dispatchDepth+=1;try{let a=createDiagnosticValueForListeners(t,!0),o=r&&createDiagnosticValueForListeners(r);if(!i.trustedListenersOnly){for(let[r,i]of e.listeners)if(isInternalDiagnosticEventInterested(i,t.type,n.trusted))try{r(a(),n)}catch(e){let n=e instanceof Error?formatErrorStackWithMessage(e):String(e);console.error(`[diagnostic-events] listener error type=${t.type} seq=${t.seq}: ${n}`)}}for(let[r,s]of e.trustedListeners)if(isInternalDiagnosticEventInterested(s,t.type,n.trusted))try{let e=a(),t=isTrustedOtelDiagnosticListener(r),c=Je;if(s?.includePrivateData!==!1&&(c=o?.()??Je,t&&(i.hostPluginId||Object.hasOwn(c,`hostPluginId`)))){let e={...c,hostPluginId:i.hostPluginId};i.hostPluginId||Reflect.deleteProperty(e,`hostPluginId`),c=Object.freeze(e)}r(e,n,c)}catch(e){let 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}}}function isPriorityAsyncDiagnosticEvent(e){return e.metadata.trusted&&Qe.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:Ye,drainBatchSize:100}),Object.freeze({internal:!0,trusted:!1}))}function emitDiagnosticEventWithTrust(e,t,n={}){let r=$e,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||Ze.has(o.type));if(p){if(r.asyncQueue.length>=Ye){if(!t||!Qe.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)}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}:{}})}const et=Symbol.for(`openclaw.loggingState`);function createUnownedAppliedLoggingConfig(){return`unowned`}function createLoggingState(){return{appliedConfig:createUnownedAppliedLoggingConfig(),cachedLogger:null,cachedSettings:null,cachedConsoleSettings:null,overrideSettings:null,invalidEnvLogLevelValue:null,consolePatched:!1,forceConsoleToStderr:!1,earlyConsoleRoutingRestore:null,consoleTimestampPrefix:!1,consoleSubsystemFilter:null,streamErrorHandlersInstalled:!1,rawConsole:null}}const tt=globalThis,w=tt[et]??createLoggingState();tt[et]=w;function shouldEmitRuntimeLog(e=process.env){return e.VITEST!==`true`||e.OPENCLAW_TEST_RUNTIME_LOG===`1`||typeof console.log.mock==`object`}function shouldEmitRuntimeStdout(e=process.env){return e.VITEST!==`true`||e.OPENCLAW_TEST_RUNTIME_LOG===`1`||typeof process.stdout.write.mock==`object`}function isPipeClosedError(e){let t=e?.code;return t===`EPIPE`||t===`EIO`}function writeStdout(e){if(!shouldEmitRuntimeStdout())return;let t=e.endsWith(`
`)?e:`${e}\n`;try{process.stdout.write(t)}catch(e){if(isPipeClosedError(e))return;throw e}}function createRuntimeIo(){return{log:(...e)=>{shouldEmitRuntimeLog()&&console.log(...e)},error:(...e)=>{console.error(...e)},writeStdout,writeJson:(e,t=2)=>{writeStdout(JSON.stringify(e,void 0,t>0?t:void 0))}}}({...createRuntimeIo()});const nt=`(?:\\x1b\\]|\\x9d)`,rt=`(?:\\x1b\\\\|\\x07|\\x9c)`,it=RegExp(`${nt}[^\\x07\\x1b\\x9c]*${rt}`,`y`);function matchAnsiOscAt(e,t){return it.lastIndex=t,it.exec(e)?.[0]}function scanAnsiCsiAt(e,t){let n=e.charCodeAt(t);if(n!==155&&(n!==27||e.charCodeAt(t+1)!==91))return;let r=t+(n===155?1:2),i=[],a=!1;for(;r<e.length;){let t=e.charCodeAt(r);if(t===24||t===26){r+=1,a=!0;break}if(t===27||t===155){a=!0;break}if(t<=31||t===127)i.push(e.charAt(r)),r+=1;else if(t>=32&&t<=63)r+=1;else{t>=64&&t<=126&&(r+=1),a=!0;break}}return{controls:i,ended:a,value:e.slice(t,r)}}const at=RegExp(`${`${nt}[\\s\\S]*?${rt}`}|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,`y`);new Intl.Segmenter(void 0,{granularity:`grapheme`});function hasAnsiIntroducer(e){return e.includes(`\x1B`)||e.includes(`›`)||e.includes(``)}function stripAnsiInternal(e,t){if(!hasAnsiIntroducer(e))return e;let n=[],r=0,i=0;for(;i<e.length;){let a=e.charCodeAt(i);if(a!==27&&a!==155&&a!==157){i+=1;continue}let o=matchAnsiOscAt(e,i),s=o?void 0:scanAnsiCsiAt(e,i);at.lastIndex=i;let c=!o&&t.compatibilityGrammar?at.exec(e)?.[0]:void 0,l=o?.length??s?.value.length??c?.length;if(l===void 0)i+=1;else{if(s&&!s.ended&&t.preserveIncompleteCsi)break;s?.controls.length===0&&c&&(l=Math.max(l,c.length)),n.push(e.slice(r,i),...s?.controls??[]),i+=l,r=i}}return n.push(e.slice(r)),n.join(``)}function stripAnsi(e){return stripAnsiInternal(e,{compatibilityGrammar:!1})}resolveGlobalSingleton(Symbol.for(`openclaw.signalExitOwner`),()=>({})),resolveGlobalSet(Symbol.for(`openclaw.signalExitBarriers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitGates`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitFinalizers`),`close-and-restart`),resolveGlobalSet(Symbol.for(`openclaw.signalExitObservers`),`close-and-restart`),resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStartupSignals`),()=>({}));function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.prototype.toString.call(e)===`[object Object]`}let ot;function isJson5Parser(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`}function setJson5Runtime(e){let t=isJson5Parser(e)?e:typeof e==`object`&&e&&`default`in e?e.default:void 0;if(!isJson5Parser(t))throw Error(`json5 parser unavailable`);return ot=t,t}function loadJson5Parser(){if(ot)return ot;if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed JSON5 runtime was not registered before use`);return setJson5Runtime(o(import.meta.url)(`json5`))}function parseJsonWithJson5Fallback(e,t){try{return JSON.parse(e)}catch{return(t??loadJson5Parser()).parse(e)}}function appendConfigPathSegment(e,t){return typeof t==`number`?`${e}[${t}]`:/^[A-Za-z_$][A-Za-z0-9_$:-]*$/.test(t)?e?`${e}.${t}`:t:`${e}[${JSON.stringify(t)}]`}const st=/^\$\{([A-Z][A-Z0-9_]{0,127})\}$/,ct=/^\$([A-Z][A-Z0-9_]{0,127})$/;function parseEnvTemplateSecretRef(e,t=`default`){if(typeof e!=`string`)return null;let n=e.trim(),r=st.exec(n)??ct.exec(n);return r?{source:`env`,provider:t.trim()||`default`,id:expectDefined(r[1],`types.secrets regex capture 1`)}:null}const lt=/^[A-Z_][A-Z0-9_]*$/;var MissingEnvVarError=class extends Error{constructor(e,t){super(`Missing env var "${e}" referenced at config path: ${t}`),this.varName=e,this.configPath=t,this.name=`MissingEnvVarError`}};function renderEnvTemplateToken(e){return e.defaultValue===void 0?`\${${e.name}}`:`\${${e.name}:-${e.defaultValue}}`}function*iterateEnvTemplateTokens(e){for(let t=e.indexOf(`$`);t!==-1;t=e.indexOf(`$`,t+1)){let n=e[t+1]===`$`&&e[t+2]===`{`;if(!n&&e[t+1]!==`{`)continue;let r=t+(n?3:2),i=e.indexOf(`}`,r);if(i===-1)continue;let a=e.slice(r,i),o=a.indexOf(`:-`),s=o===-1?a:a.slice(0,o),c=o===-1?void 0:a.slice(o+2);!lt.test(s)||c?.includes(`$`)||c?.includes(`{`)||(yield{kind:n?`escaped`:`substitution`,name:s,defaultValue:c,start:t,end:i},t=i)}}function substituteString(e,t,n,r){if(!e.includes(`$`))return e;let i=parseEnvTemplateSecretRef(e);i&&!containsEnvVarReference(e)&&r?.onPendingEnvSecretRef?.(i.id,n);let a=[],o=0;for(let s of iterateEnvTemplateTokens(e)){if(a.push(e.slice(o,s.start)),o=s.end+1,s.kind===`escaped`){a.push(renderEnvTemplateToken(s));continue}let c=t[s.name];if(c===void 0||c===``){if(s.defaultValue!==void 0){a.push(s.defaultValue);continue}if(r?.onMissing){r.onMissing({varName:s.name,configPath:n}),i?.id===s.name&&r.onPendingEnvSecretRef?.(s.name,n),a.push(renderEnvTemplateToken(s));continue}throw new MissingEnvVarError(s.name,n)}i?.id===s.name&&r?.onResolvedEnvSecretRef?.(s.name,n),a.push(c)}return a.push(e.slice(o)),a.join(``)}function containsEnvVarReference(e){for(let t of iterateEnvTemplateTokens(e))if(t.kind===`substitution`)return!0;return!1}function resolveConfigEnvVars(e,t=process.env,n){let r=[],visit=(e,i)=>{if(typeof e==`string`)return substituteString(e,t,i,n);if(Array.isArray(e)){let t=e.length,n=[];n.length=t;let a=0;return r.push(()=>{for(;a<t;){let t=a++;if(t in e)return n[t]=visit(e[t],`${i}[${t}]`),!0}return!1}),n}if(isPlainObject(e)){let t={},n=Object.entries(e)[Symbol.iterator]();return r.push(()=>{let e=n.next();if(e.done)return!1;let[r,a]=e.value;return t[r]=visit(a,appendConfigPathSegment(i,r)),!0}),t}return e},i=visit(e,``);for(let e=r.at(-1);e;e=r.at(-1))e()||r.pop();return i}function isMissingPathError(e){return oe(e,`ENOENT`)||oe(e,`ENOTDIR`)||oe(e,`not-found`)}function realpathExistingAncestorSync(e){let t=[],n=e;for(;;)try{return u.join(g.realpathSync.native(n),...t.toReversed())}catch{let e=u.dirname(n);if(e===n)return;t.push(u.basename(n)),n=e}}async function lstatIfExists(e,t=`ENOENT_OR_ENOTDIR`){try{return await l.lstat(e)}catch(e){if(t===`ENOENT`?ae(e,`ENOENT`):se(e))return;throw e}}function canAccessSync(e,t){try{return g.accessSync(e,t),!0}catch{return!1}}s.snapshot();function resolveIdentityPathViaExistingAncestorSync(e){let t=u.resolve(e);return realpathExistingAncestorSync(t)??t}function sanitizePlainObject(e){let t={};for(let[n,r]of Object.entries(e))isBlockedObjectKey(n)||(t[n]=isPlainObject(r)?sanitizePlainObject(r):r);return t}function mergeDeep(e,t,n={}){let r=n.arrays??`replace`,i=n.undefinedValues??`skip`;if(Array.isArray(e)&&Array.isArray(t))return r===`concat`?[...e,...t]:t;if(!isPlainObject(e)||!isPlainObject(t))return t===void 0&&i===`skip`?e:t;let a=sanitizePlainObject(e);for(let[e,o]of Object.entries(t)){if(isBlockedObjectKey(e)||o===void 0&&i===`skip`)continue;let t=a[e];a[e]=isPlainObject(o)?isPlainObject(t)?mergeDeep(t,o,n):sanitizePlainObject(o):r===`concat`&&Array.isArray(t)&&Array.isArray(o)?[...t,...o]:o}return a}function normalizeHomeDirValue(e){let t=e?.trim();return t&&t!==`undefined`&&t!==`null`?t:void 0}function normalizeSafe(e){try{return normalizeHomeDirValue(e())}catch{return}}function resolveTermuxHome(e){let t=normalizeHomeDirValue(e.PREFIX);if(t&&normalizeHomeDirValue(e.ANDROID_DATA)&&/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu,`/`)))return u.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=y.homedir){let n=resolveRawOsHomeDir(e,t);return n?u.resolve(n):void 0}function resolveEffectiveHomeDir(e=process.env,t=y.homedir,n){let r=normalizeHomeDirValue(e.OPENCLAW_HOME);if(!r)return resolveOsHomeDir(e,t);if(r===`~`||r.startsWith(`~/`)||r.startsWith(`~\\`)){let i=resolveRawOsHomeDir(e,t);return i?u.resolve(r.replace(/^~(?=$|[\\/])/,()=>i)):n?.preserveUnresolvedTilde?u.resolve(r):void 0}return u.resolve(r)}function sanitizeTerminalText(e){return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu,e=>e===`\r`?`\\r`:e===`
`?`\\n`:e===`	`?`\\t`:``)}function tryProcessCwd(){try{return process.cwd()}catch{return}}function getUserPathBaseDirectory(){return resolveGlobalSingleton(Symbol.for(`openclaw.userPathBaseDirectory`),()=>{let{AsyncLocalStorage:e}=process.getBuiltinModule(`async_hooks`);return new e})}function resolveRequiredHomeDir(e=process.env,t=y.homedir){let n=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(n)return u.resolve(n);throw Error(`Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.`)}function expandHomePrefix(e,t){if(!e.startsWith(`~`))return e;let n=normalizeHomeDirValue(t?.home)??resolveEffectiveHomeDir(t?.env??process.env,t?.homedir??y.homedir);return n?e.replace(/^~(?=$|[\\/])/,()=>n):e}function resolveAgainstUserBase(e){let t=getUserPathBaseDirectory().getStore();return t?u.resolve(t,e):u.resolve(e)}function resolvePathWithHome(e,t,n,r=resolveAgainstUserBase){let i=e.trim();return i&&r(i.startsWith(`~`)?expandHomePrefix(i,{home:n(t?.env??process.env,t?.homedir??y.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=y.homedir){return e?resolveHomeRelativePath(e,{env:t,homedir:n}):``}const ut=/^[a-z0-9][a-z0-9_-]{0,63}$/i;function isValidProfileName(e){return ut.test(e)}function normalizeProfileName(e){let t=e?.trim();return!t||normalizeLowercaseStringOrEmpty(t)==="default"||!isValidProfileName(t)?null:t}function resolveProfileStateDir(e,t,n){let r=e.trim();if(!isValidProfileName(r))throw Error(`Invalid profile name: ${JSON.stringify(e)}`);let i=normalizeLowercaseStringOrEmpty(r)==="default"?``:`-${r}`;return u.join(resolveRequiredHomeDir(t,n),`.openclaw${i}`)}const dt=new class{#e;#t;#n;#r=/* @__PURE__ */ new Map;#i=0;constructor(e,t){this.#e=Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):1,this.#t=t?.maxBytes??1/0,this.#n=t?.sizeOf}get size(){return this.#r.size}clear(){this.#r.clear(),this.#i=0}keys(){return this.#r.keys()}delete(e){return this.#r.has(e)?(this.#i-=this.#n?.(this.#r.get(e))??0,this.#r.delete(e)):!1}deleteValue(e){for(let[t,n]of this.#r)n===e&&this.delete(t)}peek(e){return this.#r.get(e)}get(e){if(!this.#r.has(e))return;let t=this.#r.get(e);return this.#r.delete(e),this.#r.set(e,t),t}set(e,t){this.delete(e),this.#r.set(e,t),this.#i+=this.#n?.(t)??0;for(let e of this.#r.keys()){if(this.#r.size<=this.#e&&this.#i<=this.#t)break;this.delete(e)}}}(64);function resolveNewStateDir(e=resolveRequiredHomeDir){return u.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=y.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n&&process.platform!==`win32`&&u.isAbsolute(n)){let e=dt.peek(n);if(e!==void 0)return e;let t=u.resolve(n);return dt.set(n,t),t}return n?resolveHomeRelativePath(n,{env:e,homedir:t}):resolveStateDirFromHome(e,()=>resolveRequiredHomeDir(e,t))}function resolveStateDirFromHome(e,t){let n=normalizeProfileName(e.OPENCLAW_PROFILE);return n?resolveProfileStateDir(n,e,t):resolveNewStateDir(t)}function resolveConfigDir(e=process.env,t=y.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n)return resolveUserPath(n,e,t);let r=e.OPENCLAW_CONFIG_PATH?.trim();return r?u.dirname(resolveUserPath(r,e,t)):resolveStateDir(e,t)}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sleep(e,t){let n=resolveTimerTimeoutMs(e,0,0);return t?t.aborted?Promise.reject(a(`aborted`,{cause:t.reason??/* @__PURE__ */ Error(`aborted`)})):r(n,t):new Promise(e=>{setTimeout(e,n)})}String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`,String.raw`[\s"'\x60)\]}>]`,String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`,resolveConfigDir();const ft=`$include`,T=4096;function isConfigContainer(e){return Array.isArray(e)||isPlainObject(e)}function includeLogicalPath(e){let t=[];for(let n=e;n;n=n.parent)t.push(n.key);return t.toReversed()}var ConfigIncludeError=class extends Error{constructor(e,t,n){super(e),this.includePath=t,this.cause=n,this.name=`ConfigIncludeError`}},ConfigIncludeReadError=class extends ConfigIncludeError{constructor(...e){super(...e),this.name=`ConfigIncludeReadError`}},CircularIncludeError=class extends ConfigIncludeError{constructor(e){super(`Circular include detected: ${e.join(` -> `)}`,expectDefined(e[e.length-1],`chain entry at chain.length 1`)),this.chain=e,this.name=`CircularIncludeError`}};function deepMerge(e,t){return mergeDeep(e,t,{arrays:`concat`,undefinedValues:`replace`})}var IncludeProcessor=class{constructor(e,t,n,r){this.basePath=e,this.resolver=t,this.boundary=n,this.rootProjectionKeys=r}get rootDir(){return this.boundary.configRoot.rootDir}process(e){let t=[],n=this.traverseValue(e,null,!1,{basePath:this.basePath,visited:/* @__PURE__ */ new Set([u.normalize(this.basePath)]),depth:0}),r;for(;;){let e=n.next(r);if(e.done){let i=t.pop();if(!i)return e.value;r=e.value,n=i}else t.push(n),n=this.traverseValue(e.value.value,e.value.pathLink,e.value.hasArrayAncestor,e.value.context)}}*traverseValue(e,t,n,r){if(Array.isArray(e)){let n=[];for(let[i,a]of e.entries())n.push(isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:String(i)},hasArrayAncestor:!0,context:r}:a);return n}if(!isPlainObject(e))return e;if(!(`$include`in e)){let i=t===null,a={};for(let[o,s]of Object.entries(e))i&&this.rootProjectionKeys&&!this.rootProjectionKeys.has(o)||(a[o]=isConfigContainer(s)?yield{value:s,pathLink:{parent:t,key:o},hasArrayAncestor:n,context:r}:s);return a}return yield*this.traverseInclude(e,t,n,r)}*traverseInclude(e,t,n,r){let i=e[ft],a=t===null,o=Object.keys(e).filter(e=>e!==`$include`&&(!a||!this.rootProjectionKeys||this.rootProjectionKeys.has(e))),s=Array.isArray(i);if(!s&&typeof i!=`string`)throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof i}`,String(i));let c=[];for(let e of s?i:[i]){if(typeof e!=`string`)throw new ConfigIncludeError(`Invalid $include array item: expected string, got ${typeof e}`,String(e));let i=this.loadFileSync(e,r);c.push({value:yield{value:i.parsed,pathLink:t,hasArrayAncestor:n,context:i.nestedContext},targetPath:i.resolvedPath})}let l=s?c.reduce((e,t)=>deepMerge(e,t.value),{}):c[0].value;if(this.resolver.onIncludeResolved?.({path:includeLogicalPath(t),value:l,kind:s?`multiple`:`single`,hasSiblingOverrides:o.length>0,hasArrayAncestor:n,...s?{targetPaths:c.map(e=>e.targetPath)}:{targetPath:c[0].targetPath}}),o.length===0)return l;if(!isPlainObject(l))throw new ConfigIncludeError(`Sibling keys require included content to be an object`,typeof i==`string`?i:ft);let u={};for(let i of o){let a=e[i];u[i]=isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:i},hasArrayAncestor:n,context:r}:a}return deepMerge(l,u)}loadFileSync(e,t){let{resolvedPath:n,root:r}=this.resolvePath(e,t);if(t.visited.has(n))throw new CircularIncludeError([...t.visited,n]);if(t.depth>=10)throw new ConfigIncludeError(`Maximum include depth (10) exceeded at: ${e}`,e);let i=this.readFile(e,n,r);return{parsed:this.parseFile(e,n,i),resolvedPath:n,nestedContext:{basePath:n,visited:/* @__PURE__ */ new Set([...t.visited,n]),depth:t.depth+1}}}resolvePath(e,t){if(e.includes(`\0`))throw new ConfigIncludeError(`Include path must not contain null bytes`,e);if(e.length>=T)throw new ConfigIncludeError(`Include path exceeds maximum length (${T} characters)`,e);let n=u.dirname(t.basePath),r=u.isAbsolute(e)?e:u.resolve(n,e),i=u.normalize(this.resolver.mapPath?.(r)??r);if(i.length>=T)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${T} characters)`,e);let a=this.findContainingRoot(i,`rootDir`);if(!a)throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`,e);this.resolver.onLexicalPath?.(i);try{let t=g.realpathSync(i),n=this.findContainingRoot(t,`rootRealDir`);if(!n)throw new ConfigIncludeError(`Include path resolves outside config directory (symlink): ${e} (root: ${this.rootDir})`,e);return{resolvedPath:i,root:n}}catch(t){if(t instanceof ConfigIncludeError)throw t;if(isMissingPathError(t))return{resolvedPath:i,root:a};throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${e} (resolved: ${i})`,e,t instanceof Error?t:void 0)}}findContainingRoot(e,t){if(ce(this.boundary.configRoot[t],e))return this.boundary.configRoot;for(let n of this.boundary.allowedRoots)if(ce(n[t],e))return n;return null}readFile(e,t,n){try{return this.resolver.readFileWithGuards?this.resolver.readFileWithGuards({includePath:e,resolvedPath:t,rootRealDir:n.rootRealDir}):this.resolver.readFile(t)}catch(n){throw n instanceof ConfigIncludeError?n:new ConfigIncludeReadError(`Failed to read include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}parseFile(e,t,n){try{return this.resolver.parseJson(n)}catch(n){throw new ConfigIncludeError(`Failed to parse include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}};function safeRealpath(e){try{return g.realpathSync(e)}catch{return e}}function createConfigIncludeBoundary(e,t=[]){let n=u.normalize(u.dirname(e));return{configRoot:{rootDir:n,rootRealDir:u.normalize(safeRealpath(n))},allowedRoots:t.filter(e=>typeof e==`string`&&e.length>0&&u.isAbsolute(e)).map(e=>{let t=u.normalize(e);return{rootDir:t,rootRealDir:u.normalize(safeRealpath(t))}})}}function readConfigIncludeFileWithGuards(e){let t=e.ioFs??g,n=e.maxBytes??2097152;if(!ne(t)){let n=t.readFileSync(e.resolvedPath,`utf-8`);try{e.onResolvedPath?.(u.normalize(t.realpathSync(e.resolvedPath)))}catch{}return n}let r=re({absolutePath:e.resolvedPath,rootPath:e.rootRealDir,rootRealPath:e.rootRealDir,boundaryLabel:`config directory`,skipLexicalRootCheck:!0,rejectSymlinks:!1,maxBytes:n,ioFs:t});if(!r.ok)throw r.reason===`validation`?new ConfigIncludeError(`Include file failed security checks (regular file, max ${n} bytes, no hardlinks): ${e.includePath}`,e.includePath):new ConfigIncludeReadError(`Failed to read include file: ${e.includePath} (resolved: ${e.resolvedPath})`,e.includePath,r.error instanceof Error?r.error:void 0);try{let n=t.readFileSync(r.fd,`utf-8`);return e.onResolvedPath?.(u.normalize(r.path)),n}finally{t.closeSync(r.fd)}}const pt={readFile:e=>g.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback};function resolveConfigIncludes(e,t,n=pt,r={}){return new IncludeProcessor(t,n,createConfigIncludeBoundary(t,r.allowedRoots??[])).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=pt,i={}){return new IncludeProcessor(t,r,createConfigIncludeBoundary(t,i.allowedRoots??[]),/* @__PURE__ */ new Set([n])).process(e)}function resolveIsNixMode(e=process.env){return e.OPENCLAW_NIX_MODE===`1`}resolveIsNixMode();function envHomedir(e){return()=>resolveRequiredHomeDir(e,y.homedir)}function resolveIncludeRoots(e=process.env,t=envHomedir(e)){let n=e.OPENCLAW_INCLUDE_ROOTS?.trim();if(!n)return[];let effectiveHomedir=()=>resolveRequiredHomeDir(e,t),r=/* @__PURE__ */ new Set,i=[];for(let t of n.split(u.delimiter)){let n=t.trim();if(!n)continue;let a=u.resolve(resolveHomeRelativePath(n,{env:e,homedir:effectiveHomedir}));r.has(a)||(r.add(a),i.push(a))}return i}resolveStateDir();function resolveConfigPathCandidate(e=process.env,t=envHomedir(e)){return resolveConfigPath(e,void 0,t)}function resolveConfigPath(e=process.env,t,n=envHomedir(e)){let r=e.OPENCLAW_CONFIG_PATH?.trim();return r?resolveUserPath(r,e,n):u.join(t??resolveStateDir(e,n),`openclaw.json`)}resolveConfigPathCandidate();let mt;function resolveLoggingConfigSelector(){let e=process.env;return[e.OPENCLAW_CONFIG_PATH,e.OPENCLAW_STATE_DIR,e.OPENCLAW_HOME,e.OPENCLAW_PROFILE,e.HOME,e.USERPROFILE,e.HOMEDRIVE,e.HOMEPATH,e.PREFIX,e.ANDROID_DATA,e.OPENCLAW_TEST_FAST,tryProcessCwd()??``].map(e=>e??``).join(`\0`)}function resolvePartialDiagnosticLoggingConfig(t){if(!e(t))return;let n={};if(typeof t.consoleStyle==`string`)try{let r=resolveConfigEnvVars({consoleStyle:t.consoleStyle});e(r)&&(r.consoleStyle===`pretty`||r.consoleStyle===`compact`||r.consoleStyle===`json`)&&(n.consoleStyle=r.consoleStyle)}catch{}if(Array.isArray(t.redactPatterns))try{let r=resolveConfigEnvVars({redactPatterns:t.redactPatterns});e(r)&&Array.isArray(r.redactPatterns)&&r.redactPatterns.every(e=>typeof e==`string`)&&(n.redactPatterns=r.redactPatterns)}catch{}return Object.keys(n).length>0?n:void 0}function readLoggingConfig(){try{if(w.appliedConfig!==`unowned`)return w.appliedConfig;let t=resolveLoggingConfigSelector();if(mt?.selector===t)return mt.logging;let n=resolveConfigPath();if(!g.existsSync(n)){mt={selector:t,logging:void 0};return}let r=parseJsonWithJson5Fallback(g.readFileSync(n,`utf8`)),i=resolveIncludeRoots(),a;try{a=resolveConfigIncludesForTopLevelKey(r,n,`logging`,void 0,{allowedRoots:i})}catch{let t=e(r)?r.logging:void 0;if(t===void 0)return;try{a=resolveConfigIncludes({logging:t},n,void 0,{allowedRoots:i})}catch{return resolvePartialDiagnosticLoggingConfig(t)}}let o;try{o=resolveConfigEnvVars(a)}catch{return resolvePartialDiagnosticLoggingConfig(e(a)?a.logging:void 0)}let s=e(o)?o.logging:void 0,c=e(s)?s:void 0;return mt={selector:t,logging:c},c}catch{return}}const ht=/* @__PURE__ */ new Set(/* @__PURE__ */ `token.key.api_key.apikey.secret.access_token.auth_token.password.pass.passwd.auth.jwt.session.id_token.code.client_secret.app_secret.hook_token.refresh_token.signature.x_amz_signature.x_amz_security_token.private_key.credential.authorization.sig.x_api_key.x_access_token.x_auth_token`.split(`.`)),gt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,_t=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u;function normalizeUrlQueryParamName(e){let t=e.replace(gt,``);for(let e=0;e<=8;e+=1){let e;try{e=decodeURIComponent(t).replace(gt,``)}catch{break}if(e===t)return{value:normalizeLowercaseStringOrEmpty(t).replaceAll(`-`,`_`),unresolvedEncoding:!1};t=e}return{value:normalizeLowercaseStringOrEmpty(t).replaceAll(`-`,`_`),unresolvedEncoding:t.includes(`%`)}}function isSensitiveUrlQueryParamName(e){let t=normalizeUrlQueryParamName(e);return t.unresolvedEncoding||ht.has(t.value)||_t.test(t.value)}const vt="[A-Za-z0-9!#$%&'*+.^_`|~-]+",E=String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`,D=String.raw`\\{1,64}t`,O=String.raw`(?:[ \t]+|${D})`,k=String.raw`(?:[ \t]*\r?\n${O}|[ \t]*\\{1,64}r\\{1,64}n${O}|[ \t]*\\{1,64}n${O}|[ \t]*${D}[ \t]*|[ \t]*)`,A=String.raw`(?:[ \t]*\r?\n${O}|[ \t]*\\{1,64}r\\{1,64}n${O}|[ \t]*\\{1,64}n${O}|[ \t]*${D}[ \t]*|[ \t]+)`,yt=String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${D})|[ \t]*\\{1,64}n(?:[ \t]*|${D})|[ \t]*${D}[ \t]*)`,j=String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`,M=String.raw`(?:\\{1,64}["']|["']|)`;String.raw`${j}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${M}[ \t]*[:=]${k}${M}([^\s\\"',;]+)`;const bt=new RegExp(String.raw`${j}(?:Proxy-)?Authorization${M}[ \t]*[:=]${k}${M}(${vt})${A}`,`giu`),xt=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u,St=/^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u;function skipHorizontalWhitespace(e,t){let n=t;for(;e[n]===` `||e[n]===`	`;)n+=1;return n}function skipSerializedBackslashes(e,t){let n=t;for(;n-t<64&&e[n]===`\\`;)n+=1;return n}function readSerializedLineEnd(e,t){let n=skipSerializedBackslashes(e,t);if(n===t)return null;if(e[n]===`n`)return n+1;if(e[n]!==`r`)return null;let r=skipSerializedBackslashes(e,n+1);return r>n+1&&e[r]===`n`?r+1:null}function readSerializedTabEnd(e,t){let n=skipSerializedBackslashes(e,t);return n>t&&e[n]===`t`?n+1:null}function skipAuthWhitespace(e,t){let n=t;for(;;){n=skipHorizontalWhitespace(e,n);let t=readSerializedTabEnd(e,n);if(t!==null){n=t;continue}let r=e[n]===`\r`&&e[n+1]===`
`?n+2:e[n]===`
`?n+1:readSerializedLineEnd(e,n);if(r===null||e[r]!==` `&&e[r]!==`	`&&readSerializedTabEnd(e,r)===null)return n;n=r}}function readAuthParamName(e,t){let n=xt.exec(e.slice(t));return n?{name:n[0].toLowerCase(),end:t+n[0].length}:null}function isAuthHeaderStart(e,t){let n=e[t-1];if((n!==`n`&&n!==`r`||e[t-2]!==`\\`)&&n!==void 0&&/[A-Za-z0-9_-]/u.test(n))return!1;let r=`proxy-authorization`,i=`authorization`,a=e.slice(t,t+19).toLowerCase(),o=a===r?r:a.startsWith(i)?i:null;if(!o)return!1;let s=t+o.length,c=skipSerializedBackslashes(e,s);if(e[c]===`"`||e[c]===`'`)c+=1;else if(c>s)return!1;return c=skipHorizontalWhitespace(e,c),e[c]===`:`||e[c]===`=`}function findNextAuthParamStart(e,t){let n=t;for(;;){if(n=skipAuthWhitespace(e,n),n>t&&isAuthHeaderStart(e,n)||n>=e.length||e[n]===`\r`||e[n]===`
`||e[n]===`;`)return null;if(e[n]===`,`){n+=1;continue}let r=readAuthParamName(e,n);if(r){let t=skipAuthWhitespace(e,r.end);if(e[t]===`=`&&e[t+1]!==`=`)return n}for(;n<e.length;){let r=skipAuthWhitespace(e,n);if(r>n){n=r;continue}if(n>t&&isAuthHeaderStart(e,n))return null;let i=e[n];if(i===`\r`||i===`
`||i===`;`)return null;if(n+=1,i===`,`)break}}}function usesAuthParams(e){return e===`digest`||e===`hawk`||e.startsWith(`aws4-`)}function isAuthFieldEnd(e){return e===void 0||e===`\r`||e===`
`||e===`;`||e===`\\`||e===`"`||e===`'`||e===`}`||e===`]`}function findAuthFieldEnd(e,t){let n=t;for(;n<e.length;){let r=skipAuthWhitespace(e,n);if(r>n)n=r;else{if(n>t&&isAuthHeaderStart(e,n)||isAuthFieldEnd(e[n]))break;n+=1}}return n}function readParamValue(e,t,n){let r=0;for(;e[t+r]===`\\`;)r+=1;let i=r>0&&e[t+r]===`"`,a=e[t]===`"`||e[t]===`'`?e[t]:void 0;if(a||i){let n=t+(i?r+1:1);for(;n<e.length;)if(e[n]===`\r`||e[n]===`
`){let t=skipAuthWhitespace(e,n);if(t===n)break;n=t}else if(i&&e[n]===`\\`){let t=n+1;for(;e[t]===`\\`;)t+=1;if(e[t]===`"`){if((t-n)%(2*(r+1))===r)return t+1;n=t+1;continue}n=t}else if(!i&&e[n]===`\\`&&n+1<e.length)n+=2;else{if(!i&&e[n]===a)return n+1;n+=1}return n>t+1?n:null}if(n.signedHeaders){let n=/^:?[A-Za-z0-9!#$%&'*+.^_`|~-]+(?:;:?[A-Za-z0-9!#$%&'*+.^_`|~-]+)*/u.exec(e.slice(t));if(!n)return null;let r=t+n[0].length,i=e[r];return i===void 0||i===`,`||i===` `||i===`	`||i===`\r`||i===`
`?r:null}let o=(n.awsScope?St:xt).exec(e.slice(t));return o?t+o[0].length:null}function findStructuredAuthParamRanges(e){let t=[];for(let n of e.matchAll(bt)){let r=(n[2]??``).toLowerCase(),i=(n.index??0)+n[0].length,a=i,o=i,s=readAuthParamName(e,i),c=s?skipAuthWhitespace(e,s.end):void 0;if(!s||c===void 0||e[c]!==`=`||e[c+1]===`=`){if(e[skipAuthWhitespace(e,i)]!==`,`&&!usesAuthParams(r))continue;let t=findNextAuthParamStart(e,i);if(t===null)continue;i=t}for(;;){let t=readAuthParamName(e,i);if(!t||(i=skipAuthWhitespace(e,t.end),e[i]!==`=`))break;i=skipAuthWhitespace(e,i+1);let n=readParamValue(e,i,{awsScope:r.startsWith(`aws4-`)&&t.name===`credential`,signedHeaders:t.name===`signedheaders`});if(n===null){let t=findNextAuthParamStart(e,i);if(t!==null){i=t;continue}o=Math.max(o,findAuthFieldEnd(e,i));break}o=n;let a=skipAuthWhitespace(e,n);if(e[a]!==`,`){if(!isAuthFieldEnd(e[a])){let t=findNextAuthParamStart(e,a);if(t!==null){i=t;continue}o=Math.max(o,findAuthFieldEnd(e,a))}break}let s=findNextAuthParamStart(e,a+1);if(s===null)break;i=s}o>a&&t.push({start:a,end:o})}return t}function redactStructuredAuthHeaders(e,t){let n=[],r=0;for(let i of findStructuredAuthParamRanges(e))(n.length===0||i.start>r)&&n.push(e.slice(r,i.start),t),r=Math.max(r,i.end);return n.push(e.slice(r)),n.join(``)}function pruneMapToMaxSize(e,t){if(Number.isNaN(t)||t===1/0)return;let n=Math.max(0,Math.floor(t));if(n<=0)e.clear();else for(let t of e.keys()){if(e.size<=n)break;e.delete(t)}}const Ct=/* @__PURE__ */ new Map;function createParseFrame(){return{lastToken:null,containsRepetition:!1,hasAlternation:!1,branchMinLength:0,branchMaxLength:0,altMinLength:null,altMaxLength:null}}function addLength(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?1/0:e+t}function multiplyLength(e,t){return Number.isFinite(e)?e*t:t===0?0:1/0}function recordAlternative(e){e.altMinLength===null||e.altMaxLength===null?(e.altMinLength=e.branchMinLength,e.altMaxLength=e.branchMaxLength):(e.altMinLength=Math.min(e.altMinLength,e.branchMinLength),e.altMaxLength=Math.max(e.altMaxLength,e.branchMaxLength))}function readQuantifier(e,t){let n=e[t],r=e[t+1]===`?`?2:1;if(n===`*`)return{consumed:r,minRepeat:0,maxRepeat:null};if(n===`+`)return{consumed:r,minRepeat:1,maxRepeat:null};if(n===`?`)return{consumed:r,minRepeat:0,maxRepeat:1};if(n!==`{`)return null;let i=t+1;for(;i<e.length&&/\d/.test(e.charAt(i));)i+=1;if(i===t+1)return null;let a=Number.parseInt(e.slice(t+1,i),10),o=a;if(e[i]===`,`){i+=1;let t=i;for(;i<e.length&&/\d/.test(e.charAt(i));)i+=1;o=i===t?null:Number.parseInt(e.slice(t,i),10)}return e[i]!==`}`||(i+=1,e[i]===`?`&&(i+=1),o!==null&&o<a)?null:{consumed:i-t,minRepeat:a,maxRepeat:o}}function hasNestedRepetition(e){let t=[createParseFrame()],n=!1,emitToken=e=>{let n=expectDefined(t[t.length-1],`frames entry at frames.length 1`);n.lastToken=e,e.containsRepetition&&(n.containsRepetition=!0),n.branchMinLength=addLength(n.branchMinLength,e.minLength),n.branchMaxLength=addLength(n.branchMaxLength,e.maxLength)},emitSimpleToken=()=>{emitToken({containsRepetition:!1,hasAmbiguousAlternation:!1,minLength:1,maxLength:1})};for(let r=0;r<e.length;r+=1){let i=e[r];if(n){i===`\\`?r+=1:i===`]`&&(n=!1);continue}if(i===`\\`){r+=1,emitSimpleToken();continue}if(i===`[`){n=!0,emitSimpleToken();continue}if(i===`(`){t.push(createParseFrame());continue}if(i===`)`){if(t.length>1){let e=t.pop();e.hasAlternation&&recordAlternative(e);let n=e.hasAlternation?e.altMinLength??0:e.branchMinLength,r=e.hasAlternation?e.altMaxLength??0:e.branchMaxLength;emitToken({containsRepetition:e.containsRepetition,hasAmbiguousAlternation:e.hasAlternation&&e.altMinLength!==null&&e.altMaxLength!==null&&e.altMinLength!==e.altMaxLength,minLength:n,maxLength:r})}continue}if(i===`|`){let e=expectDefined(t[t.length-1],`frames entry at frames.length 1`);e.hasAlternation=!0,recordAlternative(e),e.branchMinLength=0,e.branchMaxLength=0,e.lastToken=null;continue}let a=readQuantifier(e,r);if(!a){emitSimpleToken();continue}r+=a.consumed-1;let o=expectDefined(t[t.length-1],`frames entry at frames.length 1`),s=o.lastToken;if(!s)continue;if(s.containsRepetition||s.hasAmbiguousAlternation&&a.maxRepeat===null)return!0;let c=s.minLength,l=s.maxLength;s.minLength=multiplyLength(s.minLength,a.minRepeat),s.maxLength=a.maxRepeat===null?1/0:multiplyLength(s.maxLength,a.maxRepeat),s.containsRepetition=!0,o.containsRepetition=!0,o.branchMinLength=o.branchMinLength-c+s.minLength,o.branchMaxLength=addLength(Number.isFinite(o.branchMaxLength)&&Number.isFinite(l)?o.branchMaxLength-l:1/0,s.maxLength)}return!1}function compileSafeRegexDetailed(e,t=``){let n=e.trim();if(!n)return{regex:null,source:n,flags:t,reason:`empty`};let r=`${t}::${n}`,i=Ct.get(r);if(i)return i;let a;if(hasNestedRepetition(n))a={regex:null,source:n,flags:t,reason:`unsafe-nested-repetition`};else try{a={regex:new RegExp(n,t),source:n,flags:t,reason:null}}catch{a={regex:null,source:n,flags:t,reason:`invalid-regex`}}return Ct.set(r,a),pruneMapToMaxSize(Ct,256),a}function compileConfigRegex(e,t=``){let n=compileSafeRegexDetailed(e,t);return n.reason===`empty`?null:{regex:n.regex,pattern:n.source,flags:n.flags,reason:n.reason}}const wt=4096;function clampMessage(e){return e.length>wt?`${truncateUtf16Safe(e,wt)}...(truncated)`:e}function stringifyFileLogMessagePart(t,n){if(n)return JSON.stringify(t);if(typeof t==`string`)return t;if(typeof t==`number`||typeof t==`boolean`||typeof t==`bigint`)return String(t);if(e(t)&&typeof t.message==`string`)return t.message}function serializeFileLogRecord(t,n=[]){let r=[],i=JSON.parse(JSON.stringify(t,function(e,t){for(;r.length>0&&r.at(-1)!==this;)r.pop();if(typeof t==`bigint`)return String(t);if(typeof t==`object`&&t){if(r.includes(t))return`[Circular]`;r.push(t)}return t}));if(!e(i))throw TypeError(`File log records must serialize to objects`);let a=[];for(let{key:e,json:t,primitiveText:r}of n){let n=r??stringifyFileLogMessagePart(i[e],t);n?.trim()&&a.push(n)}if(a.length>0){let e=clampMessage(a.join(` `));if(Object.hasOwn(i,`message`))i.message=e;else{let t=Object.entries(i);return t.splice(t.findIndex(([e])=>e===`hostname`)+1,0,[`message`,e]),JSON.stringify(Object.fromEntries(t))}}return JSON.stringify(i)}const Tt=16384;function replacePatternBounded(e,t,n){if(e.length<=32768)return e.replace(t,n);let r;for(let i=0;i<e.length;i+=Tt){let a=e.slice(i,i+Tt),o=a.replace(t,n);r===void 0?o!==a&&(r=e.slice(0,i)+o):r+=o}return r??e}function composeRedactionEdits(e,t,n){if(t.length===0)return n;let r=[],i=0;for(let e of t)i<e.start&&r.push({start:i,end:e.start}),r.push(e),i=e.end;i<e&&r.push({start:i,end:e});let a=[],o=0,s=0,c=0,consume=(t,n)=>{if(t===c){let t=r[o];if(!t)return{start:e,end:e};let n=t.replacement===void 0?t.start+s:t.start;return{start:n,end:t.replacement!==void 0&&s>0?t.end:n}}let i,l=0;for(;c<t;){let e=expectDefined(r[o],`current redaction piece`),u=e.replacement?.length??e.end-e.start,d=Math.min(u-s,t-c),f=e.replacement===void 0?e.start+s:e.start,p=e.replacement===void 0?f+d:e.end;i??=f,l=p,n&&d>0&&a.push({start:f,end:p,replacement:e.replacement?.slice(s,s+d)}),c+=d,s+=d,s===u&&(o+=1,s=0)}return{start:i??l,end:l}};for(let e of n)consume(e.start,!0),a.push({...consume(e.end,!1),replacement:e.replacement});for(;o<r.length;){let e=expectDefined(r[o],`remaining redaction piece`);consume(c+(e.replacement?.length??e.end-e.start)-s,!0)}let l=[],u=[],d,flush=()=>{d&&(d.replacement=u.join(``),l.push(d),d=void 0,u=[])};for(let e of a){if(e.replacement===void 0){flush();continue}let t=d&&d.start===e.start&&d.end===e.end&&e.start===e.end;!d||e.start>=d.end&&!t?(flush(),d={start:e.start,end:e.end,replacement:``}):d.end=Math.max(d.end,e.end),u.push(e.replacement)}return flush(),l}function rebaseRedactionEdits(e,t){let n=0,r=e.map(e=>{let t=e.start+n;return n+=e.replacement.length-(e.end-e.start),{...e,currentStart:t,currentEnd:e.end+n}}),boundary=(e,t)=>{let n=0,i=r.length;for(;n<i;){let t=n+i>>>1,a=expectDefined(r[t],`source redaction span`);a.end<e||a.end===e&&a.start!==a.end?n=t+1:i=t}let a=r[n];if(a&&(e>a.start||e===a.start&&a.start===a.end))return t?a.currentEnd:a.currentStart;let o=r[n-1];return e+(o?o.currentEnd-o.end:0)};return t.map(e=>({start:boundary(e.start,!1),end:boundary(e.end,!0),replacement:e.replacement}))}function mergeRedactionEdits(e){e.sort((e,t)=>e.start-t.start||e.end-t.end);let t=[];for(let n of e){let e=t.at(-1);!e||n.start>=e.end?t.push({...n}):(n.start!==e.start||n.end!==e.end||n.replacement!==e.replacement)&&(e.end=Math.max(e.end,n.end),e.replacement=`***`)}return t}function applyRedactionEdits(e,t){let n=[],r=0;for(let i of mergeRedactionEdits(t))n.push(e.slice(r,i.start),i.replacement),r=i.end;return n.join(``)+e.slice(r)}const Et=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g;function skipWhitespace(e,t){let n=t;for(;e[n]===` `||e[n]===`	`||e[n]===`\r`||e[n]===`
`;)n+=1;return n}function readScalarTokens(e,t){let n=[],r=[],i={key:``,path:[],origins:t,origin:t.value,objectPath:!0},valueContext=e=>e?e.array?{...e.context,origin:e.context.origins?.value??e.context.origin,origins:e.context.origins?.children.get(String(e.nextIndex++))}:expectDefined(e.field,`JSON object field context`):i;for(let t of e.matchAll(Et)){let i=t[0],a=r.at(-1);if(i===`{`||i===`[`){let e=valueContext(a),o=i===`[`;r.push({array:o,nextIndex:0,context:o?{...e,objectPath:!1}:e,start:t.index,tokenStart:n.length});continue}if(i===`}`||i===`]`){let i=expectDefined(r.pop(),`JSON container`);if(i.tokenStart===n.length){let r=t.index+1,a=e.slice(i.start,r);n.push({...i.context,isKey:!1,string:!1,value:a,start:i.start,end:r,escaped:!1,edits:[],projectedEdits:[],currentValue:a,currentStart:i.start,currentEnd:r})}continue}let o=t.index,s=o+i.length,c=i.startsWith(`"`),l=c?JSON.parse(i):i,u=skipWhitespace(e,s),d=c&&e[u]===`:`,f;if(d){let t=expectDefined(a,`JSON property container`),n=t.context;f={key:``,path:[],origin:n.origin,objectPath:!1,rootKey:n.rootKey,rootValueStart:n.rootValueStart};let i=skipWhitespace(e,u+1);t.field={key:l,path:[...n.path,l],origins:n.origins?.children.get(l),origin:n.origins?.value??n.origin,objectPath:n.objectPath,rootKey:r.length===1?l:n.rootKey,rootValueStart:r.length===1?i:n.rootValueStart}}else f=valueContext(a);let p=d?{structured:!1,primitiveMask:!1}:f.origins?.value??f.origin;n.push({...f,origin:p,start:o,end:s,isKey:d,string:c,value:l,escaped:c&&i.includes(`\\`),edits:[],projectedEdits:[],currentValue:l,currentStart:o,currentEnd:s})}return n}function readBatchTokens(e,t,n=!1){let r=[],i=0;for(let a of e.split(`
`)){let e=!1;try{JSON.parse(a),e=!0}catch{}if(e)for(let e of readScalarTokens(a,t))e.deferEncoding=!e.string,e.start+=i,e.end+=i,e.currentStart+=i,e.currentEnd+=i,r.push(e);else{let e=r.at(-1);!n&&e?.raw&&e.end+1===i?(e.value+=`\n${a}`,e.currentValue=e.value,e.end=e.currentEnd=i+a.length):r.push({raw:!0,origin:t.value,key:``,path:[],objectPath:!1,isKey:!1,string:!1,value:a,escaped:!1,start:i,end:i+a.length,currentStart:i,currentEnd:i+a.length,currentValue:a,edits:[],projectedEdits:[]})}i+=a.length+1}return r}function parseRedactPatternSource(e){let t=e.match(/^\/(.+)\/([gimsuy]*)$/);if(!t)return[e,`gi`];let n=t[1]??``,r=t[2]??``;return[n,r.includes(`g`)?r:`${r}g`]}const Dt=/^\{(\d+),\}/,Ot=/^\{(?:\d+(?:,\d*)?|,\d+)\}/,kt=/[0-9A-Fa-f]/,At=/* @__PURE__ */ new Set([`b`,`B`]),escapeHexValue=(e,t)=>{let n=0;for(let r=0;r<4;r+=1){let i=e[t+r];if(i===void 0||!kt.test(i))return null;n=n*16+Number.parseInt(i,16)}return n},isHighSurrogateEscape=(e,t)=>{let n=escapeHexValue(e,t+2);return n!==null&&n>=55296&&n<=56319},isLowSurrogateEscape=(e,t)=>{let n=escapeHexValue(e,t+2);return n!==null&&n>=56320&&n<=57343};function escapeAtomEnd(e,t){let n=e[t+1];if(n===void 0)return-1;if(At.has(n))return t+2;if(n===`x`)return kt.test(e[t+2]??``)&&kt.test(e[t+3]??``)?t+4:t+2;if((n===`u`||n===`p`||n===`P`)&&e[t+2]===`{`){let n=e.indexOf(`}`,t+3);return n===-1?t+2:n+1}if(n===`u`){let n=t+2;for(;n<t+6&&kt.test(e[n]??``);)n+=1;return n}if(n===`c`)return t+3;if(n===`k`&&e[t+2]===`<`){let n=e.indexOf(`>`,t+3);return n===-1?t+2:n+1}if(n>=`0`&&n<=`9`){let n=t+2;for(let t=n;t<e.length;t+=1){let r=e[t];if(r===void 0||r<`0`||r>`9`)break;n=t+1}return n}return t+2}function classAtomEnd(e,t){let n=t+1;if(e[n]===`^`&&(n+=1),e[n]===`]`)return-1;for(;n<e.length;){let t=e[n];if(t===`\\`)n+=2;else{if(t===`]`)return n+1;n+=1}}return e.length}function rewriteOpenEndedRepeats(e,t=``){if(!e.includes(`{`))return e;let n=``,r=-1,i=-1,a=0;for(;a<e.length;){let o=e[a],s=a+1,c=!0;if(o===`\\`)s=escapeAtomEnd(e,a),s<0?(s=a+1,c=!1):t.includes(`u`)&&isHighSurrogateEscape(e,a)&&e[s]===`\\`&&isLowSurrogateEscape(e,s)?s=escapeAtomEnd(e,s):c=!At.has(e[a+1]);else if(o===`[`){if(s=classAtomEnd(e,a),s<0)return e}else if(o===`{`){let t=Dt.exec(e.slice(a)),o=t&&r>=0?t:Ot.exec(e.slice(a));if(o){n+=o===t?`{${t[1]}}${e.slice(r,i)}*`:o[0],a+=o[0].length,e[a]===`?`&&(n+=`?`,a+=1),r=-1;continue}}else t.includes(`u`)&&o>=`\ud800`&&o<=`\udbff`&&a+1<e.length&&e[a+1]>=`\udc00`&&e[a+1]<=`\udfff`?s=a+2:c=!`*+?()|^$`.includes(o);n+=e.slice(a,s),r=c?a:-1,i=s,a=s}return n}function readRedactMatch(e){let t=e.length>0&&typeof e[e.length-1]==`object`&&e[e.length-1]!==null?e.length-2:e.length-1,n=t-1,r=typeof e[0]==`string`?e[0]:``,i=e.slice(1,n).map(e=>typeof e==`string`?e:``),a=typeof e[n]==`number`?e[n]:-1;return{match:r,groups:i,input:typeof e[t]==`string`?e[t]:``,offset:a}}const jt=/* @__PURE__ */ new WeakMap;function setRedactPatternPrefilter(e,t){if(jt.has(e))return;let n=e.source,r=e.exec,i=e instanceof RegExp?e.flags:void 0,a=e instanceof RegExp?e[Symbol.replace]:void 0;jt.set(e,o=>e.source!==n||e.exec!==r||e instanceof RegExp&&(e.flags!==i||e[Symbol.replace]!==a)||t(o))}const Mt=/* @__PURE__ */ new WeakMap;function selectSecretCapture(e,t){let n={index:-1,value:e};for(let e=0;e<t.length;e++){let r=t[e];typeof r==`string`&&r.length>0&&(n.index=e,n.value=r)}return n}function getSecretCaptureStart(e,t,n,r,i){let a=i.index;if(!(e instanceof RegExp)||r<0||!t)return n.lastIndexOf(i.value);let o=Mt.get(e);o||(o=new RegExp(e.source,`${e.flags.replace(`d`,``).replace(`g`,``)}dg`),Mt.set(e,o)),o.lastIndex=r;let s=o.exec(t),c=s?.indices?.[a+1];return s?.index===r&&s[0]===n&&c?c[0]-r:n.lastIndexOf(i.value)}const Nt=/* @__PURE__ */ new WeakMap;function visitRedactMatches(e,t,n){if(jt.get(t)?.(e)===!1)return;if(!(t instanceof RegExp)){for(let r of t.exec(e))n(r,t);return}let r=t.global?t:Nt.get(t);r||(r=new RegExp(t.source,`${t.flags}g`),Nt.set(t,r));let i=r.unicode||r.flags.includes(`v`),a=0;for(;a<=e.length;){let o=r.lastIndex,s;try{r.lastIndex=a,s=r.exec(e)}finally{r.lastIndex=o}if(!s)return;if(a=s.index+s[0].length,!s[0]){let t=e.codePointAt(a);a+=i&&t!==void 0&&t>65535?2:1}n({match:s[0],groups:s.slice(1).map(e=>e??``),input:e,offset:s.index},t)}}function replaceRedactPattern(e,t,n,r){if(t instanceof RegExp)return jt.get(t)?.(e)===!1?(t.lastIndex=0,e):e.replace(t,r??((...e)=>n(readRedactMatch(e))));let i=[],a=0;return visitRedactMatches(e,t,t=>{i.push(e.slice(a,t.offset),n(t)),a=t.offset+t.match.length}),i.length?i.join(``)+e.slice(a):e}function redactPemBlock(e,t){let n=e.split(/\r?\n/).filter(Boolean);return n.length<2?`***`:`${n[0]}\n${t}\n${n[n.length-1]}`}function stringBoundaries(e,t,n){let r=/* @__PURE__ */ new Map,i=0;for(let a=t;a<n;i+=1)r.set(a,i),a+=e[a]===`\\`?e[a+1]===`u`?6:2:1;return r.set(n,i),r}function decodedBoundary(e,t,n){return t.escaped?(t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.boundaries.get(n)):n-t.start-1}function encodedBoundary(e,t,n){if(!t.escaped)return t.start+1+n;if(!t.encodedBoundaries){t.boundaries??=stringBoundaries(e,t.start+1,t.end-1),t.encodedBoundaries=[];for(let[e,n]of t.boundaries)t.encodedBoundaries[n]=e}return expectDefined(t.encodedBoundaries[n],`decoded JSON edit boundary`)}function projectMessageEdits(e,t,n,r){let i=new Map(n.parts.map(e=>[e.key,e])),a=[];for(let o of t){if(!o.isKey&&o.path.length===1&&o.key===`message`)continue;let t=o.rootKey===void 0?void 0:i.get(o.rootKey);if(!t||!t.json&&(o.isKey||(t.messageField?o.path.length!==2||o.key!==`message`:o.path.length!==1)))continue;let s=r(o);for(let r of s){let i,s,c=r.replacement;if(t.json){let n=t.start-expectDefined(o.rootValueStart,`displayed JSON argument`);o.string?(i=n+encodedBoundary(e,o,r.start),s=n+encodedBoundary(e,o,r.end),c=JSON.stringify(c).slice(1,-1)):(i=n+o.start,s=n+o.end,c=JSON.stringify(c))}else i=t.start+r.start,s=t.start+r.end;i<n.contentLength&&a.push({start:i,end:Math.min(s,n.contentLength),replacement:c,scalar:t.json&&!o.string})}}return a.toSorted((e,t)=>e.start-t.start||e.end-t.end)}function firstIntersectingToken(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;expectDefined(e[i],`bounded JSON token search`).currentEnd<=t?n=i+1:r=i}return n}function updateCurrentToken(e,t){if(t.raw||t.deferEncoding){t.currentRaw=t.currentValue;return}let n=[],r=[],i=t.start+ +!!t.string,a=0,o=0;for(let s of t.edits){let c=t.string?encodedBoundary(e,t,s.start):t.start+s.start,l=t.string?encodedBoundary(e,t,s.end):t.start+s.end,u=JSON.stringify(s.replacement).slice(1,-1),d=a+c-i,f=d+u.length;r.push({start:d,end:f,decodedStart:s.start+o,decodedEnd:s.start+o+s.replacement.length,sourceEnd:l,sourceDecodedEnd:s.end,replacement:u}),n.push(e.slice(i,c),u),a=f,o+=s.replacement.length-(s.end-s.start),i=l}n.push(e.slice(i,t.end-+!!t.string)),t.currentRaw=`"${n.join(``)}"`,t.encodedEdits=r}function currentDecodedBoundary(e,t,n,r){let i=n-t.currentStart-1,a=t.encodedEdits;if(!a)return decodedBoundary(e,t,t.start+1+i);let o=0,s=a.length;for(;o<s;){let e=o+s>>>1;expectDefined(a[e],`current encoded edit`).end<i?o=e+1:s=e}let c=a[o];if(c&&i>=c.start){let e=i-c.start;if(!c.replacement.includes(`\\`))return c.decodedStart+e;let t=r.get(c.replacement);t||(t=stringBoundaries(c.replacement,0,c.replacement.length),r.set(c.replacement,t));let n=t.get(e);return n===void 0?void 0:c.decodedStart+n}let l=a[o-1],u=decodedBoundary(e,t,i+(l?l.sourceEnd-l.end:t.start+1));return u===void 0?void 0:u+(l?l.decodedEnd-l.sourceDecodedEnd:0)}function commitPatternEdits(e){let t=e.pending;if(e.pending=void 0,!t)return!1;let n=mergeRedactionEdits(t),r=applyRedactionEdits(e.currentValue,n);return r!==e.currentValue&&(e.edits=composeRedactionEdits(e.value.length,e.edits,n),e.currentValue=r,!0)}function changedRedactionEdits(e,t){let n=0;return t.filter(t=>{for(;e[n]&&expectDefined(e[n],`previous configured edit`).start<t.start;)n+=1;let r=e[n];return!r||r.start!==t.start||r.end!==t.end||r.replacement!==t.replacement})}function commitOriginalEdits(e,t){if(t.length===0)return!1;let n=mergeRedactionEdits([...e.edits,...t]),r=applyRedactionEdits(e.value,n);return r!==e.currentValue&&(e.edits=n,e.currentValue=r,!0)}function updateCurrentRecord(e,t,n,r){let i=[],a=0,o=0;for(let s of n){let n=s.currentStart,c=s.currentEnd;if(r.has(s)){updateCurrentToken(e,s);let r=expectDefined(s.currentRaw,`changed JSON token`);i.push(t.slice(a,n),r),a=c,s.currentStart=n+o,o+=r.length-(c-n)}else s.currentStart=n+o;s.currentEnd=c+o}return i.push(t.slice(a)),i.join(``)}function projectedStringEnd(e,t,n,r,i,a){let o=new Set(n.parts.filter(e=>e.json).map(e=>e.key)),s=projectMessageEdits(e,t,n,e=>e.string&&!e.isKey&&e.rootKey!==void 0&&o.has(e.rootKey)?[{start:0,end:e.value.length,replacement:``}]:[]).filter(e=>e.end<n.contentLength),c=rebaseRedactionEdits(r.edits,s).filter(e=>e.start<=i&&i<e.end&&a<=e.end);return c.length===1?expectDefined(c[0],`displayed source string`).end:r.currentValue.length}function redactJsonRecord(e,t,n,r,i,a,o,s,c,l){let u=l?[]:readScalarTokens(e,t),d=c?u.find(e=>!e.isKey&&e.path.length===1&&e.key===`message`):void 0,f=/* @__PURE__ */ new Map,p=[],m=d?.value??``,h=e,g=/* @__PURE__ */ new Set;for(let e of u)commitOriginalEdits(e,o(e))&&g.add(e);g.size>0&&(h=updateCurrentRecord(e,h,u,g));let _=u.filter(e=>!e.isKey&&e.string&&!s(e,e.currentValue)),projectMessage=()=>{if(!d||!c)return!1;let t=projectMessageEdits(e,u,c,e=>{let t=changedRedactionEdits(e.projectedEdits,e.edits);return e.projectedEdits=e.edits,t});if(t.length===0)return!1;let n=rebaseRedactionEdits(p,t),r=rebaseRedactionEdits(d.edits,t),i=0;for(let e=0;e<r.length;e+=1){let a=expectDefined(r[e],`projected message edit`),o=expectDefined(n[e],`projected source edit`),s=expectDefined(t[e],`source projection`);for(;d.edits[i]&&expectDefined(d.edits[i],`generated message span`).start<s.start;)i+=1;let c=d.edits[i],l=s.scalar&&c?.start===s.start&&c.end===s.end&&a.replacement===JSON.stringify(c.replacement),u=d.currentValue.slice(a.start,a.end);!l&&u!==a.replacement&&u!==m.slice(o.start,o.end)&&(a.replacement=s.scalar?JSON.stringify(`***`):`***`)}return d.pending=r,m=applyRedactionEdits(m,n),p=composeRedactionEdits(d.value.length,p,n),commitPatternEdits(d)};for(let[o,s]of n.entries()){let n=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set,add=(e,t)=>{(e.pending??=[]).push(t),p.add(e)},m,visitDecodedMatch=(e,t)=>{let n=r(e,t),i=n?.redact(n);i&&i.end>=i.start&&add(m,i)};for(let i of s)if(!i.couldMatch||i.couldMatch(h))for(let a of i.patterns){if(o===0)for(m of _)visitRedactMatches(m.currentValue,a,visitDecodedMatch);else visitRedactMatches(h,a,n=>{let i=r(n,a);if(!(!i||i.end<i.start)){l&&u.length===0&&(u=readBatchTokens(e,t,l.preserveLines));for(let t=firstIntersectingToken(u,i.start);t<u.length;t+=1){let n=expectDefined(u[t],`serialized capture token`);if(n.currentStart>=i.end)break;let r=n.raw||n.deferEncoding,a=+!r,o=i.start>=n.currentStart+a&&i.end<=n.currentEnd-a;if(l&&n.isKey&&!o)continue;let s=n.currentValue;if(!n.raw&&!n.string&&n.edits.length===0){add(n,{start:0,end:s.length,replacement:`***`});continue}let p=Math.max(i.start,n.currentStart+a),m=r?p-n.currentStart:currentDecodedBoundary(e,n,p,f),g=Math.min(i.end,n.currentEnd-a),_=r?g-n.currentStart:currentDecodedBoundary(e,n,g,f);if(m===void 0||_===void 0){for(;m===void 0;)m=currentDecodedBoundary(e,n,--p,f);for(;_===void 0;)_=currentDecodedBoundary(e,n,++g,f);let t=n===d&&c?projectedStringEnd(e,u,c,n,m,_):s.length;add(n,{start:m,end:t,replacement:`***`});continue}if(_<m||l&&_===m)continue;let{start:ee,end:te}=i,v=i.redact({start:m,end:_,value:h.slice(Math.max(ee,n.currentStart+a),Math.min(te,n.currentEnd-a))});if(!v)continue;let ne=`***`;if(o)try{ne=r?v.replacement:JSON.parse(`"${v.replacement}"`)}catch{}add(n,{...v,replacement:ne})}}});if(p.size!==0){for(let e of p)commitPatternEdits(e)?o===0&&n.add(e):p.delete(e);o!==0&&p.size>0&&(h=updateCurrentRecord(e,h,u,p)),p.clear()}}for(let e of u)o===0?(e.pending=i(e,e.currentValue),commitPatternEdits(e)&&n.add(e)):commitOriginalEdits(e,a(e))&&n.add(e);(o!==0||g.size>0||n.size>0)&&projectMessage()&&d&&n.add(d),n.size>0&&(h=updateCurrentRecord(e,h,u,n))}if(d&&c){let e=c.finish(d.currentValue);if(e!==d.currentValue)return applyRedactionEdits(h,[{start:d.currentStart,end:d.currentEnd,replacement:JSON.stringify(e)}])}return applyRedactionEdits(h,u.flatMap(e=>e.deferEncoding&&e.edits.length>0?[{start:e.currentStart,end:e.currentEnd,replacement:JSON.stringify(e.currentValue)}]:[]))}const Pt=String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`;function createState(){return{scanner:{offset:0,phase:`search`,dashes:0,keyword:`BEGIN `,keywordOffset:0,start:0,suffix:``},matchEnd:0}}function resetScanner(e,t){e.phase=`search`,e.dashes=+(t===`-`),e.suffix=``}function*readDelimiters(e,t){for(let n=0;n<e.length;n+=1){if(t.phase===`search`&&t.dashes===0){let r=e.indexOf(`-`,n);if(r===-1){t.offset+=e.length-n;return}t.offset+=r-n,n=r}let r=e.charCodeAt(n),i=r>=97&&r<=122?String.fromCharCode(r-32):e.charAt(n),a=t.offset++;switch(t.phase){case`search`:i===`-`?t.dashes=Math.min(5,t.dashes+1):t.dashes===5&&(i===`B`||i===`E`)?(t.phase=`keyword`,t.keyword=i===`B`?`BEGIN `:`END `,t.keywordOffset=1,t.start=a-5):t.dashes=0;break;case`keyword`:i===t.keyword.charAt(t.keywordOffset)?++t.keywordOffset===t.keyword.length&&(t.phase=`label`,t.suffix=``):resetScanner(t,i);break;case`label`:i>=`A`&&i<=`Z`||i===` `?t.suffix=(t.suffix+i).slice(-11):i===`-`&&t.suffix===`PRIVATE KEY`?(t.phase=`close`,t.dashes=1):resetScanner(t,i);break;case`close`:i===`-`?++t.dashes===5&&(t.phase=`search`,t.suffix=``,yield{kind:t.keyword===`BEGIN `?`begin`:`end`,start:t.start,end:a+1}):resetScanner(t,i)}}}function consumeDelimiter(e,t){if(!e.open){t.kind===`begin`&&t.start>=e.matchEnd&&(e.open={start:t.start,end:t.end});return}if(t.kind!==`end`||t.start<=e.open.end)return;let n={start:e.open.start,end:t.end,bodyStart:e.open.end,bodyEnd:t.start};return e.open=void 0,e.matchEnd=t.end,n}function*matchPem(e,t,n){let r={...t,scanner:{...t.scanner},open:t.open&&{...t.open}},i=r.scanner.offset;for(let t of readDelimiters(e,r.scanner)){let a=consumeDelimiter(r,t);if(!a)continue;let o=Math.max(0,(n?a.bodyStart:a.start)-i),s=(n?a.bodyEnd:a.end)-i;s<=o||(yield{match:e.slice(o,s),groups:[],input:e,offset:o,...n?{replacement:`…redacted…`}:{}})}if(n&&r.open){let t=Math.max(0,r.open.end-i);t<e.length&&(yield{match:e.slice(t),groups:[],input:e,offset:t,replacement:`…redacted…`})}}const Ft={source:Pt,exec(e){return matchPem(e,createState(),!1)},createContext(){let e=!1,t=!0;return{resolve(n){e=n?t:e,t=e},advance(t){let n=createState();e&&(n.open={start:-1,end:-1});for(let e of readDelimiters(t,n.scanner))consumeDelimiter(n,e);return n.open!==void 0},prepend(){let n=createState(),r=createState();return r.open={start:-1,end:-1},{consume(e){for(let t of readDelimiters(e,n.scanner))consumeDelimiter(n,t),consumeDelimiter(r,t)},finish(){let i=n.open?t:e,a=r.open?t:e;return e=i,t=a,e===t}}},pattern:{source:Pt,exec(t){let n=createState();return e&&(n.open={start:-1,end:-1}),matchPem(t,n,!0)}}}}},It=String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`,N=String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`,Lt=String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`,P=String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`,Rt=String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${P}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`,zt=String.raw`${Rt}|app[-_]?secret|credential|${N}`,Bt=String.raw`access_token|refresh_token|id_token|auth[-_]?token|hook[-_]?token|api[-_]?key|client[-_]?secret|app[-_]?secret|private[-_]?key|authorization|jwt|token|secret|password|pass|passwd|credential|${N}`,F=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|credential|${N}`,Vt=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|passwd|credential|${N}`,Ht=String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`,Ut=String.raw`password|passphrase|pass|passwd`,Wt=String.raw`${P}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${N}`,Gt=String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`,Kt=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${It})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`,qt=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${It})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`,I=String.raw`(^|[\s,;({\["])(?:${Bt})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`,Jt=String.raw`(^|[\s,;({\["])(?:${Bt})=(["'\x60]?[^\s&#"'\x60<>]+)`,Yt=String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|${N}`,Xt=String.raw`/(^|[\s,{])(?:(?:${Yt})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Ut})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${F})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`,Zt=String.raw`/(^|[\s,{])(?:(?:${Vt})\s*:\s*|(?:${F})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`,Qt=String.raw`/(^|[\s,{])(?:${Ht})=([^\s#"'\x60<>]+)/g`,$t=String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Ut})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,en=String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${F})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,tn=String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${P}|credential|authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|authToken|auth_token|clientSecret|client_secret|privateKey|private_key|secret_value|raw_secret|secret_input|key_material)"\s*:\s*"([^"]+)"`,nn=String.raw`"(?:${Lt})"\s*:\s*"([^"]+)"`,rn=String.raw`(^|[\s,{])["']?(?:api[-_]key|access[-_]token|refresh[-_]token|id[-_]token|authToken|auth[-_]token|clientSecret|client[-_]secret|appSecret|app[-_]secret|private[-_]key|credential|authorization|secret[-_]value|raw[-_]secret|secret[-_]input|key[-_]material)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,an=String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,on=String.raw`(^|[^A-Za-z0-9])`,base64SafeToken=e=>String.raw`${on}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`,L=String.raw`(^|[^A-Za-z0-9_])`;function isAwsValueCharacter(e){let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||e===`/`||e===`+`||e===`=`}const sn=/(?=[A-Za-z0-9/+=]{0,39}[A-Z])(?=[A-Za-z0-9/+=]{0,39}[a-z])(?=[A-Za-z0-9/+=]{0,39}[0-9/+=])(?=[A-Za-z0-9/+=]{0,39}[G-Zg-z/+=])[A-Za-z0-9/+=]{40}/u;function couldMatchAwsSecretAccessKey(e){for(let t=39;t<e.length;){let n=t;for(;n>t-40&&isAwsValueCharacter(e[n]);)n--;if(n===t-40)return sn.test(e);t=n+40}return!1}const cn=/\s/,ln=/[A-Za-z0-9+.-]/,un=/[A-Za-z]/;function*matchAwsSecretAccessKeys(e){if(!couldMatchAwsSecretAccessKey(e))return;let t={'"':`"`,"'":`'`,"`":"`","<":`>`,"(":`)`,"[":`]`,"{":`}`},n=-1,r=-1,i,a=0,o=[];for(let s=0;s<=e.length;s++){let c=e[s]??``,l=s===e.length||cn.test(c),u=a;if(a=c===`\\`?a+1:0,c&&isAwsValueCharacter(c)?n===-1&&(n=s):n!==-1&&(s-n===40?o.push({start:n,end:s,origin:n,url:i}):s-n>40&&c===`@`&&e[s-41]===`/`&&o.push({start:s-40,end:s,origin:n,url:i}),n=-1),l){i&&(i.end=Math.min(i.end,s));for(let t of o){let n=t.url,r=n&&!n.hasAt&&n.portValid&&(n.portStart===-1||(n.authorityEnd===-1?n.end:n.authorityEnd)>n.portStart+1),i=e[t.start-1]??``,a=e[t.end]??``,o=t.start!==t.origin,s=n&&n.portStart!==-1&&t.origin===n.portStart+1&&n.authorityEnd>t.origin&&t.end>n.authorityEnd&&a===`@`;if(!o&&(i===`_`||isAwsValueCharacter(i))||a===`_`||e.slice(t.origin-8,t.origin)===`;base64,`||r&&!s&&t.start>=n.start&&t.end<=n.end)continue;let c=e.slice(t.start,t.end);sn.test(c)&&(yield{match:c,groups:[c],input:e,offset:t.start})}o.length=0,r=-1,i=void 0}else if(i&&s>=i.start&&(c===i.closing&&u===i.closingEscapeDepth?(i.end=Math.min(i.end,s),i=void 0):(`?#"'<>\`|()[]{}`.includes(c)&&(i.end=Math.min(i.end,s)),i.queryOrFragment||=c===`?`||c===`#`,i.authorityEnd===-1&&(i.hasAt||=c===`@`,`/?#`.includes(c)?i.authorityEnd=s:s<i.end&&(c===`:`?(i.portValid&&=i.portStart===-1,i.portStart=s):i.portStart!==-1&&(c<`0`||c>`9`)&&(i.portValid=!1))))),ln.test(c))r===-1&&(r=s);else{if((!i||s>=i.end&&!i.queryOrFragment)&&c===`:`&&e.startsWith(`//`,s+1)&&r!==-1&&un.test(e[r])){let n=e[r-1],a=0;for(let t=r-2;t>=0&&e[t]===`\\`;t--)a++;i={start:s+3,end:e.length,authorityEnd:-1,portStart:-1,portValid:!0,hasAt:!1,queryOrFragment:!1,closing:n?t[n]:void 0,closingEscapeDepth:a}}r=-1}}}const dn=Object.freeze({source:`aws-secret-access-key`,exec:matchAwsSecretAccessKeys,couldMatch:couldMatchAwsSecretAccessKey}),fn=new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${Vt})\s*:\s*`,`gi`),pn=/[^\s#"'\x60<>]+/y,mn=/[A-Za-z0-9]/,hn=/[ \t\r\n]/;function*matchBarePassAssignments(e){if(!/pass\s*:/.test(e))return;let t=[...e.matchAll(fn)];if(t.length===0)return;let n=0,r=!1;for(let i=0;i<e.length;i++){let a=t[n];if(!a)return;if(i===a.index){n++;let o=e[i-1]??``,s=a[1]!==`pass`||o===`.`||o===`-`||o===`_`;if(s||r||o!==` `||!mn.test(e[i-2]??``)){r=!0;let o=i+a[0].length;if(!s){pn.lastIndex=o;let t=pn.exec(e)?.[0];t&&(o+=t.length,yield{match:e.slice(i,o),groups:[t],input:e,offset:i})}let c=t[n];for(;c&&c.index<o;)n++,c=t[n];i=o-1;continue}}let o=e[i];o===`
`||o===`\r`?r=!1:(o===`=`||o===`:`&&!hn.test(e[i+1]??` `))&&(r=!0)}}const gn=Object.freeze({source:`bare-pass-assignment`,exec:matchBarePassAssignments}),_n=String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`,vn=String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`,yn=`x-goog-api-key|api-key|apikey|x-api-token|x-access-token`,bn=`X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token`,R=String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`,xn=String.raw`${R}(?:${yn})${M}[ \t]*:${k}${M}([^\s\\"',;]+)`,Sn=String.raw`${R}(?:${yn})${M}[ \t]*=${k}${M}([^\s\\"',;]+)`,Cn=String.raw`${R}(?:${bn})\s*:\s*([^\s"',;]+)`,wn=String.raw`${R}(?:${bn})\s*=\s*([^\s"',;]+)`,Tn=[String.raw`${j}Proxy-Authorization${M}[ \t]*[:=]${k}${M}${vt}${A}(${E})`,String.raw`${j}Proxy-Authorization${M}[ \t]*[:=]${k}${M}(${E})[ \t]*(?=${M}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,String.raw`${j}Authorization${M}[ \t]*[:=]${k}${M}(?!(?:Bearer|Basic|Bot)(?=${A}))${vt}${A}(${E})`,String.raw`${j}Authorization${M}[ \t]*[:=]${k}${M}(?!(?:Bearer|Basic|Bot)(?=${A}))(${E})[ \t]*(?=${M}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,xn,Sn],En=String.raw`Authorization${M}[ \t]*[:=]${yt}${M}Bearer${A}(${E})`,Dn=String.raw`Authorization${M}[ \t]*[:=]${yt}${M}Basic${A}(${E})`,On=String.raw`Authorization${M}[ \t]*[:=]${yt}${M}Bot${A}(${E})`,kn=String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`,An=[Kt,qt,tn,nn,rn,an,String.raw`--(?:${Wt})=([^\s"']+)`,String.raw`--(?:${Wt})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,En,Dn,On,...Tn,Cn,wn,kn,String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,String.raw`(^|[\s,;])(?:${zt})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,I,Jt,Xt,Zt,gn,Qt,$t,en,Pt,String.raw`(^|[\s,{])["']?(?:${P})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`],jn=[String.raw`\b(sk-[A-Za-z0-9_-]{8,})\b`,String.raw`(ghp_[A-Za-z0-9]{10,})`,String.raw`(github_pat_[A-Za-z0-9_]{10,})`,String.raw`(gho_[A-Za-z0-9]{10,})`,String.raw`(ghu_[A-Za-z0-9]{10,})`,String.raw`(ghs_[A-Za-z0-9]{10,})`,String.raw`(ghr_[A-Za-z0-9]{10,})`,String.raw`(glpat-[A-Za-z0-9._=\-]{20,})`,String.raw`(gloas-(?:[A-Fa-f0-9]{65,}|[A-Za-z0-9_-]{64}|[A-Fa-f0-9]{32,}))`,String.raw`(gldt-[A-Za-z0-9_-]{20,})`,String.raw`(glcbt-[A-Za-z0-9]{1,5}_[A-Za-z0-9_-]{20,})`,String.raw`(glptt-[A-Za-z0-9_-]{40,})`,String.raw`(glft-(?:[A-Za-z0-9_-]{20,}|[a-h0-9]+-[0-9]+_))`,String.raw`(glimt-[A-Za-z0-9_-]{25,})`,String.raw`(glagent-[A-Za-z0-9_-]{50,})`,String.raw`(glwt-[A-Za-z0-9_-]{20,})`,String.raw`(glsoat-[A-Za-z0-9_-]{20,})`,String.raw`(glffct-[A-Za-z0-9_-]{20,})`,String.raw`(glrt-[A-Za-z0-9._-]{20,})`,String.raw`(glrtr?-[A-Za-z0-9_-]{27,300}\.[0-9a-z]{2}\.[0-9a-z]{9})`,String.raw`(GR1348941[A-Za-z0-9_-]{20,})`,String.raw`(_gitlab_session=[A-Za-z0-9%._-]{20,})`,String.raw`(xox[baprs]-[A-Za-z0-9-]{10,})`,String.raw`(xapp-[A-Za-z0-9-]{10,})`,String.raw`(https:\/\/hooks\.slack\.com\/(?:services\/T[A-Z0-9]+\/B[A-Z0-9]+|workflows\/T[A-Z0-9]+\/A[A-Z0-9]+\/[0-9]{17,19})\/[A-Za-z0-9]{20,})`,String.raw`(https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_-]{60,})`,String.raw`discord(?:.|\n|\r){0,40}?\b([A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b`,String.raw`(gsk_[A-Za-z0-9_-]{10,})`,String.raw`(AIza[0-9A-Za-z\-_]{20,})`,String.raw`(ya29\.[0-9A-Za-z_\-./+=]{10,})`,String.raw`(1//0[0-9A-Za-z_\-./+=]{10,})`,String.raw`(GOCSPX-[A-Za-z0-9_-]{20,})`,String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,String.raw`(pplx-[A-Za-z0-9_-]{10,})`,String.raw`(fal_[A-Za-z0-9_-]{10,})`,String.raw`${L}(fc-[A-Za-z0-9]{10,})`,String.raw`(bb_live_[A-Za-z0-9_-]{10,})`,base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),String.raw`(sk_live_[A-Za-z0-9]{10,})`,String.raw`(sk_test_[A-Za-z0-9]{10,})`,String.raw`(rk_live_[A-Za-z0-9]{10,})`,String.raw`(SG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,String.raw`(npm_[A-Za-z0-9]{10,})`,String.raw`(pypi-[A-Za-z0-9_-]{10,})`,String.raw`(dop_v1_[A-Za-z0-9]{10,})`,String.raw`(doo_v1_[A-Za-z0-9]{10,})`,String.raw`(dor_v1_[A-Za-z0-9]{10,})`,String.raw`(dp\.(?:ct|pt|sa|scim|audit)\.[A-Za-z0-9]{40,44})`,String.raw`(dp\.st\.[A-Za-z0-9]{40,44})`,String.raw`(dp\.st\.[a-z0-9_-]{2,35}\.[A-Za-z0-9]{40,44})`,String.raw`(dckr_(?:pat|oat)_[A-Za-z0-9_-]{27,32})`,String.raw`(bkua_[a-z0-9]{40})`,String.raw`(CCIPAT_[A-Za-z0-9]{22}_[A-Fa-f0-9]{40})`,String.raw`(sbp_[a-z0-9]{40})`,base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),String.raw`(dd[pw]_[A-Za-z0-9]{36})`,String.raw`(glsa_[A-Za-z0-9_]{41})`,String.raw`(glc_eyJ[A-Za-z0-9+/=]{60,160})`,String.raw`(nfp_[A-Za-z0-9_]{36})`,String.raw`(CFPAT-[A-Za-z0-9_\-]{40,})`,base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),String.raw`(BBDC-[A-Za-z0-9+/@_-]{40,50})`,String.raw`(HRKU-AA[A-Za-z0-9_-]{20,})`,String.raw`(pat-(?:eu|na)1-[A-Za-z0-9]{8}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{12})`,String.raw`(apify_api_[A-Za-z0-9\-]{20,})`,String.raw`(FlyV1 fm\d+_[A-Za-z0-9+/=,_-]{100,})`,String.raw`(fio-u-[A-Za-z0-9_-]{40,})`,String.raw`(^|[^A-Za-z0-9_])(am_[A-Za-z0-9_-]{10,})`,String.raw`(^|[^A-Za-z0-9_])(sk_[A-Za-z0-9_]{10,})`,String.raw`(tvly-[A-Za-z0-9]{10,})`,String.raw`(exa_[A-Za-z0-9]{10,})`,String.raw`(syt_[A-Za-z0-9]{10,})`,String.raw`(retaindb_[A-Za-z0-9]{10,})`,String.raw`(hsk-[A-Za-z0-9]{10,})`,String.raw`(mem0_[A-Za-z0-9]{10,})`,String.raw`(brv_[A-Za-z0-9]{10,})`,String.raw`(xai-[A-Za-z0-9]{30,})`,String.raw`${L}(fw-[A-Za-z0-9]{30,})`,String.raw`${L}(fw_[A-Za-z0-9]{30,})`,String.raw`${L}(fpk_[A-Za-z0-9]{30,})`,base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),String.raw`(AKID[A-Za-z0-9]{10,})`,String.raw`(LTAI[A-Za-z0-9]{10,})`,String.raw`(hf_[A-Za-z0-9]{10,})`,String.raw`(api_org_[A-Za-z0-9]{20,})`,String.raw`(r8_[A-Za-z0-9]{10,})`,_n,vn],z=[...An,...jn,dn];function createBackendRedactPatterns(){let e=/* @__PURE__ */ new Set(/* @__PURE__ */ `access_token.auth_token.awssecretaccesskey.aws_secret_access_key.hook_token.refresh_token.id_token.token.api_key.apikey.client_secret.app_secret.password.pass.passwd.auth.jwt.session.code.signature.x_amz_signature.x_amz_security_token.secret.secretaccesskey.credential.private_key.authorization.key.card_number.card_cvc.card_cvv.cvc.cvv.security_code.payment_credential.shared_payment_token`.split(`.`)),t=RegExp(`^(?:${yn}|${bn})$`,`i`),n=/* @__PURE__ */ new Set([Sn,wn]),r=/* @__PURE__ */ new Set([Kt,qt,I,Jt]),i=new RegExp(String.raw`[:=](?<=(?:${F})\s*[:=])`),a=new RegExp(String.raw`[:=](?<=(?:${F})\s*[:=])\s*["'\x60]`),o=new RegExp(String.raw`[:=](?<=\.(?:${F})\s*[:=])`),s=new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${Bt})=)`,`i`);return{bodySecretKeys:e,credentialHeaderField:t,formAware:n,shellReferencePreserving:r,prefilters:new Map([[Kt,e=>/KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],[qt,e=>e.includes(`\\`)],[I,e=>/[=]["'`]/.test(e)],[Jt,e=>s.test(e)],[Xt,e=>/["'`]/.test(e)&&a.test(e)],[Zt,e=>(e.includes(`:`)||e.includes(`=`))&&i.test(e)],[Qt,e=>e.includes(`=`)],[$t,e=>/[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],[en,e=>o.test(e)],[rn,e=>/["']/.test(e)],[an,e=>/["']/.test(e)],...Tn.slice(0,4).map(e=>[e,e=>/authorization/i.test(e)]),[xn,e=>/api-key|apikey|api-token|access-token/i.test(e)],[Sn,e=>/api-key|apikey|api-token|access-token/i.test(e)],[tn,e=>e.includes(`"`)],[nn,e=>e.includes(`"`)],[Cn,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],[wn,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]]),chunkUnsafe:/* @__PURE__ */ new Set([_n,vn,En,Dn,On,kn,...Tn,...jn.filter(e=>e.startsWith(on))])}}const Mn=/* @__PURE__ */ new Set([9,10,11,12,13,32,160,5760,8232,8233,8239,8287,12288,65279]);function isJsWhitespaceAt(e,t){if(t>=e.length)return!1;let n=e.charCodeAt(t);return Mn.has(n)||n>=8192&&n<=8202}function isJsWhitespaceChar(e){return e!==void 0&&isJsWhitespaceAt(e,0)}function isAlnumChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function isLetterChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function isWordChar(e){return e===`_`||isAlnumChar(e)}function isHexChar(e){if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function isDigitChar(e){return e!==void 0&&e.charCodeAt(0)>=48&&e.charCodeAt(0)<=57}function isBase64UrlChar(e){return isAlnumChar(e)||e===`+`||e===`/`||e===`=`}const Nn=/* @__PURE__ */ new Map;function*scanPrefixOccurrences(e,t){let n=Nn.get(t);n||(n=[],Nn.set(t,n));let r=n.pop()??new RegExp(t,`gi`);try{r.lastIndex=0;for(let t=r.exec(e);t;t=r.exec(e))yield t.index}finally{r.lastIndex=0,n.push(r)}}function isDataUrlPrefix(e,t){return t>=8&&e.slice(t-8,t).toLowerCase()===`;base64,`}function runEndOf(e,t,n){let r=t;for(;r<e.length&&n(e[r]);)r+=1;return r}function makeCachedRunEnd(e,t){let n=-1,r=-1;return i=>((i<n||i>=r)&&(n=i,r=runEndOf(e,i,t)),r)}function makeBase64SafeTokenMatcher(e,t,n){function*exec(e){let r=n(),i=-1,a=-1,o=0;for(let n of scanPrefixOccurrences(e,t)){if(n<o||n>0&&isAlnumChar(e[n-1]))continue;if(n>0){let t;if(isBase64UrlChar(e[n-1])){if(n-1>=i&&n-1<a)t=i;else{let r=n-1;for(;r>0&&isBase64UrlChar(e[r-1]);)--r;i=r,a=runEndOf(e,n,isBase64UrlChar),t=r}}else t=n;if(isDataUrlPrefix(e,t))continue}let t=r(e,n);if(t===null)continue;let s=n>0?n-1:0;yield{match:e.slice(s,t),groups:[n>0?e[n-1]:``,e.slice(n,t)],input:e,offset:s},o=t+1}}return Object.freeze({source:e,exec})}const GAAAA_VALUE_CHAR=e=>isAlnumChar(e)||e===`_`||e===`=`||e===`-`,ATBB_VALUE_CHAR=e=>isAlnumChar(e)||e===`_`||e===`=`||e===`.`||e===`-`,AT_VALUE_CHAR=e=>isAlnumChar(e)||e===`+`||e===`/`||e===`=`||e===`-`||e===`_`;function fixedTailTokenEnd(e,t,n){return(r,i)=>{let a=i+e+t;for(let t=i+e;t<a;t++)if(!n(r[t]))return null;return a}}const Pn=fixedTailTokenEnd(4,32,isHexChar);function dapiTokenEnd(e,t){let n=Pn(e,t);return n===null?null:e[n]===`-`&&isDigitChar(e[n+1])?n+2:n}function makeAtEqualsTokenMatcher(e,t){let n=t.length,r=fixedTailTokenEnd(1,8,isAlnumChar);return makeBase64SafeTokenMatcher(e,t,()=>{let e=-1,t=-1,i;return(a,o)=>{let s=o+n;if(s<e||s>=t){t=runEndOf(a,s,AT_VALUE_CHAR),e=s,i=void 0;for(let e=s;e<t;e++)a[e]===`=`&&r(a,e)!==null&&(i=e)}let c=s+1;return i!==void 0&&i>=c?i+9:null}})}const Fn=makeBase64SafeTokenMatcher(`vendor-token gAAAA (linear)`,`gAAAA`,()=>(e,t)=>{let n=runEndOf(e,t+5,GAAAA_VALUE_CHAR);return n-(t+5)>=20?n:null}),In=makeBase64SafeTokenMatcher(`vendor-token ATBB (linear)`,`ATBB`,()=>(e,t)=>{let n=runEndOf(e,t+4,ATBB_VALUE_CHAR);return n-(t+4)>=16?n:null}),Ln=makeBase64SafeTokenMatcher(`vendor-token AKIA (linear)`,`AKIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),Rn=makeBase64SafeTokenMatcher(`vendor-token ASIA (linear)`,`ASIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),zn=makeBase64SafeTokenMatcher(`vendor-token dapi (linear)`,`dapi`,()=>dapiTokenEnd),Bn=makeAtEqualsTokenMatcher(`vendor-token ATCTT3xFfG (linear)`,`ATCTT3xFfG`),Vn=makeAtEqualsTokenMatcher(`vendor-token ATATT (linear)`,`ATATT`),Hn=String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,JWT_SEGMENT_CHAR=e=>isAlnumChar(e)||e===`_`||e===`-`,Un=Object.freeze({source:`jwt (linear)`,*exec(e){let t=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),n=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),r=makeCachedRunEnd(e,JWT_SEGMENT_CHAR),i=0;for(let a of scanPrefixOccurrences(e,`eyj`)){if(a<i)continue;let o=t(a+3);if(o-(a+3)<10||e[o]!==`.`)continue;let s=n(o+1);if(s-(o+1)<10||e[s]!==`.`)continue;let c=r(s+1);if(c-(s+1)<10)continue;let l=e.slice(a,c);yield{match:l,groups:[l],input:e,offset:a},i=c}}}),Wn=String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,Gn=String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,Kn=/* @__PURE__ */ new Set([`http`,`https`,`ws`,`wss`,`ftp`]),qn=/* @__PURE__ */ new Set([`postgres`,`postgresql`,`mysql`,`mongodb`,`mongodb+srv`,`redis`,`rediss`,`amqp`,`amqps`]);function makeUserInfoMatcher(e,t,n){function*exec(e){let r=0,i=-1,a=e.indexOf(`://`);for(;a!==-1;){let o=a;for(;o>0&&isWordChar(e[o-1]);)--o;let s=e.slice(o,a).toLowerCase(),c=o;if(!t.has(s)&&o>=8&&s===`srv`&&e.slice(o-8,o).toLowerCase()===`mongodb+`&&(s=`mongodb+srv`,c=o-8),a>=r&&t.has(s)&&(c===0||!isWordChar(e[c-1]))){let t=a+3;for(;t<e.length&&e[t]!==`:`&&e[t]!==`/`&&e[t]!==`@`&&!isJsWhitespaceAt(e,t);)t+=1;if(e[t]===`:`){let o=t+1;if(o>=i){let t=runEndOf(e,o,e=>!n(e));if(e[t]===`@`&&t>o){yield{match:e.slice(c,t+1),groups:[e.slice(o,t)],input:e,offset:c},r=t+1,a=e.indexOf(`://`,t+1);continue}i=t}}}a=e.indexOf(`://`,a+1)}}return Object.freeze({source:e,exec})}const Jn=makeUserInfoMatcher(`url-userinfo (linear)`,Kn,e=>e===`/`||e===`@`||isJsWhitespaceChar(e)),Yn=makeUserInfoMatcher(`connection-string (linear)`,qn,e=>e===`@`||isJsWhitespaceChar(e)),Xn=String.raw`(^|[\s,;])(?:${zt})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,Zn=RegExp(`^(?:${zt})$`,`i`),FORM_FIRST_PAIR_KEY_CHAR=e=>isAlnumChar(e)||e===`-`||e===`_`,FORM_FIRST_PAIR_TAIL_CHAR=e=>isAlnumChar(e)||e===`_`||e===`.`||e===`-`;function isFormPairBoundary(e,t){let n=e[t+1];return n===void 0||!isLetterChar(n)&&n!==`_`?!1:e[runEndOf(e,t+2,FORM_FIRST_PAIR_TAIL_CHAR)]===`=`}const Qn=Object.freeze({source:`form-body-first-pair (linear)`,*exec(e){let t=makeCachedRunEnd(e,e=>e!==`&`&&!isJsWhitespaceChar(e)),n=0,r=e.indexOf(`=`);for(;r!==-1;){let i=r;for(;i>0&&FORM_FIRST_PAIR_KEY_CHAR(e[i-1]);)--i;let a=e.slice(i,r);if(r>=n&&a.length>0&&Zn.test(a)&&(i===0||e[i-1]===`,`||e[i-1]===`;`||isJsWhitespaceAt(e,i-1))){let a=r+1,o=t(a);if(o>a&&o<e.length&&e[o]===`&`&&isFormPairBoundary(e,o)){let t=i>0?i-1:0;yield{match:e.slice(t,o),groups:[i>0?e[i-1]:``,e.slice(a,o)],input:e,offset:t},n=o,r=e.indexOf(`=`,o);continue}}r=e.indexOf(`=`,r+1)}}}),$n=String.raw`(^|[\s,;({\["])(?:${Bt})=(["'\x60])`,er=String.raw`(^|[\s,{])(?:(?:${Yt})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${Ut})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${F})\s*[:=]\s*)(["'\x60])`;function makeQuotedAssignmentMatcher(e,t,n){let r=[];function*exec(e){let i=r.pop()??new RegExp(t,n),a=/* @__PURE__ */ new Map,o=0;try{for(;;){i.lastIndex=o;let t=i.exec(e);if(!t)return;let n=t.index,r=t[2],s=n+t[0].length,c=a.get(r),l=-1;if(!(c!==void 0&&s>=c.start&&s<c.end))for(l=s;l<e.length;){let t=e[l];if(t===r||t===`\r`||t===`
`)break;l+=1}if(l>s&&e[l]===r){let i=l+1;yield{match:e.slice(n,i),groups:[t[1]??``,r,e.slice(s,l)],input:e,offset:n},o=i}else l!==-1&&a.set(r,{start:s,end:l}),o=n+1}}finally{i.lastIndex=0,r.push(i)}}return Object.freeze({source:e,exec})}const tr=makeQuotedAssignmentMatcher(`standalone-quoted-assignment (linear)`,$n,`gi`),nr=makeQuotedAssignmentMatcher(`config-quoted-assignment (linear)`,er,`g`),rr=/* @__PURE__ */ new Map([[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),Fn],[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Bn],[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),Vn],[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),In],[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),zn],[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),Ln],[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),Rn],[Hn,Un],[Wn,Jn],[Gn,Yn],[Xn,Qn],[I,tr],[Xt,nr]]),ir=/(["'`,;)}\]]+)$/u,ar=/^["'`,;)}\]]*$/u,or=/* @__PURE__ */ new Set([`"`,`'`,"`"]);function maskToken(e){return e.length<18?`***`:`${sliceUtf16Safe(e,0,6)}…${sliceUtf16Safe(e,-4)}`}function splitSecretValueForMask(e){let t=e[0]??``,n=+!!or.has(t);if(n){let n=e.lastIndexOf(t);if(n>0){let t=e.slice(n+1);if(ar.test(t))return{maskable:e.slice(1,n),suffix:t,maskStart:0,maskEnd:n+1}}}let r=e.slice(n),i=r.match(ir)?.[1]??``,a=i&&i.length<r.length?r.slice(0,-i.length):r;return{maskable:a,suffix:a===r?``:i,maskStart:0,maskEnd:n+a.length}}function splitFormAwareCredentialValue(e){let t=e.search(/&[A-Za-z_][A-Za-z0-9_.-]*=/u);return t<0?{secret:e,suffix:``}:{secret:e.slice(0,t),suffix:e.slice(t)}}function maskSecretValue(e){let{maskable:t,suffix:n}=splitSecretValueForMask(e);return`${maskToken(t)}${n}`}const sr=le(`openclaw.redaction`);function startRedactionMeasurement(e){if(!sr.hasSubscribers)return;let t=ee.now(),n=process.threadCpuUsage();return(r,i,a)=>{let o=ee.now()-t,s=process.threadCpuUsage(n);sr.publish({operation:e,outcome:r,pid:process.pid,threadId:de,isMainThread:ue,elapsedMs:o,threadCpuMs:(s.user+s.system)/1e3,...i===void 0?{}:{inputChars:i},...a===void 0?{}:{patternCount:a}})}}const cr=/KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|COOKIE|SIGNATURE|CREDENTIAL|CARD|CVC|CVV|PAYMENT|security[-_]?code|\bpass\s*[=:]|\bpassphrase\s*[=:]|_(?:password|pass|passphrase|passwd)\s*[=:]|jwt\s*[=:]|session=|code=|\bsig\s*=/iu,lr=/sk-|GOCSPX-|gh[opsur]_|github_pat_|glpat-|gloas-|gldt-|glcbt-|glptt-|glft-|glimt-|glagent-|glwt-|glsoat-|glffct-|glrt-|glrtr-|_gitlab_session=|xox[baprs]-|xapp-|gsk_|pplx-|fal_|fc-|bb_live_|[sr]k_(?:live|test)_|npm_|pypi-|do[opr]_v1_|dckr_|bkua_|CCIPAT_|sbp_|dd[pw]_|glsa_|nfp_|CFPAT-|BBDC-|HRKU-|pat-(?:eu|na)1-|apify_api_|fio-u-|tvly-|exa_|syt_|retaindb_|mem0_|brv_|xai-|fw-|fw_|fpk_|(?:^|[^A-Za-z0-9_])(?:am_|sk_)|hf_|api_org_|r8_/iu,ur=/PRIVATE KEY|\bBearer\s+|GR1348941|hooks\.slack\.com|discord|AIza|ya29\.|1\/\/0|eyJ|gAAAA|SG\.|dp\.(?:ct|pt|sa|st|scim|audit)\.|dapi[0-9a-f]|ATCTT3|ATATT|ATBB|FlyV1|A[KS]IA[A-Z0-9]|AKID|LTAI|\bbot\d{6,}:|\b\d{6,}:[A-Za-z0-9_-]{20,}/iu,dr=RegExp(`[${Gt}+%]`,`u`),fr=/JWT|Bearer\s+|am_|sk_|(?<!\d)\d{6,}:[A-Za-z0-9_-]{20,}/i;function couldMatchDefaultRedactPatterns(e){return cr.test(e)||(e.includes(`-`)||e.includes(`_`))&&lr.test(e)||ur.test(e)||e.includes(`://`)&&e.includes(`@`)||e.includes(`=`)&&dr.test(e)||dn.couldMatch(e)}function couldMatchDefaultFullContextPatterns(e){return couldMatchDefaultRedactPatterns(e)||fr.test(e)}function couldMatchVendorRedactPatterns(e){return(e.includes(`-`)||e.includes(`_`))&&lr.test(e)||ur.test(e)||fr.test(e)}function createRedactPrefilter(e){let t=/* @__PURE__ */ new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function groupPluginRecords(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}const B=resolveGlobalSingleton(Symbol.for(`openclaw.secretRedactionRegistry`),()=>({revision:0,registeredValues:/* @__PURE__ */ new Map,registeredValueRedactor:void 0}));function invalidateMatcher(){B.revision+=1,B.registeredValueRedactor=void 0}function redactRegisteredSecretValues(e,t){return!e||B.registeredValues.size===0?e:(B.registeredValueRedactor??=createSecretValueRedactor([...B.registeredValues.keys()]),B.registeredValueRedactor(e,t))}function createSecretValueRedactor(e){let t,n;return(r,i)=>{if(!r||e.length===0)return r;let a=!1;n??=new Set(e.map(e=>e.charAt(0)));for(let e of n)if(r.includes(e)){a=!0;break}if(!a)return r;if(!t){let n=groupPluginRecords(e.toSorted((e,t)=>t.length-e.length),e=>e.slice(0,6));t={prefixes:new RegExp([...n.keys()].map(escapeRegExp).join(`|`),`g`),buckets:n}}let{prefixes:o,buckets:s}=t,c=[];o.lastIndex=0;for(let e=o.exec(r);e;e=o.exec(r)){let t=e.index,n=s.get(e[0])?.find(e=>r.startsWith(e,t));n!==void 0&&c.push({index:t,value:n}),o.lastIndex=t+(n?.length??1)}let l=``,u=0;for(let e of c)l+=`${r.slice(u,e.index)}${i(e.value,e.index)}`,u=e.index+e.value.length;return l+r.slice(u)}}function resetSecretRedactionRegistryForTest(){B.registeredValues.clear(),invalidateMatcher()}process.env.VITEST&&(globalThis[Symbol.for(`openclaw.secretRedactionRegistryTestApi`)]={resetSecretRedactionRegistryForTest});const pr=/* @__PURE__ */ new Set([`ERR_TLS_CERT_ALTNAME_INVALID`,`HOSTNAME_MISMATCH`]),mr=/* @__PURE__ */ new Set(/* @__PURE__ */ `CERT_CHAIN_TOO_LONG.CERT_HAS_EXPIRED.CERT_NOT_YET_VALID.CERT_REJECTED.CERT_REVOKED.CERT_SIGNATURE_FAILURE.CERT_UNTRUSTED.CRL_HAS_EXPIRED.CRL_NOT_YET_VALID.CRL_SIGNATURE_FAILURE.DEPTH_ZERO_SELF_SIGNED_CERT.ERROR_IN_CERT_NOT_AFTER_FIELD.ERROR_IN_CERT_NOT_BEFORE_FIELD.ERROR_IN_CRL_LAST_UPDATE_FIELD.ERROR_IN_CRL_NEXT_UPDATE_FIELD.INVALID_CA.INVALID_PURPOSE.PATH_LENGTH_EXCEEDED.SELF_SIGNED_CERT_IN_CHAIN.UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY.UNABLE_TO_DECRYPT_CERT_SIGNATURE.UNABLE_TO_DECRYPT_CRL_SIGNATURE.UNABLE_TO_GET_CRL.UNABLE_TO_GET_ISSUER_CERT.UNABLE_TO_GET_ISSUER_CERT_LOCALLY.UNABLE_TO_VERIFY_LEAF_SIGNATURE`.split(`.`)),hr=[/hostname\/ip does not match certificate(?:'s)? altnames/i,/hostname mismatch/i,/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i],gr=[/certificate has expired/i,/certificate is not yet valid/i,/self[- ]signed certificate/i,/unable to get local issuer certificate/i,/unable to verify the first certificate/i];function classifyCode(e){return pr.has(e)?`hostname_mismatch`:mr.has(e)?`certificate_invalid`:null}function classifyMessage(e){return hr.some(t=>t.test(e))?`hostname_mismatch`:gr.some(t=>t.test(e))?`certificate_invalid`:null}function inspectTlsCertificateErrorInternal(e,t,n){if(n>8)return null;if(typeof e==`string`){let t=classifyMessage(e);return t?{kind:t,message:e}:null}if(!e||typeof e!=`object`||t.has(e))return null;t.add(e);let r=e,i=typeof r.code==`string`?r.code.trim().toUpperCase():void 0,a=typeof r.message==`string`&&r.message.trim()?r.message:void 0,o=i?classifyCode(i):null;if(i&&o)return{kind:o,code:i,message:a??i};let s=Array.isArray(r.errors)?r.errors:[];for(let e of[r.cause,r.error,...s]){let r=inspectTlsCertificateErrorInternal(e,t,n+1);if(r)return r}let c=a?classifyMessage(a):null;return c&&a?{kind:c,message:a}:null}function inspectTlsCertificateError(e){return inspectTlsCertificateErrorInternal(e,/* @__PURE__ */ new Set,0)}const _r=/(?:\s*:\s*|\s+)/;RegExp(`^(?:http\\s*)?(\\d{3})${_r.source}(.+)$`,`i`),RegExp(`^(?:http\\s*)?(\\d{3})(?:${_r.source}([\\s\\S]+))?$`,`i`);const vr="Couldn't connect to the AI service. Check your connection, then try again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.",yr=[{code:/\beconnrefused\b/i,phrases:/connection refused|actively refused/i,message:vr},{code:/\beconnreset\b|\beconnaborted\b|\benetreset\b|\bepipe\b/i,phrases:/socket hang up|connection reset|connection aborted/i,message:"Lost the connection to the AI service. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`."},{code:/\benotfound\b|\beai_again\b|\benetunreach\b|\behostunreach\b|\behostdown\b/i,phrases:/getaddrinfo|no such host|\bdns\b|network is unreachable|host is unreachable|fetch failed|connection error|network request failed/i,message:vr}];function isKnownTransportErrorCode(e){return yr.some(({code:t})=>t.exec(e)?.[0]===e)||inspectTlsCertificateError({code:e})?.code===e}function shouldRedactStructuredAuthorizationCode(e,t,n){if(e!==`code`)return!1;let r=t.map(e=>e.toLowerCase());return r.length===1||r.at(-1)===`code`&&[`error`,`nodeerror`,`status`,`details`,`warnings`].includes(r.at(-2)??``)?!1:!(n!==void 0&&r.length>1&&r.slice(0,-1).every(e=>e===`cause`)&&isKnownTransportErrorCode(n))}const br=`tools`,V=createBackendRedactPatterns(),xr=/* @__PURE__ */ new WeakSet,Sr=/* @__PURE__ */ new WeakSet,Cr=/* @__PURE__ */ new WeakMap,wr=new Set(jn),Tr=/* @__PURE__ */ new WeakSet,Er=new Set(z.filter(e=>typeof e==`string`)),Dr=/* @__PURE__ */ new WeakSet;let H,Or=!1;const kr=new RegExp(String.raw`[${Gt}+]`,`gu`),Ar=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,jr=/%[0-9A-Fa-f]{2}/u,U=String.raw`[${Gt}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${Gt}+])*`,Mr=`[^&\\s<>]*`,W=String.raw`${U}=${Mr}`,Nr=new RegExp(String.raw`^${W}(?:&${W})+$`,`u`),Pr=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`])(${W}(?:&${W})+)`,`gu`),Fr=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`&])(${U})=(${Mr})`,`gu`),Ir=new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${U})=(${Mr})(["'\x60]?)`,`giu`),Lr=new RegExp(String.raw`([?&])(${U})=(${`[^&#\\s<>]*`})`,`gu`),Rr=/(\r\n|\r|\n)/u,zr=/^(?:\r\n|\r|\n)$/u,Br=new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${P}|credential|authorization|private[-_]?key|privateKey|access[-_]?token|accessToken|refresh[-_]?token|refreshToken|id[-_]?token|idToken|auth[-_]?token|authToken|client[-_]?secret|clientSecret|app[-_]?secret|appSecret|secret[-_]?value|secretValue|raw[-_]?secret|rawSecret|secret[-_]?input|secretInput|key|key[-_]?material|keyMaterial|jwt|session|signature|cookie|set[-_]?cookie|${N}|${Lt})$`,`i`),Vr=/^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u,Hr=/^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i,Ur=/\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g,Wr=/* @__PURE__ */ new Set([`case`,`claw`,`demo`,`file`,`main`,`name`,`open`,`path`,`slug`,`test`]),Gr=new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${It})$`,`i`);function parsePattern(e){if(e===Pt)return Ft;if(typeof e!=`string`&&!(e instanceof RegExp))return typeof e==`object`&&e&&typeof e.exec==`function`?e:null;let t=typeof e==`string`?rr.get(e)??null:null,n=!0;if(e instanceof RegExp)t=e.flags.includes(`g`)?e:new RegExp(e.source,`${e.flags}g`);else if(!t&&e.trim()){let[r,i]=parseRedactPatternSource(e),a=Er.has(e)?rewriteOpenEndedRepeats(r,i):r;t=compileConfigRegex(a,i)?.regex??null,n=t!==null&&t.source===a&&t.flags===i&&t.exec===RegExp.prototype.exec&&t[Symbol.replace]===RegExp.prototype[Symbol.replace]}if(t&&typeof e==`string`&&V.shellReferencePreserving.has(e)&&xr.add(t),t&&typeof e==`string`&&V.formAware.has(e)&&Dr.add(t),t&&typeof e==`string`&&(e.startsWith(L)||V.chunkUnsafe.has(e))&&Tr.add(t),t&&typeof e==`string`){if(Er.has(e)&&Sr.add(t),n&&wr.has(e)&&!Cr.has(t)){let e=t.source,n=t.exec,r=t instanceof RegExp?t.flags:void 0,i=t instanceof RegExp?t[Symbol.replace]:void 0;Cr.set(t,()=>t.source===e&&t.exec===n&&(!(t instanceof RegExp)||t.flags===r&&t[Symbol.replace]===i))}let r=V.prefilters.get(e);n&&r&&setRedactPatternPrefilter(t,r)}return t}function resolvePatterns(e){if(usesBuiltInRedactPatterns(e))return H??=z.map(parsePattern).filter(e=>!!e),H;let t=/* @__PURE__ */ new Set,n=!Array.isArray(e);for(let r of Array.isArray(e)?e:[]){let e=parsePattern(r);e?t.add(e):n=!0}if(n){for(let e of resolvePatterns())t.add(e);if(!Or){Or=!0;try{console.warn(`[openclaw] Ignoring invalid logging.redactPatterns entries; keeping valid patterns and built-in redaction. Fix logging.redactPatterns in your config.`)}catch{}}}return t.add(dn),[...t]}function usesBuiltInRedactPatterns(e){return e===void 0||e===z||Array.isArray(e)&&e.length===0}function normalizeSensitiveKeyName(e){let t=e.replace(Ar,``);try{return decodeURIComponent(t).replace(Ar,``).toLowerCase().replaceAll(`-`,`_`)}catch{return t.toLowerCase().replaceAll(`-`,`_`)}}function isSensitiveBodyKey(e){return isSensitiveUrlQueryParamName(e)||V.bodySecretKeys.has(normalizeSensitiveKeyName(e))}function hasEncodedOrInvisibleFormKey(e){return jr.test(e)||e.replace(kr,``)!==e}function visitSensitiveAssignments(e,t,n){if(!e||t===`url`&&!e.includes(`?`)||t===`encoded`&&!e.includes(`%`)&&e.replace(kr,``)===e||t===`context`&&!/[=:]/u.test(e))return;let visitPair=(e,r,i)=>{if(t===`encoded`&&!hasEncodedOrInvisibleFormKey(e)||!isSensitiveBodyKey(e))return;let{maskable:a,maskStart:o,maskEnd:s}=splitSecretValueForMask(r);n(i+o,i+s,a)};if(t===`form`){let t=0;for(let n of e.split(`&`)){let e=n.indexOf(`=`);e>=0&&visitPair(n.slice(0,e),n.slice(e+1),t+e+1),t+=n.length+1}return}let r=t===`url`?Lr:t===`encoded`?Fr:Ir,i=t===`context`?3:2;r.lastIndex=0;try{for(let t=r.exec(e);t;t=r.exec(e)){let e=t[1]??``,n=t[i]??``;visitPair(n,t[i+1]??``,t.index+e.length+n.length+1)}}finally{r.lastIndex=0}}function redactAssignmentValues(e,t,n){let r=[],i=[],a=0;return visitSensitiveAssignments(e,t,(o,s,c)=>{let l=t===`url`?maskToken(c):`***`;r.push(e.slice(a,o),l),n&&i.push({start:o,end:s,replacement:l}),a=s}),i.length>0&&n?.(i),r.length>0?r.join(``)+e.slice(a):e}function redactFormBodyLine(e,t){if(!e.includes(`=`))return e;let n=redactAssignmentValues(redactAssignmentValues(e,`encoded`,t),`context`,t);if(!n.includes(`&`))return n;if(Nr.test(n))return redactAssignmentValues(n,`form`,t);let r=[],i=n.replace(Pr,(e,n,i,a)=>{let o=redactAssignmentValues(i,`form`,t?e=>{for(let t of e)r.push({...t,start:a+n.length+t.start,end:a+n.length+t.end})}:void 0);return o===i?e:`${n}${o}`});return r.length>0&&t?.(r),redactAssignmentValues(redactAssignmentValues(i,`encoded`,t),`context`,t)}function redactFormBody(e,t){if(!e.includes(`=`))return e;if(Rr.test(e)){let n=0;return e.split(Rr).map(e=>{let r=zr.test(e)?e:redactFormBodyLine(e,t?e=>t(e.map(e=>({...e,start:n+e.start,end:n+e.end}))):void 0);return n+=r.length,r}).join(``)}return redactFormBodyLine(e,t)}function isShellReferenceToKey(e,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(e))return!1;let n=t.match(/^\$([A-Z_][A-Z0-9_]*)$/);return n?n[1]===e:t.match(/^\$\{([A-Z_][A-Z0-9_]*)(?::[-=?+])?\}$/)?.[1]===e}function maskSecretFieldValue(e,t){let n=t.match(/^\$\{([A-Z_][A-Z0-9_]*):[-=?+][^{}]+\}(?![\s\S])/);return n&&n[1]===e?`${t.slice(0,t.indexOf(`:`)+2)}***}`:`***`}function shouldPreserveShellReferenceMatch(e,t){let n=e.match(/\b([A-Z_][A-Z0-9_]*)\b\s*[=:]/)?.[1];return n?isShellReferenceToKey(n,t):!1}function isEmptyShellParameterExpansionTail(e){return/^[-=?+]\}$/.test(e)}function prepareRedactionCapture({match:e,groups:t,input:n,offset:r,replacement:i},a){if(e.includes(`PRIVATE KEY-----`))return{start:r,end:r+e.length,value:e,redact:e=>({start:e.start,end:e.end,value:e.value,replacement:i??redactPemBlock(e.value,`…redacted…`)})};let o=selectSecretCapture(e,t);if(o.value===`***`)return;let s=o.value===e?0:getSecretCaptureStart(a,n,e,r,o);if(s<0)return;let c=r+s;return{start:c,end:c+o.value.length,value:o.value,redact:t=>{let n=t.value,r=Dr.has(a)?splitFormAwareCredentialValue(n):{secret:n,suffix:``};if(splitSecretValueForMask(r.secret).maskable===`***`)return;let o=xr.has(a);if(o&&(shouldPreserveShellReferenceMatch(e,n)||isEmptyShellParameterExpansionTail(n)))return;let s=i??(o?maskToken(n):`${maskSecretValue(r.secret)}${r.suffix}`);return{start:t.start,end:t.end,replacement:s}}}}function redactMatch(e,t){let n=prepareRedactionCapture(e,t),r=n?.redact(n);return r?e.match.slice(0,r.start-e.offset)+r.replacement+e.match.slice(r.end-e.offset):e.match}function redactText(e,t,n){let r=startRedactionMeasurement(`text`),i=`error`;try{let r=redactFormBody(redactAssignmentValues(redactStructuredAuthHeaders(e,`***`),`url`)),a,replace=e=>redactMatch(e,a),replaceRegex=(...e)=>replace(readRedactMatch(e)),o,s=!1;for(a of t)Cr.get(a)?.()&&(o!==r&&(o=r,s=couldMatchVendorRedactPatterns(r)),!s)?a instanceof RegExp&&(a.lastIndex=0):r=a instanceof RegExp&&!n?.fullContext&&!Sr.has(a)&&!Tr.has(a)?replacePatternBounded(r,a,replaceRegex):replaceRedactPattern(r,a,replace,replaceRegex);return i=`ok`,r}finally{r?.(i,e.length,t.length)}}function looksLikeAppSpecificPassword(e){return e.split(`-`).every(e=>!Wr.has(e.toLowerCase()))}function redactAppSpecificPasswords(e){return e.includes(`-`)?e.replace(Ur,(e,t)=>looksLikeAppSpecificPassword(t)?maskToken(t):e):e}function resolveConfigRedaction(){let e=readLoggingConfig();return{mode:br,patterns:e?.redactPatterns}}function resolveRedactOptions(e){let t=e??resolveConfigRedaction(),n=t.mode===`off`?`off`:br;return{mode:n,patterns:n===`off`?[]:resolvePatterns(t.patterns)}}function redactSensitiveText(e,t){return e&&redactSensitiveTextWithOptions(redactRegisteredSecretValues(e,maskToken),t??resolveConfigRedaction())}function redactSensitiveTextWithOptions(e,t){return t.mode===`off`||usesBuiltInRedactPatterns(t.patterns)&&!couldMatchDefaultRedactPatterns(e)?e:redactText(e,resolveRedactOptions(t).patterns)}function resolveToolPayloadRedaction(e=readLoggingConfig()){let t=e?.redactPatterns;return{mode:`tools`,patterns:Array.isArray(t)&&t.length>0?[...t,...z]:t}}function redactToolPayloadText(e){return redactToolPayloadTextWithConfig(e,readLoggingConfig())}function redactToolPayloadTextWithConfig(e,t){return redactSensitiveText(e,resolveToolPayloadRedaction(t))}function isSensitiveFieldKey(e){return Br.test(e)||Gr.test(e)}function isPublicShareIdPath(e){return e.at(-1)?.toLowerCase()===`id`&&e.at(-2)?.toLowerCase().replaceAll(`-`,``).replaceAll(`_`,``)===`publicshare`}function redactSensitiveFieldValueWithOptions(e,t,n,r=[e],i=!0,a=couldMatchDefaultRedactPatterns){let o=redactRegisteredSecretValues(t,maskToken);if(isPublicShareIdPath(r))return maskToken(o);let s=resolveRedactOptions(n);if(s.mode===`off`)return o;let c=!usesBuiltInRedactPatterns(n.patterns)||a(o)?redactText(o,s.patterns):o;if(c!==t||Hr.test(e)){let e=redactAppSpecificPasswords(c);if(e!==t)return e}return c===t?shouldRedactStructuredStringField(e,o,r,i)?maskToken(o):o:c}function shouldRedactStructuredPrimitiveField(e,t){let n=e.toLowerCase();return isPublicShareIdPath(t)||shouldRedactStructuredAuthorizationCode(n,t)||isSensitiveFieldKey(e)}function isPlainRedactableObject(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function redactStructuredSecretValue(e,t,n,r,i,a=e?[e]:[],o=!0){if(typeof t==`string`)return redactSensitiveFieldValueWithOptions(e,t,r,a,o,i);if(t==null)return t;if(typeof t==`number`||typeof t==`boolean`||typeof t==`bigint`)return shouldRedactStructuredPrimitiveField(e,a)?`***`:t;if(Array.isArray(t)){if(n.has(t))return`[Circular]`;n.add(t);let o=t.map(t=>redactStructuredSecretValue(e,t,n,r,i,a,!1));return n.delete(t),o}if(typeof t==`object`){if(n.has(t))return`[Circular]`;if(!isPlainRedactableObject(t))return t;n.add(t);let e=Object.entries(t);for(let t of e){let[e,s]=t;t[1]=redactStructuredSecretValue(e,s,n,r,i,[...a,e],o)}return n.delete(t),Object.fromEntries(e)}return t}function redactSecretsWithOptions(e,t){return typeof e==`string`?redactSensitiveText(e,t):typeof e!=`object`||!e?e:redactStructuredSecretValue(``,e,/* @__PURE__ */ new WeakSet,t,createRedactPrefilter(couldMatchDefaultRedactPatterns))}function redactSecrets(e){return redactSecretsWithOptions(e,resolveToolPayloadRedaction())}function preservesStructuredReference(e,t){return e.toLowerCase()===`session`&&Vr.test(t)||isShellReferenceToKey(e,t)}function shouldRedactStructuredStringField(e,t,n,r){return shouldRedactStructuredAuthorizationCode(e.toLowerCase(),n,r?t:void 0)||isSensitiveFieldKey(e)&&!preservesStructuredReference(e,t)}function classifyLogFieldProtection(e,t,n,r){return(r===void 0?shouldRedactStructuredPrimitiveField(e,t):isPublicShareIdPath(t)||shouldRedactStructuredStringField(e,r,t,n))?`legacy`:V.credentialHeaderField.test(e)?`header`:void 0}function getFieldRecordEdits(e,t){let{key:n,value:r,path:i,objectPath:a}=e;return t===`off`||!e.string&&r===`null`||!classifyLogFieldProtection(n,i,a,e.string?r:void 0)?[]:[{start:0,end:r.length,replacement:maskSecretFieldValue(n,r)}]}function getTextRecordEdits(e,t,n){let{value:r}=e;if(e.isKey||n&&!e.origin.structured)return[];if(n&&e.origin.primitiveMask)return[{start:0,end:r.length,replacement:`***`}];if(!e.string)return[];let i=[],a=redactRegisteredSecretValues(r,(e,t)=>{let n=maskToken(e);return i.push({start:t,end:t+e.length,replacement:n}),n});if(n&&isPublicShareIdPath(e.path))return[{start:0,end:r.length,replacement:maskToken(a)}];if(t===`off`)return i;let o=i,receive=e=>{o=composeRedactionEdits(r.length,o,e)},s=findStructuredAuthParamRanges(a).map(({start:e,end:t})=>({start:e,end:t,replacement:`***`}));return receive(s),redactFormBody(redactAssignmentValues(applyRedactionEdits(a,s),`url`,receive),receive),o}function getLegacyFieldRecordEdits(e,t){let{key:n,value:r,path:i,objectPath:a}=e;if(e.isKey||!e.origin.structured||!e.string||isPublicShareIdPath(i))return[];let o=[];if(t!==r||Hr.test(n))for(let e of t.matchAll(Ur))looksLikeAppSpecificPassword(e[0])&&o.push({start:e.index,end:e.index+e[0].length,replacement:maskToken(e[0])});return o.length>0||t!==r?o:classifyLogFieldProtection(n,i,a,t)===`legacy`?[{start:0,end:t.length,replacement:maskToken(t)}]:[]}function*redactionEditMatches(e,t){for(let n of t)yield{match:e.slice(n.start,n.end),groups:[],input:e,offset:n.start,replacement:n.replacement}}const Kr=[{source:`registered secret values`,*exec(e){let t=[];redactRegisteredSecretValues(e,(n,r)=>(t.push({match:n,groups:[],input:e,offset:r,replacement:maskToken(n)}),n)),yield*t}},{source:`structured authorization parameters`,*exec(e){for(let{start:t,end:n}of findStructuredAuthParamRanges(e))yield{match:e.slice(t,n),groups:[],input:e,offset:t,replacement:`***`}}},{source:`URL query assignments`,*exec(e){let t=[];redactAssignmentValues(e,`url`,e=>t.push(...e)),yield*redactionEditMatches(e,t)}},{source:`form bodies`,*exec(e){let t=[];redactFormBody(e,n=>{t=composeRedactionEdits(e.length,t,n)}),yield*redactionEditMatches(e,t)}}],qr=/* @__PURE__ */ new Set([`time`,`level`]);function redactLogRecordForTransport(e,t){let n=startRedactionMeasurement(`log-record`),r=`error`,i;try{let n=t?.redaction??resolveRedactOptions(),a={value:{structured:!0,primitiveMask:!1},children:/* @__PURE__ */ new Map},o=[],s=JSON.stringify(e,function(e,t){for(;o.length>0&&o.at(-1)?.value!==this;)o.pop();let n=o.at(-1),r=Array.isArray(this),i=r&&n?n.key:e,s=r&&n?n.path:n?[...n.path,e]:[],c=t,l=(n?.structured??!0)&&(typeof c!=`object`||!c||Array.isArray(c)||isPlainRedactableObject(c)),u=l&&[`number`,`boolean`,`bigint`].includes(typeof c)&&classifyLogFieldProtection(i,s,!r,void 0)===`legacy`,d=typeof t==`object`&&!!t&&o.some(e=>e.value===t),f=d?`[Circular]`:typeof t==`bigint`?String(t):t,p=typeof f==`object`&&!!f,m=a;return n&&n.structured&&(p||!l||u||d)?(m={value:{structured:l&&!d,primitiveMask:u},children:/* @__PURE__ */ new Map},n.origins.children.set(e,m)):n?m=n.origins:a.value={structured:l,primitiveMask:u},p&&o.push({value:f,path:s,key:i,origins:m,structured:l}),f});i=s.length;let c=createRedactPrefilter(couldMatchDefaultFullContextPatterns),l=JSON.parse(redactJsonRecord(s,a,[[{patterns:n.patterns}],[{patterns:Kr},{patterns:n.patterns,...n.patterns===H?{couldMatch:c}:{}}]],prepareRedactionCapture,t?getLegacyFieldRecordEdits:()=>[],e=>getFieldRecordEdits(e,n.mode),e=>getTextRecordEdits(e,n.mode,t!==void 0),(e,t)=>e.path.length===1&&qr.has(e.key)||n.patterns===H&&!c(t),t?.message));return r=`ok`,l}finally{n?.(r,i)}}const Jr=/* @__PURE__ */ new Map,Yr=/* @__PURE__ */ new Map;let Xr,G;function isValidTimeZone(e){let t=Jr.get(e);if(t!==void 0)return t;let n;try{new Intl.DateTimeFormat(`en`,{timeZone:e}).format(),n=!0}catch{n=!1}return Jr.set(e,n),n}function resolveEffectiveTimeZone(e){let t=e??process.env.TZ;return t&&isValidTimeZone(t)?t:Xr??=Intl.DateTimeFormat().resolvedOptions().timeZone}function getTimestampParts(e,t){let n=resolveEffectiveTimeZone(t),r=Math.floor(e.getTime()/1e3);if(G?.second===r&&G.timeZone===n)return G.parts;let i=Yr.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`}),Yr.set(n,i));let a={};for(let t of i.formatToParts(e))a[t.type]=t.value;return G={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(redactLogRecordForTransport(t))}function formatConsoleDiagnosticLine(e){return(w.overrideSettings?.consoleStyle??readLoggingConfig()?.consoleStyle)===`json`?formatJsonConsoleLine(e):e.message}const Zr=[`silent`,`fatal`,`error`,`warn`,`info`,`debug`,`trace`],Qr={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 Zr.includes(t)?t:void 0}function normalizeLogLevel(e,t=`info`){return tryParseLogLevel(e)??t}function levelToMinLevel(e){return Qr[e]}function isLogLevelEnabled(e,t){return e!==`silent`&&t!==`silent`&&levelToMinLevel(e)>=levelToMinLevel(t)}function resolveEnvLogLevelOverride(){let e=normalizeOptionalString(process.env.OPENCLAW_LOG_LEVEL)??``;if(!e){w.invalidEnvLogLevelValue=null;return}let t=tryParseLogLevel(e);if(t)return w.invalidEnvLogLevelValue=null,t;if(w.invalidEnvLogLevelValue!==e){w.invalidEnvLogLevelValue=e;let t=`[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${Zr.join(`|`)}).`;process.stderr.write(`${formatConsoleDiagnosticLine({level:`warn`,message:t})}\n`)}}const $r=`/tmp/openclaw`;let ei;function loadResolveSecureTempRoot(){if(ei)return ei;if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed temp-root runtime was not registered before use`);if(typeof process.getBuiltinModule!=`function`)throw Error(`Node module loading is unavailable for secure temp-root resolution`);return ei=process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@openclaw/fs-safe/secure-temp-root`).resolveSecureTempRoot,ei}function assertSafeTempAncestors(e,t){let n=t.platform??process.platform;if(n===`win32`||n===`android`)return;let r=process.getBuiltinModule(`fs`),i=t.lstatSync??r.lstatSync,a=t.lstatSync?u.resolve(e):r.realpathSync.native(e);for(let e=u.dirname(a);;e=u.dirname(e)){let t=i(e);if(t.mode!==void 0&&t.mode&18&&!(t.mode&512)){let t=`'${e.replaceAll(`'`,`'\\''`)}'`;throw Error(`Temp workspace ancestor ${JSON.stringify(e)} is group/world writable without sticky protection; have its owner run chmod +t ${t} for a shared temp directory or chmod go-w ${t} for a private ancestor.`)}if(u.dirname(e)===e)return}}function resolvePreferredOpenClawTmpDir(e={}){let t=loadResolveSecureTempRoot(),n={...e,preferredDir:e.preferredDir??`/tmp/openclaw`,fallbackPrefix:`openclaw`,warningPrefix:`[openclaw]`,unsafeFallbackLabel:`OpenClaw temp dir`,skipPreferredOnWindows:!0},r=t(n);if(e.purpose===`coordination`)return r;let i;try{return assertSafeTempAncestors(r,e),r}catch(e){i=e}let a=resolveStateDir();try{let r=t({...n,preferredDir:void 0,tmpdir:()=>u.join(a,`tmp`)});return assertSafeTempAncestors(r,e),(e.warn??console.warn)(`[openclaw] ${String(i)} Using private state temp dir: ${r}`),r}catch(e){throw Error(`No safe OpenClaw temp root is available. Default root: ${String(i)} State fallback ${JSON.stringify(a)}: ${String(e)}`,{cause:e})}}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}}function ensureLogDirectorySync(e,t=!0,n=511){try{g.mkdirSync(e,{mode:n})}catch(r){let i=extractErrorCode(r);if(i===`EEXIST`&&g.statSync(e).isDirectory())return;let a=u.dirname(e);if(!t||i!==`ENOENT`||a===e)throw r;ensureLogDirectorySync(a,!0,n),ensureLogDirectorySync(e,!1,n)}}const ti=`openclaw`,ni=`.log`;function canUseNodeFs(){try{return process.getBuiltinModule?.(`fs`)!==void 0}catch{return!1}}function formatLocalDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}const ri=/^(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${m(`sha256`).update(e).digest(`hex`)}`}function resolveDefaultRollingLogFile(e){let t=/* @__PURE__ */ new Date,n=$r;if(canUseNodeFs()){let t=resolveStateDir();n=u.join(t,`logs`),e?.prepare!==!1&&(ensureLogDirectorySync(t,!0,448),n=resolvePreferredOpenClawTmpDir({preferredDir:n,tmpdir:()=>u.join(t,`tmp`)}))}let r=resolveLogProfileSegment(),i=r?`-${r}`:``;return u.join(n,`${ti}${i}-${formatLocalDate(t)}${ni}`)}function isLegacyRollingLogFilePath(e){let t=u.basename(e);return t===`openclaw-YYYY-MM-DD.log`||ri.exec(t)?.[1]===`openclaw`}function resolveRollingLogFilePathForDate(e,t){let n=ri.exec(u.basename(e));return n?u.join(u.dirname(e),`${n[1]}-${formatLocalDate(t)}${ni}`):isLegacyRollingLogFilePath(e)?u.join(u.dirname(e),`${ti}-${formatLocalDate(t)}${ni}`):e}let K=[],q=0,J=null,Y=0,X=0,ii=null,Z=null,Q=null,$=!1,ai=!1;const oi=/* @__PURE__ */ new Map,si=/* @__PURE__ */ new Set;let ci=!1;function rotatedLogPath(e,t){let n=u.extname(e);return`${e.slice(0,e.length-n.length)}.${t}${n}`}function rotateLogFile(e){try{ensureLogDirectorySync(u.dirname(e)),g.rmSync(rotatedLogPath(e,5),{force:!0});for(let t=4;t>=1;--t){let n=rotatedLogPath(e,t);g.existsSync(n)&&g.renameSync(n,rotatedLogPath(e,t+1))}return g.existsSync(e)&&g.renameSync(e,rotatedLogPath(e,1)),!0}catch{return!1}}async function getCurrentLogFileBytes(e){try{return(await l.stat(e)).size}catch{return 0}}function getCurrentLogFileBytesSync(e){try{return g.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:redactSensitiveText(e)})}\n`;return t?g.writeSync(process.stderr.fd,n):process.stderr.write(n),!0}catch{return!1}}function warnAboutRotationFailure(e,t){oi.get(e.file)!==e.maxFileBytes&&(oi.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(si.has(e.file))return;let n=si.size>=64;n&&ci||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?ci=!0:si.add(e.file))}function clearAppendFailure(e){si.delete(e.file)&&(ci=!1)}function claimQueuedEntries(){let e=q===0?K:[...K.slice(q),...K.slice(0,q)];return K=[],q=0,X>0&&ii&&e.unshift(buildDroppedMarker(ii,X)),X=0,ii=null,e}function prepareWrite(e,t,n,r,i){let a=Buffer.byteLength(e.payload,`utf8`);t.bytes>0&&t.bytes+a>e.maxFileBytes&&(rotateLogFile(e.file)?(t.bytes=0,oi.delete(e.file)):warnAboutRotationFailure(e,n));let 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)break;let i=Buffer.byteLength(n.payload,`utf8`);if(a+i>65536||t.bytes+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($)return;let r=e[n];if(!r)return;let i=t.get(r.file);if(!i){if(i={bytes:await getCurrentLogFileBytes(r.file)},$)return;t.set(r.file,i)}let a=prepareWrite(r,i,!1,e,n);Y=a.nextIndex;try{await te({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!1)}finally{for(let t of e.slice(n,a.nextIndex))t.payload=``;n=a.nextIndex}}}function writeEntriesSync(e){let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;){let r=e[n];if(!r)return;let i=t.get(r.file);i||(i={bytes:getCurrentLogFileBytesSync(r.file)},t.set(r.file,i));let a=prepareWrite(r,i,!0,e,n);try{v({filePath:r.file,content:a.payload}),i.bytes+=a.payloadBytes,clearAppendFailure(r)}catch{warnAboutAppendFailure(r,!0)}r.payload=``,n=a.nextIndex}}async function runFlushLoop(){for(;;){if($)return;let e=claimQueuedEntries();if(e.length===0)return;J=e,Y=0,await writeEntries(e),J=null,Y=0}}function startFlush(){if(Q||$)return;let e=runFlushLoop().catch(()=>void 0);Q=e,e.then(()=>{Q=null,(K.length>0||X>0)&&scheduleFlush()})}function scheduleFlush(){Z||Q||$||(Z=setImmediate(()=>{Z=null,startFlush()}))}function handleProcessBeforeExit(){flushFileLogQueue()}function handleProcessExit(){$=!0,drainFileLogQueueSync()}function installProcessHooks(){ai||(ai=!0,process.on(`beforeExit`,handleProcessBeforeExit),process.on(`exit`,handleProcessExit))}function enqueueFileLog(e){if($)writeEntriesSync([e]);else{if(installProcessHooks(),K.length>=4096){let t=K[q];t&&(t.payload=``,ii??=t,X+=1),K[q]=e,q=(q+1)%K.length}else K.push(e);scheduleFlush()}}async function flushFileLogQueue(){for(;;){Z&&=(clearImmediate(Z),null),!Q&&(K.length>0||X>0)&&startFlush();let e=Q;if(!e)return;await e}}function drainFileLogQueueSync(){Z&&=(clearImmediate(Z),null);let e=J?J.slice(Y):[];J=null,Y=0,e.push(...claimQueuedEntries()),writeEntriesSync(e)}const li=resolveGlobalSingleton(Symbol.for(`openclaw.fileLogTransport`),()=>(process.env.VITEST!==`true`&&installProcessHooks(),{drainSync:drainFileLogQueueSync,enqueue:enqueueFileLog,flush:flushFileLogQueue})),ui=`${$r}/openclaw.log`,di=104857600;let fi=null;const pi=/^[A-Za-z0-9_.:-]{1,64}$/u;function clampLogText(e,t){return e.length>t?`${truncateUtf16Safe(e,t)}...(truncated)`:e}function sanitizeDiagnosticLogText(e,t){return clampLogText(redactSensitiveText(clampLogText(e,t)),t)}function normalizeDiagnosticLogName(e){if(!e||e.trim().startsWith(`{`))return;let t=sanitizeDiagnosticLogText(e.trim(),120);return pi.test(t)?t:void 0}function assignDiagnosticLogAttribute(e,t,n,r){if(t.count>=32)return;let i=n.trim();if(isBlockedObjectKey(i)||redactSensitiveText(i)!==i||!pi.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(t){if(!e(t))return!1;let n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}function normalizeTraceContext(e){let n=t(e);if(n&&isValidDiagnosticTraceId(n.traceId)&&(n.spanId===void 0||isValidDiagnosticSpanId(n.spanId))&&(n.parentSpanId===void 0||isValidDiagnosticSpanId(n.parentSpanId))&&(n.traceFlags===void 0||isValidDiagnosticTraceFlags(n.traceFlags)))return{traceId:n.traceId,...n.spanId?{spanId:n.spanId}:{},...n.parentSpanId?{parentSpanId:n.parentSpanId}:{},...n.traceFlags?{traceFlags:n.traceFlags}:{}}}function extractTraceContext(e){return normalizeTraceContext(e)??normalizeTraceContext(t(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(fi)return fi;let e=y.hostname().trim();return e?(fi=e,e):`unknown`}function withResolvedLogMetaHostname(t,n){return e(t)?{...t,hostname:n}:t}function extractLogBindingPrefix(t){if(typeof t[0]==`string`&&t[0].length<=8192&&t[0].trim().startsWith(`{`))try{let n=JSON.parse(t[0]);if(e(n))return{bindings:n,args:t.slice(1)}}catch{}return{args:t}}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(redactSecrets(e));(t.trustedTraceContext?emitDiagnosticEventWithTrustedTraceContext:emitDiagnosticEvent)(t.event)}catch{}}})}function canUseSilentVitestFileLogFastPath(e){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`&&!e&&!w.overrideSettings}function resolveDefaultActiveLogFile(e=!1){return process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG===`1`?u.join(process.cwd(),`.artifacts`,`test-logs`,`${ti}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date)}${ni}`):resolveDefaultRollingLogFile(e?void 0:{prepare:!1})}function resolveSettings(e=!1){if(!canUseNodeFs())return{level:`silent`,file:ui,maxFileBytes:di,rolling:!1,defaultFile:!1};let t=resolveEnvLogLevelOverride();if(canUseSilentVitestFileLogFastPath(t))return{level:`silent`,file:resolveDefaultRollingLogFile(e?void 0:{prepare:!1}),maxFileBytes:di,rolling:!0,defaultFile:!0};let n=w.overrideSettings??readLoggingConfig(),r=process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_FILE_LOG!==`1`?`silent`:`info`,i=normalizeLogLevel(n?.level,r),a=t??i,o=!n?.file||isLegacyRollingLogFilePath(n.file);return{level:a,file:resolveActiveLogFileWithMode(n?.file??resolveDefaultActiveLogFile(e),o),maxFileBytes:resolveMaxLogFileBytes(n?.maxFileBytes),rolling:o,defaultFile:!n?.file}}function getRuntimeSettings(){let e=w.cachedSettings??resolveSettings();return w.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 fe{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 buildLogger(){let e=new RuntimeLogger({name:`openclaw`,mask:{keys:[]},meta:{property:`_meta`},minLevel:levelToMinLevel(`fatal`),type:`hidden`});inheritLogLevel(e,()=>levelToMinLevel(getRuntimeSettings().level));let t,n;return e.attachTransport({format:()=>``,write:e=>{try{let r=getRuntimeSettings();if(r.level===`silent`)return;n?.settings!==r&&(n={settings:r,file:r.defaultFile?resolveDefaultActiveLogFile(!0):r.file});let i=resolveActiveLogFileWithMode(n.file,r.rolling);if(i!==t){t=i;try{ensureLogDirectorySync(u.dirname(t)),r.rolling&&pruneOldRollingLogs(u.dirname(t))}catch{}}let a=formatTimestamp(e.date??/* @__PURE__ */ new Date,{style:`long`}),{fields:o,messageParts:s}=prepareFileLogRecord(e),c=serializeFileLogRecord({...e,_meta:withResolvedLogMetaHostname(e._meta,o.hostname),time:a,...o},s);li.enqueue({file:t,hostname:o.hostname,maxFileBytes:r.maxFileBytes,payload:`${c}\n`})}catch{}}}),attachDiagnosticEventTransport(e),e}function resolveMaxLogFileBytes(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):di}function getLogger(){let e=w.cachedLogger;if(e)return e;getRuntimeSettings();let t=buildLogger();return w.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=expandHomePrefix(e);return t?resolveRollingLogFilePathForDate(n,/* @__PURE__ */ new Date):n}function pruneOldRollingLogs(e){try{let t=g.readdirSync(e,{withFileTypes:!0}),n=Date.now()-864e5;for(let r of t){if(!r.isFile()||!r.name.startsWith(`openclaw-`)||!r.name.endsWith(`.log`))continue;let t=u.join(e,r.name);try{g.statSync(t).mtimeMs<n&&g.rmSync(t,{force:!0})}catch{}}}catch{}}function normalizeConsoleLevel(e){return isVerbose()?`debug`:!e&&process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_CONSOLE!==`1`?`silent`:normalizeLogLevel(e,`info`)}function normalizeConsoleStyle(e){return e===`compact`||e===`json`||e===`pretty`?e:process.stdout.isTTY?`pretty`:`compact`}function resolveConsoleSettings(){let e=resolveEnvLogLevelOverride();if(process.env.VITEST===`true`&&process.env.OPENCLAW_TEST_CONSOLE!==`1`&&!isVerbose()&&!e&&!w.overrideSettings)return{level:`silent`,style:normalizeConsoleStyle(void 0)};let t=w.overrideSettings??readLoggingConfig();return{level:e??normalizeConsoleLevel(t?.consoleLevel),style:normalizeConsoleStyle(t?.consoleStyle)}}function getConsoleSettings(){let e=w.cachedConsoleSettings;if(e)return e;let t=resolveConsoleSettings();return w.cachedConsoleSettings=t,t}function shouldLogSubsystemToConsole(e){let t=w.consoleSubsystemFilter;if(!t||t.length===0)return!0;let n=normalizeOptionalString(e);return n?t.some(e=>n===e||n.startsWith(`${e}/`)):!1}`${process.release.name}${process.pid}`;function formatConsoleTimestamp(e){let t=/* @__PURE__ */ new Date;return e===`pretty`?formatTimestamp(t,{style:`short`}).replace(/[+-]\d{2}:\d{2}$/,``):formatTimestamp(t,{style:`long`})}var mi=/* @__PURE__ */ __exportAll({createSubsystemLogger:()=>createSubsystemLogger});function isRichConsoleEnv(){let e=normalizeLowercaseStringOrEmpty(process.env.TERM);return process.env.COLORTERM||process.env.TERM_PROGRAM?!0:e.length>0&&e!==`dumb`}const hi=[],gi=[`cyan`,`green`,`yellow`,`blue`,`magenta`,`red`],_i=/* @__PURE__ */ new Map([[`gmail-watcher`,`blue`]]),vi=/* @__PURE__ */ new Set([`gateway`,`channels`,`providers`]),yi=/* @__PURE__ */ new Set(/* @__PURE__ */ `clickclack.discord.feishu.googlechat.imessage.irc.line.matrix.mattermost.msteams.nextcloud-talk.nostr.openclaw-weixin.qqbot.signal.slack.synology-chat.telegram.tlon.twitch.webchat.wecom.whatsapp.yuanbao.zalo.zalouser`.split(`.`));function pickSubsystemColor(e){let t=_i.get(e);if(t)return t;let n=0;for(let t=0;t<e.length;t+=1)n=n*31+e.charCodeAt(t)|0;let r=Math.abs(n)%gi.length;return expectDefined(gi[r],`subsystem colors entry at idx`)}function formatSubsystemForConsole(e){let t=e.split(`/`).filter(Boolean),n=t.join(`/`)||e;for(;t[0]!==void 0&&vi.has(t[0]);)t.shift();let r=t.at(0);return r===void 0?n:yi.has(normalizeLowercaseStringOrEmpty(r))?r:t.slice(-2).join(`/`)}function stripRedundantSubsystemPrefixForConsole(e,t){if(!t)return e;if(e.startsWith(`[`)){let n=e.indexOf(`]`);if(n>1&&normalizeLowercaseStringOrEmpty(e.slice(1,n))===normalizeLowercaseStringOrEmpty(t))return e.slice(n+1).replace(/^ */,``)}if(normalizeLowercaseStringOrEmpty(e.slice(0,t.length))!==normalizeLowercaseStringOrEmpty(t))return e;let n=e.slice(t.length,t.length+1);return n!==`:`&&n!==` `?e:e.slice(t.length).replace(/^ *:? */,``)}function createConsoleLineFormatter(e){let t=formatSubsystemForConsole(e),n=`[${t}]`,r=pickSubsystemColor(t);return(e,i,a)=>{let o=typeof process.env.FORCE_COLOR==`string`&&process.env.FORCE_COLOR.trim().length>0&&process.env.FORCE_COLOR.trim()!==`0`||!process.env.NO_COLOR&&(process.stdout.isTTY||process.stderr.isTTY||isRichConsoleEnv())?1:0,s=hi[o]??=new p({level:o}),c=e===`error`||e===`fatal`?s.red:e===`warn`?s.yellow:e===`debug`||e===`trace`?s.gray:s.cyan,l=stripRedundantSubsystemPrefixForConsole(redactSensitiveText(i),t),u=a===`pretty`||w.consoleTimestampPrefix?s.gray(formatConsoleTimestamp(a)):``,d=s[r](n);return`${u?`${u} ${d}`:d} ${c(l)}`}}function writeConsoleLine(e,t,n={}){let r=process.platform===`win32`&&process.env.GITHUB_ACTIONS===`true`?t.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,`?`).replace(/[\uD800-\uDFFF]/g,`?`):t,i=n.redacted?r:redactSensitiveText(r),a=w.rawConsole??console;w.forceConsoleToStderr||e===`error`||e===`fatal`?(a.error??console.error)(i):e===`warn`?(a.warn??console.warn)(i):(a.log??console.log)(i)}function shouldSuppressProbeConsoleLine(e){if(isVerbose()||e.level===`error`||e.level===`fatal`)return!1;let t=typeof e.message==`string`?e.message:``;return e.suppressProbeMessages?(typeof e.meta?.runId==`string`?e.meta.runId:typeof e.meta?.sessionId==`string`?e.meta.sessionId:void 0)?.startsWith(`probe-`)?!0:/(sessionId|runId)=probe-/.test(t):!1}const bi=/* @__PURE__ */ new Set([`warn`,`error`,`fatal`]),xi=2048;function formatConsoleMetaValue(e){if(e!==void 0)return typeof e==`string`?/\s|=/.test(e)||e.length===0?JSON.stringify(e):e:e===null||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function prepareLogMetaRecord(e,t=!1){let n;for(let[r,i]of Object.entries(e))i instanceof Error&&(n??={...e},n[r]={name:i.name,message:i.message,errorCode:extractErrorCode(i),stack:t?i.stack?.split(`
`).slice(0,6).join(`
`):i.stack});return n??e}function formatConsoleMeta(e){let t;try{t=redactLogRecordForTransport(e)}catch{return``}let n=[];for(let[e,r]of Object.entries(t)){let t=formatConsoleMetaValue(r);t!==void 0&&n.push(`${e}=${t}`)}let r=n.join(` `);return r.length>xi?`${r.slice(0,xi)}...(truncated)`:r}function logToFile(e,t,n,r){t!==`silent`&&(r&&Object.keys(r).length>0?e[t](r,n):e[t](n))}function createSubsystemLogger(e){let t=normalizeOptionalString(e)??`unknown`,n=t===`agent/embedded`||t.startsWith(`agent/embedded/`)||t===`model-fallback`||t.startsWith(`model-fallback/`),r,i,a,getFileLogger=e=>(r??=getChildLogger({subsystem:t}),e===`error`||e===`fatal`||e!==`info`&&areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`log.record`)?r:(i||(i=r.getSubLogger({stack:{capture:`off`}}),i.settings.parentNames=r.settings.parentNames),i)),emitLog=(e,r,i)=>{let o=getConsoleSettings(),s=i?.consoleMessage!==!1&&isLogLevelEnabled(e,o.level)&&shouldLogSubsystemToConsole(t),c=isFileLogLevelEnabled(e);if(!s&&!c)return;let l,u=i,d=i;if(i&&Object.keys(i).length>0){let{consoleMessage:e,...t}=i;typeof e==`string`&&(l=e),u=Object.keys(t).length>0?prepareLogMetaRecord(t):void 0,d=u&&s?prepareLogMetaRecord(t,!0):void 0}if(c&&logToFile(getFileLogger(e),e,r,u),!s)return;let f=o.style!==`json`&&l===void 0&&d&&bi.has(e)?formatConsoleMeta(d):``,p=l??(f?`${r} ${f}`:r);shouldSuppressProbeConsoleLine({level:e,suppressProbeMessages:n,message:p,meta:d})||writeConsoleLine(e,o.style===`json`?formatJsonConsoleLine({level:e,subsystem:t,message:r,meta:d}):(a??=createConsoleLineFormatter(t))(e,p,o.style),{redacted:!0})};return{subsystem:t,isEnabled(e,n=`any`){let r=isLogLevelEnabled(e,getConsoleSettings().level)&&shouldLogSubsystemToConsole(t),i=isFileLogLevelEnabled(e);return n===`console`?r:n===`file`?i:r||i},trace(e,t){emitLog(`trace`,e,t)},debug(e,t){emitLog(`debug`,e,t)},info(e,t){emitLog(`info`,e,t)},warn(e,t){emitLog(`warn`,e,t)},error(e,t){emitLog(`error`,e,t)},fatal(e,t){emitLog(`fatal`,e,t)},raw(e){isFileLogLevelEnabled(`info`)&&logToFile(getFileLogger(`info`),`info`,e,{raw:!0});let r=getConsoleSettings();if(isLogLevelEnabled(`info`,r.level)&&shouldLogSubsystemToConsole(t)){if(shouldSuppressProbeConsoleLine({level:`info`,suppressProbeMessages:n,message:e}))return;writeConsoleLine(`info`,r.style===`json`?formatJsonConsoleLine({level:`info`,subsystem:t,message:e}):e,{redacted:r.style===`json`})}},child(e){return createSubsystemLogger(`${t}/${e}`)}}}export{runWithAsyncStore as A,resolveTimerTimeoutMs as B,runInDetachedAsyncContext as C,runWithDiagnosticTraceContext as D,getActiveDiagnosticTraceContext as E,truncateUtf16Safe as F,formatErrorMessage as G,expectDefined as H,asPositiveFiniteNumber as I,toErrorObject as K,clampPositiveTimerTimeoutMs as L,resolveGlobalMap as M,resolveGlobalSingleton as N,AsyncContext as O,sliceUtf16Safe as P,resolveIntegerOption as R,runWithMainThreadTask as S,parseDiagnosticEnvFlags as T,collectNestedErrorCandidates as U,normalizeLowercaseStringOrEmpty as V,extractErrorCode as W,stripAnsi as _,groupPluginRecords as a,emitTrustedDiagnosticEvent as b,escapeRegExp as c,sanitizeTerminalText as d,resolveIdentityPathViaExistingAncestorSync as f,isMissingPathError as g,oe as h,redactToolPayloadText as i,hasInternalDiagnosticEventInterest as j,xe as k,resolveStateDir as l,lstatIfExists as m,mi as n,pruneMapToMaxSize as o,canAccessSync as p,__exportAll as q,redactSensitiveText as r,sleep as s,createSubsystemLogger as t,expandHomePrefix as u,w as v,isDiagnosticFlagEnabled as w,workerScriptName as x,areDiagnosticsEnabledForProcess as y,resolveOptionalIntegerOption as z};