openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 16.4 kB
JavaScript
import{i as isPidDefinitelyDead,s as readLinuxProcessStat}from"./pid-alive-Ecz7y-AF.mjs";import{t as escapeRegExp}from"./regexp-DvzVyjZw.mjs";import{t as createSubsystemLogger}from"./subsystem-BMw5Czn-.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{n as runtimeProcessEntrypoints}from"./runtime-process-entrypoints-BWulaDTJ.mjs";import{n as isNodeRuntime,r as resolveRuntimeScriptPosition,t as isBunRuntime}from"./runtime-binary-DNstBs1K.mjs";import{s as readProcessGroupMembers}from"./service-child-group-ownership-odODSk8D.mjs";import{t as isContainerEnvironment}from"./container-environment-DYX0eMDL.mjs";import{a as referencesRetainedArtifact,f as getRootOptionAwareCommandPath,i as readProcessWorkingDirectories,m as rewriteUpdateFlagArgv,n as classifyOpenClawEntrypointPath,p as isUpdateCommandArgv,r as readProcessPackageIdentity,t as classifyOpenClawArgv}from"./gateway-process-argv-CgLuhI_P.mjs";import{r as getWindowsPowerShellExePath}from"./windows-install-roots-BXU3EsrD.mjs";import{t as parseWindowsNativeCommandLine}from"./windows-command-line-CVuYGnJa.mjs";import{spawnSync}from"node:child_process";import{ProcSafeError}from"@openclaw/proc-safe/errors";import{readProcessAncestry,readProcessIdentity}from"@openclaw/proc-safe/identity";import path from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";import os from"node:os";import{listProcesses,readProcessCommand}from"@openclaw/proc-safe/inspect";import{PinnedProcess}from"@openclaw/proc-safe/windows-job";
//!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/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 o;if(t===`unknown`&&!n&&!r)try{readProcessIdentity(e)}catch(e){if(e instanceof ProcSafeError&&e.code===`access-denied`)o=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}:{},...o?{accessDenied:o}:{}}]})}
//!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:o}=resolveRuntimeScriptPosition(r);const s={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:workerEntrypoints,inspectPackage:true};let c;const l=i.flatMap(e=>{const t=classifyOpenClawEntrypointPath(e,s);if(t.kind===`openclaw`&&t.artifactPath)return[t.artifactPath];c??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`;return[]});if(i.length&&o.length===0)return c?{kind:`unknown`,reason:c}:{kind:`holder`,paths:l};const u=classifyOpenClawArgv(r,s);const d=process.getuid?.();const f=process.platform===`linux`&&u.kind===`unclassified`&&u.cause===`service-marker`&&e.uid!==void 0&&d!==void 0&&e.uid!==d;const p=isGatewayProcess(r,u);let m=i.length>0||l.length>0;const unscoped=()=>m||!p?{kind:`holder`}:{kind:`holder`,gateway:true};if(u.kind===`openclaw`){if(!u.artifactPath)return o.some(({module:e})=>e)?{kind:`holder`}:unscoped();l.push(u.artifactPath);m=true}let h=l.length?{kind:`holder`,paths:l}:void 0;c??=u.kind===`unclassified`&&u.cause!==`runtime-syntax`?u.reason:void 0;if(!n||!path.isAbsolute(n)){if(u.kind===`other`&&typeof a!==`number`&&a.kind===`not-runtime`&&i.length===0)return{kind:`not-holder`};if(!f)return{kind:`unknown`,reason:c??`working directory is unavailable`}}const g=n&&path.isAbsolute(n)&&typeof a!==`number`&&a.kind!==`not-runtime`?readProcessPackageIdentity(n,true):void 0;if(g?.kind===`package`&&g.name===`openclaw`)h=unscoped();const _=g?.kind===`package`?g.scripts:{};if(g?.kind===`unknown`)c??=g.reason;for(const{value:e,module:t}of o){let n=e;if(t){if(e.startsWith(`file:`))try{n=fileURLToPath(e)}catch(e){c??=String(e);continue}else if(!path.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){c??=`runtime module package identity is unavailable`;continue}}else if(isBunRuntime(r[0]??``)&&!/[\\/]/u.test(e)&&!path.extname(e)&&typeof _[e]===`string`&&_[e].trim())continue;const i=classifyOpenClawEntrypointPath(n,s);if(i.kind===`unclassified`)c??=i.reason;else if(i.kind===`openclaw`){m||=i.artifactPath!==void 0;h=i.artifactPath&&(!h||h.paths)?{kind:`holder`,paths:[...h?.paths??[],i.artifactPath]}:unscoped()}}if(f&&!m&&!h)return{kind:`not-holder`};return c?{kind:`unknown`,reason:c}:h??{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 o=e?[...readWindowsProcessCensus(15e3)]:void 0;const s=new Map(o?.map(e=>[e.pid,e]));const c=e&&t?.windowsUserSid!==void 0&&readWindowsUserSid()===t.windowsUserSid;const l=o?.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 u=new Map(l.map(e=>[e.pid,e]));const d=u.get(process.pid);if(!d||!t&&(!d.command&&process.platform!==`darwin`||process.platform===`linux`&&l.some(e=>e.command&&!(`argv`in e.command))))throw new Error(`OpenClaw process census is incomplete.`);const f=o?new Map(o.map(({pid:e,cwd:t})=>[e,t])):readProcessWorkingDirectories(l.map(({pid:e})=>e));const p=/* @__PURE__ */ new Set;const m=!t&&isUpdateCommandArgv(process.argv);const h=/* @__PURE__ */ new Set([process.pid]);let g=d;let _=d.command?.ppid??d.ppid??0;while(_>0){const n=u.get(_);if(!n?.command||h.has(_)){if(t||(n?!n.command:e))break;throw new Error(`OpenClaw process ancestry is incomplete.`)}const r=s.get(_)?.startIdentity;const i=s.get(g.pid)?.startIdentity;if(e&&(!r||!i||BigInt(r)>=BigInt(i)))break;h.add(_);if(`argv`in n.command){const{argv:e,serviceMarker:r,serviceMarkerUnavailable:i}=n.command;const a=classifyOpenClawArgv(e,{pid:_,serviceMarker:r,serviceMarkerUnavailable:i,cwd:f.get(_)??``,additionalEntrypoints:workerEntrypoints});const o=a.kind===`openclaw`&&a.entryIndex!==void 0?getRootOptionAwareCommandPath(rewriteUpdateFlagArgv([`node`,...e.slice(a.entryIndex)]),1)[0]:void 0;if(o===(t?`update`:`doctor`)||m&&o===`update`&&_===(d.command?.ppid??d.ppid))p.add(_)}g=n;_=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 v=t?.artifactPaths??(n?[n]:[]);const y=referencePattern(v);const rootKey=e=>normalize(e.replace(/[\\/]+$/,``));const b=new Set(t?.sharedRoots?.map(rootKey));const x=referencePattern(v.filter(e=>!b.has(rootKey(e))));const S=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=u.get(e.pid)?.command;return e.startTimeMicros>t*1e3||process.platform===`linux`&&n?.uid===S&&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:o,state:d,command:m}of l){if(t&&Date.now()>=a)throw new Error(`Process census deadline exceeded`);if(o===process.pid||p.has(o))continue;if((d?.startsWith(`Z`)||t)&&isPidDefinitelyDead(o))continue;const l=m&&`argv`in m?m.argv:void 0;if(t){if(!e&&l?.length===0)continue;const n=s.get(o);const a=f.get(o);const d=[...l??[],n?.commandLine??``,n?.executable??``,a??``];const p=classifyOpenClawArgv(l??[n?.executable??``],{pid:o,cwd:a??``,serviceMarker:m&&`argv`in m?m.serviceMarker:void 0,additionalEntrypoints:workerEntrypoints});if(d.some(e=>y.test(normalize(e)))||!t.artifactPathsOnly&&p.kind===`openclaw`){if(!outsideHandoffFamily(o,d.some(e=>x.test(normalize(e)))?void 0:t.familyDeadline))i.matchingPids.push(o);continue}const h=t.familyExited?`unrelated`:n&&classifyWindowsHandoffAncestry(n,s,t.drivers??[]);if(h===`descendant`){i.matchingPids.push(o);continue}if(h===`unrelated`||c&&n?.accessDenied)continue;const g=n?.foreignOwner||m?.owner===`different`||m?.uid!==void 0&&S!==void 0&&m.uid!==S;if((!l||a===void 0)&&!g&&!isStandardSystemdLoginProcess(m,u.get(m?.ppid??0)?.command,S)&&!outsideHandoffFamily(o)&&!predatesHandoffDrivers(o)){i.unverifiedPids.push(o);const t=n?.executable??l?.[0];r.push(`Could not verify handoff ancestry for PID ${o} (${t?(e?path.win32:path).basename(t):`image unavailable`}).`)}continue}const h=s.get(o);const g=h&&!m?classifyOpaqueWindowsCustody(h,o):classifyProcessArtifactCustody(m,o,f.get(o));if(g.kind===`not-holder`)continue;if(g.kind===`holder`&&n&&(g.paths?!g.paths.some(e=>y.test(normalize(e))):g.gateway))continue;i.matchingPids.push(o);if(g.kind===`unknown`)r.push(`Could not verify runtime custody for PID ${o}: ${g.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{inspectOtherOpenClawProcesses};