openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
769 lines • 221 kB
JavaScript
import*as e from"node:module";import{createRequire as t}from"node:module";import{setImmediate as n}from"node:timers/promises";import{isDeepStrictEqual as r,types as i}from"node:util";import{GCProfiler as a,getHeapSpaceStatistics as o,getHeapStatistics as s,setFlagsFromString as c}from"node:v8";import{Script as l,createContext as u}from"node:vm";import{MessageChannel as d,MessagePort as f,Worker as p,getEnvironmentData as m,isMainThread as h,parentPort as g,receiveMessageOnPort as _,setEnvironmentData as v,threadId as y,workerData as b}from"node:worker_threads";import{channel as x}from"node:diagnostics_channel";import{AsyncLocalStorage as S}from"node:async_hooks";import{performance as C}from"node:perf_hooks";import w,{basename as ee}from"node:path";import{fileURLToPath as te}from"node:url";import{randomUUID as ne}from"node:crypto";import T,{fstatSync as re,readdirSync as ie}from"node:fs";import E from"node:fs/promises";import D from"node:os";import{hasNodeErrorCode as ae,isPathInside as oe}from"@openclaw/fs-safe/path";import{isPromise as se}from"node:util/types";import{Session as ce}from"node:inspector/promises";import{canUseRootFileOpen as le,openRootFileSync as ue}from"@openclaw/fs-safe/advanced";import"@openclaw/fs-safe/errors";import{Buffer as de}from"node:buffer";import{parse as fe}from"acorn";const pe={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},O=/* @__PURE__ */ new Set;let k,me,he;function getOldGenerationAfterGcBytes(){return he}function drain(e){let t=k?.stop();e&&k?.start();let n=[];for(let e of t?.statistics??[]){let t=pe[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,he=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(he+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of O)e(n)}function flushGcSamples(){k&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return k?drain(!0):(k=new a,k.start(),me=setInterval(()=>drain(!0),1e3).unref()),O.add(e),()=>{if(!O.has(e))return;let t=O.size===1;drain(!t),O.delete(e),t&&(clearInterval(me),me=void 0,k=void 0,he=void 0)}}const ge=`${process.execArgv.join(` `)} ${process.env.NODE_OPTIONS??``}`;h&&!process.versions.bun&&/--max[-_](?:old[-_]space[-_]size(?:[-_]percentage)?|heap[-_]size)(?:=|\s)/u.test(ge)&&(/--(?:freeze[-_]flags[-_]after[-_]init|(?:abort|exit)[-_]on[-_]contradictory[-_]flags)(?:=(?:true|1))?(?:\s|$)/u.test(ge)?process.emitWarning(`V8 startup flags prevent enforcing per-worker heap limits.`):c(`--max-old-space-size=0 --max-heap-size=0`));function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function asOptionalRecord(e){return isRecord(e)?e:void 0}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 resolveGlobalSet(e,t){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Set,e=>e.clear(),t)}const ve=typeof process>`u`?void 0:process.getBuiltinModule?.(`node:async_hooks`);ve&&resolveGlobalSingleton(Symbol.for(`openclaw.detachedAsyncContext`),()=>new ve.AsyncResource(`openclaw.detached-async-context`)),resolveGlobalSingleton(Symbol.for(`openclaw.mainThreadTask`),()=>({context:new S}));function createRuntimeProcessEntrypoints(e){function runtimeProcessEntrypoint(t,n=t,r=`.js`,i){return{currentModuleUrl:e,sourceModulePath:`src/${t}${i??`.ts`}`,sourceExtension:i,sourceWorkerName:t.startsWith(`infra/`)?t.slice(6):`../${t}`,distWorkerPath:`${n}${r}`}}let loaderFreeEntrypoint=e=>runtimeProcessEntrypoint(e,void 0,void 0,`.mjs`);return{daemonRuntimeProbe:runtimeProcessEntrypoint(`infra/daemon-runtime-probe.entry`),pluginToolsServe:runtimeProcessEntrypoint(`mcp/plugin-tools-serve`),openclawToolsServe:runtimeProcessEntrypoint(`mcp/openclaw-tools-serve`),repositoryPublicationRestore:loaderFreeEntrypoint(`gateway/repository-publication-restore.generated.worker`),nodeWorkspacePublicationSnapshot:loaderFreeEntrypoint(`node-host/node-worker-publication-snapshot.generated.worker`),nodeWorkspaceManifest:loaderFreeEntrypoint(`node-host/node-worker-workspace-manifest.generated.worker`),nodeWorkspaceGitHistory:loaderFreeEntrypoint(`node-host/node-worker-workspace-git-history.generated.worker`),doctorDatabaseEngineInspection:runtimeProcessEntrypoint(`commands/doctor-database-engine-inspection.worker`),backupDatabaseDiscovery:runtimeProcessEntrypoint(`infra/backup-database-discovery.worker`),sqliteHeaderProbe:runtimeProcessEntrypoint(`infra/sqlite-header-probe.worker`),databaseBackup:runtimeProcessEntrypoint(`snapshot/database-backup.worker`),managedHandoffEngine:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-engine.worker`),updatePostgresState:runtimeProcessEntrypoint(`infra/update-candidate-state.postgres.worker`),databasePortCommand:runtimeProcessEntrypoint(`infra/database-engine/port-command.entry.worker`),systemCaWarmup:runtimeProcessEntrypoint(`gateway/system-ca-warmup.worker`),shutdownHardExit:loaderFreeEntrypoint(`cli/gateway-cli/shutdown-hard-exit.worker`),packageIntegrityHasher:runtimeProcessEntrypoint(`infra/package-update-integrity-hasher.worker`),packageLocalOverrides:runtimeProcessEntrypoint(`infra/package-local-overrides.worker`),directoryWatchHost:runtimeProcessEntrypoint(`infra/directory-watch-host.worker`),directoryWatchParent:runtimeProcessEntrypoint(`infra/directory-watch-parent.worker`),workspaceQuiescenceAcquire:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-acquire.generated.worker`),workspaceQuiescenceRenew:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-renew.generated.worker`),workspaceQuiescenceRelease:loaderFreeEntrypoint(`gateway/worker-environments/workspace-quiescence-release.generated.worker`),packageActivationRecovery:runtimeProcessEntrypoint(`infra/package-update-activation-sealed`,`package-update-activation-recovery`,`.mjs`),managedHandoffPostgresBridge:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-postgres.worker`,`managed-handoff-postgres-bridge.worker`,`.mjs`),managedHandoffRuntime:runtimeProcessEntrypoint(`infra/update-managed-service-handoff-sealed`,`managed-handoff-runtime`,`.mjs`),sqliteVector:runtimeProcessEntrypoint(`infra/database-engine/sqlite-vector.child`),postgresBridge:runtimeProcessEntrypoint(`infra/postgres-sync/bridge.worker`),secretEgressProxy:runtimeProcessEntrypoint(`secrets/egress-proxy/proxy.worker`),codeModeNode:runtimeProcessEntrypoint(`agents/code-mode-node.worker`),cronReadOnly:runtimeProcessEntrypoint(`cron/store/read-only.worker`),stateRead:runtimeProcessEntrypoint(`state/openclaw-state-read.worker`),workerNativeLifecycle:runtimeProcessEntrypoint(`infra/worker-native-lifecycle.worker`),spawnBroker:runtimeProcessEntrypoint(`process/spawn-broker/worker`),cronStreamMatcher:runtimeProcessEntrypoint(`gateway/cron-stream-matcher.worker`),controlUiFile:runtimeProcessEntrypoint(`gateway/control-ui-file.worker`),publicSessionCard:runtimeProcessEntrypoint(`gateway/control-ui-public-session-card.worker`),nodeBootstrapArtifact:runtimeProcessEntrypoint(`gateway/worker-environments/node-bootstrap-artifact.worker`),nativeHookRelayClient:runtimeProcessEntrypoint(`agents/harness/native-hook-relay-client.worker`),computerHost:runtimeProcessEntrypoint(`gateway/desktop/computer.worker`),imageProcessor:runtimeProcessEntrypoint(`media/image-processor.worker`),fileToolPlanning:runtimeProcessEntrypoint(`agents/sessions/tools/file-tool-planning.worker`),fileToolRead:runtimeProcessEntrypoint(`agents/sessions/tools/read-file.worker`),attachmentProcessor:runtimeProcessEntrypoint(`media/attachment-processor.worker`),widgetScriptSyntax:runtimeProcessEntrypoint(`canvas/widget-script-syntax.worker`),gitOperations:runtimeProcessEntrypoint(`infra/git-operation.worker`),gitPackCleanup:runtimeProcessEntrypoint(`agents/worktrees/git-pack-cleanup.worker`),fsSafeCopy:runtimeProcessEntrypoint(`infra/fs-safe-copy.worker`),sharedStateStore:runtimeProcessEntrypoint(`state/openclaw-state.worker`),clientCredentials:runtimeProcessEntrypoint(`infra/client-credential.worker`),ttsPreferences:runtimeProcessEntrypoint(`tts/tts-settings-write.worker`),authProfileInlineUsage:runtimeProcessEntrypoint(`agents/auth-profiles/inline-usage.worker`),pluginModelCatalogRead:runtimeProcessEntrypoint(`agents/plugin-model-catalog-read.worker`),pluginModelCatalogCredentials:runtimeProcessEntrypoint(`agents/plugin-model-catalog.worker`),pluginCaptureNativeResource:runtimeProcessEntrypoint(`plugins/plugin-capture-native-resource`),pluginGenerationPreparation:runtimeProcessEntrypoint(`plugins/plugin-generation-preparation.worker`),agentDatabaseExecution:runtimeProcessEntrypoint(`state/openclaw-agent-execution.worker`),workspaceMemory:runtimeProcessEntrypoint(`worker/memory-worker-entry`,`agents/workspace-memory.worker`),localAgentAvatar:runtimeProcessEntrypoint(`agents/identity-avatar-file.worker`),identityFile:runtimeProcessEntrypoint(`agents/identity-file.worker`),workspaceSkills:runtimeProcessEntrypoint(`worker/skills-worker-entry`,`agents/workspace-skills.worker`),skillsDiscovery:runtimeProcessEntrypoint(`skills/runtime/discovery.worker`),boardStore:runtimeProcessEntrypoint(`boards/sqlite-board-store.worker`),progressCardStore:runtimeProcessEntrypoint(`session-cards/progress-card-store.worker`),sessionSharingStore:runtimeProcessEntrypoint(`config/sessions/session-sharing-store.worker`),sessionForkDomain:runtimeProcessEntrypoint(`config/sessions/session-fork-domain.worker`),sessionGoalOperations:runtimeProcessEntrypoint(`config/sessions/goals-operations.worker`),sessionLifecyclePlanningDomain:runtimeProcessEntrypoint(`config/sessions/session-lifecycle-projection.worker`),sessionMessageRewriteDomain:runtimeProcessEntrypoint(`config/sessions/session-message-rewrite.worker`),sessionDiskBudget:runtimeProcessEntrypoint(`config/sessions/disk-budget.worker`),contextEngineTurnOutbox:runtimeProcessEntrypoint(`agents/harness/context-engine-turn-outbox.worker`),sqliteStore:runtimeProcessEntrypoint(`infra/sqlite-store.worker`),sqliteWriterAdmission:runtimeProcessEntrypoint(`infra/sqlite-writer-admission.worker`),agentSchemaInspection:runtimeProcessEntrypoint(`state/openclaw-agent-schema-inspection.worker`),stateMigrationSnapshot:runtimeProcessEntrypoint(`infra/state-migrations.snapshot.worker`),githubExec:runtimeProcessEntrypoint(`agents/github-exec-launcher`),shellSnapshotEnvironment:runtimeProcessEntrypoint(`agents/shell-snapshot-env.worker`),sqliteReadOnly:runtimeProcessEntrypoint(`infra/sqlite-readonly-location.worker`),sqliteSnapshotStaging:runtimeProcessEntrypoint(`infra/sqlite-snapshot-staging.worker`),sqliteReadOnlyNativeResource:runtimeProcessEntrypoint(`infra/sqlite-readonly-native-resource`),sqliteSourceRevision:runtimeProcessEntrypoint(`infra/sqlite-source-revision.worker`),sqliteIntegrity:runtimeProcessEntrypoint(`infra/sqlite-integrity.worker`),sqliteCloseProbe:runtimeProcessEntrypoint(`infra/bun-sqlite-close-probe.worker`),preparedModelCatalog:runtimeProcessEntrypoint(`agents/prepared-model-catalog.worker`),providerPromptState:runtimeProcessEntrypoint(`agents/embedded-agent-runner/provider-prompt-state.worker`),retiredWorktreeCleanup:runtimeProcessEntrypoint(`agents/worktrees/retired-worktree-cleanup.worker`),updateNativeGate:runtimeProcessEntrypoint(`cli/update-cli/update-command-native-gate.worker`),updateStateSizes:runtimeProcessEntrypoint(`infra/update-state-sizes.entry`),updateRepair:runtimeProcessEntrypoint(`infra/update-repair.worker`),immutableBuild:runtimeProcessEntrypoint(`infra/update-immutable-build.worker`),updateMigratedFinalize:runtimeProcessEntrypoint(`infra/update-migrated-finalize.worker`),updateAutomaticCleanup:runtimeProcessEntrypoint(`infra/update-automatic-cleanup.worker`),updateCandidateState:runtimeProcessEntrypoint(`infra/update-candidate-state.worker`),doctorLint:runtimeProcessEntrypoint(`commands/doctor-lint.worker`),doctor:runtimeProcessEntrypoint(`commands/doctor.worker`),databaseVerify:runtimeProcessEntrypoint(`state/openclaw-database-verify.worker`),stateOwnership:runtimeProcessEntrypoint(`state/openclaw-state-ownership.worker`),stateLeaseHeartbeat:runtimeProcessEntrypoint(`state/openclaw-state-lease-heartbeat.worker`),gatewayStateOwnerHeartbeat:runtimeProcessEntrypoint(`infra/gateway-state-owner-heartbeat.worker`),sessionTranscriptArchive:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-archive.worker`),sessionTranscript:runtimeProcessEntrypoint(`config/sessions/session-transcript.worker`),usageOverview:runtimeProcessEntrypoint(`infra/session-cost-usage-overview-report.worker`),workerTranscriptCommit:runtimeProcessEntrypoint(`gateway/worker-environments/transcript-commit.worker`),sessionManagerMetadata:runtimeProcessEntrypoint(`agents/sessions/session-manager-metadata.worker`),sessionTranscriptProjectionPublication:runtimeProcessEntrypoint(`config/sessions/session-transcript-projection-publication.worker`),sessionTranscriptReports:runtimeProcessEntrypoint(`config/sessions/session-accessor.sqlite-transcript-reports.worker`),sessionTranscriptReconcile:runtimeProcessEntrypoint(`config/sessions/session-transcript-reconcile.worker`),tailscaleRouteOwner:runtimeProcessEntrypoint(`infra/tailscale-route-owner.worker`),serviceChildRelay:runtimeProcessEntrypoint(`process/supervisor/service-child-relay`),terminalPty:runtimeProcessEntrypoint(`process/terminal-pty-worker`),serviceChildGroupAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-group-anchor`),serviceChildWindowsJobAnchor:runtimeProcessEntrypoint(`process/supervisor/service-child-windows-job-anchor`),bunSqliteLibrary:runtimeProcessEntrypoint(`infra/bun-sqlite-library`)}}function pluginRuntimeProcess(e,t,n){return{plugin:e,ownerSource:`extensions/${e}/${t}.ts`,sourceWorkerName:n,distWorkerPath:`extensions/${e}/${n}.js`,package:{name:`@openclaw/${e}`,distWorkerPath:`${n}.js`}}}const ye={browserNativeHost:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`native-host-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`native-host-entry.js`}},browserRelayDaemon:{...pluginRuntimeProcess(`browser`,`native-host-entry`,`relay-daemon-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`relay-daemon-entry.js`}},browserSetup:{...pluginRuntimeProcess(`browser`,`setup-entry`,`setup-entry`),package:{name:`@openclaw/browser-plugin`,distWorkerPath:`setup-entry.js`}},quickJsCodeMode:{...pluginRuntimeProcess(`code-mode-quickjs`,`src/executor`,`src/code-mode.worker`),sourceWorkerName:`code-mode.worker`},codexStdio:pluginRuntimeProcess(`codex`,`stdio-worker-entrypoint`,`stdio.worker`),codexCatalogPage:pluginRuntimeProcess(`codex`,`catalog-page-worker-entrypoint`,`catalog-page.worker`),codexSessionHistory:pluginRuntimeProcess(`codex`,`session-history-worker-entrypoint`,`session-history.worker`),discordAudio:{...pluginRuntimeProcess(`discord`,`src/voice/audio-worker-thread`,`src/voice/audio-worker.runtime`),sourceWorkerName:`audio-worker.runtime`},documentExtractor:{...pluginRuntimeProcess(`document-extract`,`document-extractor-worker-entrypoint`,`document-extractor.worker`),package:{name:`@openclaw/document-extract-plugin`,distWorkerPath:`document-extractor.worker.js`}},webReadability:{...pluginRuntimeProcess(`web-readability`,`web-content-extractor-worker.runtime`,`web-content-extractor.worker`),package:{name:`@openclaw/web-readability-plugin`,distWorkerPath:`web-content-extractor.worker.js`}},fileTransferDirFetch:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-fetch-archive.ts`,sourceWorkerName:`dir-fetch-archive.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-fetch-archive.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-fetch-archive.worker.js`}},fileTransferDirList:{plugin:`file-transfer`,ownerSource:`extensions/file-transfer/src/node-host/dir-list-worker-command.ts`,sourceWorkerName:`dir-list.worker`,distWorkerPath:`extensions/file-transfer/src/node-host/dir-list.worker.js`,package:{name:`@openclaw/file-transfer`,distWorkerPath:`src/node-host/dir-list.worker.js`}},iMessageChatDb:{...pluginRuntimeProcess(`imessage`,`src/chat-db`,`src/chat-db.worker`),sourceWorkerName:`chat-db.worker`},knowledgeRegistry:{...pluginRuntimeProcess(`knowledge`,`src/registry-client`,`src/registry-worker`),sourceWorkerName:`registry-worker`},knowledgeStorage:{...pluginRuntimeProcess(`knowledge`,`src/storage-client`,`src/storage-worker`),sourceWorkerName:`storage-worker`},mxcLauncher:{plugin:`mxc`,ownerSource:`extensions/mxc/src/plugin-root.ts`,sourceWorkerName:`mxc-spawn-launcher`,sourceExtension:`.mjs`,build:`static-asset`,distWorkerPath:`extensions/mxc/mxc-spawn-launcher.mjs`,package:{name:`@openclaw/mxc-sandbox`,distWorkerPath:`mxc-spawn-launcher.mjs`}},onePasswordSecretResolver:{plugin:`onepassword`,ownerSource:`extensions/onepassword/onepassword-secret-ref-resolver.js`,sourceWorkerName:`onepassword-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/onepassword/onepassword-secret-ref-resolver.js`,package:{name:`@openclaw/onepassword`,distWorkerPath:`onepassword-secret-ref-resolver.js`}},vaultSecretResolver:{plugin:`vault`,ownerSource:`extensions/vault/vault-secret-ref-resolver.js`,sourceWorkerName:`vault-secret-ref-resolver`,sourceExtension:`.js`,build:`static-asset`,distWorkerPath:`extensions/vault/vault-secret-ref-resolver.js`,package:{name:`@openclaw/vault`,distWorkerPath:`vault-secret-ref-resolver.js`}},memorySearch:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-search.worker`),sourceWorkerName:`manager-search.worker`,distWorkerPath:`extensions/memory-core/memory-search.worker.js`},memoryIndex:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-index.worker`),sourceWorkerName:`manager-index.worker`,distWorkerPath:`extensions/memory-core/memory-index.worker.js`},memoryPublication:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory/manager-publication.worker`),sourceWorkerName:`manager-publication.worker`,distWorkerPath:`extensions/memory-core/memory-publication.worker.js`},memoryStandingIntents:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/standing-intents.worker`),sourceWorkerName:`../standing-intents.worker`,distWorkerPath:`extensions/memory-core/standing-intents.worker.js`},memoryEntryOrigins:{...pluginRuntimeProcess(`memory-core`,`src/memory/manager-cpu-entrypoints`,`src/memory-entry-origins.worker`),sourceWorkerName:`../memory-entry-origins.worker`,distWorkerPath:`extensions/memory-core/memory-entry-origins.worker.js`},memoryStatsRuntime:pluginRuntimeProcess(`memory-lancedb`,`memory-stats-entrypoint`,`memory-stats.worker`),memoryWikiQuery:{...pluginRuntimeProcess(`memory-wiki`,`src/query-reader`,`src/query-reader.worker`),sourceWorkerName:`query-reader.worker`},openAiRealtimeAudio:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-peer.runtime`,`realtime-quicksilver-audio.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-audio.worker.js`}},openAiRealtimeSocket:{...pluginRuntimeProcess(`openai`,`realtime-quicksilver-socket`,`realtime-quicksilver-socket.worker`),package:{name:`@openclaw/openai-provider`,distWorkerPath:`realtime-quicksilver-socket.worker.js`}},qaExecutionIdentityInspection:{...pluginRuntimeProcess(`qa-lab`,`src/execution-identity-storage-inspection`,`src/execution-identity-storage-inspection.worker`),sourceWorkerName:`execution-identity-storage-inspection.worker`},telegramIngress:{...pluginRuntimeProcess(`telegram`,`src/telegram-ingress-worker`,`src/telegram-ingress-worker.runtime`),sourceWorkerName:`telegram-ingress-worker.runtime`,distWorkerPath:`telegram-ingress-worker.runtime.js`},telegramWidgetCheck:{...pluginRuntimeProcess(`telegram`,`src/widgets/widget-check`,`src/widgets/widget-check.worker`),sourceWorkerName:`widget-check.worker`},onnxInference:pluginRuntimeProcess(`onnx`,`index`,`src/inference.worker`),teamReportsStore:pluginRuntimeProcess(`team-reports`,`index`,`src/store.worker`),teamReportsRun:pluginRuntimeProcess(`team-reports`,`index`,`src/run.worker`),logbookStore:pluginRuntimeProcess(`logbook`,`index`,`src/store.worker`),workboardSqlite:pluginRuntimeProcess(`workboard`,`index`,`src/sqlite-store.worker`)},be={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=>ee(e).replace(/\.[cm]?[jt]s$/u,`.js`),xe=createRuntimeProcessEntrypoints(import.meta.url),A=/* @__PURE__ */ new Map;for(let e of Object.values(xe)){let t=scriptBasename(e.distWorkerPath);A.set(t,t),A.set(scriptBasename(e.sourceModulePath),t)}for(let e of Object.values(ye)){let t=scriptBasename(e.distWorkerPath);A.set(t,t),A.set(scriptBasename(e.package.distWorkerPath),t),A.set(scriptBasename(`${e.sourceWorkerName}.js`),t)}for(let e of Object.values(be))for(let[t,n]of e.entries){let e=scriptBasename(`${n}.mjs`);A.has(e)||A.set(e,scriptBasename(xe[t].distWorkerPath))}const Se=new Set(A.values());function normalizeDiagnosticWorkerScript(e){return typeof e==`string`&&Se.has(e)?e:`other`}const Ce=/* @__PURE__ */ `admit,audit.events.list,audit.writer.process,audit.writer.prune,database.domain.bind,database.domain.close,database.domain.publish,database.prepareWrite,database.walMaintenance,stateLease.acquire,stateLease.release,stateLease.renew,stateLease.verify,worktrees.assertPredicates,worktrees.delete,worktrees.slotCount,worktrees.pendingSlots,worktrees.reservePending,worktrees.releasePending,worktrees.insert,worktrees.update,worktrees.claimRemoval,worktrees.finalizeRemoval,worktrees.abortRemoval,worktrees.findLiveByOwner,worktrees.get,worktrees.sessionBinding,worktrees.findLiveByPath,worktrees.list,worktrees.liveIds,worktrees.provisionedPaths,worktrees.provisionedState,worktrees.provisionedChunk,worktrees.writeProvisionedSnapshot,worktrees.retireMissing,worktrees.deferCleanup,worktrees.admitRunLease,worktrees.releaseRunLease,worktrees.reapRunLeases,worktrees.reserveCapacity,worktrees.recoverPending,worktrees.templates.read,worktrees.templates.has,worktrees.templates.list,worktrees.templates.reserve,worktrees.templates.ready,worktrees.templates.delete,worktrees.templates.retainReader,worktrees.templates.releaseReader,worktrees.templates.hasReaders`.split(`,`),we=/* @__PURE__ */ `acp.acpSessions.agentDatabaseDeletion.agentDatabaseRegistry.agentDatabases.agentDeletionJournal.agentProvenance.apns.audit.authProfiles.backup.bootstrap.capture.channelIngress.templates.config.conversation.conversationBindings.database.deliveryQueue.deviceAuth.deviceIdentity.devicePairing.diagnostic.doctor.exec-approvals.execApprovals.generatedHtmlProvenance.githubPublication.githubRepository.legacyMcpOAuth.localWorkspace.managedImages.mcpOAuth.mentions.modelCatalog.nativeHookRelay.node.nodeHost.nodeWorker.onboardingRecommendations.operator.operatorApprovals.pairing.placementJournals.placementTools.placementTranscript.placementTurns.pluginBlob.pluginModelCatalogCredentials.plugins.preparedPoolPresence.projects.promotions.repositoryWorkspaces.restartSentinel.sandboxRegistry.secrets.sessionDelivery.sessionGroups.sessionRepositoryWorkspaces.sessionState.sessionUpstream.skillLibrary.skillUploads.skills.stateLease.subagents.telemetry.tts.tui.updateRuns.usageCache.userModelAccounts.userPreferences.userProfiles.webPush.workerEnvironments.workerInference.workerPlacements.workers.workspace.workshop.worktrees`.split(`.`),Te=/* @__PURE__ */ new Set([...Ce,...we]),Ee=/* @__PURE__ */ new Set(/* @__PURE__ */ `devicePairing.lookup,devicePairing.list,devicePairing.updateMetadata,devicePairing.updatePresence,devicePairing.verifyToken,devicePairing.ensureToken,session.actor.read,session.actor.acceptInput,session.actor.adoptRun,session.actor.appendToolResult,session.actor.appendTranscriptEvent,session.actor.completeTurn,session.actor.deliveryPending,session.actor.deliverySettled,session.actor.patch,session.entry.read,session.entry.patch.prepare,session.entry.patch.commit,session.entry.replacements.prepare,session.entry.replacements.commit,session.lifecycle.project,session.maintenance.metadata,session.maintenance.prepare,session.maintenance.finalize,session.maintenance.size,session.rowTranscript.backfill,usageCache.writeRollup,usageCache.writeQuarters,usageCache.prune,trajectory.events.append,trajectory.retention.begin,trajectory.retention.delete,session.pendingInputs.read,session.pendingInputs.mutate,session.turn.prepare,session.turn.commit,transcript.prepare,transcript.commit`.split(`,`)),De=/* @__PURE__ */ new Map([[`preflight`,`transcript-projection.preflight`],[`sweep`,`transcript-projection.sweep`],[`claim`,`transcript-projection.claim`],[`deleteChunk`,`transcript-projection.deleteChunk`],[`appendChunk`,`transcript-projection.appendChunk`],[`finalize`,`transcript-projection.finalize`]]),Oe=[[`pluginState.`,`plugin_state`],[`session.history.`,`transcript_read`],[`trajectory.`,`transcripts`],[`session.transcript.`,`transcripts`],[`transcripts.`,`transcripts`],[`session.`,`sessions`],[`cron.`,`cron`]],ke=/* @__PURE__ */ new Set([...Ee,...De.values(),...Te,...Oe.map(([,e])=>e),`task`,`open`,`close`,`execute`,`domain_execute`,`auth_profiles`]);function normalizeWorkerRequestClass(e){return e!==void 0&&ke.has(e)?e:`other`}const Ae=resolveGlobalSingleton(Symbol.for(`openclaw.workerMessageMetrics`),()=>/* @__PURE__ */ new Map);function recordWorkerMessage(e,t,n,r){if(!h)return;let i=Ae.get(e);i||(i={},Ae.set(e,i));let a=i[t]??={kind:e,direction:t,messages:0,payloadBytes:0,unmeasuredMessages:0};if(a.messages++,n===void 0)a.unmeasuredMessages++;else if(a.payloadBytes+=n,e===`sqlite_request`||e===`sqlite_reply`||e===`authority`){let e=a.payloadBytesByRequestClass??={},t=normalizeWorkerRequestClass(r);e[t]=(e[t]??0)+n}}function messageData(e){return isRecord(e)&&!i.isProxy(e)?e:void 0}function dataProperty(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function messageBody(e){let t=messageData(e),n=t&&dataProperty(t,`type`);return t&&(n===`post`||n===`message`)?dataProperty(t,`value`):e}function workerMessagePayloadBytes(e){if(!h)return;let t=messageBody(e),n=messageData(t),r=n&&(Object.getOwnPropertyDescriptor(n,`value`)??Object.getOwnPropertyDescriptor(n,`input`));if(r&&!(`value`in r))return;let a=r?r.value:t;if(!i.isProxy(a)){if(ArrayBuffer.isView(a)||a instanceof ArrayBuffer){let e=n&&dataProperty(n,`type`)===`open`?dataProperty(n,`preparation`):void 0;return a.byteLength+(ArrayBuffer.isView(e)?e.byteLength:0)}if(typeof a==`string`)return a.length*2;if(a==null)return 0}}function messageKind(e,t){let n=messageData(messageBody(e));if(!n)return t;switch(dataProperty(n,`status`)){case`ok`:case`failed`:return`task_reply`;case`request`:return`task_request`;case`notification`:return`task_notification`;case`consumed`:return`task_consumed`;case`memory`:return`memory`;case`ready`:return`lifecycle`}if(typeof dataProperty(n,`taskId`)==`number`)return`task_input`;if(typeof dataProperty(n,`actor`)==`number`)return`sqlite_request`;if(typeof dataProperty(n,`id`)==`number`&&typeof dataProperty(n,`ok`)==`boolean`)return`sqlite_reply`;if(typeof dataProperty(n,`operationId`)==`number`)switch(dataProperty(n,`type`)){case`prepare`:case`reclaim`:case`canonical-validation`:return`sqlite_request`;case`reclaimed`:case`refused`:case`checkpoint`:return`sqlite_reply`;case`admission`:case`admission-request`:case`admission-release`:return`admission`;case`commit-request`:return`authority`}switch(dataProperty(n,`type`)){case`resource-owner`:case`resource-message`:case`resource-closed`:return`resource`;case`cpu`:case`heap`:return`memory`;case`create`:case`created`:case`stop`:case`stopped`:case`close`:case`closed`:case`release`:case`execution-exit`:case`error`:case`messageerror`:case`create-error`:case`stop-error`:case`request-error`:return`lifecycle`}return dataProperty(n,`closeResource`)===!0?`resource`:t}function observeWorkerMessage(e,t,n=`other`,r,i){h&&recordWorkerMessage(messageKind(e,n),t,r===void 0?workerMessagePayloadBytes(e):r??void 0,i)}function canObserveWorkerMessages(e){if(!Object.isExtensible(e))return!1;for(let t of[`postMessage`,`emit`]){let n=e;for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(!e.writable||typeof e.value!=`function`)return!1;break}n=Reflect.getPrototypeOf(n)}if(!n)return!1}return!0}function collectPostgresBridgeCounters(e,t,n){let r=/* @__PURE__ */ new Map([[y,{threadId:y,count:e,selfRootCount:n}]]);for(let e of t)for(let t of e.postgresBridgeCounters??[])r.set(t.threadId,t);return[...r.values()]}x(`openclaw.code-mode.gc-storm`);const j=resolveGlobalSingleton(Symbol.for(`openclaw.workerCpuSources`),()=>(process.on(`worker`,trackWorker),{gcObserver:void 0,postgresBridgeCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresPoolSelfRootCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresBridgeObservers:/* @__PURE__ */ new Set,revision:0,cpuSources:void 0,nextPoolId:0,poolIds:/* @__PURE__ */ new WeakMap,workers:/* @__PURE__ */ new Map,lifecycle:/* @__PURE__ */ new Map,taskMetrics:/* @__PURE__ */ new Map}));function getTrackedPostgresBridgeCounters(){return collectPostgresBridgeCounters(j.postgresBridgeCount,j.workers.values(),j.postgresPoolSelfRootCount)}function observeTrackedPostgresBridgeCounters(e){return j.postgresBridgeObservers.add(e),()=>j.postgresBridgeObservers.delete(e)}function publishPostgresBridgeCounters(){for(let e of j.postgresBridgeObservers)e()}function forgetWorker(e){let t=j.workers.get(e);if(!t)return;let n=countWorkerStart(t),r=t.retirementReason??`exit`;n.retired.set(r,(n.retired.get(r)??0)+1),t.script===`bridge.worker.js`&&Atomics.sub(j.postgresBridgeCount,0,1),t.memoryFlush?.resolve(),t.memoryPort?.close(),j.workers.delete(e),j.revision++,j.cpuSources=void 0,t.postgresBridgeCounters&&publishPostgresBridgeCounters()}function countWorkerStart(e){let t=j.lifecycle.get(e.script);return t||(t={started:0,retired:/* @__PURE__ */ new Map},j.lifecycle.set(e.script,t)),e.started||(e.started=!0,t.started++),t}function trackWorker(e){if(j.workers.has(e))return;if(h&&e instanceof p&&recordWorkerMessage(`lifecycle`,`to_worker`),h&&e instanceof p&&canObserveWorkerMessages(e)){let t=Object.getPrototypeOf(e)===p.prototype,r=!t||Object.hasOwn(e,`postMessage`)?e.postMessage:void 0;e.postMessage=function(e,t){let i=n.internalMessages?workerMessagePayloadBytes(e):void 0;(r??p.prototype.postMessage).call(this,e,t),n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`to_worker`,i):n.internalMessages?observeWorkerMessage(e,`to_worker`,`other`,i??null,n.requestClass?.()):recordWorkerMessage(`other`,`to_worker`)};let i=!t||Object.hasOwn(e,`emit`)?e.emit:void 0;e.emit=function(e,...t){if(e===`error`&&n.script===`code-mode-node.worker.js`){let e=t[0];n.retirementReason??=isRecord(e)&&e.code===`ERR_CODE_MODE_GC_THRASH`?`gc-thrash`:`crash`}return e===`message`&&(n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`from_worker`,workerMessagePayloadBytes(t[0])):n.internalMessages?observeWorkerMessage(t[0],`from_worker`,`other`,void 0,n.requestClass?.()):recordWorkerMessage(`other`,`from_worker`)),(i??p.prototype.emit).call(this,e,...t)}}let t=!1,finishCpuUsage=e=>(t=!1,e),failCpuUsage=()=>finishCpuUsage(void 0),n={script:`other`,cpuUsage(){if(t)return Promise.resolve(void 0);t=!0;try{return e.cpuUsage().then(finishCpuUsage,failCpuUsage)}catch{return Promise.resolve(failCpuUsage())}}};j.workers.set(e,n),queueMicrotask(()=>countWorkerStart(n)),j.revision++,j.cpuSources=void 0,e.once(`exit`,()=>forgetWorker(e))}let M,je=0;function publishWorkerGcStorm(e){M&&(`retireWorkerId`in e?M.postMessage(e,[]):(performance.now()>=je&&(je=performance.now()+36e5,e.captureStatus=`requested`),M.postMessage({gcStorm:e},[])))}function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new d;M=n;let i=observeTrackedPostgresBridgeCounters(()=>{n.postMessage({postgresBridgeCounters:getTrackedPostgresBridgeCounters()})}),a=process.versions.bun?void 0:s().heap_size_limit,c,l=!1,flushGc=()=>{c&&=(n.postMessage({gc:c}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:s}=process.memoryUsage(),l=process.versions.bun?void 0:o().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:s,heapSizeLimitBytes:a,oldGenerationAfterGcBytes:getOldGenerationAfterGcBytes(),heapSpaces:l,retainedData:t?.(),gc:c}),c=void 0},u,setGcEnabled=e=>{e?u??=observeGcSamples(e=>{(c??=[]).push(...e),(l||c.length>=256)&&flushGc()}):(u?.(),u=void 0,c=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)flushGcSamples(),flushGc(),n.postMessage({flushed:!0,heapUsed:s().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;import(`./code-mode-node.worker-diagnostic-worker-gc-profile-XSCs3y03.mjs`).then(({captureWorkerGcProfiles:e})=>e()).then(e=>{n.postMessage({gcStorm:e.status===`complete`?{...t,captureStatus:`complete`,profiles:e.result}:{...t,captureStatus:`unavailable`,captureReason:e.reason}})}).catch(()=>{n.postMessage({gcStorm:{...t,captureStatus:`unavailable`,captureReason:`capture-failed`}})})}else e?setGcEnabled(e.gc):sample()}),n.once(`close`,()=>{M=void 0,i(),u?.(),c=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:getTrackedPostgresBridgeCounters()},[r]),{setTaskMetrics(e){l=e,setGcEnabled(e)},collectTask(){return l?!0:void 0},close(){M=void 0,i(),u?.(),u=void 0,flushGc(),n.close()}}}const Me=Symbol.for(`openclaw.workerTaskNativeSection`),Ne=globalThis,Pe=Ne[Me]??=new S;function assertWorkerTaskActive(e,t){if(!t()||e&1)throw Error(`worker task cancelled`)}function acquireWorkerNativeSection(e,t){for(;;){let n=Atomics.load(e,0);if(assertWorkerTaskActive(n,t),Atomics.compareExchange(e,0,n,n+2)===n)break}let n=!1;return()=>{n||(n=!0,Atomics.sub(e,0,2),Atomics.notify(e,0))}}function withWorkerTaskNativeSectionScope(e,t,n){return Pe.run(()=>acquireWorkerNativeSection(e,t),n)}function observeWorkerTaskCancellation(e,t,n){let r=!0,i=(async()=>{for(;;){if(!r||!t())return;let i=Atomics.load(e,0);if(i&1){n();return}await Atomics.waitAsync(e,0,i).value}})();return()=>(r=!1,Atomics.notify(e,0),i)}function createWorkerTaskControl(e,t){let throwIfCancelled=()=>assertWorkerTaskActive(Atomics.load(e,0),t);return{throwIfCancelled,runNativeSection:async n=>{let r=acquireWorkerNativeSection(e,t),i;try{i=await n()}finally{r()}return throwIfCancelled(),i}}}function postTaskMessage(e,t,n,r=[]){e.postMessage(t,r),n&&(Atomics.add(n,0,1),Atomics.notify(n,0))}function serveOwnedWorkerTasks$1(e,t,n){if(!g)return;let r=g,i=r,a=!1,o=!1;n.initialize(i);let s,c=Promise.resolve(),l=Promise.resolve(),u;i.on(`message`,function receive(d){if(o){d.resourcePort?.close();return}if(!a){a=!0;let e=n.selectStartupPort?.(d);if(e){i.off(`message`,receive),i=e,n.initialize(i),i.on(`message`,receive),n.onReady?.();return}}if(n.onMessage(d.sampleMemory===!0),d.closeResource&&d.resourcePort){let e=d.resourcePort,r=c;l=l.then(()=>r).then(async()=>{if(o)throw Error(`Worker is retiring after a terminal task failure`);await t.closeResource(d.key),e.postMessage({ok:!0},[])}).catch(n=>{e.postMessage({ok:!1,error:n instanceof Error?n.message:String(n),detail:t.encodeResourceError?.(n)},[])}).finally(()=>{e.close(),!s&&!o&&n.onIdle()});return}if(d.responseId!==void 0){if(d.taskId===u?.taskId&&d.responseId===u.responseId)return;if(!s||d.taskId!==s.taskId||d.responseId!==s.responseId||!s.pending)throw Error(`stale worker task response`);try{s.assertCurrent()}catch(e){s.cancelPending(e);return}let e=s.pending;s.pending=void 0;let t=!1,n=d.taskId,r=d.responseId,a=s.progressSignal;e.resolve({input:d.input,consumed:()=>{t||(t=!0,postTaskMessage(i,{status:`consumed`,taskId:n,id:r},a))}});return}if(s)throw Error(`overlapping worker tasks`);let f=new Int32Array(d.nativeSections),p={taskId:d.taskId,responseId:0,progressSignal:d.progressSignal,assertCurrent:()=>m.throwIfCancelled(),cancelPending:e=>{let t=p.pending;t&&(p.pending=void 0,u={taskId:p.taskId,responseId:p.responseId},t.reject(e))}},m=createWorkerTaskControl(f,()=>s===p);s=p;let h=d.interactive?observeWorkerTaskCancellation(f,()=>s===p,()=>p.cancelPending(/* @__PURE__ */ Error(`worker task cancelled`))):void 0,g=d.interactive?{notify:e=>{m.throwIfCancelled(),postTaskMessage(i,{status:`notification`,taskId:p.taskId,value:e},p.progressSignal)},consumeInput:()=>postTaskMessage(i,{status:`consumed`,taskId:p.taskId,id:0},p.progressSignal),request:(e,t)=>{if(m.throwIfCancelled(),s!==p||p.pending)throw Error(`closed or busy worker channel`);let n=Promise.withResolvers();p.pending=n;try{let n=t?[...t]:[];m.throwIfCancelled(),postTaskMessage(i,{status:`request`,taskId:p.taskId,id:++p.responseId,value:e},p.progressSignal,n)}catch(e){p.pending=void 0,n.reject(e)}return n.promise}}:void 0,_=l;c=Promise.resolve().then(async()=>{try{return await _,m.throwIfCancelled(),n.installTaskContext(d.taskContext),await withWorkerTaskNativeSectionScope(f,()=>s===p,()=>e(d.input,g,m))}finally{await h?.(),s=void 0}}).then(e=>{postTaskMessage(i,{status:`ok`,value:e,taskId:p.taskId,...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},p.progressSignal,t.transferList?.(e)??[])}).catch(e=>{t.retireOnError?o=!0:postTaskMessage(i,{status:`failed`,taskId:p.taskId,error:e instanceof Error?e.message:String(e),...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},p.progressSignal)}).finally(()=>{o?(async()=>{try{await l}finally{try{await n.onRetire?.()}finally{process.exitCode=1;try{i.close()}finally{i!==r&&r.close()}}}})().catch(()=>{process.exitCode=1}):n.onIdle()})}),n.onReady?.()}h&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED);const Fe=36e5,Ie=3e4,Le=/^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/,sanitize=e=>{let t=e.replace(/[^A-Za-z0-9._-]+/g,`_`).replace(/^_+|_+$/g,``);return t&&t!==`.`&&t!==`..`?t:`unknown`};function scheduleOpenClawCompileCacheFlush(){if(!e.getCompileCacheDir?.())return;let t=globalThis[Symbol.for(`openclaw.nodeCompileCacheBase`)]??={};t.flush||(t.flush=setImmediate(()=>{t.flush=void 0;try{e.flushCompileCache()}catch{}}),t.flush.unref())}async function maintain(e){let t=w.dirname(w.dirname(e)),n=w.basename(w.dirname(e));if(w.basename(t)!==`openclaw`||sanitize(n)!==n||!Le.test(w.basename(e)))return;let r=Date.now(),i=await E.lstat(t).catch(()=>void 0);for(let n of[t,w.dirname(e),e]){let e=n===t?i:await E.lstat(n).catch(()=>void 0);if(e&&!e.isDirectory())return}if(i&&r-i.mtimeMs<Fe)return;await E.mkdir(t,{recursive:!0});let a=`${t}.maintenance`,o=await E.lstat(a).catch(()=>void 0);if(o&&r-o.mtimeMs>3e5&&await E.rmdir(a).catch(()=>{}),!await E.mkdir(a).then(()=>!0,()=>!1))return;let s=[],c=0,l=0,u=!1;async function prune(){for(s.sort((e,t)=>t.mtimeMs-e.mtimeMs);s.length;){if(Date.now()-r>Ie)return!1;let e=s[s.length-1];if(c<=536870912&&s.length<=4096&&r-e.mtimeMs<=6048e5)break;await E.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),c-=e.size,s.pop()}return!0}async function visit(e){for await(let t of await E.opendir(e)){if(++l>16384||Date.now()-r>Ie)return!1;let n=w.join(e,t.name);if(t.isDirectory()){if(!await visit(n))return!1}else if(t.isFile()){let e=await E.lstat(n).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(c+=e.size,s.push({file:n,size:e.size,mtimeMs:e.mtimeMs}),s.length%256==0&&!await prune())return!1}}return!0}try{if(r-(await E.lstat(t)).mtimeMs<Fe){u=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await E.utimes(t,e,e),u=!0}}finally{u||await E.utimes(t,i?.atime??/* @__PURE__ */ new Date(0),i?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await E.rmdir(a)}}process.argv[2]===`--maintain`&&process.argv[1]===te(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{});const Re=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 ze=globalThis,N=ze[Re]??createLoggingState();ze[Re]=N;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 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})}function throwIfSettledRejected(e,t){throwCollectedErrors(e.flatMap(e=>e.status===`rejected`?[e.reason]:[]),t)}function throwCollectedErrors(e,t){if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,t)}function materializeErrorStack(e){try{for(let t of collectNestedErrorCandidates(e))try{if(!(t instanceof Error))continue;try{t.stack=String(t.stack)}catch{t.stack=`Stack trace unavailable: custom formatter failed`}}catch{}}catch{}}const P=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseReaders`),()=>({closers:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Map}));function installDeletedAgentDatabaseFences(e){P.deleted.clear();for(let[t,n]of e)P.deleted.set(t,n)}async function applyAgentDatabaseReaderRequest(e){if(e.kind===`revive`){for(let[t,n]of P.deleted)e.agentIds.includes(n)&&P.deleted.delete(t);return}if(e.deleted)for(let t of e.candidates)P.deleted.set(w.resolve(t.path),e.agentId);let t=e.deleted?void 0:new Set(e.retainedPaths?.map(e=>w.resolve(e)));throwIfSettledRejected(await Promise.allSettled([...P.closers].map(async n=>n(e.candidates,t))),`Agent database reader cleanup failed`)}function normalizeCandidates(e){if(Array.isArray(e)&&e.every(e=>isRecord(e)&&typeof e.path==`string`&&(e.scope===void 0||e.scope===`sibling-family`)))return e.map(e=>e.scope?{path:e.path,scope:e.scope}:{path:e.path})}function decodeAgentDatabaseReaderRequest(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}if(Array.isArray(t)){let e=normalizeCandidates(t);return e?{kind:`close`,candidates:e,deleted:!1}:void 0}if(isRecord(t)){if(`candidates`in t&&!(`deleted`in t)){let e=normalizeCandidates(t.candidates),n=t.retainedPaths;return e&&isStringArray(n)?{kind:`close`,candidates:e,retainedPaths:n,deleted:!1}:void 0}if(`deleted`in t){let e=normalizeCandidates(t.deleted);return e&&typeof t.agentId==`string`&&t.agentId.length>0?{kind:`close`,candidates:e,deleted:!0,agentId:t.agentId}:void 0}if(`revive`in t&&isStringArray(t.revive))return{kind:`revive`,agentIds:t.revive}}}resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineSelection`),()=>({}));const Be=resolveGlobalSingleton(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new S);function withDatabaseEngineSelection(e,t){return Be.run(e,t)}const Ve=b,He=resolveGlobalSingleton(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:Ve?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}));function postgresPoolWorkerFailure(){return He.failure}function bindPostgresPool(e){if(He.endpoints){if(He.endpoints===e)return;for(let{port:t}of e.services)t.close()}else He.endpoints=e}const Ue=`openclaw.sqliteDatabaseAdmissions.v1`;function changedAdmissionEntries(e,t){let n=/* @__PURE__ */ new Map;for(let[r,i]of e)t.get(r)!==i&&n.set(r,i);return n}function changedAdmissionWriteScopes(e,t){let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{e!==t[r]&&e.forEach((e,i)=>{t[r].get(i)!==e&&n.set(i,e)})}),n}function isMissingPathError(e){return ae(e,`ENOENT`)||ae(e,`ENOTDIR`)||ae(e,`not-found`)}function normalizeWindowsPathPreservingCase(e){let t=w.win32.normalize(e);if(!t.startsWith(`\\\\?\\`))return t;let n=t.slice(4);return n.toUpperCase().startsWith(`UNC\\`)?`\\\\${n.slice(4)}`:n}const We=process.platform!==`linux`&&process.platform!==`android`;function readDatabaseIdentityBirthtime(e){return We?e.birthtimeNs.toString():`0`}function normalizeDatabasePath(e){let t=process.platform===`win32`?normalizeWindowsPathPreservingCase(e):e;return process.platform===`win32`&&!/^(?:[a-z]:[\\/]|[\\/]{2})/iu.test(t)?e:t}function isSoleDatabaseFileDescriptor(e,t,n){if(process.platform!==`linux`)return!1;try{for(let r of ie(`/proc/self/fd`))if(/^\d+$/u.test(r)&&Number(r)!==e&&!n?.has(Number(r)))try{let e=re(Number(r),{bigint:!0});if(e.dev===t.dev&&e.ino===t.ino)return!1}catch(e){if(!ae(e,`EBADF`))return!1}return!0}catch{return!1}}function readSqliteDatabaseAdmissionIdentity(e){return`${e.dev}:${e.ino}:${readDatabaseIdentityBirthtime(e)}`}const F={schemaRevision:0,factRevision:1,publicationRevision:2,retired:3,writeRevision:4,hostRevision:5,unscopedWriteRevision:6,writeScopeRevision:7,sealPresent:8},Ge=Object.keys(F).length,Ke=1048576,qe=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseWriteScopeRetention`),()=>/* @__PURE__ */ new WeakMap),writeScopeBytes=e=>e.length*2+256;function retainSqliteDatabaseWriteScope(e,t,n){let r=e.writeScopes,i=qe.get(r);i||(i={bytes:[...r.keys()].reduce((e,t)=>e+writeScopeBytes(t),0),retired:/* @__PURE__ */ new Set},qe.set(r,i)),r.delete(t)||(i.bytes+=writeScopeBytes(t)),r.set(t,n),pruneSqliteDatabaseWriteScopes(e)}function pruneSqliteDatabaseWriteScopes(e){let t=qe.get(e.writeScopes);if(t.bytes<=Ke)return!1;let n=!1;for(let[r,i]of e.writeScopes)if(!(Atomics.compareExchange(i.state,2,0,-1)>0&&Atomics.load(i.state,1)===0)&&(Atomics.store(i.state,1,1),advanceSqliteDatabaseGeneration(e,`writeScopeRevision`),e.writeScopes.delete(r),t.bytes-=writeScopeBytes(r),t.retired.add(r),n=!0,t.bytes<=Ke))break;return n}function readSqliteDatabaseAdmissions(e){return Array.isArray(e)?e:void 0}function isSqliteDatabaseAdmissionRetired(e){return readSqliteDatabaseGeneration(e,`retired`)!==0}function isSqliteDatabaseAdmissionFactCurrent(e,t){return!isSqliteDatabaseAdmissionRetired(e)&&Atomics.load(new Int32Array(t.current),0)===1&&t.revision===readSqliteDatabaseFactRevision(e,t.schemaDependent)}function hasSqliteDatabaseSchemaAdmission(e){let t=e?.facts.get(`sqlite-schema`);return!!(e&&t&&isSqliteDatabaseAdmissionFactCurrent(e,t))}function readSqliteDatabaseFactRevision(e,t){return readSqliteDatabaseGeneration(e,t?`schemaRevision`:`factRevision`)}function readSqliteDatabaseGeneration(e,t){return Atomics.load(new Int32Array(e.generation),F[t])}function advanceSqliteDatabaseGeneration(e,t){return Atomics.add(new Int32Array(e.generation),F[t],1)}const Je=Array.from({length:128},()=>/* @__PURE__ */ new Map);function snapshotWriteScopes(e,t=Je,n){let r=t,i=qe.get(e),visit=(n,a)=>{let o=0;for(let e=0;e<a.length;e++)o=o*31+a.charCodeAt(e)|0;let s=o&Je.length-1,c=!n||Atomics.load(n.state,1)!==0;c&&e.delete(a)&&i&&(i.bytes-=writeScopeBytes(a)),!(c?!t[s].has(a):t[s].get(a)===n)&&(r===t&&(r=t.slice()),r[s]===t[s]&&(r[s]=new Map(t[s])),c?r[s].delete(a):r[s].set(a,n))};if(n)for(let t of n)visit(e.get(t),t);else e.forEach(visit);for(let t of i?.retired??[])visit(e.get(t),t);return i?.retired.clear(),r}function createSqliteDatabaseAdmissionCursor(){return{revision:-1,records:/* @__PURE__ */ new WeakMap}}var SqliteDatabaseAdmissionRegistry=class{constructor(){this.records=/* @__PURE__ */ new Map,this.exchangeCursor=createSqliteDatabaseAdmissionCursor(),this.locations=/* @__PURE__ */ new Map,this.published=/* @__PURE__ */ new Map,this.scopeSweeps=/* @__PURE__ */ new WeakMap,this.descriptors=/* @__PURE__ */ new Map,this.revision=0,this.retainProcessFacts=!0}useConnectionScopedFacts(){this.retainProcessFacts=!1}changeReferences(e,t){let n=e.references.get(y);return n||(n=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),e.references.set(y,n)),Atomics.add(new Int32Array(n),0,t)+t===+(t===1)&&(t===-1&&this.retireUnreferenced(e),this.publish(e),!0)}retireUnreferenced(e){if(y!==0||isSqliteDatabaseAdmissionRetired(e)||[...e.references.values()].some(e=>Atomics.load(new Int32Array(e),0)>0))return;for(let[t,n]of e.facts)(!this.retainProcessFacts||n.lifetime!==`process`||!isSqliteDatabaseAdmissionFactCurrent(e,n))&&e.facts.delete(t);let t=this.descriptors.get(e.identity);t&&(t.facts=e.facts),Atomics.compareExchange(new Int32Array(e.generation),F.retired,0,2),e.writeScopes.clear()}releaseWorker(e){let t=/* @__PURE__ */ new Map;for(let n of this.records.values()){let r=e>0?n.references.get(e):void 0;r&&(Atomics.store(new Int32Array(r),0,-1),this.retireUnreferenced(n),t.set(n,void 0))}t.size>0&&this.publish(t)}observeLocation(e,t){let n=normalizeDatabasePath(w.resolve(e));t===void 0?this.locations.delete(n):this.locations.set(n,t)}forLocation(e){let t=this.locations.get(normalizeDatabasePath(w.resolve(e))),n=t===void 0?void 0:this.records.get(t);return n&&!isSqliteDatabaseAdmissionRetired(n)?n:void 0}hasSchemaAdmissionForIdentity(e){if(!e.key.startsWith(`file:`)||e.birthtime===void 0)return!1;let t=`${e.key.slice(5)}:${e.birthtime}`;return hasSqliteDatabaseSchemaAdmission(this.records.get(t))}forget(e){this.records.delete(e),this.published.delete(e);for(let[t,n]of this.locations)n===e&&this.locations.delete(t)}retainDescriptorCustody(e,t){let n=readSqliteDatabaseAdmissionIdentity(t),r=this.descriptors.get(n);r&&r.descriptor!==e&&(r.additionalDescriptors??=/* @__PURE__ */ new Set).add(e),r||this.descriptors.set(n,{descriptor:e,file:t,facts:/* @__PURE__ */ new Map})}retainDescriptor(e,t,n){let r=this.descriptors.get(readSqliteDatabaseAdmissionIdentity(n)),i={identity:readSqliteDatabaseAdmissionIdentity(n),physicalIdentity:{key:`file:${n.dev}:${n.ino}`,birthtime:readDatabaseIdentityBirthtime(n)},location:e,descriptor:t,descriptorOwner:0,generationId:ne(),generation:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*Ge),writeScopes:/* @__PURE__ */ new Map,writeScopeRevision:0,references:/* @__PURE__ */ new Map,facts:new Map([...r?.facts??[]].filter(([,e])=>Atomics.load(new Int32Array(e.current),0)===1).map(([e,t])=>[e,{...t,revision:0}]))};this.records.set(i.identity,i);let a=r?.descriptor===t?r:{descriptor:t,file:n,facts:/* @__PURE__ */ new Map};return a.file=n,a.facts=/* @__PURE__ */ new Map,this.descriptors.set(i.identity,a),this.observeLocation(e,i.identity),this.publish(i),i}retireDescriptor(e,t){let n=this.records.get(e),r=this.descriptors.get(e),i=r?.descriptor??n?.descriptor;if(i===void 0)return!1;let a=T.fstatSync(i,{bigint:!0});return a.nlink>1n||t.requireSoleDescriptor&&!isSoleDatabaseFileDescriptor(i,a,r?.additionalDescriptors)?!1:(n&&Atomics.store(new Int32Array(n.generation),F.retired,1),T.closeSync(i),r?.additionalDescriptors?.forEach(e=>T.closeSync(e)),this.descriptors.delete(e),this.forget(e),this.publish(),!0)}publish(e,t){let n=e instanceof Map;if(!e||n||this.records.get(e.identity)===e){for(let r of this.records.values()){if(isSqliteDatabaseAdmissionRetired(r)){readSqliteDatabaseGeneration(r,`retired`)===1&&(this.descriptors.get(r.identity)?.additionalDescriptors?.forEach(T.closeSync),this.descriptors.delete(r.identity)),this.forget(r.identity);continue}if(e&&e!==r&&!(n&&e.has(r)))continue;let i=e===r||n;for(let[e,t]of r.references)Atomics.load(new Int32Array(t),0)<0&&(r.references.delete(e),i=!0);let a=this.published.get(r.identity),o=readSqliteDatabaseGeneration(r,`writeScopeRevision`),s=a&&e?n?e.get(r):t:void 0,c=s===void 0&&this.scopeSweeps.get(r)!==o,l=snapshotWriteScopes(r.writeScopes,a?.writeScopes,s??(c?void 0:[]));if(c&&this.scopeSweeps.set(r,o),i||=l!==a?.writeScopes,!i)continue;y===0&&(r.writeScopeRevision=readSqliteDatabaseGeneration(r,`writeScopeRevision`));let{writeScopes:u,...d}=r,f={...d,facts:new Map(r.facts),references:new Map(r.references),hostRevision:y===0?readSqliteDatabaseGeneration(r,`hostRevision`):r.hostRevision},p={...f,writeScopes:l.filter(e=>e.size>0)};this.published.set(r.identity,{metadata:f,writeScopes:l,snapshot:p})}this.revision++,v(Ue,[...this.published.values()].map(e=>e.snapshot))}}capture(e,t){let n=t?/* @__PURE__ */ new Set([...t.admissions?.map(e=>e.identity)??[],...t.location===void 0?[]:[this.forLocation(t.location)?.identity].filter(e=>e!==void 0)]):void 0;if(!n&&!e&&this.publish(),!n&&e?.revision===this.revision)return[];let r=n?[...n].flatMap(e=>{let t=this.published.get(e);return t&&!isSqliteDatabaseAdmissionRetired(t.snapshot)?[t]:[]}):[...this.published.values()];return e?(n||(e.revision=this.revision),r.flatMap(t=>{let n=e.records.get(t.metadata.generation);return n===t?[]:(e.records.set(t.metadata.generation,t),[n?{...t.metadata,facts:changedAdmissionEntries(t.metadata.facts,n.metadata.facts),writeScopes:[changedAdmissionWriteScopes(t.writeScopes,n.writeScopes)],references:changedAdmissionEntries(t.metadata.references,n.metadata.references)}:t.snapshot])})):r.map(e=>e.snapshot)}captureExchange(e,t){return t&&typeof t!=`string`&&isSqliteDatabaseAdmissionRetired(t)?[{...t,facts:/* @__PURE__ */ new Map,writeScopes:[],references:/* @__PURE__ */ new Map}]:this.capture(this.exchangeCursor,e)}resetExchangeCursor(){this.exchangeCursor=createSqliteDatabaseAdmissionCursor()}install(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=this.records.get(n.identity);if(n.descriptorOwner!==0||isSqliteDatabaseAdmissionRetired(n)){e&&isSqliteDatabaseAdmissionRetired(e)&&t.set(e,void 0);continue}let r=!1;if(e&&isSqliteDatabaseAdmissionRetired(e)&&(e=void 0),!e)e={...n,facts:new Map(n.facts),writeScopes:/* @__PURE__ */ new Map,references:new Map(n.references),hostRevision:void 0},this.records.set(n.identity,e),this.observeLocation(n.location,n.identity),r=!0;else if(e.generationId!==n.generationId)continue;!e.cleanCloseRefusal&&n.cleanCloseRefusal&&(e.cleanCloseRefusal=n.cleanCloseRefusal,r=!0);for(let[t,i]of n.facts)isSqliteDatabaseAdmissionFactCurrent(n,i)&&e.facts.get(t)?.publication!==i.publication&&(e.facts.set(t,i),r=!0);let i=t.get(e)??[];for(let t of n.writeScopes)for(let[n,a]of t){if(Atomics.load(a.state,1)!==0)continue;let t=e.writeScopes.get(n);if(!(t?.identity===a.identity||y===0&&t&&Atomics.load(t.state,1)===0)){if(y===0){let t=advanceSqliteDatabaseGeneration(e,`writeScopeRevision`);this.scopeSweeps.get(e)===t&&this.scopeSweeps.set(e,t+1|0)}retainSqliteDatabaseWriteScope(e,n,a),i.push(n),r=!0}}let a=readSqliteDatabaseGeneration(e,`writeScopeRevision`);(y===0||n.writeScopeRevision===a)&&(r||=e.writeScopeRevision!==a,e.writeScopeRevision=a);for(let[t,i]of n.references)!e.references.has(t)&&Atomics.load(new Int32Array(i),0)>=0&&(e.references.set(t,i),r=!0);y!==0&&n.hostRevision!==void 0&&n.hostRevision!==e.hostRevision&&n.hostRevision===readSqliteDatabaseGeneration(e,`hostRevision`)&&(e.hostRevision=n.hostRevision,r=!0),this.retireUnreferenced(e),(r||isSqliteDatabaseAdmissionRetired(e))&&t.set(e,i.length>0?i:void 0)}return t.size>0&&this.publish(t),t.size>0}};const Ye=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissions`),()=>({registry:new SqliteDatabaseAdmissionRegistry,descriptorPreparation:Promise.resolve(),connections:/* @__PURE__ */ new WeakMap,openedIdentities:/* @__PURE__ */ new WeakMap,unproven:/* @__PURE__ */ new WeakSet,suspended:/* @__PURE__ */ new WeakSet,local:/* @__PURE__ */ new WeakMap,rolledBack:/* @__PURE__ */ new WeakSet,dataWriters:/* @__PURE__ */ new WeakMap,localWriteRevisions:/* @__PURE__ */ new WeakMap,writeListeners:/* @__PURE__ */ new WeakMap,ddlRevisions:/* @__PURE__ */ new WeakMap,schemaDirty:/* @__PURE__ */ new WeakSet,localSchemaRevisions:/* @__PURE__ */ new Map,misses:/* @__PURE__ */ new WeakMap,exchange:new S,exchanging:!1,publication:0}));function installSqliteDatabaseAdmissions(e){Ye.registry.install(e)}function withSqliteDatabaseAdmissionExchange(e,t){return Ye.exchange.run(e,t)}const Xe=readSqliteDatabaseAdmissions(m(Ue));Xe&&(installSqliteDatabaseAdmissions(Xe),Ye.registry.captureExchange());var StateDatabaseAccessError=class extends Error{constructor(...e){super(...e),this.name=`StateDatabaseAccessError`}};resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateOwnerContentionError`),()=>class extends Error{constructor(e,t,n,r){super(`OpenClaw state database is busy at ${e}. ${n?`${n} `:``}Wait for the other OpenClaw process to finish, then retry. If it persists, run \`openclaw gateway status\` and check for other OpenClaw processes using the same state directory. A running Gateway can hold this ownership until it stops; stop it through its service manager or original terminal before retrying.`),this.databasePath=e,this.cause=t,this.holderDetail=n,this.holder=r,this.name=`GatewayStateOwnerContentionError`}}),resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseMaintenanceScopeError`),()=>class extends StateDatabaseAccessError{constructor(e){super(`Internal state ownership error at ${e}: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error.`),this.name=`StateDatabaseMaintenanceScopeError`}});const Ze=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}});resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends StateDatabaseAccessError{constructor(e,t){super(t),this.databasePath=e}});const I=resolveGlobalSingleton(Symbol.for(`openclaw.asyncContext`),()=>new S);var AsyncContext=class{constructor(e){this.key=e}getStore(){return I.getStore()?.[this.key]}run(e,t){let n=I.getStore(),r=n?.[this.key];if(Object.is(r,e))return t();let i={...n,[this.key]:e};I.enterWith(i);try{return t()}finally{let e=I.getStore();I.enterWith(e===i?n:{...e,[this.key]:r})}}exit(e){return this.run(void 0,e)}enterWith(e){I.enterWith({...I.getStore(),[this.key]:e})}};const Qe=new AsyncContext(Symbol.for(`openclaw.sqliteReaderOwners`)),$e=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteReaderConnections`),()=>({nextId:0,byDatabase:/* @__PURE__ */ new WeakMap,byPath:/* @__PURE__ */ new Map,finalizer:new FinalizationRegistry(e=>forgetConnection(e))}));function currentSqliteOperationTiming(){return Qe.getStore()?.timing}function forgetConnection(e){if(e.path){let t=$e.byPath.get(e.path);t?.delete(e.id),t?.size===0&&$e.byPath.delete(e.path)}}const et=Symbol.for(`openclaw.sqliteWorkerErrorCode`);var SqliteWorkerError=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`SqliteWorkerError`,Object.defineProperty(this,et,{value:t})}};function wrapSqliteWorkerError(e,t,...n){let i=n.filter(e=>e!==void 0).map(t=>toErrorObject(t,e)).filter((e,t,n)=>n.findIndex(t=>r(t,e))===t);return Object.assign(t===void 0?Error(e):new SqliteWorkerError(e,t),{cause:i.length>1?AggregateError(i,e):i[0]})}const tt=process.hrtime;function readSqliteWorkerMonotonicNs(){return tt.bigint()}resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerOpenRefusedError`),()=>class extends Error{constructor(e){super(`SQLite worker admission was refused before agent open`,{cause:e}),this.originalError=e,this.name=`SqliteWorkerOpenRefusedError`}}),resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWorkerAdmissionTimeoutError`),()=>class extends Error{constructor(){super(`SQLite host admission timed out; retry after transaction rollback`),this.code=`admission-timeout`,this.name=`SqliteWorkerAdmissionTimeoutError`}});var SqliteDatabaseAdmissionTimeoutError=class extends SqliteWorkerError{constructor(){super(`SQLite admission facts exchange timed out; the host did not reply`,`unavailable`)}};const L=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionWait`),()=>new S);function withSqliteDatabaseAdmissionWait(e,t){let n={wait:e,parent:L.getStore(),active:!0},close=()=>{n.active=!1},r=!1;try{let e=L.run(n,t);return se(e)&&(r=!0,e.then(close,close)),e}finally{r||close()}}function readSqliteDatabaseAdmissionDeadline(){let e;for(let t=L.getStore();t;t=t.parent){if(!t.active)continue;let n=t.wait.deadlineAtMs;n!==void 0&&(e=Math.min(e??1/0,n))}return e}function assertSqliteDatabaseAdmissionWaitActive(){try{for(let e=L.getStore();e;e=e.parent)e.active&&e.wait.assertActive?.()}catch(e){throw wrapSqliteWorkerError(`SQLite admission facts exchange cancelled by its caller`,`unavailable`,e)}}const nt=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteDatabaseAdmissionUpstream`),()=>({}));function bindSqliteDatabaseAdmissionUpstream(e){let t=nt.connection;if(t){if(t.port!==e)throw new SqliteWorkerError(`SQLite admission upstream changed owner`,`closed`);return}let n={port:e,closed:!1};nt.connection=n,e.once(`close`,()=>{n.closed=!0}),e.unref()}function exchangeSqliteDatabaseAdmissions(e,t,n,r){return exchangeDatabaseAdmissions(e,t,n,r)}function exchangeDatabaseAdmissions(e,t,n,r){let{port1:i,port2:a}=new d,o=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),s=currentSqliteOperationTiming(),c=Date.now(),l=readSqliteDatabaseAdmissionDeadline(),u=l===void 0?6e5:Math.max(0,l-Date.now()),f=readSqliteWorkerMonotonicNs()+BigInt(Math.ceil(u))*1000000n,remaining=()=>{assertSqliteDatabaseAdmissionWaitActive();let e=Number(f-readSqliteWorkerMonotonicNs())/1e6;if(e<=0)throw new SqliteDatabaseAdmissionTimeoutError;return e};try{for(remaining(),e.postMessage({kind:`sqlite-database-admissions`,admissions:t,location:n,create:r,deadlineAtMs:l,port:a,decision:o.buffer},[a]);Atomics.load(o,0)===0;){let e=remaining();Atomics.wait(o,0,0,L.getStore()?Math.min(100,e):e)}remaining();let s=Atomics.load(o,0);if(s===4&&n&&r===!0)throw new Ze(n,`OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`);if(s!==1)throw new SqliteWorkerError(`SQLite admission facts exchange failed`,`unavailable`);let c=readSqliteDatabaseAdmissions(_(i)?.message);if(!c)throw new SqliteWorkerError(`SQLite admission facts reply is unavailable`,`unavailable`);return c}finally{Atomics.compareExchange(o,0,0,2),s&&(s.databaseAdmissionWaitMs+=Date.now()-c),i.close(),a.close()}}const rt=33554432;let it={heapUsed:0,external:0},R,z,at=!1;function hasIdleGarbageGrowth(){let e=process.memoryUsage();return e.heapUsed>it.heapUsed+rt||e.external>it.external+rt}async function collectWorkerIdleGarbage(){if(z=void 0,hasIdleGarbageGrowth()){at=!0;try{if(!R){let e=new ce;e.connect(),R=e}await R.post(`HeapProfiler.collectGarbage`),it=process.memoryUsage()}catch(e){e instanceof Error&&e.message.startsWith(`Inspector error -32601:`)?R=null:process.emitWarning(e instanceof Error?e:String(e))}finally{at=!1}}}function scheduleWorkerIdleGc(){h||R===null||z||at||hasIdleGarbageGrowth()&&(z=setTimeout(()=>{collectWorkerIdleGarbage()},1e3).unref())}function cancelWorkerIdleGc(){clearTimeout(z),z=void 0}function serveWorkerTasks(e,t={}){serveOwnedWorkerTasks(e,t)}function serveOwnedWorkerTasks(e,t={}){let n,r,i,a,o,s,runWithTaskContext=async e=>{let run=async()=>{let t=i;if(!t)return e();let n=!0;try{return await withSqliteDatabaseAdmissionExchange((e,r,i)=>{if(!n)throw Error(`SQLite admission facts outlived their worker task`);return exchangeSqliteDatabaseAdmissions(t,e,r,i)},e)}finally{n=!1}};return o?withDatabaseEngineSelection(o,run):run()};serveOwnedWorkerTasks$1((t,n,r)=>withSqliteDatabaseAdmissionWait({deadlineAtMs:a,assertActive:()=>r.throwIfCancelled()},()=>runWithTaskContext(async()=>{let i=await e(t,n,r),a=postgresPoolWorkerFailure();if(a)throw a;return i})),{...t,get retireOnError(){return t.retireOnError||postgresPoolWorkerFailure()!==void 0},closeResource:e=>runWithTaskContext(async()=>{let n=decodeAgentDatabaseReaderRequest(e);if(!n&&!t.closeResource)throw Error(`Worker does not own retained resources`);n&&await applyAgentDatabaseReaderRequest(n),(!n||n.kind===`close`)&&await t.closeResource?.(e)})},{selectStartupPort(e){if(isRecord(e)&&e.type===`openclaw.worker-task-port`){if(!(e.port instanceof f))throw Error(`Retained worker task port is invalid`);return r=e.port,r}},initialize(e){N.forceConsoleToStderr=!0,n=e},onReady(){r?.postMessage({status:`ready`},[])},onMessage(e){e&&!s&&(s=serveWorkerMemorySamples(n,t.retainedData)),cancelWorkerIdleGc()},installTaskContext(e){s?.setTaskMetrics(e.collectWorkerMetrics===!0),a=e.databaseAdmissionDeadlineAtMs,o=e.databaseEngineSelection,e.postgresPool&&bindPostgresPool(e.postgresPool),installDeletedAgentDatabaseFences(e.deletedAgentDatabaseFences),e.databaseAdmissionPort&&bindSqliteDatabaseAdmissionUpstream(e.databaseAdmissionPort),i??=e.databaseAdmissionPort},onIdle(){scheduleOpenClawCompileCacheFlush(),t.idleGc!==!1&&scheduleWorkerIdleGc()},collectTaskDiagnostics:()=>s?.collectTask(),onRetire(){cancelWorkerIdleGc();try{s?.close()}finally{i?.close()}}})}const ot=[`search`,`describe`,`callValue`,`resultSave`,`resultLoad`,`resultDelete`,`nodes`,`yield`,`namespace`,`agentSpawn`,`agentWait`,`skillsList`,`skillsSearch`,`skillsRead`,`sleep`,`swarmNote`],st=String.raw`
(() => {
const output = [];
const pending = new Map();
const queued = new Map();
// Only ordinary requests use this quota. Swarm retains its group/VM bounds
// while sharing the same ordered queue and in-flight slots.
const maxQueuedOrdinary = ${128};
let queuedOrdinaryCount = 0;
let admissionError;
const maxPending = globalThis.__openclawMaxPendingToolCalls;
delete globalThis.__openclawMaxPendingToolCalls;
const catalogBindings = Array.isArray(globalThis.__openclawCatalog) ? globalThis.__openclawCatalog : [];
const apiFiles = Array.isArray(globalThis.__openclawApiFiles) ? globalThis.__openclawApiFiles : [];
const namespaceDescriptors = Array.isArray(globalThis.__openclawNamespaces) ? globalThis.__openclawNamespaces : [];
const hostRequest = globalThis.__openclawHostRequest;
const hostCancelRequest = globalThis.__openclawHostCancelRequest;
const hostTakeBridgeReply = globalThis.__openclawHostTakeBridgeReply;
const hostObserveNetworkContent = globalThis.__openclawHostObserveNetworkContent;
const hostOutput = globalThis.__openclawHostOutput;
delete globalThis.__openclawHostOutput;
delete globalThis.__openclawHostObserveNetworkContent;
delete globalThis.__openclawHostRequest;
delete globalThis.__openclawHostCancelRequest;
delete globalThis.__openclawHostTakeBridgeReply;
delete globalThis.__openclawCatalog;
delete globalThis.__openclawApiFiles;
delete globalThis.__openclawNamespaces;
const bridgeSequences = new Map();
const timers = new Map();
// Keep rejection ownership in the snapshot so a handler attached after wait
// can clear it; an unawaited failure must not become a successful cell.
const unhandledRejections = new Set();
// Rejection callbacks cross the VM boundary. Guest prototype changes must not
// make them throw into the dependency's eager, uncapped exception formatter.
const addUnhandledRejection = unhandledRejections.add.bind(unhandledRejections);
const deleteUnhandledRejection = unhandledRejections.delete.bind(unhandledRejections);
const unhandledRejectionValues = unhandledRejections.values.bind(unhandledRejections);
const nextUnhandledRejection = Function.prototype.call.bind(unhandledRejections.values().next);
// Maps each host-rejected bridge error to its terminal failure code. Guest
// writes to error.code never reach the cell result; only this record does.
const bridgeErrors = new WeakMap();
// Guest prototype changes must not replace the operations that own error provenance.
const rememberBridgeError = bridgeErrors.set.bind(bridgeErrors);
const bridgeFailureCode = bridgeErrors.get.bind(bridgeErrors);
let nextTimerId = 0;
const GuestPromise = Promise;
const GuestError = Error;
const GuestTypeError = TypeError;
const GuestRangeError = RangeError;
const stringifyJson = JSON.stringify;
const string = String;
const sliceString = Function.prototype.call.bind(String.prototype.slice);
const maxErrorUnits = Math.min(globalThis.__openclawMaxOutputBytes ?? 16_384, 16_384);
delete globalThis.__openclawMaxOutputBytes;
// Bridge payloads carry trusted failure codes; guest JSON replacements must not rewrite them.
const parseJson = JSON.parse;
function encodeError(error) {
// Recover provenance before diagnostic getters can fail. Only bounded primitive
// strings cross to the host; thrown arrays/objects must never be recursively dumped.
const bridgeCode = bridgeFailureCode(error) ?? null;
const diagnostic = (read, fallback) => {
try {
const value = read();
const text = value !== null && (typeof value === "object" || typeof value === "function")
? "[Thrown object]" : string(value);
return text.length <= maxErrorUnits ? text
: sliceString(text, 0, maxErrorUnits) + " [error truncated]";
} catch { return fallback; }
};
return stringifyJson({
__proto__: null,
bridgeCode,
name: diagnostic(() => error?.name ?? "Error", "Error"),
message: diagnostic(() => error?.message ?? error, "Error"),
stack: diagnostic(() => {
const stack = error?.stack;
return typeof stack === "string" ? stack : "";
}, ""),
});
}
function emitOutput(entry) {
if (hostOutput) return hostOutput(encodeFinalValue(entry));
return output.push(entry);
}
const promiseOutput = "[Unawaited Promise: use await or Promise.all(...) before emitting or returning values.]";
let networkContentObserved = false;
function observeNetworkContent() {
if (networkContentObserved) return;
networkContentObserved = true;
hostObserveNetworkContent();
}
// The counter lives in the VM snapshot. JSON code units are a conservative
// bound (at most three UTF-8 bytes each), including empty-message overhead.
let consoleUnits = 0;
const consoleLimit = 16_384;
const consoleMarker = "[console output truncated]";
function consoleWrite(level, args) {
if (consoleUnits >= consoleLimit) return;
let nodes = 100;
const seen = new Set();
const clip = (value, limit) => {
if (value.length <= limit) return value;
// Do not split a surrogate pair at a diagnostic boundary.
let end = limit;
const last = value.charCodeAt(end - 1);
if (last >= 0xd800 && last <= 0xdbff) end--;
return value.slice(0, end) + "…[truncated]";
};
const inspect = (value, depth = 0) => {
if (--nodes < 0) return "[truncated]";
if (typeof value === "string") return clip(value, 512);
if (value === null || typeof value === "boolean" || typeof value === "number") return value;
if (typeof value === "undefined") return "undefined";
if (typeof value === "bigint") return clip(String(value), 512) + "n";
if (typeof value === "symbol") return clip(String(value), 512);
if (typeof value === "function") return "[Function]";
if (seen.has(value)) return "[Circular]";
if (depth >= 4) return "[truncated]";
seen.add(value);
try {
if (value instanceof GuestPromise) return promiseOutput;
const array = Array.isArray(value);
const result = array ? [] : Object.create(null);
let count = 0;
for (const key in value) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
if (count++ >= 50 || nodes <= 0) {
if (array) result.push("[truncated]");
else result["…"] = "[truncated]";
break;
}
const descriptor = Object.getOwnPropertyDescriptor(value, key);
const item = descriptor && "value" in descriptor
? inspect(descriptor.value, depth + 1) : "[Accessor]";
if (array) result.push(item);
else result[clip(key, 512)] = item;
}
if (value instanceof Error) {
const message = Object.getOwnPropertyDescriptor(value, "message");
result.message = message && "value" in message ? inspect(message.value, depth + 1) : "[Accessor]";
}
return result;
} finally {
seen.delete(value);
}
};
let message = level === "log" ? "" : "[" + level + "] ";
for (let i = 0; i < args.length; i++) {
if (i > 0) message += " ";
if (nodes <= 0 || message.length >= 4096) { message += "[truncated]"; break; }
try {
const value = inspect(args[i]);
message += typeof value === "string" ? value : JSON.stringify(value);
} catch {
message += "[Unserializable]";
}
}
const entry = { type: "text", text: clip(message, 4096) };
const units = JSON.stringify(entry).length;
if (consoleUnits + units > consoleLimit - 100) {
emitOutput({ type: "text", text: consoleMarker });
consoleUnits = consoleLimit;
return;
}
consoleUnits += units;
emitOutput(entry);
}
const guestConsole = Object.freeze(Object.fromEntries(
["log", "info", "warn", "error", "debug"].map((level) => [level, (...args) => consoleWrite(level, args)]),
));
function safe(value, diagnosePromises = false) {
if (value === undefined) return null;
try {
return JSON.parse(JSON.stringify(diagnosePromises ? serializeOutputValue(value) : value));
} catch {
if (value instanceof Error) {
return { name: value.name, message: value.message };
}
if (value === null) return null;
const type = typeof value;
if (type === "string" || type === "number" || type === "boolean") return value;
return String(value);
}
}
function asText(value) {
if (typeof value === "string") return value;
const encoded = JSON.stringify(safe(value, true));
return typeof encoded === "string" ? encoded : String(value);
}
function assertQueueCapacity(queue) {
if (!admissionError && !queue && pending.size >= maxPending && queuedOrdinaryCount >= maxQueuedOrdinary) {
admissionError = "code mode bridge queue limit exceeded (" + maxQueuedOrdinary + " ordinary requests queued; " + maxPending + " in-flight slots). Await smaller batches before creating more tool calls or timers.";
}
// Sticky even if guest code catches the immediate error: the worker refuses
// this entire synchronous frontier before dispatching any admitted prefix.
if (admissionError) throw new Error(admissionError);
}
function beginRequest(method, args, { queue = false } = {}) {
assertQueueCapacity(queue);
const methodName = String(method);
const sequence = (bridgeSequences.get(methodName) ?? 0) + 1;
bridgeSequences.set(methodName, sequence);
const id = "bridge:" + methodName + ":" + String(sequence);
const argsJson = stringifyJson(args ?? []);
// Guest toJSON/getters can create requests while serializing this input.
assertQueueCapacity(queue);
const callStack = new GuestError().stack;
let callbacks;
const promise = new Promise((resolve, reject) => { callbacks = { resolve, reject }; });
const admit = () => {
callbacks.stack = callStack;
callbacks.location = hostRequest(methodName, argsJson, id, callStack);
pending.set(id, callbacks);
};
if (queue || pending.size >= maxPending) {
queued.set(id, { admit, callbacks, ordinary: !queue });
if (!queue) queuedOrdinaryCount++;
} else admit();
return { id, promise };
}
// Admission and cancellation release capacity through the same owner.
function takeQueuedRequest(id) {
const entry = queued.get(id);
if (!entry) return;
queued.delete(id);
if (entry.ordinary) queuedOrdinaryCount--;
return entry;
}
// Refill after guest continuations run so dependent ordinary calls retain
// first use of released slots. Waiting requests refill in insertion order.
// Closures, copied inputs, and stable IDs live only in the bounded VM snapshot.
function drainQueuedRequests() {
while (queued.size > 0 && pending.size < maxPending) {
const id = queued.keys().next().value;
takeQueuedRequest(id).admit();
}
}
function request(method, args, options) {
return beginRequest(method, args, options).promise;
}
function scheduleTimer(callback, delay, args) {
if (typeof callback !== "function") {
throw new TypeError("setTimeout callback must be a function");
}
const numericDelay = Number(delay);
const delayMs = Number.isFinite(numericDelay) ? Math.max(0, Math.floor(numericDelay)) : 0;
const timerId = ++nextTimerId;
const timerRequest = beginRequest("sleep", [delayMs]);
timers.set(timerId, timerRequest.id);
void timerRequest.promise.then(() => {
if (!timers.delete(timerId)) return;
callback(...args);
});
return timerId;
}
function cancelTimer(timerId) {
const requestId = timers.get(Number(timerId));
if (!requestId) return;
timers.delete(Number(timerId));
const queuedEntry = takeQueuedRequest(requestId);
if (queuedEntry) {
queuedEntry.callbacks.resolve(null);
return;
}
hostCancelRequest(requestId);
const entry = pending.get(requestId);
if (!entry) return;
pending.delete(requestId);
entry.resolve(null);
}
class SwarmAgentError extends Error {
constructor(runId, status, detail) {
super("Swarm agent " + runId + " " + status + ": " + detail);
this.name = "SwarmAgentError";
this.runId = runId;
this.status = status;
}
}
function swarmNote(kind, value) {
if (typeof value !== "string" || !value.trim()) {
throw new TypeError(kind + " note must be a non-empty string");
}
void request("swarmNote", [{ kind, text: value }], { queue: true }).catch(() => {});
}
async function runAgent(prompt, options = {}) {
if (typeof prompt !== "string" || !prompt.trim()) {
throw new TypeError("agents.run prompt must be a non-empty string");
}
if (options === null || typeof options !== "object" || Array.isArray(options)) {
throw new TypeError("agents.run options must be an object");
}
if (options.phase !== undefined && (typeof options.phase !== "string" || !options.phase.trim())) {
throw new TypeError("agents.run phase must be a non-empty string");
}
// Match the submitted contract even when callers reuse options while the child runs.
const structured = options.schema !== undefined;
if (options.phase !== undefined) swarmNote("phase", options.phase);
const spawned = await request("agentSpawn", [prompt, options], { queue: true });
const completion = await request("agentWait", [spawned.runId], { queue: true });
if (!completion || completion.status !== "done") {
const runId = completion?.runId ?? spawned.runId ?? "unknown";
const status = completion?.status ?? "failed";
const detail = [completion?.error, completion?.schemaError, completion?.result].find(
(value) => typeof value === "string" && value.trim()
) || "collector returned no result";
throw new SwarmAgentError(runId, status, detail);
}
return structured ? completion.structured : completion.result;
}
function namespaceFunction(namespaceId, path) {
const callablePath = Object.freeze((Array.isArray(path) ? path : []).map((entry) => String(entry)));
return (...args) => request("namespace", [namespaceId, callablePath, args]);
}
function deserializeNamespaceValue(namespaceId, value) {
if (!value || typeof value !== "object") return null;
if (value.kind === "function") {
return namespaceFunction(namespaceId, Array.isArray(value.path) ? value.path.slice() : []);
}
if (value.kind === "array") {
return Object.freeze((Array.isArray(value.items) ? value.items : []).map((item) => deserializeNamespaceValue(namespaceId, item)));
}
if (value.kind === "object") {
const object = Object.create(null);
for (const entry of Array.isArray(value.entries) ? value.entries : []) {
const key = Array.isArray(entry) && typeof entry[0] === "string" ? entry[0] : "";
if (!key) continue;
const projected = deserializeNamespaceValue(namespaceId, entry[1]);
Object.defineProperty(object, key, namespaceId === "mcp" && entry[1]?.kind === "value"
? { get: () => { observeNetworkContent(); return projected; }, enumerable: true }
: { value: projected, enumerable: true });
}
return Object.freeze(object);
}
// Producers normalize these guest-owned values; a second JSON copy can OOM into safe()'s text fallback.
return value.value;
}
function settle(id, ok, payload) {
const entry = pending.get(String(id));
if (!entry) return false;
// Host replies are encoded JSON. Decoding failure must terminate the cell;
// resolving raw transport text would silently change the tool result's type.
const parsed = parseJson(payload);
pending.delete(String(id));
if (ok) {
entry.resolve(parsed);
} else {
const error = new GuestError(typeof parsed === "string" ? parsed : parsed?.message ?? "nested tool failed");
if (entry.stack) Object.defineProperty(error, "stack", { value: entry.stack, writable: true, configurable: true });
if (entry.location) error.location = entry.location;
const code = parsed && typeof parsed === "object" ? parsed.code : undefined;
if (parsed && typeof parsed === "object") {
error.code = code;
error.effectStatus = "unknown";
}
rememberBridgeError(
error,
code === "invalid_input" || code === "input_contract" || code === "store_range" || code === "store_type"
? "invalid_input" : "internal_error",
);
entry.reject(error);
}
return true;
}
function settleHostReplies() {
// Reply data comes only from the host, so guest calls cannot forge settlement or provenance.
for (;;) {
const reply = hostTakeBridgeReply();
if (reply === undefined || reply === null) return;
settle(reply.id, reply.ok === true, reply.json);
}
}
function nodeHandle(descriptor) {
const handle = Object.create(null);
Object.defineProperties(handle, {
id: { value: descriptor.id, enumerable: true },
name: { value: descriptor.name, enumerable: true },
invoke: {
value: (command, params) => request("nodes", ["invoke", descriptor.id, command, params]),
enumerable: true,
},
});
if (typeof descriptor.listDirCommand === "string") {
Object.defineProperty(handle, "listDir", {
value: (path) => request("nodes", ["invoke", descriptor.id, descriptor.listDirCommand, { path }]),
enumerable: true,
});
}
return Object.freeze(handle);
}
const nodes = Object.freeze({
list: () => request("nodes", ["list"]),
get: async (idOrName) => nodeHandle(await request("nodes", ["get", idOrName])),
});
const skills = Object.freeze({
list: (offset = 0) => request("skillsList", [offset]),
search: (query, limit) => request("skillsSearch", limit === undefined ? [query] : [query, limit]),
read: (name) => request("skillsRead", [name]),
});
const results = Object.freeze({
save: (value) => request("resultSave", [value]),
load: (id) => request("resultLoad", [id]),
delete: (id) => request("resultDelete", [id]),
});
// Session operations use the existing result bridge; buffers stay with the host cell.
async function sessionResult(method, key, value) {
if (typeof key !== "string") throw new GuestTypeError("Code Mode store key must be a string.");
try {
const result = await request(method, method === "resultSave"
? [value, "session", key]
: [key, "session"]);
return method === "resultLoad" ? result.value : undefined;
} catch (error) {
if (!(error instanceof GuestError)) throw error;
const Constructor = error.code === "store_range" ? GuestRangeError
: error.code === "store_type" ? GuestTypeError : undefined;
if (!Constructor) throw error;
const typed = new Constructor(error.message);
typed.code = error.code;
typed.stack = error.stack;
const bridgeCode = bridgeFailureCode(error);
if (bridgeCode) rememberBridgeError(typed, bridgeCode);
throw typed;
}
}
if (globalThis.__openclawSwarmEnabled === true) {
Object.defineProperties(globalThis, {
agents: {
value: Object.freeze({ run: runAgent }),
enumerable: true,
},
phase: { value: (title) => swarmNote("phase", title), enumerable: true },
log: { value: (message) => swarmNote("log", message), enumerable: true },
});
}
function normalizeApiPath(value) {
const text = String(value ?? "").trim().replace(/^\/+/, "");
if (!text || text.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
throw new Error("invalid API file path");
}
return text;
}
const apiFileMap = new Map();
for (const file of apiFiles) {
if (!file || typeof file !== "object") continue;
const path = typeof file.path === "string" ? file.path : "";
const content = typeof file.content === "string" ? file.content : "";
if (!path || !content) continue;
apiFileMap.set(path, Object.freeze({
path,
content,
description: typeof file.description === "string" ? file.description : undefined,
bytes: file.bytes,
}));
}
// Native declarations are generated by describe only when read, not injected
// for every tool into every VM. Listing needs only the bounded callable metadata.
const nativeApiFiles = new Map(catalogBindings.map(binding => [
"tools/" + binding.callableName + ".d.ts", binding.callableName,
]));
const api = Object.freeze({
list: async (prefix = "") => {
// list takes a directory prefix, so tolerate a trailing slash (API.list("mcp/"))
// that read's exact-path normalizer would otherwise reject as an empty segment.
const rawPrefix = prefix == null ? "" : String(prefix).trim().replace(/\/+$/, "");
const normalizedPrefix = rawPrefix === "" ? "" : normalizeApiPath(rawPrefix);
const files = [...apiFileMap.values(), ...[...nativeApiFiles.keys()].map(path => ({ path }))]
.filter((file) => !normalizedPrefix || file.path === normalizedPrefix || file.path.startsWith(normalizedPrefix.replace(/\/?$/, "/")))
.map((file) => Object.freeze({
path: file.path,
description: file.description,
bytes: file.bytes,
}));
if (files.some(file => file.path.startsWith("mcp/"))) observeNetworkContent();
return { files };
},
read: async (path) => {
const normalizedPath = normalizeApiPath(path);
const file = apiFileMap.get(normalizedPath);
if (file) {
if (normalizedPath.startsWith("mcp/")) observeNetworkContent();
return file;
}
const callableName = nativeApiFiles.get(normalizedPath);
if (callableName) return request("describe", [callableName, "declaration"]);
throw new Error("Unknown API file: " + normalizedPath);
},
});
const callableHandles = new Map();
const callableMetadata = new WeakMap();
function callableHandle(binding) {
const callableName = typeof binding?.callableName === "string" ? binding.callableName : "";
if (!callableName) return null;
const existing = callableHandles.get(callableName);
if (existing) return existing;
const isMcp = binding.source === "mcp";
const path = isMcp ? Object.freeze(binding.path.slice()) : undefined;
const handle = isMcp
? namespaceFunction(binding.namespaceId, path)
: (input) => request("callValue", [callableName, input]);
const metadata = Object.freeze({
callableName,
toolName: typeof binding.name === "string" ? binding.name : callableName,
label: typeof binding.label === "string" ? binding.label : undefined,
description: typeof binding.description === "string" ? binding.description : "",
source: binding.source,
input: binding.input,
output: binding.output,
...(isMcp ? { apiPath: binding.apiPath } : {}),
...(isMcp && typeof binding.instructions === "string" ? { instructions: binding.instructions } : {}),
...(isMcp && typeof binding.instructionsHint === "string" ? { instructionsHint: binding.instructionsHint } : {}),
});
for (const [key, value] of Object.entries(metadata)) {
Object.defineProperty(handle, key, binding.source !== "openclaw"
? { get: () => { observeNetworkContent(); return value; }, enumerable: true }
: { value, enumerable: true });
}
Object.defineProperties(handle, {
name: { value: callableName },
describe: {
value: isMcp
? () => request("namespace", [binding.namespaceId, [path[0], "$api"], [path.slice(1).join("."), { schema: true }]])
: () => request("describe", [callableName]),
enumerable: true,
},
toJSON: { value: () => {
if (binding.source !== "openclaw") observeNetworkContent();
return metadata;
} },
});
const frozen = Object.freeze(handle);
callableHandles.set(callableName, frozen);
callableMetadata.set(frozen, metadata);
return frozen;
}
// Project nested catalog handles before ordinary JSON conversion drops functions.
function serializeOutputValue(value, seen = new Map(), finalState) {
if (value instanceof GuestPromise) return promiseOutput;
const metadata = callableMetadata.get(value);
if (metadata) {
if (metadata.source !== "openclaw") observeNetworkContent();
return finalState ? serializeOutputValue(metadata, seen, finalState) : metadata;
}
if (finalState) {
if (typeof value === "function") return undefined;
if (typeof value === "bigint") finalState.hasBigInt = true;
}
if (value === null || typeof value !== "object") return value;
if (seen.has(value)) return seen.get(value);
const proto = Object.getPrototypeOf(value);
const isError = value instanceof Error;
if (!finalState && !isError && !Array.isArray(value) && proto !== Object.prototype && proto !== null) return value;
const plain = Array.isArray(value) ? new Array(value.length) : isError ? { name: value.name, message: value.message } : {};
// Project before JSON.stringify can invoke Error.toJSON, and preserve graph
// identity so cyclic custom fields use the ordinary bounded JSON fallback.
seen.set(value, plain);
if (finalState) {
// Final conversion never invokes inherited toJSON hooks. Expanding sparse
// arrays here keeps their allocation inside the guest's memory/time limits.
Object.setPrototypeOf(plain, null);
if (Array.isArray(value)) {
for (let index = 0; index < plain.length; index++) {
plain[index] = serializeOutputValue(value[index], seen, finalState);
}
return plain;
}
if (isError) {
plain.name = serializeOutputValue(plain.name, seen, finalState);
plain.message = serializeOutputValue(plain.message, seen, finalState);
}
}
for (const key of Object.keys(value)) {
if (isError && key === "toJSON") continue;
Object.defineProperty(plain, key, {
value: serializeOutputValue(value[key], seen, finalState), enumerable: true, configurable: true, writable: true,
});
}
return plain;
}
function encodeFinalValue(value) {
const state = { hasBigInt: false };
const plain = serializeOutputValue(value, new Map(), state);
if (typeof plain === "bigint") return stringifyJson("" + plain);
const fallback = Array.isArray(plain) ? '"[object Array]"' : '"[object Object]"';
// Detect BigInts before stringify can invoke a guest BigInt.toJSON hook.
if (state.hasBigInt) return fallback;
try {
return stringifyJson(plain) ?? "null";
} catch (error) {
if (error instanceof GuestTypeError) return fallback;
throw error;
}
}
const catalog = Object.freeze({
search: async (query, options) => {
const matches = await request("search", [query, options]);
return Object.freeze(matches.map((match) => {
const handle = typeof match === "string" ? callableHandles.get(match) : callableHandle(match);
if (!handle) throw new Error("Search result has no callable handle.");
return handle;
}));
},
all: () => Object.freeze(catalogBindings.map(binding => callableHandles.get(binding.callableName))),
});
const namespaceGlobals = Object.create(null);
for (const descriptor of namespaceDescriptors) {
const id = typeof descriptor?.id === "string" ? descriptor.id : "";
const globalName = typeof descriptor?.globalName === "string" ? descriptor.globalName : "";
if (!id || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(globalName)) continue;
const scope = deserializeNamespaceValue(id, descriptor.scope);
Object.defineProperty(namespaceGlobals, globalName, {
value: scope,
enumerable: true,
});
const existingGlobal = Object.getOwnPropertyDescriptor(globalThis, globalName);
if (existingGlobal && existingGlobal.configurable === false) continue;
Object.defineProperty(globalThis, globalName, {
value: scope,
enumerable: true,
configurable: true,
});
}
for (const binding of catalogBindings) {
const handle = callableHandle(binding);
const callableName = typeof binding?.callableName === "string" ? binding.callableName : "";
if (!handle || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(callableName)) continue;
Object.defineProperty(globalThis, callableName, {
value: handle,
enumerable: true,
configurable: true,
});
}
Object.defineProperties(globalThis, {
API: { value: api, enumerable: true },
catalog: { value: catalog, enumerable: true },
nodes: { value: nodes, enumerable: true },
namespaces: { value: Object.freeze(namespaceGlobals), enumerable: true },
skills: { value: skills, enumerable: true },
results: { value: results, enumerable: true },
store: { value: (key, value) => sessionResult(value === undefined ? "resultDelete" : "resultSave", key, value), enumerable: true },
load: { value: (key) => sessionResult("resultLoad", key), enumerable: true },
setTimeout: { value: (callback, delay, ...args) => scheduleTimer(callback, delay, args), enumerable: true },
clearTimeout: { value: cancelTimer, enumerable: true },
console: { value: guestConsole, enumerable: true },
text: { value: (value) => emitOutput({ type: "text", text: asText(value) }), enumerable: true },
json: { value: (value) => emitOutput({ type: "json", value: safe(value, true) }), enumerable: true },
yield_control: { value: (reason) => request("yield", [reason]), enumerable: true },
__openclawSettleBridge: { value: settleHostReplies },
__openclawBridgeFailureCode: { value: bridgeFailureCode },
__openclawEncodeError: { value: encodeError },
__openclawDrainQueuedRequests: { value: drainQueuedRequests },
__openclawAdmissionError: { value: () => admissionError },
// Final getters must run before the worker drains output and settles host work.
__openclawRunCell: { value: async (run) => encodeFinalValue(await run()) },
__openclawTakeOutputJson: { value: () => encodeFinalValue(output.splice(0)) },
__openclawTrackRejection: {
value: (promise, _reason, handled) => {
if (handled) deleteUnhandledRejection(promise);
else addUnhandledRejection(promise);
},
},
__openclawUnhandledRejection: { value: () => nextUnhandledRejection(unhandledRejectionValues()).value },
});
})();
`;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)??``}const ct=/* @__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(`.`)),lt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,ut=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u;function normalizeUrlQueryParamName(e){let t=e.replace(lt,``);for(let e=0;e<=8;e+=1){let e;try{e=decodeURIComponent(t).replace(lt,``)}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||ct.has(t.value)||ut.test(t.value)}const dt="[A-Za-z0-9!#$%&'*+.^_`|~-]+",B=String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`,V=String.raw`\\{1,64}t`,H=String.raw`(?:[ \t]+|${V})`,U=String.raw`(?:[ \t]*\r?\n${H}|[ \t]*\\{1,64}r\\{1,64}n${H}|[ \t]*\\{1,64}n${H}|[ \t]*${V}[ \t]*|[ \t]*)`,W=String.raw`(?:[ \t]*\r?\n${H}|[ \t]*\\{1,64}r\\{1,64}n${H}|[ \t]*\\{1,64}n${H}|[ \t]*${V}[ \t]*|[ \t]+)`,ft=String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${V})|[ \t]*\\{1,64}n(?:[ \t]*|${V})|[ \t]*${V}[ \t]*)`,G=String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`,K=String.raw`(?:\\{1,64}["']|["']|)`;String.raw`${G}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${K}[ \t]*[:=]${U}${K}([^\s\\"',;]+)`;const pt=new RegExp(String.raw`${G}(?:Proxy-)?Authorization${K}[ \t]*[:=]${U}${K}(${dt})${W}`,`giu`),mt=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u,ht=/^[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=mt.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?ht:mt).exec(e.slice(t));return o?t+o[0].length:null}function findStructuredAuthParamRanges(e){let t=[];for(let n of e.matchAll(pt)){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(``)}const gt={},_t=/[\p{ASCII}]+|[^\p{ASCII}]/gu,vt=[[[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]]],yt=RegExp(`[${vt.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),bt=(()=>{let e=Math.max(...vt.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,n]of vt.entries())for(let[r,i]of n)t.fill(e+1,r,i+1);return t})();function estimateStringChars(e){return estimateStringCharsWithMinimumRawWeight(e)}function estimateStringCharsWithMinimumRawWeight(e,t=gt){let n=Math.max(1,t.minimumRawWeight??1);if(n!==1&&n!==2){let t=0;for(let r of e.matchAll(_t)){let e=r[0],i=Math.ceil(e.length*n);t+=e.charCodeAt(0)<=127?i:Math.max(estimateStringChars(e),i)}return t}let r=e.search(yt);if(r<0)return e.length*n;let i=0,a=0,o=0,s=0,c=0;for(let t=r;t<e.length;t+=1){let n=e.charCodeAt(t);if(!(n<128)){if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);r>=56320&&r<=57343&&(n=65536+(n-55296)*1024+r-56320,t+=1)}switch(bt[n]){case 1:i+=1;break;case 2:a+=1;break;case 3:o+=1;break;case 4:s+=1;break;case 5:c+=1}}}return e.length*n+i*(4-n)+a*(12-n)+o*(8-n)+s*(12-2*n)+c*(16-2*n)}function expectDefined(e,t){if(e==null)throw Error(`expected `+t+` to be defined`);return e}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 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 xt=/* @__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=xt.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 xt.set(r,a),pruneMapToMaxSize(xt,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}}function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.prototype.toString.call(e)===`[object Object]`}const St=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]);function isBlockedObjectKey(e){return St.has(e)}function getSealedRuntimeSecureTempRoot(){}let Ct;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 Ct=t,t}function loadJson5Parser(){if(Ct)return Ct;if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`sealed JSON5 runtime was not registered before use`);return setJson5Runtime(t(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 wt=/^\$\{([A-Z][A-Z0-9_]{0,127})\}$/,Tt=/^\$([A-Z][A-Z0-9_]{0,127})$/;function parseEnvTemplateSecretRef(e,t=`default`){if(typeof e!=`string`)return null;let n=e.trim(),r=wt.exec(n)??Tt.exec(n);return r?{source:`env`,provider:t.trim()||`default`,id:expectDefined(r[1],`types.secrets regex capture 1`)}:null}const Et=/^[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);!Et.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}S.snapshot();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 w.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=D.homedir){let n=resolveRawOsHomeDir(e,t);return n?w.resolve(n):void 0}function resolveEffectiveHomeDir(e=process.env,t=D.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?w.resolve(r.replace(/^~(?=$|[\\/])/,()=>i)):n?.preserveUnresolvedTilde?w.resolve(r):void 0}return w.resolve(r)}const Dt=`(?:\\x1b\\]|\\x9d)`,Ot=`(?:\\x1b\\\\|\\x07|\\x9c)`;RegExp(`${Dt}[^\\x07\\x1b\\x9c]*${Ot}`,`y`),RegExp(`${`${Dt}[\\s\\S]*?${Ot}`}|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,`y`),new Intl.Segmenter(void 0,{granularity:`grapheme`});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=D.homedir){let n=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(n)return w.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??D.homedir);return n?e.replace(/^~(?=$|[\\/])/,()=>n):e}function resolveAgainstUserBase(e){let t=getUserPathBaseDirectory().getStore();return t?w.resolve(t,e):w.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??D.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=D.homedir){return e?resolveHomeRelativePath(e,{env:t,homedir:n}):``}const kt=/^[a-z0-9][a-z0-9_-]{0,63}$/i;function isValidProfileName(e){return kt.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 w.join(resolveRequiredHomeDir(t,n),`.openclaw${i}`)}const At=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 w.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=D.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n&&process.platform!==`win32`&&w.isAbsolute(n)){let e=At.peek(n);if(e!==void 0)return e;let t=w.resolve(n);return At.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=D.homedir){let n=e.OPENCLAW_STATE_DIR?.trim();if(n)return resolveUserPath(n,e,t);let r=e.OPENCLAW_CONFIG_PATH?.trim();return r?w.dirname(resolveUserPath(r,e,t)):resolveStateDir(e,t)}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const jt=2147e6,Mt={attempts:3,minDelayMs:300,maxDelayMs:3e4,jitter:0},defaultSleep=async e=>{let t=e;do{let e=Math.min(t,jt);await new Promise(t=>{setTimeout(t,e)}),t-=e}while(t>0)};function clampNumber(e,t,n,r){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(Math.max(e,n??-1/0),r??1/0)}function resolveRetryDelayMs(e){return Math.min(Math.max(Math.round(e===1/0?jt:Number.isFinite(e)?e:0),0),jt)}function resolveRetryConfig(e=Mt,t){let n=Math.max(1,Math.round(clampNumber(t?.attempts,e.attempts))),r=resolveRetryDelayMs(clampNumber(t?.minDelayMs,e.minDelayMs,0)),i=Math.max(r,resolveRetryDelayMs(clampNumber(t?.maxDelayMs,e.maxDelayMs,0))),a=t?.jitter,o=e.jitter;return{attempts:n,minDelayMs:r,maxDelayMs:i,jitter:a===`full`?a:typeof a==`number`&&Number.isFinite(a)?Math.min(Math.max(a,0),1):o}}function applyJitter(e,t,n,r){if(t===`full`)return n===`symmetric`?Math.max(0,Math.round(e*(.5+r()*.5))):Math.max(0,Math.ceil(e*(1+r())));if(t<=0)return n===`positive`?Math.ceil(e):e;let i=r(),a=e*(1+(n===`positive`?i*t:(i*2-1)*t));return Math.max(0,n===`positive`?Math.ceil(a):Math.round(a))}function toRetryError(e,t=`Non-Error thrown`){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 createRetryRunner(e={}){let t=e.sleep??defaultSleep,n=e.random??Math.random,r=e.createFailure??(e=>toRetryError(e.at(-1)??/* @__PURE__ */ Error(`Retry failed`)));return async function(i,a=3,o=300){let s=[],c=typeof a==`number`,l=typeof a==`number`?{attempts:a}:a,u=resolveRetryConfig(Mt,l),d=u.attempts,f=u.minDelayMs,p=u.maxDelayMs>0?u.maxDelayMs:1/0,m=l.retryAfterMaxDelayMs===void 0?p:Math.max(f,resolveRetryDelayMs(clampNumber(l.retryAfterMaxDelayMs,p,0))),h=l.random??n,g=l.sleep??t,_=l.shouldRetry??(()=>!0);for(let n=1;n<=d;n+=1)try{return await i()}catch(r){if(s.push(r),n>=d||e.shouldRetry?.(r)===!1||!_(r,n))break;if(c){await t(resolveRetryDelayMs(o*2**(n-1)));continue}let i={attempt:n,maxAttempts:d,err:r,label:l.label},a=l.retryAfterMs?.(r),v=typeof a==`number`&&Number.isFinite(a),y=typeof l.delayMs==`function`?l.delayMs(i):l.delayMs,b=y===void 0?void 0:resolveRetryDelayMs(y),x=v?Math.max(a,f):b===void 0?f*2**(n-1):Math.max(b,f),S=v?m:p,C=Math.min(x,S),w=v&&(a??0)<=S,ee=u.jitter===`full`&&!v||w;C=applyJitter(C,u.jitter,ee?`positive`:`symmetric`,h),C=Math.min(Math.max(C,f),S),await l.onRetry?.({...i,delayMs:C}),C>0&&await g(C)}throw r(s)}}createRetryRunner(),String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`,String.raw`[\s"'\x60)\]}>]`,String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`,resolveConfigDir();const Nt=`$include`,Pt=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([w.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[Nt],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:Nt);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>=Pt)throw new ConfigIncludeError(`Include path exceeds maximum length (${Pt} characters)`,e);let n=w.dirname(t.basePath),r=w.isAbsolute(e)?e:w.resolve(n,e),i=w.normalize(this.resolver.mapPath?.(r)??r);if(i.length>=Pt)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${Pt} 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=T.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(oe(this.boundary.configRoot[t],e))return this.boundary.configRoot;for(let n of this.boundary.allowedRoots)if(oe(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 T.realpathSync(e)}catch{return e}}function createConfigIncludeBoundary(e,t=[]){let n=w.normalize(w.dirname(e));return{configRoot:{rootDir:n,rootRealDir:w.normalize(safeRealpath(n))},allowedRoots:t.filter(e=>typeof e==`string`&&e.length>0&&w.isAbsolute(e)).map(e=>{let t=w.normalize(e);return{rootDir:t,rootRealDir:w.normalize(safeRealpath(t))}})}}function readConfigIncludeFileWithGuards(e){let t=e.ioFs??T,n=e.maxBytes??2097152;if(!le(t)){let n=t.readFileSync(e.resolvedPath,`utf-8`);try{e.onResolvedPath?.(w.normalize(t.realpathSync(e.resolvedPath)))}catch{}return n}let r=ue({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?.(w.normalize(r.path)),n}finally{t.closeSync(r.fd)}}const Ft={readFile:e=>T.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback};function resolveConfigIncludes(e,t,n=Ft,r={}){return new IncludeProcessor(t,n,createConfigIncludeBoundary(t,r.allowedRoots??[])).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=Ft,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,D.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(w.delimiter)){let n=t.trim();if(!n)continue;let a=w.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):w.join(t??resolveStateDir(e,n),`openclaw.json`)}resolveConfigPathCandidate();let It;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(e){if(!isRecord(e))return;let t={};if(typeof e.consoleStyle==`string`)try{let n=resolveConfigEnvVars({consoleStyle:e.consoleStyle});isRecord(n)&&(n.consoleStyle===`pretty`||n.consoleStyle===`compact`||n.consoleStyle===`json`)&&(t.consoleStyle=n.consoleStyle)}catch{}if(Array.isArray(e.redactPatterns))try{let n=resolveConfigEnvVars({redactPatterns:e.redactPatterns});isRecord(n)&&Array.isArray(n.redactPatterns)&&n.redactPatterns.every(e=>typeof e==`string`)&&(t.redactPatterns=n.redactPatterns)}catch{}return Object.keys(t).length>0?t:void 0}function readLoggingConfig(){try{if(N.appliedConfig!==`unowned`)return N.appliedConfig;let e=resolveLoggingConfigSelector();if(It?.selector===e)return It.logging;let t=resolveConfigPath();if(!T.existsSync(t)){It={selector:e,logging:void 0};return}let n=parseJsonWithJson5Fallback(T.readFileSync(t,`utf8`)),r=resolveIncludeRoots(),i;try{i=resolveConfigIncludesForTopLevelKey(n,t,`logging`,void 0,{allowedRoots:r})}catch{let e=isRecord(n)?n.logging:void 0;if(e===void 0)return;try{i=resolveConfigIncludes({logging:e},t,void 0,{allowedRoots:r})}catch{return resolvePartialDiagnosticLoggingConfig(e)}}let a;try{a=resolveConfigEnvVars(i)}catch{return resolvePartialDiagnosticLoggingConfig(isRecord(i)?i.logging:void 0)}let o=isRecord(a)?a.logging:void 0,s=isRecord(o)?o:void 0;return It={selector:e,logging:s},s}catch{return}}const Lt=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+=Lt){let a=e.slice(i,i+Lt),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 Rt=/"(?:[^"\\]|\\.)*"|-?\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(Rt)){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 zt=/^\{(\d+),\}/,Bt=/^\{(?:\d+(?:,\d*)?|,\d+)\}/,Vt=/[0-9A-Fa-f]/,Ht=/* @__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||!Vt.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(Ht.has(n))return t+2;if(n===`x`)return Vt.test(e[t+2]??``)&&Vt.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&&Vt.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=!Ht.has(e[a+1]);else if(o===`[`){if(s=classAtomEnd(e,a),s<0)return e}else if(o===`{`){let t=zt.exec(e.slice(a)),o=t&&r>=0?t:Bt.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 Ut=/* @__PURE__ */ new WeakMap;function setRedactPatternPrefilter(e,t){if(Ut.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;Ut.set(e,o=>e.source!==n||e.exec!==r||e instanceof RegExp&&(e.flags!==i||e[Symbol.replace]!==a)||t(o))}const Wt=/* @__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=Wt.get(e);o||(o=new RegExp(e.source,`${e.flags.replace(`d`,``).replace(`g`,``)}dg`),Wt.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 Gt=/* @__PURE__ */ new WeakMap;function visitRedactMatches(e,t,n){if(Ut.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:Gt.get(t);r||(r=new RegExp(t.source,`${t.flags}g`),Gt.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 Ut.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:v,end:y}=i,b=i.redact({start:m,end:_,value:h.slice(Math.max(v,n.currentStart+a),Math.min(y,n.currentEnd-a))});if(!b)continue;let x=`***`;if(o)try{x=r?b.replacement:JSON.parse(`"${b.replacement}"`)}catch{}add(n,{...b,replacement:x})}}});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 Kt=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 qt={source:Kt,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:Kt,exec(t){let n=createState();return e&&(n.open={start:-1,end:-1}),matchPem(t,n,!0)}}}}},Jt=String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`,q=String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`,Yt=String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`,J=String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`,Xt=String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${J}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`,Zt=String.raw`${Xt}|app[-_]?secret|credential|${q}`,Qt=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|${q}`,Y=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|${q}`,$t=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|${q}`,en=String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`,tn=String.raw`password|passphrase|pass|passwd`,nn=String.raw`${J}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${q}`,rn=String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`,an=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Jt})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`,on=String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Jt})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`,sn=String.raw`(^|[\s,;({\["])(?:${Qt})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`,cn=String.raw`(^|[\s,;({\["])(?:${Qt})=(["'\x60]?[^\s&#"'\x60<>]+)`,ln=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|${q}`,un=String.raw`/(^|[\s,{])(?:(?:${ln})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${tn})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Y})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`,dn=String.raw`/(^|[\s,{])(?:(?:${$t})\s*:\s*|(?:${Y})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`,fn=String.raw`/(^|[\s,{])(?:${en})=([^\s#"'\x60<>]+)/g`,pn=String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${tn})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,mn=String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${Y})\s*[:=]\s*([^\s#"'\x60<>]+)/g`,hn=String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${J}|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*"([^"]+)"`,gn=String.raw`"(?:${Yt})"\s*:\s*"([^"]+)"`,_n=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`,vn=String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`,yn=String.raw`(^|[^A-Za-z0-9])`,base64SafeToken=e=>String.raw`${yn}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`,X=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 bn=/(?=[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 bn.test(e);t=n+40}return!1}const xn=/\s/,Sn=/[A-Za-z0-9+.-]/,Cn=/[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||xn.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);bn.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))))),Sn.test(c))r===-1&&(r=s);else{if((!i||s>=i.end&&!i.queryOrFragment)&&c===`:`&&e.startsWith(`//`,s+1)&&r!==-1&&Cn.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 wn=Object.freeze({source:`aws-secret-access-key`,exec:matchAwsSecretAccessKeys,couldMatch:couldMatchAwsSecretAccessKey}),Tn=new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${$t})\s*:\s*`,`gi`),En=/[^\s#"'\x60<>]+/y,Dn=/[A-Za-z0-9]/,On=/[ \t\r\n]/;function*matchBarePassAssignments(e){if(!/pass\s*:/.test(e))return;let t=[...e.matchAll(Tn)];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!==` `||!Dn.test(e[i-2]??``)){r=!0;let o=i+a[0].length;if(!s){En.lastIndex=o;let t=En.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===`:`&&!On.test(e[i+1]??` `))&&(r=!0)}}const kn=Object.freeze({source:`bare-pass-assignment`,exec:matchBarePassAssignments}),An=String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`,jn=String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`,Mn=`x-goog-api-key|api-key|apikey|x-api-token|x-access-token`,Nn=`X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token`,Pn=String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`,Fn=String.raw`${Pn}(?:${Mn})${K}[ \t]*:${U}${K}([^\s\\"',;]+)`,In=String.raw`${Pn}(?:${Mn})${K}[ \t]*=${U}${K}([^\s\\"',;]+)`,Ln=String.raw`${Pn}(?:${Nn})\s*:\s*([^\s"',;]+)`,Rn=String.raw`${Pn}(?:${Nn})\s*=\s*([^\s"',;]+)`,zn=[String.raw`${G}Proxy-Authorization${K}[ \t]*[:=]${U}${K}${dt}${W}(${B})`,String.raw`${G}Proxy-Authorization${K}[ \t]*[:=]${U}${K}(${B})[ \t]*(?=${K}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,String.raw`${G}Authorization${K}[ \t]*[:=]${U}${K}(?!(?:Bearer|Basic|Bot)(?=${W}))${dt}${W}(${B})`,String.raw`${G}Authorization${K}[ \t]*[:=]${U}${K}(?!(?:Bearer|Basic|Bot)(?=${W}))(${B})[ \t]*(?=${K}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,Fn,In],Bn=String.raw`Authorization${K}[ \t]*[:=]${ft}${K}Bearer${W}(${B})`,Vn=String.raw`Authorization${K}[ \t]*[:=]${ft}${K}Basic${W}(${B})`,Hn=String.raw`Authorization${K}[ \t]*[:=]${ft}${K}Bot${W}(${B})`,Un=String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`,Wn=[an,on,hn,gn,_n,vn,String.raw`--(?:${nn})=([^\s"']+)`,String.raw`--(?:${nn})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,Bn,Vn,Hn,...zn,Ln,Rn,Un,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_.-]*=)`,sn,cn,un,dn,kn,fn,pn,mn,Kt,String.raw`(^|[\s,{])["']?(?:${J})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`],Gn=[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`${X}(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`${X}(fw-[A-Za-z0-9]{30,})`,String.raw`${X}(fw_[A-Za-z0-9]{30,})`,String.raw`${X}(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,})`,An,jn],Kn=[...Wn,...Gn,wn];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(`^(?:${Mn}|${Nn})$`,`i`),n=/* @__PURE__ */ new Set([In,Rn]),r=/* @__PURE__ */ new Set([an,on,sn,cn]),i=new RegExp(String.raw`[:=](?<=(?:${Y})\s*[:=])`),a=new RegExp(String.raw`[:=](?<=(?:${Y})\s*[:=])\s*["'\x60]`),o=new RegExp(String.raw`[:=](?<=\.(?:${Y})\s*[:=])`),s=new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${Qt})=)`,`i`);return{bodySecretKeys:e,credentialHeaderField:t,formAware:n,shellReferencePreserving:r,prefilters:new Map([[an,e=>/KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],[on,e=>e.includes(`\\`)],[sn,e=>/[=]["'`]/.test(e)],[cn,e=>s.test(e)],[un,e=>/["'`]/.test(e)&&a.test(e)],[dn,e=>(e.includes(`:`)||e.includes(`=`))&&i.test(e)],[fn,e=>e.includes(`=`)],[pn,e=>/[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],[mn,e=>o.test(e)],[_n,e=>/["']/.test(e)],[vn,e=>/["']/.test(e)],...zn.slice(0,4).map(e=>[e,e=>/authorization/i.test(e)]),[Fn,e=>/api-key|apikey|api-token|access-token/i.test(e)],[In,e=>/api-key|apikey|api-token|access-token/i.test(e)],[hn,e=>e.includes(`"`)],[gn,e=>e.includes(`"`)],[Ln,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],[Rn,e=>/x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]]),chunkUnsafe:/* @__PURE__ */ new Set([An,jn,Bn,Vn,Hn,Un,...zn,...Gn.filter(e=>e.startsWith(yn))])}}const qn=/* @__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 qn.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 Jn=/* @__PURE__ */ new Map;function*scanPrefixOccurrences(e,t){let n=Jn.get(t);n||(n=[],Jn.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 Yn=fixedTailTokenEnd(4,32,isHexChar);function dapiTokenEnd(e,t){let n=Yn(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 Xn=makeBase64SafeTokenMatcher(`vendor-token gAAAA (linear)`,`gAAAA`,()=>(e,t)=>{let n=runEndOf(e,t+5,GAAAA_VALUE_CHAR);return n-(t+5)>=20?n:null}),Zn=makeBase64SafeTokenMatcher(`vendor-token ATBB (linear)`,`ATBB`,()=>(e,t)=>{let n=runEndOf(e,t+4,ATBB_VALUE_CHAR);return n-(t+4)>=16?n:null}),Qn=makeBase64SafeTokenMatcher(`vendor-token AKIA (linear)`,`AKIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),$n=makeBase64SafeTokenMatcher(`vendor-token ASIA (linear)`,`ASIA`,()=>fixedTailTokenEnd(4,16,isAlnumChar)),er=makeBase64SafeTokenMatcher(`vendor-token dapi (linear)`,`dapi`,()=>dapiTokenEnd),tr=makeAtEqualsTokenMatcher(`vendor-token ATCTT3xFfG (linear)`,`ATCTT3xFfG`),nr=makeAtEqualsTokenMatcher(`vendor-token ATATT (linear)`,`ATATT`),rr=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===`-`,ir=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}}}),ar=String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,or=String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,sr=/* @__PURE__ */ new Set([`http`,`https`,`ws`,`wss`,`ftp`]),cr=/* @__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 lr=makeUserInfoMatcher(`url-userinfo (linear)`,sr,e=>e===`/`||e===`@`||isJsWhitespaceChar(e)),ur=makeUserInfoMatcher(`connection-string (linear)`,cr,e=>e===`@`||isJsWhitespaceChar(e)),dr=String.raw`(^|[\s,;])(?:${Zt})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,fr=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 pr=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&&fr.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)}}}),mr=String.raw`(^|[\s,;({\["])(?:${Qt})=(["'\x60])`,hr=String.raw`(^|[\s,{])(?:(?:${ln})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${tn})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${Y})\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 gr=makeQuotedAssignmentMatcher(`standalone-quoted-assignment (linear)`,mr,`gi`),_r=makeQuotedAssignmentMatcher(`config-quoted-assignment (linear)`,hr,`g`),vr=/* @__PURE__ */ new Map([[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),Xn],[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),tr],[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),nr],[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),Zn],[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),er],[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),Qn],[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),$n],[rr,ir],[ar,lr],[or,ur],[dr,pr],[sn,gr],[un,_r]]),yr=/(["'`,;)}\]]+)$/u,br=/^["'`,;)}\]]*$/u,xr=/* @__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=+!!xr.has(t);if(n){let n=e.lastIndexOf(t);if(n>0){let t=e.slice(n+1);if(br.test(t))return{maskable:e.slice(1,n),suffix:t,maskStart:0,maskEnd:n+1}}}let r=e.slice(n),i=r.match(yr)?.[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=x(`openclaw.redaction`);function startRedactionMeasurement(e){if(!Sr.hasSubscribers)return;let t=C.now(),n=process.threadCpuUsage();return(r,i,a)=>{let o=C.now()-t,s=process.threadCpuUsage(n);Sr.publish({operation:e,outcome:r,pid:process.pid,threadId:y,isMainThread:h,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,wr=/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,Tr=/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,Er=RegExp(`[${rn}+%]`,`u`),Dr=/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(`_`))&&wr.test(e)||Tr.test(e)||e.includes(`://`)&&e.includes(`@`)||e.includes(`=`)&&Er.test(e)||wn.couldMatch(e)}function couldMatchDefaultFullContextPatterns(e){return couldMatchDefaultRedactPatterns(e)||Dr.test(e)}function couldMatchVendorRedactPatterns(e){return(e.includes(`-`)||e.includes(`_`))&&wr.test(e)||Tr.test(e)||Dr.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 Z=resolveGlobalSingleton(Symbol.for(`openclaw.secretRedactionRegistry`),()=>({revision:0,registeredValues:/* @__PURE__ */ new Map,registeredValueRedactor:void 0}));function invalidateMatcher(){Z.revision+=1,Z.registeredValueRedactor=void 0}function redactRegisteredSecretValues(e,t){return!e||Z.registeredValues.size===0?e:(Z.registeredValueRedactor??=createSecretValueRedactor([...Z.registeredValues.keys()]),Z.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(){Z.registeredValues.clear(),invalidateMatcher()}process.env.VITEST&&(globalThis[Symbol.for(`openclaw.secretRedactionRegistryTestApi`)]={resetSecretRedactionRegistryForTest});const Or=/* @__PURE__ */ new Set([`ERR_TLS_CERT_ALTNAME_INVALID`,`HOSTNAME_MISMATCH`]),kr=/* @__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(`.`)),Ar=[/hostname\/ip does not match certificate(?:'s)? altnames/i,/hostname mismatch/i,/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i],jr=[/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 Or.has(e)?`hostname_mismatch`:kr.has(e)?`certificate_invalid`:null}function classifyMessage(e){return Ar.some(t=>t.test(e))?`hostname_mismatch`:jr.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 Mr=/(?:\s*:\s*|\s+)/;RegExp(`^(?:http\\s*)?(\\d{3})${Mr.source}(.+)$`,`i`),RegExp(`^(?:http\\s*)?(\\d{3})(?:${Mr.source}([\\s\\S]+))?$`,`i`);const Nr="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`.",Pr=[{code:/\beconnrefused\b/i,phrases:/connection refused|actively refused/i,message:Nr},{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:Nr}];function isKnownTransportErrorCode(e){return Pr.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 Fr=`tools`,Q=createBackendRedactPatterns(),Ir=/* @__PURE__ */ new WeakSet,Lr=/* @__PURE__ */ new WeakSet,Rr=/* @__PURE__ */ new WeakMap,zr=new Set(Gn),Br=/* @__PURE__ */ new WeakSet,Vr=new Set(Kn.filter(e=>typeof e==`string`)),Hr=/* @__PURE__ */ new WeakSet;let Ur,Wr=!1;const Gr=new RegExp(String.raw`[${rn}+]`,`gu`),Kr=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,qr=/%[0-9A-Fa-f]{2}/u,Jr=String.raw`[${rn}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${rn}+])*`,Yr=`[^&\\s<>]*`,Xr=String.raw`${Jr}=${Yr}`,Zr=new RegExp(String.raw`^${Xr}(?:&${Xr})+$`,`u`),Qr=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`])(${Xr}(?:&${Xr})+)`,`gu`),$r=RegExp(String.raw`(^|[\s:({\[,="'`+"`"+String.raw`&])(${Jr})=(${Yr})`,`gu`),ei=new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${Jr})=(${Yr})(["'\x60]?)`,`giu`),ti=new RegExp(String.raw`([?&])(${Jr})=(${`[^&#\\s<>]*`})`,`gu`),ni=/(\r\n|\r|\n)/u,ri=/^(?:\r\n|\r|\n)$/u,ii=new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${J}|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|${q}|${Yt})$`,`i`),ai=/^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u,oi=/^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i,si=/\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g,ci=/* @__PURE__ */ new Set([`case`,`claw`,`demo`,`file`,`main`,`name`,`open`,`path`,`slug`,`test`]),li=new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${Jt})$`,`i`);function parsePattern(e){if(e===Kt)return qt;if(typeof e!=`string`&&!(e instanceof RegExp))return typeof e==`object`&&e&&typeof e.exec==`function`?e:null;let t=typeof e==`string`?vr.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=Vr.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`&&Q.shellReferencePreserving.has(e)&&Ir.add(t),t&&typeof e==`string`&&Q.formAware.has(e)&&Hr.add(t),t&&typeof e==`string`&&(e.startsWith(X)||Q.chunkUnsafe.has(e))&&Br.add(t),t&&typeof e==`string`){if(Vr.has(e)&&Lr.add(t),n&&zr.has(e)&&!Rr.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;Rr.set(t,()=>t.source===e&&t.exec===n&&(!(t instanceof RegExp)||t.flags===r&&t[Symbol.replace]===i))}let r=Q.prefilters.get(e);n&&r&&setRedactPatternPrefilter(t,r)}return t}function resolvePatterns(e){if(usesBuiltInRedactPatterns(e))return Ur??=Kn.map(parsePattern).filter(e=>!!e),Ur;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(!Wr){Wr=!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(wn),[...t]}function usesBuiltInRedactPatterns(e){return e===void 0||e===Kn||Array.isArray(e)&&e.length===0}function normalizeSensitiveKeyName(e){let t=e.replace(Kr,``);try{return decodeURIComponent(t).replace(Kr,``).toLowerCase().replaceAll(`-`,`_`)}catch{return t.toLowerCase().replaceAll(`-`,`_`)}}function isSensitiveBodyKey(e){return isSensitiveUrlQueryParamName(e)||Q.bodySecretKeys.has(normalizeSensitiveKeyName(e))}function hasEncodedOrInvisibleFormKey(e){return qr.test(e)||e.replace(Gr,``)!==e}function visitSensitiveAssignments(e,t,n){if(!e||t===`url`&&!e.includes(`?`)||t===`encoded`&&!e.includes(`%`)&&e.replace(Gr,``)===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`?ti:t===`encoded`?$r:ei,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(Zr.test(n))return redactAssignmentValues(n,`form`,t);let r=[],i=n.replace(Qr,(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(ni.test(e)){let n=0;return e.split(ni).map(e=>{let r=ri.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=Hr.has(a)?splitFormAwareCredentialValue(n):{secret:n,suffix:``};if(splitSecretValueForMask(r.secret).maskable===`***`)return;let o=Ir.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)Rr.get(a)?.()&&(o!==r&&(o=r,s=couldMatchVendorRedactPatterns(r)),!s)?a instanceof RegExp&&(a.lastIndex=0):r=a instanceof RegExp&&!n?.fullContext&&!Lr.has(a)&&!Br.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=>!ci.has(e.toLowerCase()))}function redactAppSpecificPasswords(e){return e.includes(`-`)?e.replace(si,(e,t)=>looksLikeAppSpecificPassword(t)?maskToken(t):e):e}function resolveConfigRedaction(){let e=readLoggingConfig();return{mode:Fr,patterns:e?.redactPatterns}}function resolveRedactOptions(e){let t=e??resolveConfigRedaction(),n=t.mode===`off`?`off`:Fr;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,...Kn]:t}}function redactToolPayloadText(e){return redactToolPayloadTextWithConfig(e,readLoggingConfig())}function redactToolPayloadTextWithConfig(e,t){return redactSensitiveText(e,resolveToolPayloadRedaction(t))}function isSensitiveFieldKey(e){return ii.test(e)||li.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||oi.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`&&ai.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`:Q.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||oi.test(n))for(let e of t.matchAll(si))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 ui=[{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)}}],di=/* @__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:ui},{patterns:n.patterns,...n.patterns===Ur?{couldMatch:c}:{}}]],prepareRedactionCapture,t?getLegacyFieldRecordEdits:()=>[],e=>getFieldRecordEdits(e,n.mode),e=>getTextRecordEdits(e,n.mode,t!==void 0),(e,t)=>e.path.length===1&&di.has(e.key)||n.patterns===Ur&&!c(t),t?.message));return r=`ok`,l}finally{n?.(r,i)}}const fi=/* @__PURE__ */ new WeakSet;var ToolInputError=class extends Error{constructor(e){super(e),this.status=400,this.name=`ToolInputError`,fi.add(this)}},CodeModeHeadlessTimeoutError=class extends Error{constructor(e=`code mode headless wall-clock timeout exceeded`){super(e),this.name=`CodeModeHeadlessTimeoutError`}};function jsonUtf8Bytes(e){try{return Buffer.byteLength(JSON.stringify(e),`utf8`)}catch{return Buffer.byteLength(String(e),`utf8`)}}function jsonUtf8BytesOrInfinity(e){try{let t=JSON.stringify(e);return typeof t==`string`?Buffer.byteLength(t,`utf8`):1/0}catch{return 1/0}}function jsonStringByteLengthUpToLimit(e,t){return e.length+2>t||e.length*3+2>t&&Buffer.byteLength(e,`utf8`)+2>t?t+1:jsonUtf8BytesOrInfinity(e)}function boundedJsonUtf8Bytes(e,t){let n=0,r,add=e=>{if(n+=e,n>t)throw Error(`json_byte_limit_exceeded`)},visit=(e,i)=>{if(e===null){add(4);return}switch(typeof e){case`string`:add(jsonStringByteLengthUpToLimit(e,t-n));return;case`number`:add(jsonUtf8BytesOrInfinity(Number.isFinite(e)?e:null));return;case`boolean`:add(e?4:5);return;case`undefined`:case`function`:case`symbol`:i&&add(4);return;case`bigint`:throw Error(`json_byte_length_unsupported`)}let a=e;if((r??=/* @__PURE__ */ new WeakSet).has(a))throw Error(`json_byte_length_circular`);if(typeof a.toJSON==`function`&&!(a instanceof Date))throw Error(`json_byte_length_custom_to_json`);r.add(a);try{if(a instanceof Date){visit(a.toJSON(),i);return}let e=Array.isArray(a);if(add(1),e)for(let e=0;e<a.length;e+=1)e>0&&add(1),visit(a[e],!0);else{let e=!1,r=a;for(let i in r){if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=r[i];a!==void 0&&typeof a!=`function`&&typeof a!=`symbol`&&(e&&add(1),e=!0,add(jsonStringByteLengthUpToLimit(i,t-n)),add(1),visit(a,!1))}}add(1)}finally{r.delete(a)}};try{return visit(e,!1),{bytes:n,complete:!0}}catch{return{bytes:Math.max(n,t+1),complete:!1}}}function isContinuationByte(e){return e!==void 0&&(e&192)==128}function truncateEncodedPrefix(e,t){let n=t;for(;n>0&&isContinuationByte(e[n]);)--n;return e.subarray(0,n).toString(`utf8`)}function truncateUtf8Prefix(e,t){return t<=0?``:e.length<=t&&de.byteLength(e)<=t?e:truncateEncodedPrefix(de.from(e.slice(0,t)),t)}function createJsonPrefixFitter(e,t,n){let r=Buffer.byteLength(e,`utf8`),i,a,o,s,c=0,l=0,u=0,d=[],f=256;return p=>{if(p<=0)return{text:``,bytes:0,jsonBytes:2,budget:{chars:2,contextChars:4}};if(r<=p&&(o??=Buffer.byteLength(a??=JSON.stringify(e),`utf8`))+n(r)<=p)return{text:e,bytes:r,jsonBytes:o,get budget(){return s??={chars:estimateStringCharsWithMinimumRawWeight(a),contextChars:estimateStringCharsWithMinimumRawWeight(a,{minimumRawWeight:2})}}};i??=Buffer.from(e.slice(0,Math.ceil(Math.min(r,t))));let m=0,h=2,g=0,_=d.length-1;for(;g<=_;){let e=g+_>>>1,t=d[e];t.end<=p&&t.jsonBytes+n(t.end)<=p?(m=t.end,h=t.jsonBytes,g=e+1):_=e-1}for(;m<i.byteLength;){let e=i[m],t=e<128?1:e<224?2:e<240?3:4,a=m+t;if(a>=r||a>p)break;let o=h+(e===34||e===92||e===8||e===9||e===10||e===12||e===13?2:e<32?6:t);if(o+n(a)>p)break;m=a,h=o,m>=f&&(d.push({end:m,jsonBytes:h}),f=m+256)}let v=i,y,b;return{get text(){return y??=v.toString(`utf8`,0,m)},bytes:m,jsonBytes:h,get budget(){if(!b){let e=Math.min(c,m),t=Math.max(c,m),n=v.toString(`utf8`,e,t),r=m>=c?1:-1;l+=r*(estimateStringCharsWithMinimumRawWeight(n)-(t-e)),u+=r*(estimateStringCharsWithMinimumRawWeight(n,{minimumRawWeight:2})-2*(t-e)),c=m,b={chars:h+l,contextChars:2*h+u}}return b}}}}resolveGlobalSingleton(Symbol.for(`openclaw.fullToolResultDelivery`),()=>new AsyncContext(Symbol(`fullToolResultDelivery`))),new RegExp([...[`<|im_start|>`,`<|im_end|>`,`<|endoftext|>`,`<|begin_of_text|>`,`<|end_of_text|>`,`<|start_header_id|>`,`<|end_header_id|>`,`<|eot_id|>`,`<|python_tag|>`,`<|eom_id|>`,`[INST]`,`[/INST]`,`<<SYS>>`,`<</SYS>>`,`<s>`,`</s>`,`<|channel|>`,`<|message|>`,`<|return|>`,`<|call|>`,`<start_of_turn>`,`<end_of_turn>`].map(escapeRegExp),`<\\|reserved_special_token_\\d+\\|>`].join(`|`),`g`);const pi={65308:`<`,65310:`>`,9001:`<`,9002:`>`,12296:`<`,12297:`>`,8249:`<`,8250:`>`,10216:`<`,10217:`>`,65124:`<`,65125:`>`,171:`<`,187:`>`,12298:`<`,12299:`>`,10218:`<`,10219:`>`,10220:`<`,10221:`>`,10222:`<`,10223:`>`,10092:`<`,10093:`>`,10094:`<`,10095:`>`,706:`<`,707:`>`,8203:``,8204:``,8205:``,8288:``,65279:``,173:``};for(let e of[65313,65345])for(let t=e;t<e+26;t+=1)pi[t]=String.fromCharCode(t-65248);RegExp(`[${Object.keys(pi).map(e=>String.fromCharCode(Number(e))).join(``)}]`,`u`);function stringifyCodeModeJsonSafe(e){try{return JSON.stringify(e)??`null`}catch{if(e instanceof Error)return JSON.stringify({name:e.name,message:e.message});switch(typeof e){case`number`:return JSON.stringify(e);case`bigint`:case`symbol`:case`function`:return JSON.stringify(String(e));default:return JSON.stringify(Object.prototype.toString.call(e))}}}const mi={count:0,source:{kind:`complete`,json:`[]`}};function retainSource(e,t,n){return t<=n?{kind:`complete`,json:e}:{kind:`prefix`,json:truncateUtf8Prefix(e,n),originalBytes:t}}function captureCodeModeValue(e,t,n=t){let r=stringifyCodeModeJsonSafe(e),i=r.startsWith(`{`)||r.startsWith(`[`)?Math.max(t,n):t;return retainSource(r,Buffer.byteLength(r,`utf8`),i)}function createErrorFitter(e,t){let n=createJsonPrefixFitter(e,t,()=>18);return e=>{let t=n(e);return{text(){return`${t.text} [error truncated]`},budget(){return{chars:t.budget.chars+18,contextChars:t.budget.contextChars+36}},jsonBytes:t.jsonBytes+18}}}function boundCodeModeError(e,t){return jsonUtf8Bytes(e)<=t?e:createErrorFitter(e,t)(t).text()}var CodeModeNodeProgress=class{constructor(e){this.buffer=typeof e==`number`?new SharedArrayBuffer(64+e):e,this.state=new Int32Array(this.buffer,0,2),this.headers=new DataView(this.buffer),this.bytes=Buffer.from(this.buffer,64)}get deadline(){return this.headers.getFloat64(56)}set deadline(e){this.headers.setFloat64(56,e)}get networkContentObserved(){return Atomics.load(this.state,1)===1}observeNetworkContent(){Atomics.store(this.state,1,1)}append(e){let t=Atomics.load(this.state,0),[n,r,i]=this.header(t),a=(n===0?`[`:`,`)+e,o=r+Buffer.byteLength(a),s=r===i?this.bytes.write(a,i):0,c=8+(1-t)*24;return this.headers.setFloat64(c,n+1),this.headers.setFloat64(c+8,o),this.headers.setFloat64(c+16,i+s),Atomics.store(this.state,0,1-t),n+1}resetOutput(){let e=1-Atomics.load(this.state,0);for(let t=0;t<3;t++)this.headers.setFloat64(8+e*24+t*8,0);Atomics.store(this.state,0,e)}output(){let[e,t,n]=this.header(Atomics.load(this.state,0)),r=e===0?`[]`:this.bytes.toString(`utf8`,0,n);return{count:e,source:e===0||t+1<=this.bytes.length?{kind:`complete`,json:e===0?r:r+`]`}:{kind:`prefix`,json:r,originalBytes:t+1}}}header(e){let t=8+e*24;return[this.headers.getFloat64(t),this.headers.getFloat64(t+8),this.headers.getFloat64(t+16)]}};const hi=`openclaw-code-mode:user.js`;function sourceExtent(e,t){let n=1,r=0;for(let t of e.matchAll(/\r\n|[\r\n\u2028\u2029]/gu))n+=1,r=t.index+t[0].length;let i=e.slice(r);return{lines:n,lastColumn:(t===`utf8`?Buffer.byteLength(i,`utf8`):i.length)+1}}function normalizeSourceStack(e,t){return!e||!t?e:e.replace(/^[^\S\r\n]+at [^\r\n]*openclaw-code-mode:(?:user|controller)\.js:\d+:\d+\)?(?:\r?\n|$)/gmu,e=>{let n=/openclaw-code-mode:user\.js:(\d+):(\d+)(?=\)?(?:\r?\n)?$)/u.exec(e);if(!n)return``;let r=Number(n[1])-t.lineOffset,i=Number(n[2]),a=i-(r===1?t.columnOffset:0);return r<1||r>t.lineCount||a<1||r===t.lineCount&&i>t.endColumn?``:e.replace(n[0],t.file+`:`+r+`:`+a)})}function buildUserSource(e,t=``,n=`utf8`){let r=`globalThis.__openclawResult = __openclawRunCell(async () => {\n${t}`,i=sourceExtent(r,n),a=sourceExtent(e,n),o=i.lastColumn-1;return{source:`${r}${e}\n})`,location:{file:hi,lineOffset:i.lines-1,lineCount:a.lines,columnOffset:o,endColumn:a.lastColumn+(a.lines===1?o:0)}}}function buildCodeModeScriptParseSource(e){return{source:`(async () => {
${e}\n})`,codeOffset:15}}function parseCodeModeScriptSyntax(e){let{source:t}=buildCodeModeScriptParseSource(e);try{return{ok:!0,program:fe(t,{ecmaVersion:`latest`})}}catch(e){let t=e;return{ok:!1,message:t.message.replace(/ \(\d+:\d+\)$/u,``),line:t.loc.line-1,column:t.loc.column}}}const gi=/^export\s+(?:(?:abstract|as|async|class|const|declare|default|enum|function|import|interface|let|namespace|type|var)\b|[={*])/u,_i=/^(?:abstract|as|async|await|break|case|catch|class|const|continue|debugger|declare|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|namespace|new|null|of|private|protected|public|return|satisfies|static|super|switch|this|throw|true|try|typeof|undefined|var|void|while|with|yield)$/u,vi=/^(?:API|MCP|AggregateError|Array|ArrayBuffer|BigInt|BigInt64Array|BigUint64Array|Boolean|DataView|Date|Error|EvalError|Float32Array|Float64Array|Function|Infinity|Int16Array|Int32Array|Int8Array|Intl|JSON|Map|Math|NaN|Number|Object|Promise|Proxy|RangeError|ReferenceError|Reflect|RegExp|Set|String|Symbol|SyntaxError|TypeError|URIError|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|WeakMap|WeakSet|catalog|clearTimeout|console|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|globalThis|isFinite|isNaN|json|nodes|parseFloat|parseInt|setTimeout|skills|text|yield_control)$/u,yi=/^(?:\/(?:usr\/(?:local\/)?)?bin\/)?(alias|apt|awk|bash|bg|brew|builtin|bun|cargo|cat|cd|chmod|cmd|command|cp|curl|cut|date|declare|df|dir|docker|dotnet|du|echo|env|exec|exit|export|fg|file|find|getopts|git|go|gradle|grep|hash|head|help|hostname|id|java|javac|jobs|jq|kill|kubectl|ln|local|logout|ls|make|mkdir|mvn|mv|node|npm|npx|perl|php|pip|pip3|pnpm|poetry|popd|powershell|printf|ps|pushd|pwd|pwsh|pytest|python|python3|read|readonly|rg|rm|ruby|rustc|rustup|sed|set|sh|shift|sleep|sort|source|stat|sudo|swift|systemctl|tail|tar|tee|test|touch|trap|tree|type|ulimit|umask|uname|uniq|unset|unzip|uv|uvx|vitest|wait|wc|wget|which|whoami|xargs|yarn|zip|zsh)(?=$|[\s;&|<>])/u,bi=/^([A-Za-z_][\w-]*)(?=$|[\s;&|<>])/u,xi=/^(?:(?:\.{1,2}|~)[\\/]|\/|[A-Za-z]:[\\/])[^\s;|&()]+(?=$|[\t \r\n;&|])/u,Si=/^(?:-{1,2}[a-z\d][\w-]*(?:[\t =;&|]|$)|(?:(?:\.{1,2}|~)[\\/]|\/|[A-Za-z]:[\\/])[^\s]+)/iu,Ci=/^(?:(?:if|elif|while|until)[\t ]+(?:\[{1,2}(?=[\t ]|$)|test\b|[A-Za-z_][\w-]*(?=[\t ;]))|for[\t ]+(?:[A-Za-z_]\w*[\t ]+in\b|\(\([^\r\n]*\)\)[\t ]*;[\t ]*do\b)|case[\t ]+\S+[\t ]+in\b|function[\t ]+[A-Za-z_][\w-]*[\t ]*\{)/u,wi=/^(?:\d*(?:>>?|<<?)|&>>?)/u,Ti=/^(?:(?:\/\/[^\r\n]*(?:\r?\n|$)|\/\*[\s\S]*?\*\/|#[^\r\n]*(?:\r?\n|$))[\t \r\n]*)+/u;function parsesAsGuestJavaScript(e,t=``){return parseCodeModeScriptSyntax(`${t}${e}`).ok}function stripShellEnvAssignments(e){let t=/[A-Za-z_]\w*=/uy;if(!t.test(e))return e;let n=new Uint32Array(e.length+3),r=new Uint32Array(e.length+3),i=new Uint32Array(e.length+3),a=0,o=0;for(let s=e.length-1;s>=t.lastIndex;--s){let t=e[s],c=t===` `||t===` `,l=/\s/u.test(t),u=c?a||o:t===`
`?a:t===`\r`&&e[s+1]===`
`?o:0;c||(a=l?0:s,o=u);let d=t===`\\`&&s+1<e.length&&!/[\r\n\u2028\u2029]/u.test(e[s+1]),f=s+(d&&e.codePointAt(s+1)>65535?3:2);r[s]=(d?r[f]:0)||(t===`"`?n[s+1]:r[s+1]),i[s]=t===`'`?n[s+1]:i[s+1],n[s]=(t===`"`?r[s+1]:0)||(t===`'`?i[s+1]:0)||(d?n[f]:0)||(!l&&t!==`;`&&t!==`&`&&t!==`|`?n[s+1]:0)||u}let s=0;do{let e=n[t.lastIndex];if(!e)break;s=e,t.lastIndex=e}while(t.test(e));return e.slice(s)}function isShellLikeCodeModeSource(e){let t=e.trim();if(t.startsWith(`#!`))return!0;let n=t.replace(Ti,``);if(!n||gi.test(n))return!1;if(Ci.test(n))return!0;let r=stripShellEnvAssignments(n),i=yi.exec(r),a=bi.exec(r),o=i??(a&&!_i.test(a[1]??``)&&!vi.test(a[1]??``)?a:null);if(!o&&!xi.test(r))return!1;let s=o?r.slice(o[0].length):``,c=s.trimStart();if(o&&!c)return i!==null;if(!parsesAsGuestJavaScript(e))return!0;let l=o?.[1];return l&&!parsesAsGuestJavaScript(e,`let ${l};\n`)&&parsesAsGuestJavaScript(e,`var ${l};\n`)?!1:/^[\t ]*(?:[;\r\n]|&&?|\|{1,2})/u.test(s)?i!==null:!(!o||!Si.test(c)&&!(i!==null&&wi.test(c))&&!(l===`jq`&&c.startsWith(`.`)))}function isModuleLoaderCallee(e){if(e.type===`ParenthesizedExpression`||e.type===`ChainExpression`)return isModuleLoaderCallee(e.expression);if(e.type===`SequenceExpression`){let t=e.expressions[e.expressions.length-1];return t!==void 0&&isModuleLoaderCallee(t)}return e.type===`Identifier`&&e.name===`require`}function containsModuleAccess(e){if(e.type===`ImportExpression`||e.type===`CallExpression`&&isModuleLoaderCallee(e.callee))return!0;for(let t of Object.values(e))for(let e of Array.isArray(t)?t:[t])if(typeof e==`object`&&e&&`type`in e&&typeof e.type==`string`&&containsModuleAccess(e))return!0;return!1}const Ei=`code mode module access is disabled. Call an enabled async tool global from guest JavaScript; use catalog.search(query) when the bounded quick index omits it. Do not retry the same source with require() or an import.`;function prepareSource(e){let t=parseCodeModeScriptSyntax(e);if(isShellLikeCodeModeSource(e))throw new ToolInputError(`code-mode exec runs JavaScript, not shell commands. Call an enabled async tool global from guest JavaScript; use catalog.search(query) when the bounded quick index omits it. Do not retry the same shell command as code.`);if(!t.ok){let e=truncateUtf16Safe(t.message,240);throw new ToolInputError(`SyntaxError at openclaw-code-mode:user.js:${t.line}:${t.column+1}: ${e}. No tools were dispatched; correct the JavaScript source and submit it again.`)}if((e.includes(`import`)||e.includes(`require`)||e.includes(`\\u`))&&containsModuleAccess(t.program))throw new ToolInputError(Ei);return e}let $;process.on(`unhandledRejection`,(e,t)=>$?.rejections.set(t,e)),process.on(`rejectionHandled`,e=>$?.rejections.delete(e));let Di=performance.now(),Oi=0,ki=Di,Ai=0,ji=0,Mi=-1/0,Ni=0,Pi;observeGcSamples(e=>{for(let t of e)t.kind===`mark_sweep_compact`&&(Oi++,Ai++);let t=performance.now(),n=t-ki;if(n>=1e4){let e=Ai>n/100;if(ji=e?Math.min(2,ji+1):0,ji===2&&Pi&&publishWorkerGcStorm({retireWorkerId:Pi}),e&&t-Mi>=6e4){let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:a}=process.memoryUsage();publishWorkerGcStorm({workerId:Pi,...$?.gcAttribution,cellCount:Ni,activeCellCount:+!!$,bridgeMethods:[...new Set($?.pendingRequests.map(e=>e.method)??[])],majorCollections:Ai,intervalMs:n,heapUsed:e,heapTotal:r,external:i,arrayBuffers:a,heapSizeLimitBytes:s().heap_size_limit}),Mi=t}ki=t,Ai=0}let r=t-Di;if(!(r<1e3)){if(Oi>=r/50){let e=s();if(e.used_heap_size>=e.heap_size_limit*.85)throw Object.assign(/* @__PURE__ */ Error(`Code Mode worker stopped after sustained garbage collection near its JavaScript heap limit`),{code:`ERR_CODE_MODE_GC_THRASH`})}Di=t,Oi=0}});const Fi=new Set(ot);function isBridgeMethod(e){return Fi.has(e)}function rejectModuleImport(){throw $&&($.moduleImportRejected=!0),Error(Ei)}function compileController(e){return new l(e,{filename:`openclaw-code-mode:controller.js`,importModuleDynamically:rejectModuleImport})}const Ii=compileController(String.raw`
(() => {
// Keep native encoding prototypes private when this worker is reused.
const Encoder = globalThis.__openclawNodeTextEncoder;
const Decoder = globalThis.__openclawNodeTextDecoder;
const Bytes = Uint8Array;
delete globalThis.__openclawNodeTextEncoder;
delete globalThis.__openclawNodeTextDecoder;
Object.defineProperties(globalThis, {
TextEncoder: { value: class TextEncoder {
#encoder = new Encoder();
get encoding() { return this.#encoder.encoding; }
encode(input) { return new Bytes(this.#encoder.encode(input)); }
encodeInto(input, destination) {
const { read, written } = this.#encoder.encodeInto(input, destination);
return { read, written };
}
}, enumerable: true },
TextDecoder: { value: class TextDecoder {
#decoder;
constructor(label, options) { this.#decoder = new Decoder(label, options); }
get encoding() { return this.#decoder.encoding; }
get fatal() { return this.#decoder.fatal; }
get ignoreBOM() { return this.#decoder.ignoreBOM; }
decode(input, options) { return this.#decoder.decode(input, options); }
}, enumerable: true },
});
})();
Object.assign(globalThis, JSON.parse(__openclawNodeInit));
delete globalThis.__openclawNodeInit;
globalThis.__openclawMaxPendingToolCalls = __openclawNodeMaxPending;
delete globalThis.__openclawNodeMaxPending;
${st}
(() => {
const finish = globalThis.__openclawNodeFinish;
delete globalThis.__openclawNodeFinish;
Object.defineProperties(globalThis, {
__openclawNodeObserveResult: { value: (result) => {
result.then(value => finish(true, value), error => finish(false, __openclawEncodeError(error)));
}},
});
})();
`),Li=compileController(`__openclawSettleBridge()`),Ri=compileController(`(() => {
const error = __openclawAdmissionError();
if (!error) __openclawDrainQueuedRequests();
return error;
})()`),zi=compileController(`__openclawNodeObserveResult(__openclawResult)`),Bi=compileController(`(() => {
const error = __openclawNodeRejection;
delete globalThis.__openclawNodeRejection;
return __openclawEncodeError(error);
})()`);function evaluate(e,t){if(e.deadline-performance.now()<=0)throw new CodeModeHeadlessTimeoutError;return t.runInContext(e.context)}function sourceFrames(e,t){return normalizeSourceStack(e,t)?.split(`
`).filter(e=>e.includes(`openclaw-code-mode:user.js`)&&/^\s+at /u.test(e))??[]}function createCell(e,t,n,r,i){let a=performance.now(),o=Math.min(n+e.config.timeoutMs,a+(e.executionTimeoutMs??1/0));if(o<=a)throw new CodeModeHeadlessTimeoutError;let s=buildUserSource(t,e.prelude,`utf16`),c=u(Object.create(null),{microtaskMode:`afterEvaluate`,importModuleDynamically:rejectModuleImport});Ni++;let d={context:c,gcAttribution:e.gcAttribution,config:e.config,location:s.location,pendingRequests:[],canceledRequestIds:[],replyIndex:0,rejections:/* @__PURE__ */ new Map,deadline:o,progress:r};return $=d,c.__openclawNodeTextEncoder=TextEncoder,c.__openclawNodeTextDecoder=TextDecoder,c.__openclawHostRequest=(e,t,n,r)=>{if(d.pendingRequests.length>=d.config.maxPendingToolCalls)throw d.admissionError=`too many pending code mode tool calls`,Error(d.admissionError);if(!isBridgeMethod(e))throw Error(`unsupported code mode bridge method`);let i=JSON.parse(t);if(!Array.isArray(i))throw Error(`invalid code mode bridge arguments: expected an array`);if(!n.startsWith(`bridge:${e}:`)||!/^bridge:[A-Za-z]+:[1-9]\d*$/u.test(n))throw Error(`invalid code mode bridge id`);if(d.pendingRequests.some(e=>e.id===n))throw Error(`duplicate code mode bridge id`);return d.pendingRequests.push({id:n,method:e,args:i}),sourceFrames(typeof r==`string`?r.slice(0,8192):``,d.location).join(`
`)},c.__openclawHostCancelRequest=e=>{let t=d.pendingRequests.findIndex(t=>t.id===e);t>=0&&(d.pendingRequests.splice(t,1),d.canceledRequestIds.push(e))},c.__openclawHostTakeBridgeReply=()=>{let e=d.replies?.[d.replyIndex];if(!e)return;d.replyIndex++;let t={__proto__:null,id:e.id,ok:e.ok,json:e.json};return e.json=``,t},c.__openclawHostObserveNetworkContent=()=>{d.networkContentObserved=!0,d.progress.observeNetworkContent()},c.__openclawHostOutput=e=>d.progress.append(e),c.__openclawNodeInit=new TextDecoder().decode(e.initialization),c.__openclawNodeMaxPending=e.config.maxPendingToolCalls,c.__openclawMaxOutputBytes=e.config.maxOutputBytes,c.__openclawNodeFinish=(e,t)=>{d.outcome={ok:e,json:t}},r.deadline=performance.timeOrigin+o,i?.(),evaluate(d,Ii),evaluate(d,new l(s.source,{filename:hi,importModuleDynamically:rejectModuleImport})),evaluate(d,zi),d}function settle(e,t){e.replies=t,e.replyIndex=0;try{evaluate(e,Li)}finally{e.replies=void 0,e.replyIndex=0;for(let e of t)e.json=``;t.length=0}}function formatGuestFailure(e,t){let n=JSON.parse(t);return n.bridgeCode===null&&n.name===`ReferenceError`&&/^(?:require|module|process) is not defined$/u.test(n.message)?{code:`invalid_input`,error:Ei}:{code:n.bridgeCode??`internal_error`,...n.bridgeCode===null?{}:{failurePhase:`bridge`},error:[`${n.name}: ${n.message}`,...sourceFrames(n.stack,e.location)].join(`
`)}}function failed(e,t,n=mi,r){return{status:`failed`,code:e,error:t,output:n,failurePhase:r??(e===`invalid_input`?`input`:`guest`),bridgeDispatchStarted:!1}}async function run(e,t){let r=mi,a=t?.consumeInput,consume=()=>{let e=a;a=void 0,e?.()},o=e.config;Pi=e.gcAttribution?.workerId;let c=performance.now(),l=new CodeModeNodeProgress(e.progress);try{let i=e.kind===`exec`?createCell(e,prepareSource(e.source),c,l,consume):$;if(!i)throw Error(`code mode continuation is no longer available`);for(e.kind===`resume`&&(i.progress=l,i.config=o,i.deadline=performance.now()+o.timeoutMs,l.deadline=performance.timeOrigin+i.deadline,i.networkContentObserved&&l.observeNetworkContent(),i.pendingRequests=e.pendingRequests??[],i.canceledRequestIds=[],settle(i,e.settledRequests));;){consume();let c=i.admissionError??evaluate(i,Ri);if(c!==void 0&&typeof c!=`string`)throw Error(`invalid code mode admission error`);if(c)throw new ToolInputError(c);if(await n(),i.moduleImportRejected){i.moduleImportRejected=!1;continue}r=l.output();let u=!i.outcome;if(u&&i.pendingRequests.length===0)throw new ToolInputError(`code mode promise is pending without host work`);if(u||i.outcome?.ok&&i.pendingRequests.length>0){let n=u?{kind:`awaiting`}:{kind:`draining`,requiredRequestIds:i.pendingRequests.map(e=>e.id)},c={pendingRequests:i.pendingRequests,canceledRequestIds:i.canceledRequestIds,settlementMode:n,output:r,memoryUsedBytes:s().used_heap_size,...i.networkContentObserved?{networkContentObserved:!0}:{}};if(!t||!e.inlineHost)return{status:`waiting`,...c,continuation:void 0};let l=await t.request({status:`boundary`,...c});r=mi,a=l.consumed;let d=l.input;if(d.kind===`checkpoint`)return consume(),{status:`waiting`,...c,continuation:void 0,output:mi};if(d.kind!==`continue`)throw Error(`invalid code mode continuation`);if(!Number.isFinite(d.timeoutMs)||d.timeoutMs<=0||d.timeoutMs>o.timeoutMs)throw Error(`invalid code mode continuation timeout`);i.deadline=performance.now()+d.timeoutMs,i.pendingRequests=d.pendingRequests,i.canceledRequestIds=[],settle(i,d.settledRequests);continue}let d=i.outcome,f=d.ok?void 0:d.json;if(d.ok&&i.rejections.size>0&&(i.context.__openclawNodeRejection=i.rejections.values().next().value,f=String(evaluate(i,Bi))),f!==void 0){let e=formatGuestFailure(i,f);return t?.notify({status:`failure`,error:JSON.parse(f),failurePhase:e.failurePhase??`guest`}),failed(e.code,boundCodeModeError(e.error,o.maxOutputBytes),r,e.failurePhase)}return{status:`completed`,output:r,value:captureCodeModeValue(JSON.parse(d.json),o.maxOutputBytes,e.retainFinalValue?Math.min(o.memoryLimitBytes,o.maxSnapshotBytes):o.maxOutputBytes)}}}catch(e){let n=e instanceof CodeModeHeadlessTimeoutError,a=e instanceof ToolInputError?`input`:n&&l.deadline?`guest`:`host`;return t?.notify({status:`failure`,error:i.isNativeError(e)?{name:e.name,message:e.message,stack:e.stack}:String(e),failurePhase:a}),$&&r.count===0&&!n&&(r=l.output()),failed(n?`timeout`:e instanceof ToolInputError?`invalid_input`:`internal_error`,boundCodeModeError(n?`code mode timeout exceeded`:i.isNativeError(e)?e.message:String(e),o.maxOutputBytes),n?l.output():r,a)}finally{consume()}}serveWorkerTasks(async(e,t)=>{let n=await run(e,t);return $?.networkContentObserved&&(n.networkContentObserved=!0),n.status!==`waiting`&&($=void 0),n},{idleGc:!1});export{asOptionalRecord as C,resolveGlobalSingleton as S,extractErrorCode as _,redactToolPayloadText as a,normalizeDiagnosticWorkerScript as b,expandHomePrefix as c,truncateUtf16Safe as d,expectDefined as f,materializeErrorStack as g,AsyncContext as h,redactSensitiveText as i,getSealedRuntimeSecureTempRoot as l,normalizeOptionalString as m,redactLogRecordForTransport as n,readLoggingConfig as o,normalizeLowercaseStringOrEmpty as p,redactSecrets as r,resolveStateDir as s,boundedJsonUtf8Bytes as t,isBlockedObjectKey as u,formatErrorStackWithMessage as v,isRecord as w,resolveGlobalSet as x,N as y};