UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

28 lines • 31.9 kB
import{C as isRecord,h as normalizeLowercaseStringOrEmpty}from"./global-singleton-CTnqrmaI.js";import{y as canAccessSync}from"./runtime-doctor-migrations-D8alsOFs.js";import"./account-core-34NfXidI.js";import{K as escapeRegExp,V as extractErrorCode,t as createSubsystemLogger}from"./subsystem-ovCC_dQD.js";import{a as runtimeProcessEntrypoints,n as isNodeRuntime,r as resolveRuntimeScriptPosition,t as isBunRuntime}from"./runtime-binary-CSMtzJzW.js";import{i as isPidDefinitelyDead,l as resolveDiagnosticProcessEnv,s as readLinuxProcessStat}from"./pid-alive-DoXpy4Fr.js";import{_ as readProcessGroupMembers}from"./logger-file-worker-DsGWGQt0.js";import{createRequire}from"node:module";import path from"node:path";import fs,{closeSync,openSync}from"node:fs";import{sha256FileSync}from"@openclaw/fs-safe/durability";import{createHash,hash}from"node:crypto";import os from"node:os";import{fileURLToPath,pathToFileURL}from"node:url";import{execFileSync,spawnSync}from"node:child_process";import{ProcSafeError}from"@openclaw/proc-safe/errors";import{readProcessAncestry,readProcessIdentity}from"@openclaw/proc-safe/identity";import{listProcesses,readProcessCommand}from"@openclaw/proc-safe/inspect";import{PinnedProcess}from"@openclaw/proc-safe/windows-job"; //!\0@oxc-project+runtime@0.155.0/helpers/esm/usingCtx.js function _usingCtx(){var e=`function`==typeof SuppressedError?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(null!=t){if(Object(t)!==t)throw new TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol[`for`](`Symbol.asyncDispose`)];if(void 0===r&&(r=t[Symbol.dispose||Symbol[`for`](`Symbol.dispose`)],e))var i=r;if(`function`!=typeof r)throw new TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&1===a)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(1===a)return i!==t?Promise.reject(i):Promise.resolve();if(i!==t)throw i}function err(n){return i=i!==t?new e(n,i):n,next()}return next()}}} //!src/infra/crypto-digest.ts function sha256Base64Url(e){return hash(`sha256`,e,`base64url`)}function sha256FileSync$1(e){const t=openSync(e,`r`);try{return sha256FileSync(t).digest}finally{closeSync(t)}} //!src/infra/container-environment.ts let containerEnvironmentCache;function isContainerEnvironment(){return containerEnvironmentCache??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return true;for(const e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{fs.accessSync(e,fs.constants.F_OK);return true}catch{}try{const e=fs.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return true}catch{}return false}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 s=i?0:consumeRootCommandOptionToken(n,e);if(s>0){e+=s-1;continue}if(!i&&a.startsWith(`-`))continue;r.push(a);if(r.length>=t)break}return r}function rewriteUpdateFlagArgv(e){const t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){const r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];const i=consumeRootOptionToken(e,n);if(i>0){n+=i-1;continue}if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){const a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;const s=a.indexOf(`=`);const c=s===-1?a:a.slice(0,s);if(n.has(c))return s===-1?1:0;if(!r.has(c))return 0;if(s!==-1)return i===`command-path`||a.slice(s+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 s=new Set(t.valueFlags??[]);const c=[];const l=[];const u=[];let f=0;let p=false;for(let e=0;e<i.length;e+=1){const m=i[e];if(m===void 0)break;if(!p&&m===`--`){if(t.mode!==`command-path`)break;p=true;continue}const h=p?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(h>0){(f>0&&a.has(m)?u:l).push(...i.slice(e,e+h));e+=h-1;continue}if(!p&&m.startsWith(`-`)){const n=consumeKnownOptionToken(i,e,a,s,t.mode);if(n===0||f===0)return null;u.push(m);e+=n-1;continue}if(f<t.commandPath.length){if(m!==t.commandPath[f])return null;f+=1;if(n&&f===t.commandPath.length){const t=i.slice(e+1);return p?[`--`,...t]:t}continue}c.push(m);if(!r&&c.length===t.maxPositionals)return c}return f<t.commandPath.length?null:r?{rootOptions:l,commandOptions:u}:c} //!src/plugins/plugin-source-capture-path.ts const PLUGIN_SOURCE_CAPTURE_PREFIX=`openclaw-plugin-build-`;function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)} //!src/infra/gateway-process-argv.ts function normalizeProcArg(e){return normalizeLowercaseStringOrEmpty(e.replaceAll(`\\`,`/`))}const ENTRY_CANDIDATES=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`];function referencesRetainedArtifact(e){return e.split(/[\\/=]/u).some(e=>isLegacyPluginSourceCaptureName(e)||/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e))}function readProcessPackageIdentity(e,t=false){for(let n=e;;){let e;try{e=JSON.parse(fs.readFileSync(path.join(n,`package.json`),`utf8`))}catch(e){const r=path.dirname(n);if(t&&extractErrorCode(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(path.basename(n)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};n=r;continue}return{kind:`unknown`,reason:`could not read package identity`}}if(!isRecord(e)||typeof e.name!==`string`||!e.name.trim()||e.name!==e.name.trim())return{kind:`unknown`,reason:`package identity has no valid name`};return{kind:`package`,name:e.name,scripts:isRecord(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){const t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0));const n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(const e of t)try{n.set(e,fs.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){const e=spawnSync(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:resolveDiagnosticProcessEnv()});if(e.error||e.status!==0&&e.status!==1)return n;const r=e.stdout.split(`\0`);r.pop();const i=/* @__PURE__ */ new Set;let a;for(const e of r){const r=e.replace(/^\n/,``);if(r.startsWith(`p`)){const e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else if(a!==void 0&&r.startsWith(`n`)&&path.isAbsolute(r.slice(1))){if(n.delete(a))i.add(a);else if(!i.has(a))n.set(a,r.slice(1))}}}}catch{}return n}function classifyEntrypoint(e,t={}){const n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};const r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:resolveRuntimeScriptPosition(e).position;if(typeof r!==`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};const i=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&path.isAbsolute(t.cwd)&&isBunRuntime(e[0]??``)&&!/[\\/]/u.test(i)&&!path.extname(i)){const e=readProcessPackageIdentity(t.cwd,true);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};const n=e.kind===`package`?e.scripts[i]:void 0;if(typeof n===`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}const a=classifyOpenClawEntrypointPath(i,t);return a.kind===`openclaw`?{...a,entryIndex:r}:a}function classifyOpenClawEntrypointPath(e,t={}){const n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};const r=[...ENTRY_CANDIDATES,...t.additionalEntrypoints??[]];let i=e;if(!path.isAbsolute(e)){const n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!path.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=path.resolve(n,e)}let a;let s;try{a=fs.realpathSync(i);if(t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};const n=t.requirePackageIdentity||t.inspectPackage?fs.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};s=n?.isDirectory()??false}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}const c=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};const l=s?void 0:r.find(e=>c.endsWith(`/${e}`));if(!l&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};const u=l?a.slice(0,-l.length):s?a:path.dirname(a);const f=readProcessPackageIdentity(u,t.inspectPackage&&!t.requirePackageIdentity||!l&&!s);if(f.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:f.reason};return f.kind===`package`&&f.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:path.resolve(u),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){const{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};const s=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(s))return!n||s===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};const c=classifyEntrypoint(e,t);if(n)return c.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(c.entryIndex)],1)[0]??``)!==n?{kind:`other`}:c;if(c.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return c.kind===`openclaw`?c:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let l=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(isNodeRuntime(s)||isBunRuntime(s)||s===`tsx`))try{l=fs.readFileSync(`/proc/${i}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${extractErrorCode(e)??`unavailable`})`}}return!t.requirePackageIdentity&&l===`openclaw`?{kind:`openclaw`}:c} //!src/infra/windows-appcontainer-spawn.ts var AppContainerSpawnUnsupportedError=class extends Error{constructor(e){super(`AppContainer: libuv ${e} cannot create child pipes; 1.53.0+ required. Run OpenClaw outside the AppContainer or use a Node build with libuv >= 1.53.0.`);this.code=`APPCONTAINER_SPAWN_UNSUPPORTED`;this.name=`AppContainerSpawnUnsupportedError`}};let checked=false;let unsupported;function assertAppContainerSpawnSupported(e){if(process.platform!==`win32`)return;if(e===`ignore`||e===`inherit`||Array.isArray(e)&&e.length>=3&&e.every(e=>e!==void 0&&e!==null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e===`number`&&e<0)))return;if(!checked){checked=true;try{const{readCurrentAppContainerSid:e}=createRequire(import.meta.url)(`@openclaw/proc-safe/windows-token`);const t=e();const n=process.versions.uv;const r=Number(n.split(`.`)[0]);const i=Number(n.split(`.`)[1]);if(t!==null&&(r<1||r===1&&i<53))unsupported=new AppContainerSpawnUnsupportedError(n)}catch(e){import(`./windows-appcontainer-spawn-log.runtime-CRP4xFC_.js`).then(({logAppContainerTokenProbeFailure:t})=>t(e)).catch(()=>{})}}if(unsupported)throw unsupported} //!src/process/supervisor/darwin-process-command.ts let reportedForeignArguments=false;const REDACTED_ARGUMENTS_ENTITLEMENT=/\[Key\] com\.apple\.private\.no-read-procargs\s*\[Value\]\s*\[Bool\] true|<key>com\.apple\.private\.no-read-procargs<\/key>\s*<true\/>/u;function readDarwinImagePath(e){const t={encoding:`utf8`,timeout:2e3};const n=spawnSync(`/usr/sbin/lsof`,[`-a`,`-p`,String(e),`-d`,`txt`,`-Fn`],t);const r=n.status===0?/^n(\/.+)$/mu.exec(n.stdout)?.[1]:void 0;const i=r&&spawnSync(`/bin/ps`,[`-o`,`ucomm=`,`-p`,String(e)],t);return i&&i.status===0&&i.stdout.trim()===path.basename(r).slice(0,16)?r:void 0}function isRedactedSystemImage(e){if(!e.startsWith(`/System/`))return false;const t=spawnSync(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&REDACTED_ARGUMENTS_ENTITLEMENT.test(t.stdout)}function readCommandWithServiceMarker(e){try{return readProcessCommand(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof ProcSafeError)||t.code!==`incomplete`)throw t;const n=readProcessCommand(e);return n&&[n.executable,n.argv[0]??``].some(e=>isNodeRuntime(e)||isBunRuntime(e)||path.basename(e)===`tsx`)?{...n,serviceMarkerUnavailable:true}:n}}function readDarwinProcessCommand(e,t,n={}){try{const t=n.serviceMarker===false?readProcessCommand(e):readCommandWithServiceMarker(e);if(!t)return;const r=t.environment.OPENCLAW_SERVICE_MARKER;return{argv:[...t.argv],executable:t.executable,...r===void 0?{}:{serviceMarker:r},...`serviceMarkerUnavailable`in t?{serviceMarkerUnavailable:true}:{}}}catch(n){if(!(n instanceof ProcSafeError))throw n;if(n.code===`layout-mismatch`||n.code===`incomplete`){const r=readDarwinImagePath(e);if(r&&isRedactedSystemImage(r))return{argvUnavailable:true,executable:r,...t?{owner:t}:{}};throw n}if(n.code===`unsupported-platform`&&process.platform===`darwin`)throw new Error(`Cannot inspect Darwin process arguments under Rosetta; run OpenClaw with native arm64 Node.js.`,{cause:n});if(n.code!==`access-denied`&&n.code!==`operation-failed`)throw n;if(isPidDefinitelyDead(e))return;if(t===`different`){if(!reportedForeignArguments){reportedForeignArguments=true;createSubsystemLogger(`process/census`).debug(`Unreadable Darwin arguments for another UID do not establish capture custody.`,{pid:e,code:n.code})}return{argvUnavailable:true,owner:t}}throw new Error(`Could not classify PID ${e}: cannot inspect Darwin arguments (${n.code}).`,{cause:n})}} //!src/process/windows-command-line.ts function parseWindowsNativeArguments(e){const t=[];let n=0;while(n<e.length){while(/[ \t]/.test(e.charAt(n)))n++;if(n===e.length)break;let r=``;let i=false;while(n<e.length){let t=0;while(e[n]===`\\`){t++;n++}if(e[n]===`"`){r+=`\\`.repeat(Math.floor(t/2));if(t%2===1){r+=`"`;n++}else if(i&&e[n+1]===`"`){r+=`"`;n+=2}else{i=!i;n++}continue}r+=`\\`.repeat(t);if(n===e.length||!i&&/[ \t]/.test(e.charAt(n)))break;r+=e.charAt(n++)}t.push(r)}return t}function parseWindowsNativeCommandLine(e){if(e.includes(`\0`))return null;let t=0;while(/[ \t]/.test(e.charAt(t)))t++;if(t===e.length)return[];let n=``;let r=false;while(t<e.length&&(r||!/[ \t]/.test(e.charAt(t)))){const i=e.charAt(t++);if(i===`"`)r=!r;else n+=i}if(r||!n)return null;return[n,...parseWindowsNativeArguments(e.slice(t))]} //!src/shared/rosetta-translation.ts let translated;function isRosettaTranslatedProcess(){if(process.platform!==`darwin`||process.arch!==`x64`)return false;translated??=os.cpus()[0]?.model.includes(`Apple`)===true;return translated} //!src/infra/windows-process-census.ts function readWindowsProcessCensus(e){return listProcesses({timeoutMs:e,includeCommand:true}).flatMap(({pid:e,owner:t,identity:n,command:r})=>{if(e===0||e===4||n?.exited)return[];let i=r?.executable;if(!r&&n)try{try{var a=_usingCtx();i=a.u(PinnedProcess.open(e,{access:`observe`,expect:{startTimeMicros:n.startTimeMicros}}))?.imagePath}catch(e){a.e=e}finally{a.d()}}catch{}let s;if(t===`unknown`&&!n&&!r)try{readProcessIdentity(e)}catch(e){if(e instanceof ProcSafeError&&e.code===`access-denied`)s=true}return[{pid:e,...n?{parentPid:n.parentPid,startIdentity:String(Math.floor(n.startTimeMicros/1e3))}:{},...r?.commandLine===void 0?{}:{commandLine:r.commandLine},...i?{executable:i}:{},...r?.cwd===void 0?{}:{cwd:r.cwd},...t===`different`?{foreignOwner:true}:{},...s?{accessDenied:s}:{}}]})} //!src/infra/windows-install-roots.ts const DEFAULT_WINDOWS_SYSTEM_ROOT=`C:\\Windows`;const WINDOWS_NT_CURRENT_VERSION_KEY=`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`;const REG_QUERY_TIMEOUT_MS=5e3;let cachedProcessRoots=null;function locateWindowsRegExe(){const e=path.win32.join(DEFAULT_WINDOWS_SYSTEM_ROOT,`System32`,`reg.exe`);return canAccessSync(e,fs.constants.R_OK)?e:null}function trimTrailingSeparators(e){const t=path.win32.parse(e);let n=e;while(n.length>t.root.length&&/[\\/]/.test(n.at(-1)??``))n=n.slice(0,-1);return n}function normalizeWindowsInstallRoot(e){if(typeof e!==`string`)return null;const t=e.trim();if(!t||t.includes(`\0`)||t.includes(`\r`)||t.includes(` `)||t.includes(`;`))return null;const n=trimTrailingSeparators(path.win32.normalize(t));if(!path.win32.isAbsolute(n)||n.startsWith(`\\\\`))return null;const r=path.win32.parse(n);if(!/^[A-Za-z]:\\$/.test(r.root))return null;if(n.length<=r.root.length)return null;return n}function getEnvValueCaseInsensitive(e,t){const n=e[t];if(n!==void 0)return n;const r=t.toUpperCase();const i=Object.keys(e).find(e=>e.toUpperCase()===r);return i?e[i]:void 0}function queryWindowsRegistryValue(e,t,n){const r=locateWindowsRegExe();if(!r)return null;for(const i of[[`/reg:64`],[]]){const a=n===void 0?REG_QUERY_TIMEOUT_MS:Math.min(REG_QUERY_TIMEOUT_MS,Math.ceil(n-performance.now()));if(a<=0)return null;assertAppContainerSpawnSupported();try{const n=execFileSync(r,[`query`,e,`/v`,t,...i],{env:resolveDiagnosticProcessEnv(),encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:a,windowsHide:true});const s=new RegExp(`^\\s*${escapeRegExp(t)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`,`im`);const c=n.match(s)?.[1]?.trim();if(c)return c}catch{}}return null}function resolveSystemRootFromEnv(e){return normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`SystemRoot`))??normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`WINDIR`))??DEFAULT_WINDOWS_SYSTEM_ROOT}function getProcessRoots(e){if(!cachedProcessRoots){const t={};for(const e of[`SystemRoot`,`WINDIR`,`ProgramFiles`,`ProgramFiles(x86)`,`ProgramW6432`])t[e]=getEnvValueCaseInsensitive(process.env,e);const n={env:t,systemRoot:normalizeWindowsInstallRoot(queryWindowsRegistryValue(WINDOWS_NT_CURRENT_VERSION_KEY,`SystemRoot`,e)??void 0)??resolveSystemRootFromEnv(t)};if(e!==void 0&&performance.now()>=e)return n;cachedProcessRoots=n}return cachedProcessRoots}function getWindowsSystemRoot(e,t){if(e!==process.env)return resolveSystemRootFromEnv(e);const n=getProcessRoots(t);return n.installRoots?.systemRoot??n.systemRoot}function getWindowsPowerShellExePath(e=process.env,t){return path.win32.join(getWindowsSystemRoot(e,t),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)} //!src/infra/windows-user-sid.ts function readWindowsUserSid(){if(process.platform!==`win32`)return;try{const e=spawnSync(getWindowsPowerShellExePath(),[`-NoProfile`,`-NonInteractive`,`-Command`,`[Security.Principal.WindowsIdentity]::GetCurrent().User.Value`],{encoding:`utf8`,windowsHide:true,timeout:5e3});const t=e.stdout?.trim();return!e.error&&e.status===0&&/^S-1-\d+(?:-\d+)+$/.test(t)?t:void 0}catch{return}} //!src/infra/openclaw-process-census.ts const workerEntrypoints=Object.values(runtimeProcessEntrypoints).flatMap(e=>[path.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]);function isStandardSystemdUserManager(e){const t=e&&`argv`in e?e.argv:[];return t.length<=3&&t[1]===`--user`&&t.slice(2).every(e=>/^--deserialize=\d+$/u.test(e))&&(t[0]===`/usr/lib/systemd/systemd`||t[0]===`/lib/systemd/systemd`)}function isStandardSystemdLoginProcess(e,t,n){if(process.platform!==`linux`||n===void 0||e?.uid!==n||!(`argv`in e))return false;return isStandardSystemdUserManager(e)||e.argv.length===1&&e.argv[0]===`(sd-pam)`&&t?.uid===e.uid&&isStandardSystemdUserManager(t)}const gatewayWorkerEntrypoints=[runtimeProcessEntrypoints.spawnBroker,runtimeProcessEntrypoints.directoryWatchHost,runtimeProcessEntrypoints.serviceChildWindowsJobAnchor].flatMap(e=>[path.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]);function isGatewayProcess(e,t){if(path.basename((e[0]??``).replaceAll(`\\`,`/`)).replace(/\.(exe|cmd|bat)$/iu,``)===`openclaw-gateway`)return true;if(t.kind!==`openclaw`||t.entryIndex===void 0)return false;const n=(e[t.entryIndex]??``).replaceAll(`\\`,`/`);return gatewayWorkerEntrypoints.some(e=>n.endsWith(`/${e}`))||getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(t.entryIndex)]),1)[0]===`gateway`}function classifyProcessArtifactCustody(e,t,n){if(!e)return{kind:`unknown`,reason:`process command is unavailable`};const r=`argv`in e?e.argv:[];const i=[...r.map(e=>e.replace(/^--[^=]+=/u,``).replace(/^-r(?=.)/u,``)),n??``,`executable`in e?e.executable??``:``].filter(referencesRetainedArtifact);if(`argvUnavailable`in e||r.length===0)return i.length?{kind:`holder`}:{kind:`not-holder`};const{position:a,operands:s}=resolveRuntimeScriptPosition(r);const c={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:workerEntrypoints,inspectPackage:true};let l;const u=i.flatMap(e=>{const t=classifyOpenClawEntrypointPath(e,c);if(t.kind===`openclaw`&&t.artifactPath)return[t.artifactPath];l??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`;return[]});if(i.length&&s.length===0)return l?{kind:`unknown`,reason:l}:{kind:`holder`,paths:u};const f=classifyOpenClawArgv(r,c);const p=process.getuid?.();const m=process.platform===`linux`&&f.kind===`unclassified`&&f.cause===`service-marker`&&e.uid!==void 0&&p!==void 0&&e.uid!==p;const h=isGatewayProcess(r,f);let g=i.length>0||u.length>0;const unscoped=()=>g||!h?{kind:`holder`}:{kind:`holder`,gateway:true};if(f.kind===`openclaw`){if(!f.artifactPath)return s.some(({module:e})=>e)?{kind:`holder`}:unscoped();u.push(f.artifactPath);g=true}let _=u.length?{kind:`holder`,paths:u}:void 0;l??=f.kind===`unclassified`&&f.cause!==`runtime-syntax`?f.reason:void 0;if(!n||!path.isAbsolute(n)){if(f.kind===`other`&&typeof a!==`number`&&a.kind===`not-runtime`&&i.length===0)return{kind:`not-holder`};if(!m)return{kind:`unknown`,reason:l??`working directory is unavailable`}}const v=n&&path.isAbsolute(n)&&typeof a!==`number`&&a.kind!==`not-runtime`?readProcessPackageIdentity(n,true):void 0;if(v?.kind===`package`&&v.name===`openclaw`)_=unscoped();const y=v?.kind===`package`?v.scripts:{};if(v?.kind===`unknown`)l??=v.reason;for(const{value:e,module:t}of s){let n=e;if(t){if(e.startsWith(`file:`))try{n=fileURLToPath(e)}catch(e){l??=String(e);continue}else if(!path.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){l??=`runtime module package identity is unavailable`;continue}}else if(isBunRuntime(r[0]??``)&&!/[\\/]/u.test(e)&&!path.extname(e)&&typeof y[e]===`string`&&y[e].trim())continue;const i=classifyOpenClawEntrypointPath(n,c);if(i.kind===`unclassified`)l??=i.reason;else if(i.kind===`openclaw`){g||=i.artifactPath!==void 0;_=i.artifactPath&&(!_||_.paths)?{kind:`holder`,paths:[..._?.paths??[],i.artifactPath]}:unscoped()}}if(m&&!g&&!_)return{kind:`not-holder`};return l?{kind:`unknown`,reason:l}:_??{kind:`not-holder`}}function classifyOpaqueWindowsCustody(e,t){const n=e.commandLine?parseWindowsNativeCommandLine(e.commandLine):null;if(n?.length)return classifyProcessArtifactCustody({argv:n,...e.executable?{executable:e.executable}:{}},t,e.cwd);if([e.executable,e.cwd].some(e=>e&&referencesRetainedArtifact(e)))return{kind:`holder`};if(e.foreignOwner||e.accessDenied)return{kind:`not-holder`};const r=e.executable;return r&&!isNodeRuntime(r)&&!isBunRuntime(r)&&!/openclaw/iu.test(path.win32.basename(r))?{kind:`not-holder`}:{kind:`unknown`,reason:`process command line is unavailable`}}function classifyWindowsHandoffAncestry(e,t,n){const r=e.startIdentity;if(r&&n.length&&n.every(({startIdentity:e})=>/^\d+$/.test(e)&&BigInt(e)>BigInt(r)))return`unrelated`;const i=/* @__PURE__ */ new Set;let a=e;while(a.startIdentity&&!i.has(a.pid)){const e=a.startIdentity;i.add(a.pid);if(n.some(({pid:t,startIdentity:n})=>t===a.pid&&n===e||t===a.parentPid&&/^\d+$/.test(n)&&BigInt(n)<=BigInt(e)))return`descendant`;if(a.parentPid===0||a.parentPid===4)return`unrelated`;const r=t.get(a.parentPid??0);if(!r?.startIdentity||BigInt(r.startIdentity)>BigInt(e))break;a=r}return`unknown`}function inspectOtherOpenClawProcesses(e){const t=typeof e===`object`?e:void 0;const n=typeof e===`string`?e:void 0;const r=[];const i={matchingPids:[],unverifiedPids:[]};try{if(process.platform===`linux`&&isContainerEnvironment())throw new Error(`Host process visibility cannot be established from this container. Run Doctor on the host after stopping OpenClaw containers that share its temporary directory.`);const e=process.platform===`win32`;const a=Date.now()+(t?15e3:1e3);const s=e?[...readWindowsProcessCensus(15e3)]:void 0;const c=new Map(s?.map(e=>[e.pid,e]));const l=e&&t?.windowsUserSid!==void 0&&readWindowsUserSid()===t.windowsUserSid;const u=s?.map(({pid:e,parentPid:t,commandLine:n})=>{const r=n?parseWindowsNativeCommandLine(n):null;return{pid:e,state:``,command:r?.length&&t!==void 0?{ppid:t,argv:r}:void 0}})??[...readProcessGroupMembers(t?15e3:1e3,{readDarwinCommand:t?(e,t)=>readDarwinProcessCommand(e,t,{serviceMarker:false}):readDarwinProcessCommand})];const f=new Map(u.map(e=>[e.pid,e]));const p=f.get(process.pid);if(!p||!t&&(!p.command&&process.platform!==`darwin`||process.platform===`linux`&&u.some(e=>e.command&&!(`argv`in e.command))))throw new Error(`OpenClaw process census is incomplete.`);const m=s?new Map(s.map(({pid:e,cwd:t})=>[e,t])):readProcessWorkingDirectories(u.map(({pid:e})=>e));const h=/* @__PURE__ */ new Set;const g=!t&&isUpdateCommandArgv(process.argv);const _=/* @__PURE__ */ new Set([process.pid]);let v=p;let y=p.command?.ppid??p.ppid??0;while(y>0){const n=f.get(y);if(!n?.command||_.has(y)){if(t||(n?!n.command:e))break;throw new Error(`OpenClaw process ancestry is incomplete.`)}const r=c.get(y)?.startIdentity;const i=c.get(v.pid)?.startIdentity;if(e&&(!r||!i||BigInt(r)>=BigInt(i)))break;_.add(y);if(`argv`in n.command){const{argv:e,serviceMarker:r,serviceMarkerUnavailable:i}=n.command;const a=classifyOpenClawArgv(e,{pid:y,serviceMarker:r,serviceMarkerUnavailable:i,cwd:m.get(y)??``,additionalEntrypoints:workerEntrypoints});const s=a.kind===`openclaw`&&a.entryIndex!==void 0?getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(a.entryIndex)]),1)[0]:void 0;if(s===(t?`update`:`doctor`)||g&&s===`update`&&y===(p.command?.ppid??p.ppid))h.add(y)}v=n;y=n.command.ppid}const normalize=t=>e?t.replaceAll(`\\`,`/`).replace(/\/{2,}\?\/UNC\//gi,`//`).replace(/\/{2,}\?\//g,``).replace(/\/{2,}/g,`/`).toLowerCase():t;const literal=e=>escapeRegExp(normalize(e));const referencePattern=n=>{const r=n.flatMap(t=>[t.replace(/[\\/]+$/,``),pathToFileURL(t,{windows:e}).href]);return new RegExp(`(?:^|[^\\w-])(?:${t?literal(t.runId):`(?!)`}(?=$|[^\\w-])|(?:${r.map(literal).join(`|`)||`(?!)`})(?=$|[/\\s"'\x60);,\\]]))`)};const b=t?.artifactPaths??(n?[n]:[]);const x=referencePattern(b);const rootKey=e=>normalize(e.replace(/[\\/]+$/,``));const S=new Set(t?.sharedRoots?.map(rootKey));const C=referencePattern(b.filter(e=>!S.has(rootKey(e))));const w=process.getuid?.();const outsideHandoffFamily=(e,t)=>{let n;try{n=readProcessAncestry(e,{throughPid:process.pid})}catch{return false}if(n?.stoppedBy===`through-pid`)return true;return t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{const n=f.get(e.pid)?.command;return e.startTimeMicros>t*1e3||process.platform===`linux`&&n?.uid===w&&isStandardSystemdUserManager(n)})};const predatesHandoffDrivers=e=>{if(process.platform!==`linux`||!t?.drivers?.length)return false;const n=readLinuxProcessStat(e)?.startedAt;return n!==void 0&&t.drivers.every(({startIdentity:e})=>BigInt(e)>BigInt(n))};for(const{pid:s,state:p,command:g}of u){if(t&&Date.now()>=a)throw new Error(`Process census deadline exceeded`);if(s===process.pid||h.has(s))continue;if((p?.startsWith(`Z`)||t)&&isPidDefinitelyDead(s))continue;const u=g&&`argv`in g?g.argv:void 0;if(t){if(!e&&u?.length===0)continue;const n=c.get(s);const a=m.get(s);const p=[...u??[],n?.commandLine??``,n?.executable??``,a??``];const h=classifyOpenClawArgv(u??[n?.executable??``],{pid:s,cwd:a??``,serviceMarker:g&&`argv`in g?g.serviceMarker:void 0,additionalEntrypoints:workerEntrypoints});if(p.some(e=>x.test(normalize(e)))||!t.artifactPathsOnly&&h.kind===`openclaw`){if(!outsideHandoffFamily(s,p.some(e=>C.test(normalize(e)))?void 0:t.familyDeadline))i.matchingPids.push(s);continue}const _=t.familyExited?`unrelated`:n&&classifyWindowsHandoffAncestry(n,c,t.drivers??[]);if(_===`descendant`){i.matchingPids.push(s);continue}if(_===`unrelated`||l&&n?.accessDenied)continue;const v=n?.foreignOwner||g?.owner===`different`||g?.uid!==void 0&&w!==void 0&&g.uid!==w;if((!u||a===void 0)&&!v&&!isStandardSystemdLoginProcess(g,f.get(g?.ppid??0)?.command,w)&&!outsideHandoffFamily(s)&&!predatesHandoffDrivers(s)){i.unverifiedPids.push(s);const t=n?.executable??u?.[0];r.push(`Could not verify handoff ancestry for PID ${s} (${t?(e?path.win32:path).basename(t):`image unavailable`}).`)}continue}const _=c.get(s);const v=_&&!g?classifyOpaqueWindowsCustody(_,s):classifyProcessArtifactCustody(g,s,m.get(s));if(v.kind===`not-holder`)continue;if(v.kind===`holder`&&n&&(v.paths?!v.paths.some(e=>x.test(normalize(e))):v.gateway))continue;i.matchingPids.push(s);if(v.kind===`unknown`)r.push(`Could not verify runtime custody for PID ${s}: ${v.reason}`)}}catch(e){const n=/Could not classify PID (\d+):/.exec(e instanceof Error?e.message:``);if(t&&n)i.unverifiedPids.push(Number(n[1]));i.error=!t?`Could not inspect OpenClaw processes: ${String(e)}`:isRosettaTranslatedProcess()?`Host process census is unavailable under Rosetta; run openclaw update repair with native arm64 Node.js.`:`Host process census is incomplete; verify process-inspection permissions and retry update repair.`}return t?{...i,...r.length?{warnings:r}:{}}:i.error?{error:i.error}:{pids:i.matchingPids,...r.length?{warnings:r}:{}}}export{sha256FileSync$1 as a,sha256Base64Url as i,inspectOtherOpenClawProcesses,getCommandPositionalsWithRootOptions as n,_usingCtx as o,isContainerEnvironment as r,classifyOpenClawArgv as t};