openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
89 lines • 45.8 kB
JavaScript
import path from"node:path";import os from"node:os";import fs from"node:fs";import{readRegularFileSync}from"@openclaw/fs-safe/advanced";import{parse}from"dotenv";import{AsyncLocalStorage}from"node:async_hooks";import{compareBuild,parse as parse$1}from"semver";import"@openclaw/fs-safe/path";
//!packages/normalization-core/src/string-coerce.ts
function normalizeNullableString(e){if(typeof e!==`string`)return null;const t=e.trim();return t?t:null}function normalizeOptionalString(e){return normalizeNullableString(e)??void 0}function normalizeOptionalLowercaseString(e){return normalizeOptionalString(e)?.toLowerCase()}function normalizeLowercaseStringOrEmpty(e){return normalizeOptionalLowercaseString(e)??``}
//!src/daemon/constants.ts
const GATEWAY_LAUNCH_AGENT_LABEL=`ai.openclaw.gateway`;const GATEWAY_SYSTEMD_SERVICE_NAME=`openclaw-gateway`;const GATEWAY_WINDOWS_TASK_NAME=`OpenClaw Gateway`;const GATEWAY_SERVICE_MARKER=`openclaw`;const GATEWAY_SERVICE_KIND=`gateway`;const GATEWAY_SERVICE_SELECTOR_ENV_KEYS=[`OPENCLAW_STATE_DIR`,`OPENCLAW_CONFIG_PATH`,`OPENCLAW_PROFILE`,`OPENCLAW_GATEWAY_PORT`,`OPENCLAW_LAUNCHD_LABEL`,`OPENCLAW_SYSTEMD_UNIT`,`OPENCLAW_WINDOWS_TASK_NAME`];function isGatewayServiceEnv(e){if(e.OPENCLAW_SERVICE_MARKER?.trim()!==`openclaw`)return false;const t=e.OPENCLAW_SERVICE_KIND?.trim();return!t||t===`gateway`}const NODE_LAUNCH_AGENT_LABEL=`ai.openclaw.node`;const NODE_SYSTEMD_SERVICE_NAME=`openclaw-node`;const NODE_WINDOWS_TASK_NAME=`OpenClaw Node`;const NODE_SERVICE_MARKER=`openclaw`;const NODE_SERVICE_KIND=`node`;const NODE_WINDOWS_TASK_SCRIPT_NAME=`node.cmd`;function normalizeGatewayProfile(e){const t=e?.trim();return t&&normalizeLowercaseStringOrEmpty(t)!=="default"?t:null}function resolveGatewayProfileSuffix(e){const t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveGatewayLaunchAgentLabel(e){const t=normalizeGatewayProfile(e);return t?`ai.openclaw.${t}`:GATEWAY_LAUNCH_AGENT_LABEL}function resolveGatewaySystemdServiceName(e){return`${GATEWAY_SYSTEMD_SERVICE_NAME}${resolveGatewayProfileSuffix(e)}`}function resolveGatewayWindowsTaskName(e){const t=normalizeGatewayProfile(e);return t?`${GATEWAY_WINDOWS_TASK_NAME} (${t})`:GATEWAY_WINDOWS_TASK_NAME}function resolveNodeLaunchAgentLabel(e){const t=normalizeGatewayProfile(e);return t?`${NODE_LAUNCH_AGENT_LABEL}.${t}`:NODE_LAUNCH_AGENT_LABEL}function resolveNodeSystemdServiceName(e){return`${NODE_SYSTEMD_SERVICE_NAME}${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){const t=normalizeGatewayProfile(e);return t?`${NODE_WINDOWS_TASK_NAME} (${t})`:NODE_WINDOWS_TASK_NAME}function resolveNodeServiceIdentityEnvironment(e={}){const t=e.OPENCLAW_PROFILE;return{OPENCLAW_PROFILE:t,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(t),OPENCLAW_SYSTEMD_UNIT:resolveNodeSystemdServiceName(t),OPENCLAW_WINDOWS_TASK_NAME:resolveNodeWindowsTaskName(t),OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER:`1`,OPENCLAW_TASK_SCRIPT_NAME:NODE_WINDOWS_TASK_SCRIPT_NAME,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:NODE_SERVICE_MARKER,OPENCLAW_SERVICE_KIND:NODE_SERVICE_KIND}}const FLAG_TERMINATOR=`--`;const ROOT_BOOLEAN_FLAGS=/* @__PURE__ */ new Set([`--dev`,`--no-color`]);const ROOT_VALUE_FLAGS=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){if(!e||e===`--`)return false;if(!e.startsWith(`-`))return true;return/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){const n=e[t];if(!n)return 0;if(ROOT_BOOLEAN_FLAGS.has(n))return 1;if(n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`))return 1;if(ROOT_VALUE_FLAGS.has(n))return isValueToken(e[t+1])?2:1;return 0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,ROOT_BOOLEAN_FLAGS,ROOT_VALUE_FLAGS,`command-path`)}function getRootOptionAwareCommandPath(e,t){const n=e.slice(2);const r=[];let i=false;for(let e=0;e<n.length;e+=1){const a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=true;continue}const o=i?0:consumeRootCommandOptionToken(n,e);if(o>0){e+=o-1;continue}if(!i&&a.startsWith(`-`))continue;r.push(a);if(r.length>=t)break}return r}function consumeKnownOptionToken(e,t,n,r,i){const a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;const o=a.indexOf(`=`);const s=o===-1?a:a.slice(0,o);if(n.has(s))return o===-1?1:0;if(!r.has(s))return 0;if(o!==-1)return i===`command-path`||a.slice(o+1).trim()?1:0;if(i===`command-path`)return e[t+1]!==void 0?2:0;return isValueToken(e[t+1])?2:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,false)}function parseCommandArgsWithRootOptions(e,t,n,r=false){const i=e.slice(2);const a=new Set(t.booleanFlags??[]);const o=new Set(t.valueFlags??[]);const s=[];const c=[];const l=[];let u=0;let d=false;for(let e=0;e<i.length;e+=1){const f=i[e];if(f===void 0)break;if(!d&&f===`--`){if(t.mode!==`command-path`)break;d=true;continue}const p=d?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(p>0){(u>0&&a.has(f)?l:c).push(...i.slice(e,e+p));e+=p-1;continue}if(!d&&f.startsWith(`-`)){const n=consumeKnownOptionToken(i,e,a,o,t.mode);if(n===0||u===0)return null;l.push(f);e+=n-1;continue}if(u<t.commandPath.length){if(f!==t.commandPath[u])return null;u+=1;if(n&&u===t.commandPath.length){const t=i.slice(e+1);return d?[`--`,...t]:t}continue}s.push(f);if(!r&&s.length===t.maxPositionals)return s}return u<t.commandPath.length?null:r?{rootOptions:c,commandOptions:l}:s}
//!packages/normalization-core/src/home-dir.ts
function normalizeHomeDirValue(e){const t=e?.trim();return t&&t!==`undefined`&&t!==`null`?t:void 0}function normalizeSafe(e){try{return normalizeHomeDirValue(e())}catch{return}}function resolveTermuxHome(e){const t=normalizeHomeDirValue(e.PREFIX);if(!t||!normalizeHomeDirValue(e.ANDROID_DATA))return;if(!/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu,`/`)))return;return path.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=os.homedir){const n=resolveRawOsHomeDir(e,t);return n?path.resolve(n):void 0}function resolveEffectiveHomeDir(e=process.env,t=os.homedir,n){const r=normalizeHomeDirValue(e.OPENCLAW_HOME);if(!r)return resolveOsHomeDir(e,t);if(r===`~`||r.startsWith(`~/`)||r.startsWith(`~\\`)){const i=resolveRawOsHomeDir(e,t);if(!i)return n?.preserveUnresolvedTilde?path.resolve(r):void 0;return path.resolve(r.replace(/^~(?=$|[\\/])/,()=>i))}return path.resolve(r)}
//!src/shared/global-singleton.ts
const GLOBAL_SINGLETON_RESETS_KEY=Symbol.for(`openclaw.globalSingletonLifecycleResets`);function resolveGlobalSingletonResetRegistry(){const e=globalThis;const t=e[GLOBAL_SINGLETON_RESETS_KEY];if(t instanceof Map)return t;const n=/* @__PURE__ */ new Map;e[GLOBAL_SINGLETON_RESETS_KEY]=n;return n}function resolveGlobalSingleton(e,t,n,r=`close-and-restart`){const i=globalThis;let a;if(Object.hasOwn(i,e))a=i[e];else{a=t();i[e]=a}if(n)resolveGlobalSingletonResetRegistry().set(e,{lifecycle:r,reset:()=>n(a)});return a}
//!src/infra/safe-cwd.ts
function tryProcessCwd(){try{return process.cwd()}catch{return}}
//!src/infra/home-dir.ts
function getUserPathBaseDirectory(){return resolveGlobalSingleton(Symbol.for(`openclaw.userPathBaseDirectory`),()=>{const{AsyncLocalStorage:e}=process.getBuiltinModule(`async_hooks`);return new e})}function resolveRequiredHomeDir(e=process.env,t=os.homedir){const n=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(n)return path.resolve(n);throw new 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;const n=normalizeHomeDirValue(t?.home)??resolveEffectiveHomeDir(t?.env??process.env,t?.homedir??os.homedir);if(!n)return e;return e.replace(/^~(?=$|[\\/])/,()=>n)}function resolveAgainstUserBase(e){const t=getUserPathBaseDirectory().getStore();return t?path.resolve(t,e):path.resolve(e)}function resolvePathWithHome(e,t,n,r=resolveAgainstUserBase){const i=e.trim();if(!i)return i;return r(i.startsWith(`~`)?expandHomePrefix(i,{home:n(t?.env??process.env,t?.homedir??os.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=os.homedir){if(!e)return``;return resolveHomeRelativePath(e,{env:t,homedir:n})}
//!src/shared/browser-pair.ts
function splitBrowserPairCodeProfile(e){const t=e.indexOf(`:`);return t<0?{profile:null,code:e}:{profile:e.slice(0,t).trim(),code:e.slice(t+1)}}
//!packages/normalization-core/src/number-coercion.ts
const MAX_TIMER_TIMEOUT_MS=2147e6;const MAX_TIMER_TIMEOUT_SECONDS=Math.floor(MAX_TIMER_TIMEOUT_MS/1e3);
//!src/daemon/runtime-binary.ts
const RUNTIME_MODULE_OPTIONS=/* @__PURE__ */ new Set([`-r`,`--preload`,`--require`,`--import`,`--loader`,`--experimental-loader`,`--test-reporter`,`--test-global-setup`]);const RUNTIME_VALUE_OPTIONS=/* @__PURE__ */ new Set([...RUNTIME_MODULE_OPTIONS,`-C`,`--env-file`,`--env-file-if-exists`,`--tsconfig`,`--cwd`,`--conditions`,`--icu-data-dir`,`--openssl-config`,`--title`,`--disable-warning`,`--disable-proto`,`--cpu-prof-name`,`--max-old-space-size`,`--max-semi-space-size`]);
//!src/cli/update-option-specs.ts
const UPDATE_OPTION_SPECS=[[`--json`,`Output result as JSON`,false],[`--no-restart`,`Skip updater restart (package Gateways may restart themselves)`],[`--dry-run`,`Preview update actions without making changes`,false],[`--full-integrity-check`,`Run full database integrity checks during migrations`,false],[`--admission <auto|installed>`,`Select candidate or installed admission checks (default: auto)`],[`--channel <stable|extended-stable|beta|dev>`,`Persist update channel (git + npm)`],[`--tag <dist-tag|version|spec>`,`Override the package target for this update (dist-tag, version, or package spec)`],[`--timeout <seconds>`,`Set an overall update budget in seconds`],[`--drain-timeout <seconds>`,`Set the immutable activation drain budget before interruption`],[`--sha <commit>`,`Prepare an exact official commit for an adopted immutable installation`],[`--yes`,`Skip confirmation prompts (non-interactive)`,false],[`--reapply-local-overrides`,`Replay trusted packaged dist edits when the target baseline is unchanged`,false],[`--accept-capabilities`,`Accept widened plugin capabilities`,false]];
//!src/cli/parent-command-path.ts
const AGENT_PARENT_BOOLEAN_FLAGS=[`--local`,`--deliver`,`--json`];const AGENT_PARENT_VALUE_FLAGS=[`-m`,`--message`,`--message-file`,`-t`,`--to`,`--session-key`,`--session-id`,`--agent`,`--model`,`--thinking`,`--verbose`,`--channel`,`--reply-to`,`--reply-channel`,`--reply-account`,`--timeout`];const MODELS_PARENT_BOOLEAN_FLAGS=[`--json`,`--status-json`,`--status-plain`];const MODELS_PARENT_VALUE_FLAGS=[`--agent`];const UPDATE_PARENT_BOOLEAN_FLAGS=UPDATE_OPTION_SPECS.filter(([e])=>!e.includes(`<`)).map(([e])=>e);const UPDATE_PARENT_VALUE_FLAGS=UPDATE_OPTION_SPECS.filter(([e])=>e.includes(`<`)).map(([e])=>e.slice(0,e.indexOf(` `)));const PARENT_COMMAND_FLAGS=/* @__PURE__ */ new Map([[`agent`,[AGENT_PARENT_BOOLEAN_FLAGS,AGENT_PARENT_VALUE_FLAGS]],[`models`,[MODELS_PARENT_BOOLEAN_FLAGS,MODELS_PARENT_VALUE_FLAGS]],[`config`,[[],[`--section`]]],[`skills`,[[`--json`],[`--agent`]]],[`channels`,[[],[`--agent`]]],[`update`,[UPDATE_PARENT_BOOLEAN_FLAGS,UPDATE_PARENT_VALUE_FLAGS]]]);function resolveCliParentCommandPath(e,t){const[n]=getRootOptionAwareCommandPath(e,1);if(!n||t&&n!==t)return null;const r=PARENT_COMMAND_FLAGS.get(n);if(!r)return null;const[i,a]=r;const o=getCommandPositionalsWithRootOptions(e,{commandPath:[n],booleanFlags:i,valueFlags:a,maxPositionals:1,mode:`command-path`})?.[0];return o?[n,o]:[n]}
//!src/cli/config-output-mode.ts
function isConfigMachineOutput(e){const t=resolveCliParentCommandPath(e,`config`)?.[1];return t===`get`||t===`file`||t===`schema`}
//!src/cli/program/command-tree.ts
function getCommandHierarchy(e){const t=[];for(let n=e;n;n=n.parent??null)t.unshift(n);return t}
//!src/cli/program/commander-parse-facts.ts
function requiresFollowingValue(e,t){if(e.includes(`=`))return false;const n=t.find(t=>t.short===e||t.long===e);if(n)return n.required;if(!e.startsWith(`-`)||e.startsWith(`--`))return false;const r=e.slice(1);for(let e=0;e<r.length;e+=1){const n=t.find(t=>t.short===`-${r[e]}`);if(!n)return false;if(n.required||n.optional)return n.required&&e===r.length-1}return false}function hasCommanderOptionToken(e,t,n,r){const i=getCommandHierarchy(e);const a=t.slice(2);let o=0;for(let e=0;e<a.length;e+=1){const t=a[e];if(t===void 0||t===`--`)break;const s=i[o+1];if(s&&(t===s.name()||s.aliases().includes(t))){o+=1;continue}if(requiresFollowingValue(t,i[o]?.options??[])){const t=a[e+1];if(r===`value`&&t&&n.has(t))return true;e+=1;continue}if(r===`flag`&&n.has(t.split(`=`)[0]??t))return true}return false}
//!src/cli/machine-output-argv.ts
function hasMachineOutputOption(e,t,n){if(n)return hasCommanderOptionToken(n,e,/* @__PURE__ */ new Set([t]),`flag`);for(const n of e.slice(2)){if(n===`--`)return false;if(n===t||n.startsWith(`${t}=`))return true}return false}
//!src/cli/doctor-output-mode.ts
function isDoctorMachineOutput(e){if(hasMachineOutputOption(e.argv,`--lint`))return hasMachineOutputOption(e.argv,`--json`)||!e.stdoutIsTTY;const t=hasMachineOutputOption(e.argv,`--post-upgrade`)||hasMachineOutputOption(e.argv,`--state-sqlite`)||hasMachineOutputOption(e.argv,`--session-sqlite`);return hasMachineOutputOption(e.argv,`--json`)&&!t}
//!src/cli/program/core-command-descriptors.ts
function command$1(e,t,n,r={}){return{name:e,description:t,hasSubcommands:n,...r}}const CORE_CLI_COMMAND_DESCRIPTORS=[command$1(`setup`,`Chat with OpenClaw; onboard when setup is incomplete`,false),command$1(`crestodian`,`Deprecated: use openclaw setup`,false,{hidden:true}),command$1(`onboard`,`Guided setup for auth, models, Gateway, workspace, channels, and skills`,true),command$1(`configure`,`Interactive configuration for credentials, channels, gateway, and agent defaults`,false),command$1(`config`,`Non-interactive config helpers (get/set/patch/unset/file/schema/validate). Run without subcommand for guided setup.`,true,{machineOutput:({argv:e})=>isConfigMachineOutput(e)}),command$1(`templates`,`Author and add OpenClaw Templates`,true,{parentDefaultHelp:true}),command$1(`backup`,`Create, verify, and restore backup archives and SQLite snapshots`,true),command$1(`database`,`Inspect database compatibility, manage ownership, and port database stores`,true,{parentDefaultHelp:true,machineOutput:({argv:e})=>hasMachineOutputOption(e,`--json`)}),command$1(`migrate`,`Import state from another agent system`,true),command$1(`storage`,`List, initialize, and test configured storage locations`,true,{parentDefaultHelp:true,machineOutput:({argv:e})=>hasMachineOutputOption(e,`--json`)}),command$1(`doctor`,`Health checks + quick fixes for the gateway and channels`,false,{machineOutput:isDoctorMachineOutput}),command$1(`triage`,`Collect sanitized diagnostics and open a local coding agent for repair`,false,{machineOutput:({argv:e})=>hasMachineOutputOption(e,`--json`)}),command$1(`dashboard`,`Open the Control UI with your current token`,false),command$1(`reset`,`Reset local config/state (keeps the CLI installed)`,false),command$1(`uninstall`,`Uninstall the gateway service + local data`,false),command$1(`message`,`Send, read, and manage messages and channel actions`,true),command$1(`mcp`,`Manage OpenClaw mcp.servers config and channel bridge`,true,{parentDefaultHelp:true}),command$1(`transcripts`,`Inspect stored transcripts`,true),command$1(`agent`,`Run an agent turn via the Gateway (use --local for embedded)`,true),command$1(`agents`,`Manage isolated agents (workspaces + auth + routing)`,true),command$1(`status`,`Show channel health and recent session recipients`,false),command$1(`health`,`Fetch health from the running gateway`,false),command$1(`audit`,`Inspect activity records and exact-run identity context`,false),command$1(`sessions`,`List stored conversation sessions`,true)];
//!src/cli/program/private-qa-policy.ts
function isPrivateQaCliEnabled(e=process.env){return e.OPENCLAW_ENABLE_PRIVATE_QA_CLI===`1`}
//!src/cli/program/subcli-command-metadata.ts
function command(e,t,n={}){return{name:e,description:t,hasSubcommands:true,...n}}const commands=[command(`acp`,`Run an ACP bridge backed by the Gateway`),command(`gateway`,`Run, inspect, and query the WebSocket Gateway`),command(`daemon`,`Manage the Gateway service (launchd/systemd/schtasks)`),command(`logs`,`Tail gateway file logs via RPC`,{hasSubcommands:false}),command(`system`,`System tools (events, heartbeat, presence)`),command(`models`,`Model discovery, scanning, and configuration`),command(`promos`,`Discover and claim promotional model offers from ClawHub`),command(`tools`,`Inspect and manage learned tool usage`,{parentDefaultHelp:true}),command(`telemetry`,`Inspect and manage anonymous usage telemetry`,{parentDefaultHelp:true}),command(`infer`,`Run provider-backed inference commands through a stable CLI surface`),command(`capability`,`Run provider capability commands (fallback alias: infer)`),command(`approvals`,`Manage approval policy and pending requests`,{parentDefaultHelp:true}),command(`exec-approvals`,`Manage exec approvals (alias for approvals)`),command(`exec-policy`,`Show or synchronize requested exec policy with host approvals`),command(`nodes`,`Manage gateway-owned nodes (pairing, status, invoke, and media)`),command(`devices`,"Device pairing and auth tokens (for mobile app setup codes, use `openclaw qr` instead)",{parentDefaultHelp:true}),command(`users`,`Manage durable user profiles and email aliases`,{parentDefaultHelp:true}),command(`id`,`OpenClaw ID remote access of this machine's Gateway`,{parentDefaultHelp:true}),command(`node`,`Run and manage the headless node host service`),command(`connect`,`Connect this machine to an OpenClaw Gateway as a node`,{hasSubcommands:false}),command(`worker`,`Run the restricted cloud worker runtime`,{hasSubcommands:false}),command(`sandbox`,`Manage sandbox containers (Docker-based agent isolation)`),command(`worktrees`,`Create, inspect, restore, and clean up managed worktrees`,{parentDefaultHelp:true}),command(`attach`,`Attach Claude Code to a gateway session with scoped MCP tools`,{hasSubcommands:false}),command(`tui`,`Open a terminal UI connected to the Gateway`,{hasSubcommands:false}),command(`resume`,`Resume a recent Gateway session in the TUI`,{hasSubcommands:false}),command(`terminal`,`Open a local terminal UI (alias for tui --local)`,{hasSubcommands:false}),command(`chat`,`Open a local terminal UI (alias for tui --local)`,{hasSubcommands:false}),command(`cron`,`Manage automations (via Gateway)`,{parentDefaultHelp:true}),command(`automations`,`Manage automations (alias for cron)`,{parentDefaultHelp:true}),command(`dns`,`DNS helpers for wide-area discovery (Tailscale + CoreDNS)`),command(`docs`,`Search the live OpenClaw docs`,{hasSubcommands:false}),command(`qa`,`Run QA scenarios and launch the private QA debugger UI`),command(`proxy`,`Run the OpenClaw debug proxy and inspect captured traffic`),command(`hooks`,`Manage internal agent hooks`),command(`webhooks`,`Webhook helpers and integrations`),command(`qr`,`Generate a mobile pairing QR code and setup code`,{hasSubcommands:false}),command(`pair`,`Approve a browser showing a pairing code`,{hasSubcommands:false}),command(`clawbot`,`Legacy clawbot command aliases`),command(`pairing`,`Secure DM pairing (approve inbound requests)`),command(`plugins`,`Manage OpenClaw plugins and extensions`,{parentDefaultHelp:true}),command(`channels`,`Manage connected chat channels and accounts`,{parentDefaultHelp:true}),command(`directory`,`Lookup contact and group IDs (self, peers, groups) for supported chat channels`),command(`security`,`Audit local config and state for common security foot-guns`),command(`secrets`,`Secrets runtime controls`),command(`skills`,`List and inspect available skills`),command(`update`,`Update OpenClaw and inspect update channel status`),command(`completion`,`Generate shell completion script`,{hasSubcommands:false})];function getSubCliCommandMetadata(){return isPrivateQaCliEnabled()?commands:commands.filter(e=>e.name!==`qa`)}const SUB_CLI_COMMAND_METADATA=getSubCliCommandMetadata();
//!src/cli/argv.ts
const HELP_FLAGS=/* @__PURE__ */ new Set([`-h`,`--help`]);const ROOT_VERSION_ALIAS_FLAGS=/* @__PURE__ */ new Set([`-v`]);const VERSION_FLAGS=/* @__PURE__ */ new Set([`-V`,`--version`,...ROOT_VERSION_ALIAS_FLAGS]);const ROOT_COMMAND_DESCRIPTORS=[...CORE_CLI_COMMAND_DESCRIPTORS,...SUB_CLI_COMMAND_METADATA];const KNOWN_ROOT_COMMANDS=new Set(ROOT_COMMAND_DESCRIPTORS.map(e=>e.name));const ROOT_COMMANDS_WITH_SUBCOMMANDS=new Set(ROOT_COMMAND_DESCRIPTORS.filter(e=>e.hasSubcommands).map(e=>e.name));function isHelpOrVersionInvocation(e){if(isRootVersionInvocation(e))return true;const t=e.slice(2);let n=false;let r=false;const i=[];for(let e=0;e<t.length;e+=1){const a=t[e];if(!a)break;if(!r&&a===`--`){r=true;continue}const o=r?0:consumeRootOptionToken(t,e);if(o>0){e+=o-1;continue}if(!r&&HELP_FLAGS.has(a))return true;if(!r&&a.startsWith(`-`)){n=true;continue}i.push(a);if(a!==`help`)continue;if(n)return false;if(i.length===1)return true;const[s]=i;if(!s||!KNOWN_ROOT_COMMANDS.has(s))return true;if(i.length===2&&ROOT_COMMANDS_WITH_SUBCOMMANDS.has(s))return true;return false}return false}function isRootVersionInvocation(e){return isRootInvocationForFlags(e,VERSION_FLAGS)}function isRootInvocationForFlags(e,t){const n=e.slice(2);let r=false;for(let e=0;e<n.length;e+=1){const i=n[e];if(!i)continue;if(i===`--`)break;if(t.has(i)){r=true;continue}const a=consumeRootOptionToken(n,e);if(a>0){e+=a-1;continue}return false}return r}function isRootHelpInvocation(e){return isRootInvocationForFlags(e,HELP_FLAGS)}function getCommandPathWithRootOptions(e,t=2){return getRootOptionAwareCommandPath(e,t)}function getPrimaryCommand(e){const[t]=getCommandPathWithRootOptions(e,1);return t??null}const GATEWAY_RUN_VALUE_FLAGS=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]);const GATEWAY_RUN_BOOLEAN_FLAGS=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);
//!src/daemon/windows-task-supervisor-contract.ts
const WINDOWS_TASK_SUPERVISOR_FLAG=`--task-supervisor`;const WINDOWS_TASK_SUPERVISOR_CHILD_FLAG=`--task-supervisor-child`;
//!src/cli/gateway-run-argv.ts
function resolveGatewayCommandPath(e,t=2){const n=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...GATEWAY_RUN_BOOLEAN_FLAGS,WINDOWS_TASK_SUPERVISOR_FLAG],valueFlags:[...GATEWAY_RUN_VALUE_FLAGS,WINDOWS_TASK_SUPERVISOR_CHILD_FLAG],maxPositionals:t-1,mode:`command-path`});return n?[`gateway`,...n]:null}
//!src/cli/argv-invocation.ts
function resolveCliArgvInvocation(e){return{argv:e,commandPath:resolveGatewayCommandPath(e)??resolveCliParentCommandPath(e)??getCommandPathWithRootOptions(e,2),primary:getPrimaryCommand(e),hasHelpOrVersion:isHelpOrVersionInvocation(e),isRootHelpInvocation:isRootHelpInvocation(e)}}
//!src/cli/root-option-scan.ts
function scanCliRootOptions(e,t){if(e.length<2)return{ok:true,argv:e};const n=e.slice(0,2);const r=e.slice(2);for(let e=0;e<r.length;e+=1){const i=r[e];if(i===void 0)continue;if(i===`--`){n.push(i,...r.slice(e+1));break}const a=t({arg:i,args:r,index:e,out:n});if(a.kind===`error`)return{ok:false,error:a.error};if(a.kind===`handled`){if(a.consumedNext)e+=1;continue}const o=consumeRootOptionToken(r,e);if(o>0){n.push(...r.slice(e,e+o));e+=o-1;continue}n.push(i)}return{ok:true,argv:n}}
//!src/infra/inline-option-token.ts
function parseInlineOptionToken(e){const t=e.indexOf(`=`);if(t<0)return{name:e,hasInlineValue:false};return{name:e.slice(0,t),hasInlineValue:true,inlineValue:e.slice(t+1)}}
//!src/cli/root-option-value.ts
function takeCliRootOptionValue(e,t){const n=parseInlineOptionToken(e);if(n.hasInlineValue)return{value:(n.inlineValue??``).trim()||null,consumedNext:false};const r=isValueToken(t);return{value:(r?t.trim():``)||null,consumedNext:r}}
//!src/cli/container-target.ts
function parseCliContainerArgs(e){let t=null;const n=scanCliRootOptions(e,({arg:e,args:n,index:r})=>{if(e===`--container`||e.startsWith(`--container=`)){const i=n[r+1];const{value:a,consumedNext:o}=takeCliRootOptionValue(e,i);if(!a)return{kind:`error`,error:`--container requires a value`};t=a;return{kind:`handled`,consumedNext:o}}return{kind:`pass`}});return n.ok?{ok:true,container:t,argv:n.argv}:n}
//!src/cli/profile-utils.ts
const PROFILE_NAME_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/i;function isValidProfileName(e){return PROFILE_NAME_RE.test(e)}function normalizeProfileName(e){const t=e?.trim();if(!t)return null;if(normalizeLowercaseStringOrEmpty(t)==="default")return null;if(!isValidProfileName(t))return null;return t}function resolveProfileGatewayPort(e){if(e===`dev`)return 19001;let t=2166136261;for(const n of Buffer.from(e,`utf8`))t=Math.imul(t^n,16777619)>>>0;return 2e4+t%4e4}function resolveProfileStateDir(e,t,n){const r=e.trim();if(!isValidProfileName(r))throw new Error(`Invalid profile name: ${JSON.stringify(e)}`);const i=normalizeLowercaseStringOrEmpty(r)==="default"?``:`-${r}`;return path.join(resolveRequiredHomeDir(t,n),`.openclaw${i}`)}
//!src/cli/profile.ts
function parseCliProfileArgs(e,t){let n=null;let r=false;const i=scanCliRootOptions(e,({arg:e,args:t,index:i,out:a})=>{if(e===`--dev`){if(resolveCliArgvInvocation(a).primary===`gateway`){a.push(e);return{kind:`handled`}}if(n&&n!==`dev`)return{kind:`error`,error:`Cannot combine --dev with --profile`};r=true;n=`dev`;return{kind:`handled`}}if(e===`--profile`||e.startsWith(`--profile=`)){const o=t[i+1];const{value:s,consumedNext:c}=takeCliRootOptionValue(e,o);const[l,u]=resolveCliArgvInvocation(a).commandPath;if(l===`qa`&&u===`matrix`){a.push(e);if(c&&o!==void 0)a.push(o);return{kind:`handled`,consumedNext:c}}if(r)return{kind:`error`,error:`Cannot combine --dev with --profile`};if(!s)return{kind:`error`,error:`--profile requires a value`};if(!isValidProfileName(s))return{kind:`error`,error:`Invalid --profile (use letters, numbers, "_", "-" only)`};n=s;return{kind:`handled`,consumedNext:c}}return{kind:`pass`}});if(!i.ok)return i;const a=t===void 0?parseCliContainerArgs(e):null;return t??(a?.ok?a.container:null)??normalizeOptionalString(process.env.OPENCLAW_CONTAINER)?{ok:true,profile:n,argv:i.argv}:selectPairCodeProfile(i.argv,n)}function selectPairCodeProfile(e,t){const[n]=getCommandPositionalsWithRootOptions(e,{commandPath:[`pair`],booleanFlags:[`--yes`,`--json`,`--expect-final`],valueFlags:[`--url`,`--port`,`--token`,`--password`,`--timeout`],maxPositionals:1,mode:`command-path`})??[];const r=n?splitBrowserPairCodeProfile(n).profile:null;if(r===null)return{ok:true,profile:t,argv:e};if(!isValidProfileName(r))return{ok:false,error:`The pairing code names an invalid profile "${r}". Copy the code shown in the browser again.`};if(t&&t!==r)return{ok:false,error:`This pairing code is for profile "${r}", but profile "${t}" was selected. Drop --profile or use the matching one.`};return{ok:true,profile:r,argv:e}}function applyCliProfileEnv(e){const t=e.env??process.env;const n=e.homedir??os.homedir;const r=e.profile.trim();if(!r)return;const i=normalizeOptionalString(t.OPENCLAW_PROFILE)??`default`;const a=normalizeOptionalString(t.OPENCLAW_STATE_DIR);const o=normalizeOptionalString(t.OPENCLAW_CONFIG_PATH);const s=resolveProfileStateDir(i,t,n);const c=resolveProfileStateDir(r,t,n);const l=s!==c;const u=resolveGatewaySystemdServiceName(i);const d={OPENCLAW_LAUNCHD_LABEL:[resolveGatewayLaunchAgentLabel(i)],OPENCLAW_SYSTEMD_UNIT:[u,`${u}.service`],OPENCLAW_WINDOWS_TASK_NAME:[resolveGatewayWindowsTaskName(i)]};const f=Boolean(a&&l&&resolveHomeRelativePath(a,{env:t,homedir:n})===s);const p=Boolean(l&&(!a||f)&&o&&resolveHomeRelativePath(o,{env:t,homedir:n})===path.join(s,`openclaw.json`));const m=isGatewayServiceEnv(t)&&f&&p;if(m)for(const e of GATEWAY_SERVICE_SELECTOR_ENV_KEYS)delete t[e];t.OPENCLAW_PROFILE=r;const h=a&&!f?a:c;if(!a||f)t.OPENCLAW_STATE_DIR=h;if(!m&&(!o||p))t.OPENCLAW_CONFIG_PATH=path.join(h,`openclaw.json`);if(l&&!m)for(const[e,n]of Object.entries(d)){const r=normalizeOptionalString(t[e]);if(r&&n.includes(r))delete t[e]}if(r===`dev`&&!t.OPENCLAW_GATEWAY_PORT?.trim())t.OPENCLAW_GATEWAY_PORT=String(resolveProfileGatewayPort(r))}
//!src/infra/lru-cache.ts
var LruCache=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??Number.POSITIVE_INFINITY;this.#n=t?.sizeOf}get size(){return this.#r.size}clear(){this.#r.clear();this.#i=0}keys(){return this.#r.keys()}delete(e){if(!this.#r.has(e))return false;this.#i-=this.#n?.(this.#r.get(e))??0;return this.#r.delete(e)}deleteValue(e){for(const[t,n]of this.#r)if(n===e)this.delete(t)}peek(e){return this.#r.get(e)}get(e){if(!this.#r.has(e))return;const t=this.#r.get(e);this.#r.delete(e);this.#r.set(e,t);return t}set(e,t){this.delete(e);this.#r.set(e,t);this.#i+=this.#n?.(t)??0;for(const e of this.#r.keys()){if(this.#r.size<=this.#e&&this.#i<=this.#t)break;this.delete(e)}}};
//!src/config/state-dir.ts
const absoluteStateDirs=new LruCache(64);function resolveNewStateDir(e=resolveRequiredHomeDir){return path.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=os.homedir){const n=e.OPENCLAW_STATE_DIR?.trim();if(n&&process.platform!==`win32`&&path.isAbsolute(n)){const e=absoluteStateDirs.peek(n);if(e!==void 0)return e;const t=path.resolve(n);absoluteStateDirs.set(n,t);return t}if(n)return resolveHomeRelativePath(n,{env:e,homedir:t});return resolveStateDirFromHome(e,()=>resolveRequiredHomeDir(e,t))}function resolveStateDirFromHome(e,t){const n=normalizeProfileName(e.OPENCLAW_PROFILE);return n?resolveProfileStateDir(n,e,t):resolveNewStateDir(t)}
//!src/infra/config-dir.ts
function resolveConfigDir(e=process.env,t=os.homedir){const n=e.OPENCLAW_STATE_DIR?.trim();if(n)return resolveUserPath(n,e,t);const r=e.OPENCLAW_CONFIG_PATH?.trim();if(r)return path.dirname(resolveUserPath(r,e,t));return resolveStateDir(e,t)}
//!src/shared/environment-key.ts
const processEnvironment=resolveGlobalSingleton(Symbol.for(`openclaw.processEnvironmentKey`),()=>({key:{},aliases:new WeakSet([process.env])}));function resolveEnvironmentKey(e){if(e===void 0||e===process.env)return processEnvironment.key;return processEnvironment.aliases.has(e)?processEnvironment.key:e}function captureEnvironmentKey(e=process.env){const t=resolveEnvironmentKey(e);if(t===processEnvironment.key)processEnvironment.aliases.add(e);return t}
//!src/infra/fs-safe-env.ts
const nativeModeKey=`OPENCLAW_FS_SAFE_NATIVE_MODE`;const legacyModeKeys=[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`];const legacyKeys=[...legacyModeKeys,`FS_SAFE_PYTHON`,`OPENCLAW_FS_SAFE_PYTHON`,`OPENCLAW_PINNED_PYTHON`,`OPENCLAW_PINNED_WRITE_PYTHON`];const fallbacks=/* @__PURE__ */ new WeakMap;let warned=false;function nativeModeIsValid(e){const t=e?.trim().toLowerCase()??``;return/^(?:0|false|off|never|1|true|on|auto|required|require)$/u.test(t)}function currentFallback(e){const t=fallbacks.get(resolveEnvironmentKey(e));return t&&e[t.key]===t.value?t:void 0}function clearFsSafeEnvFallback(e){const t=currentFallback(e);fallbacks.delete(resolveEnvironmentKey(e));if(!t)return;if(!t.existed)delete e[t.key];else e[t.key]=t.previous}function normalizeFsSafeNativeEnv(e=process.env){clearFsSafeEnvFallback(e);const t=legacyKeys.filter(t=>e[t]!==void 0);if(t.length&&e===process.env&&!warned){warned=true;process.emitWarning(`${t.join(`, `)} is deprecated. OpenClaw maps legacy mode values to native mode only when neither FS_SAFE_NATIVE_MODE nor OPENCLAW_FS_SAFE_NATIVE_MODE selects a mode. Replace Python mode variables with native mode variables; interpreter path settings are ignored.`,{code:`FS_SAFE_PYTHON_DEPRECATED`,type:`DeprecationWarning`})}if(nativeModeIsValid(e.FS_SAFE_NATIVE_MODE)||nativeModeIsValid(e[nativeModeKey]))return;const n=legacyModeKeys.map(t=>e[t]).find(e=>e!==void 0);if(n===void 0)return;const r=Object.keys(e);const i=!r.includes(nativeModeKey)&&Object.hasOwn(e,nativeModeKey)?r.find(e=>e.toUpperCase()===nativeModeKey)??nativeModeKey:nativeModeKey;const a=Object.hasOwn(e,i);const o=e[i];e[i]=n;fallbacks.set(captureEnvironmentKey(e),{key:i,value:n,previous:o,existed:a})}
//!src/infra/host-env-security-policy.json
var host_env_security_policy_default={blockedEverywhereKeys:[`NODE_OPTIONS`,`NODE_PATH`,`NODE_REDIRECT_WARNINGS`,`NODE_REPL_EXTERNAL_MODULE`,`NODE_REPL_HISTORY`,`NODE_V8_COVERAGE`,`PYTHONHOME`,`PYTHONPATH`,`PERL5LIB`,`PERL5OPT`,`PERL5SHELL`,`PERLLIB`,`RUBYLIB`,`RUBYOPT`,`BASHOPTS`,`BASH_ENV`,`ENV`,`KSH_ENV`,`BROWSER`,`GIT_ALLOW_PROTOCOL`,`GIT_EDITOR`,`GIT_EXTERNAL_DIFF`,`GIT_DIR`,`GIT_WORK_TREE`,`GIT_COMMON_DIR`,`GIT_EXEC_PATH`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_NAMESPACE`,`GIT_PROTOCOL_FROM_USER`,`GIT_SEQUENCE_EDITOR`,`GIT_TEMPLATE_DIR`,`GIT_SSL_NO_VERIFY`,`GIT_SSL_CAINFO`,`GIT_SSL_CAPATH`,`CC`,`CPP`,`CXX`,`CXXCPP`,`CARGO_BUILD_RUSTC`,`CARGO_BUILD_RUSTC_WRAPPER`,`CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER`,`CARGO_BUILD_RUSTDOC`,`RUSTC`,`RUSTC_WRAPPER`,`RUSTC_WORKSPACE_WRAPPER`,`RUSTDOC`,`CMAKE_C_COMPILER`,`CMAKE_CXX_COMPILER`,`SHELL`,`SHELLOPTS`,`PS4`,`GCONV_PATH`,`IFS`,`SSLKEYLOGFILE`,`JAVA_OPTS`,`JAVA_TOOL_OPTIONS`,`_JAVA_OPTIONS`,`JDK_JAVA_OPTIONS`,`PYTHONBREAKPOINT`,`DOTNET_STARTUP_HOOKS`,`DOTNET_ADDITIONAL_DEPS`,`FPATH`,`GLIBC_TUNABLES`,`MAVEN_OPTS`,`MAKE`,`MAKEFLAGS`,`MFLAGS`,`SBT_OPTS`,`GRADLE_OPTS`,`ANT_OPTS`,`HGRCPATH`,`HGEDITOR`,`HGMERGE`,`EXINIT`,`VIMINIT`,`MYVIMRC`,`GVIMINIT`,`LUA_INIT`,`LUA_INIT_5_1`,`LUA_INIT_5_2`,`LUA_INIT_5_3`,`LUA_INIT_5_4`,`EMACSLOADPATH`,`RUBYSHELL`,`GIT_HOOK_PATH`,`SVN_EDITOR`,`SVN_SSH`,`BZR_EDITOR`,`BZR_SSH`,`BZR_PLUGIN_PATH`,`SUDO_ASKPASS`,`JULIA_EDITOR`,`CONFIG_SITE`,`CONFIG_SHELL`,`CMAKE_TOOLCHAIN_FILE`,`CATALINA_OPTS`,`CORECLR_PROFILER`,`HELM_PLUGINS`,`PACKER_PLUGIN_PATH`,`VAGRANT_VAGRANTFILE`,`ERL_AFLAGS`,`ERL_FLAGS`,`ERL_ZFLAGS`,`ELIXIR_ERL_OPTIONS`,`R_ENVIRON`,`R_PROFILE`,`R_ENVIRON_USER`,`R_PROFILE_USER`,`TCLLIBPATH`,`HOSTALIASES`],blockedOverrideOnlyKeys:[`HOME`,`GRADLE_USER_HOME`,`ZDOTDIR`,`GIT_DIR`,`GIT_WORK_TREE`,`GIT_COMMON_DIR`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_NAMESPACE`,`GIT_SSH_COMMAND`,`GIT_SSH`,`GIT_PROXY_COMMAND`,`GIT_ASKPASS`,`GIT_SSL_NO_VERIFY`,`GIT_SSL_CAINFO`,`GIT_SSL_CAPATH`,`SSH_ASKPASS`,`LESSOPEN`,`LESSCLOSE`,`PAGER`,`MANPAGER`,`GIT_PAGER`,`EDITOR`,`VISUAL`,`FCEDIT`,`SUDO_EDITOR`,`PROMPT_COMMAND`,`HISTFILE`,`PERL5DB`,`PERL5DBCMD`,`OPENSSL_CONF`,`OPENSSL_ENGINES`,`PYTHONSTARTUP`,`WGETRC`,`CURL_HOME`,`CLASSPATH`,`CFLAGS`,`CGO_CFLAGS`,`CGO_LDFLAGS`,`GOFLAGS`,`MAKEFLAGS`,`MFLAGS`,`CORECLR_PROFILER_PATH`,`PHPRC`,`PHP_INI_SCAN_DIR`,`DENO_DIR`,`BUN_CONFIG_REGISTRY`,`YARN_RC_FILENAME`,`HTTP_PROXY`,`HTTPS_PROXY`,`ALL_PROXY`,`NO_PROXY`,`NODE_TLS_REJECT_UNAUTHORIZED`,`NODE_EXTRA_CA_CERTS`,`SSL_CERT_FILE`,`SSL_CERT_DIR`,`REQUESTS_CA_BUNDLE`,`CURL_CA_BUNDLE`,`DOCKER_HOST`,`DOCKER_TLS_VERIFY`,`DOCKER_CERT_PATH`,`PIP_INDEX_URL`,`PIP_PYPI_URL`,`PIP_EXTRA_INDEX_URL`,`PIP_CONFIG_FILE`,`PIP_FIND_LINKS`,`PIP_TRUSTED_HOST`,`UV_INDEX`,`UV_INDEX_URL`,`UV_PYTHON`,`UV_EXTRA_INDEX_URL`,`UV_DEFAULT_INDEX`,`DOCKER_CONTEXT`,`LIBRARY_PATH`,`LDFLAGS`,`CPATH`,`C_INCLUDE_PATH`,`CPLUS_INCLUDE_PATH`,`OBJC_INCLUDE_PATH`,`GOPROXY`,`GONOSUMCHECK`,`GONOSUMDB`,`GONOPROXY`,`GOPRIVATE`,`GOENV`,`GOPATH`,`HGRCPATH`,`PYTHONUSERBASE`,`RUSTC_WRAPPER`,`RUSTFLAGS`,`RUSTUP_DIST_ROOT`,`RUSTUP_DIST_SERVER`,`RUSTUP_HOME`,`RUSTUP_TOOLCHAIN`,`RUSTUP_UPDATE_ROOT`,`CARGO_HOME`,`VIRTUAL_ENV`,`LUA_PATH`,`LUA_CPATH`,`GEM_HOME`,`GEM_PATH`,`BUNDLE_GEMFILE`,`COMPOSER_HOME`,`CONDA_DEFAULT_ENV`,`CONDA_PREFIX`,`CARGO_BUILD_RUSTC_WRAPPER`,`XDG_CACHE_HOME`,`XDG_CONFIG_DIRS`,`XDG_CONFIG_HOME`,`XDG_DATA_DIRS`,`XDG_DATA_HOME`,`XDG_RUNTIME_DIR`,`XDG_STATE_HOME`,`AWS_CONFIG_FILE`,`KUBECONFIG`,`GOOGLE_APPLICATION_CREDENTIALS`,`AWS_SHARED_CREDENTIALS_FILE`,`AWS_WEB_IDENTITY_TOKEN_FILE`,`AZURE_AUTH_LOCATION`,`HELM_HOME`,`ANSIBLE_CONFIG`,`ANSIBLE_LIBRARY`,`ANSIBLE_CALLBACK_PLUGINS`,`ANSIBLE_COLLECTIONS_PATH`,`ANSIBLE_CONNECTION_PLUGINS`,`ANSIBLE_FILTER_PLUGINS`,`ANSIBLE_INVENTORY_PLUGINS`,`ANSIBLE_LOOKUP_PLUGINS`,`ANSIBLE_MODULE_UTILS`,`ANSIBLE_REMOTE_TEMP`,`ANSIBLE_ROLES_PATH`,`ANSIBLE_STRATEGY_PLUGINS`,`R_LIBS_USER`,`TF_CLI_CONFIG_FILE`,`TF_PLUGIN_CACHE_DIR`,`AMQP_URL`,`AWS_ACCESS_KEY_ID`,`AWS_CONTAINER_CREDENTIALS_FULL_URI`,`AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`,`AWS_SECRET_ACCESS_KEY`,`AWS_SECURITY_TOKEN`,`AWS_SESSION_TOKEN`,`AZURE_CLIENT_ID`,`AZURE_CLIENT_SECRET`,`DATABASE_URL`,`GH_TOKEN`,`GITHUB_TOKEN`,`GITLAB_TOKEN`,`MONGODB_URI`,`NODE_AUTH_TOKEN`,`NPM_TOKEN`,`REDIS_URL`,`SSH_AUTH_SOCK`,`SYSTEMROOT`,`WINDIR`],allowedInheritedOverrideOnlyKeys:[`ALL_PROXY`,`AWS_CONFIG_FILE`,`AWS_SHARED_CREDENTIALS_FILE`,`AWS_WEB_IDENTITY_TOKEN_FILE`,`AZURE_AUTH_LOCATION`,`CURL_CA_BUNDLE`,`DOCKER_CERT_PATH`,`DOCKER_CONTEXT`,`DOCKER_HOST`,`DOCKER_TLS_VERIFY`,`GIT_PAGER`,`GOOGLE_APPLICATION_CREDENTIALS`,`GRADLE_USER_HOME`,`HISTFILE`,`HOME`,`HTTPS_PROXY`,`HTTP_PROXY`,`KUBECONFIG`,`MANPAGER`,`NODE_EXTRA_CA_CERTS`,`NODE_TLS_REJECT_UNAUTHORIZED`,`NO_PROXY`,`PAGER`,`REQUESTS_CA_BUNDLE`,`RUSTUP_DIST_ROOT`,`RUSTUP_DIST_SERVER`,`RUSTUP_HOME`,`RUSTUP_TOOLCHAIN`,`RUSTUP_UPDATE_ROOT`,`SSH_AUTH_SOCK`,`SSL_CERT_DIR`,`SSL_CERT_FILE`,`SYSTEMROOT`,`WINDIR`,`XDG_CACHE_HOME`,`XDG_CONFIG_DIRS`,`XDG_CONFIG_HOME`,`XDG_DATA_DIRS`,`XDG_DATA_HOME`,`XDG_RUNTIME_DIR`,`XDG_STATE_HOME`,`ZDOTDIR`],blockedOverridePrefixes:[`GIT_CONFIG_`,`NPM_CONFIG_`,`CARGO_REGISTRIES_`,`TF_VAR_`],blockedPrefixes:[`DYLD_`,`LD_`,`BASH_FUNC_`]};
//!src/infra/host-env-security-policy.js
function sortUniqueUppercase(e){return Object.freeze(Array.from(new Set(e.map(e=>e.toUpperCase()))).toSorted((e,t)=>e<t?-1:e>t?1:0))}function derivePolicyArrays(e){const t=e.blockedEverywhereKeys??[];const n=e.blockedOverrideOnlyKeys??[];const r=e.allowedInheritedOverrideOnlyKeys??[];const i=new Set(r.map(e=>e.toUpperCase()));const a=e.blockedPrefixes??[];const o=e.blockedOverridePrefixes??[];const s=e.blockedInheritedPrefixes??a;return{blockedInheritedKeys:sortUniqueUppercase([...t,...n.filter(e=>!i.has(e.toUpperCase()))]),blockedInheritedPrefixes:sortUniqueUppercase(s),blockedKeys:sortUniqueUppercase(t),blockedOverrideKeys:sortUniqueUppercase(n),blockedPrefixes:sortUniqueUppercase(a),blockedOverridePrefixes:sortUniqueUppercase(o)}}function loadHostEnvSecurityPolicy(e=host_env_security_policy_default){const t=derivePolicyArrays(e);return Object.freeze({blockedEverywhereKeys:Object.freeze(e.blockedEverywhereKeys??[]),blockedOverrideOnlyKeys:Object.freeze(e.blockedOverrideOnlyKeys??[]),allowedInheritedOverrideOnlyKeys:Object.freeze(e.allowedInheritedOverrideOnlyKeys??[]),blockedInheritedKeys:t.blockedInheritedKeys,blockedInheritedPrefixes:t.blockedInheritedPrefixes,blockedPrefixes:t.blockedPrefixes,blockedOverridePrefixes:t.blockedOverridePrefixes,blockedKeys:t.blockedKeys,blockedOverrideKeys:t.blockedOverrideKeys})}const HOST_ENV_SECURITY_POLICY=loadHostEnvSecurityPolicy();
//!src/infra/host-env-security.ts
const PORTABLE_ENV_VAR_KEY=/^[A-Za-z_][A-Za-z0-9_]*$/;const HOST_DANGEROUS_ENV_KEYS=new Set(HOST_ENV_SECURITY_POLICY.blockedKeys);const HOST_DANGEROUS_INHERITED_ENV_KEYS=new Set(HOST_ENV_SECURITY_POLICY.blockedInheritedKeys);const HOST_DANGEROUS_OVERRIDE_ENV_KEYS=new Set(HOST_ENV_SECURITY_POLICY.blockedOverrideKeys);const NODE_SERVICE_ENV_KEYS=/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`]);NODE_SERVICE_ENV_KEYS.delete(`OPENCLAW_PROFILE`);const scopedBlockedInheritedEnvKeys=new AsyncLocalStorage;function normalizeEnvVarKey(e,t){const n=e.trim();if(!n)return null;if(t?.portable&&!PORTABLE_ENV_VAR_KEY.test(n))return null;return n}
//!src/infra/dotenv-global-core.ts
const MAX_DOTENV_FILE_BYTES=1048576;function parseDotEnvFile(e,t){const n=[];for(const[r,i]of Object.entries(parse(t))){const t=normalizeEnvVarKey(r,{portable:true});if(t&&(e.entryFilter?.(t,i)??true))n.push({key:t,value:i})}return{filePath:e.filePath,entries:n}}function readDotEnvFileCore(e){let t;try{const n=fs.realpathSync(e.filePath);const{buffer:r}=readRegularFileSync({filePath:n,maxBytes:MAX_DOTENV_FILE_BYTES});t=r}catch{return null}return parseDotEnvFile(e,t)}function loadParsedDotEnvFiles(e,t,n,r){clearFsSafeEnvFallback(t);const i=new Set(Object.keys(t));const canonicalizeKey=e=>normalizeEnvVarKey(e,{portable:true})?.toUpperCase()??null;const a=new Set([...n??[]].flatMap(e=>{const t=canonicalizeKey(e);return t?[t]:[]}));const o=/* @__PURE__ */ new Map;const s=/* @__PURE__ */ new Map;const c=/* @__PURE__ */ new Map;for(const n of e)for(const{key:e,value:r}of n.entries){const l=canonicalizeKey(e);const u=l!==null&&a.has(l);const d=u&&l?l:e;if(i.has(e)&&!u)continue;const f=s.get(d);if(f){if(f.value!==r){const t=`${f.filePath}\u0000${n.filePath}`;const r=o.get(t);if(r)r.keys.add(e);else o.set(t,{keptPath:f.filePath,ignoredPath:n.filePath,keys:/* @__PURE__ */ new Set([e])})}continue}s.set(d,{value:r,filePath:n.filePath});if(t[e]===void 0||u){if(u){for(const e of i)if(canonicalizeKey(e)===l)t[e]=r}t[e]=r;const a=c.get(n.filePath);if(a)a.push(e);else c.set(n.filePath,[e])}}normalizeFsSafeNativeEnv(t);for(const e of o.values()){const t=[...e.keys].toSorted();r?.(`Conflicting values in ${e.keptPath} and ${e.ignoredPath} for ${t.join(`, `)}; keeping ${e.keptPath}.`,{keptPath:e.keptPath,ignoredPath:e.ignoredPath,keys:t})}return c}function resolveGlobalDotEnvFiles(e,t){const n=e.stateEnvPath??path.join(resolveConfigDir(t),`.env`);const r=[.../* @__PURE__ */ new Set([n,...e.additionalEnvPaths??[]])];const i=resolveRequiredHomeDir(t,os.homedir);const a=path.join(i,`.openclaw`,`.env`);const o=t.OPENCLAW_STATE_DIR?.trim()!==void 0&&path.resolve(n)!==path.resolve(a);const s={entryFilter:e.entryFilter};return{globalFiles:r.map(e=>Object.assign({},s,{filePath:e})),gatewayFile:o?void 0:{...s,filePath:path.join(i,`.config`,`openclaw`,`gateway.env`)}}}function applyGlobalDotEnvFiles(e,t,n,r,i){const a=[...e,t].filter(e=>e!==null);const o=loadParsedDotEnvFiles(a,n,r,i);return{dotenvPresentKeys:[...new Set(a.flatMap(e=>e.entries.map(({key:e})=>e)))],stateEnvAppliedKeys:e.flatMap(e=>e?o.get(e.filePath)??[]:[]),gatewayEnvAppliedKeys:t?o.get(t.filePath)??[]:[]}}function loadGlobalRuntimeDotEnvFilesCore(e={}){const t=e.env??process.env;const{globalFiles:n,gatewayFile:r}=resolveGlobalDotEnvFiles(e,t);return applyGlobalDotEnvFiles(n.map(readDotEnvFileCore),r?readDotEnvFileCore(r):null,t,e.overrideKeys,e.onWarning)}
//!src/infra/semver.ts
const RELEASE_PREFIX_RE=/^\d{4}\./;function isOpenClawCorrectionSemver(e){return e.prerelease.length===1&&typeof e.prerelease[0]===`number`}function toOpenClawComparableVersion(e){if(isOpenClawCorrectionSemver(e))return`${e.major}.${e.minor}.${e.patch}+${e.prerelease[0]}`;return e.version}function compareOpenClawSemver(e,t){return compareBuild(toOpenClawComparableVersion(e),toOpenClawComparableVersion(t))}function parseOpenClawReleaseVersion(e){const t=e.trim();const n=RELEASE_PREFIX_RE.test(t)?parse$1(t):null;if(!n||n.build.length>0)return null;if(n.minor<1||n.minor>12||n.patch<1)return null;const[r,i]=n.prerelease;const a=n.prerelease.length===0;const o=isOpenClawCorrectionSemver(n)&&typeof r===`number`&&r>0;const s=n.prerelease.length===2&&(r===`alpha`||r===`beta`)&&typeof i===`number`&&i>0;if(!a&&!o&&!s)return null;return n}function compareOpenClawReleaseVersions(e,t){const n=parseOpenClawReleaseVersion(e);const r=parseOpenClawReleaseVersion(t);return n&&r?compareOpenClawSemver(n,r):null}
//!src/infra/path-guards.ts
function normalizeWindowsPathPreservingCase(e){const t=path.win32.normalize(e);if(!t.startsWith(`\\\\?\\`))return t;const n=t.slice(4);return n.toUpperCase().startsWith(`UNC\\`)?`\\\\${n.slice(4)}`:n}
//!src/infra/sqlite-worker-identity.ts
const useDatabaseBirthtime=process.platform!==`linux`&&process.platform!==`android`;function normalizeDatabasePath(e){const t=process.platform===`win32`?normalizeWindowsPathPreservingCase(e):e;return process.platform===`win32`&&!/^(?:[a-z]:[\\/]|[\\/]{2})/iu.test(t)?e:t}
//!src/state/openclaw-state-db.paths.ts
const stateSqlitePaths=new LruCache(64);function resolveOpenClawStateSqlitePath(e=process.env){const t=resolveStateDir(e);const n=stateSqlitePaths.peek(t);if(n!==void 0)return n;const r=normalizeDatabasePath(path.join(t,`state`,`openclaw.sqlite`));stateSqlitePaths.set(t,r);return r}
//!src/node-host/launcher-client.ts
function watchNodeHostParentStdin(e){const t=process.stdin;let n=false;const close=()=>{if(!n){n=true;e()}};t.once(`end`,close);t.once(`error`,close);t.once(`close`,close);t.resume();if(t.readableEnded||t.destroyed)queueMicrotask(close);return()=>{n=true;t.off(`end`,close);t.off(`error`,close);t.off(`close`,close);t.pause()}}
//!src/node-host/launcher-bootstrap.ts
function resolveNodeHostLauncherStateDir(e,t){const n=parseCliProfileArgs(e);if(!n.ok)return null;const r={...t};if(n.profile)applyCliProfileEnv({profile:n.profile,env:r});loadGlobalRuntimeDotEnvFilesCore({env:r,stateEnvPath:path.join(resolveStateDir(r),`.env`),onWarning:e=>process.stderr.write(`openclaw: ${e}\n`)});return resolveStateDir(r)}export{compareOpenClawReleaseVersions,resolveNodeHostLauncherStateDir,resolveOpenClawStateSqlitePath,watchNodeHostParentStdin};