openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2 lines • 17.1 kB
JavaScript
import{b as e,t}from"./session-transcript-reconcile.worker-subsystem-BUNaGCPF.mjs";import{t as n}from"./session-transcript-reconcile.worker-usingCtx-03vOGQ3v.mjs";import{d as r,g as i,m as a,s as o}from"./session-transcript-reconcile.worker-service-child-group-ownership-AVmJ78Uc.mjs";import{a as s,n as c,r as l,t as u}from"./session-transcript-reconcile.worker-runtime-binary-DoB2Z7UB.mjs";import{t as d}from"./session-transcript-reconcile.worker-path-existence-BSsZ8dW-.mjs";import{a as f,c as p,i as m,l as h,n as g,r as _,s as v,t as y,u as b}from"./session-transcript-reconcile.worker-gateway-process-argv-BLuCIIZP.mjs";import{l as x}from"./session-transcript-reconcile.worker.js";import S from"node:fs";import C from"node:path";import w from"node:os";import{fileURLToPath as T,pathToFileURL as E}from"node:url";import{execFileSync as D,spawnSync as O}from"node:child_process";import{ProcSafeError as k}from"@openclaw/proc-safe/errors";import{readProcessAncestry as A,readProcessIdentity as j}from"@openclaw/proc-safe/identity";import{listProcesses as M,readProcessCommand as N}from"@openclaw/proc-safe/inspect";import{PinnedProcess as P}from"@openclaw/proc-safe/windows-job";let F=!1;const I=/\[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){let t={encoding:`utf8`,timeout:2e3},n=O(`/usr/sbin/lsof`,[`-a`,`-p`,String(e),`-d`,`txt`,`-Fn`],t),r=n.status===0?/^n(\/.+)$/mu.exec(n.stdout)?.[1]:void 0,i=r&&O(`/bin/ps`,[`-o`,`ucomm=`,`-p`,String(e)],t);return i&&i.status===0&&i.stdout.trim()===C.basename(r).slice(0,16)?r:void 0}function isRedactedSystemImage(e){if(!e.startsWith(`/System/`))return!1;let t=O(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&I.test(t.stdout)}function readCommandWithServiceMarker(e){try{return N(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof k)||t.code!==`incomplete`)throw t;let n=N(e);return n&&[n.executable,n.argv[0]??``].some(e=>c(e)||u(e)||C.basename(e)===`tsx`)?{...n,serviceMarkerUnavailable:!0}:n}}function readDarwinProcessCommand(e,n,i={}){try{let t=i.serviceMarker===!1?N(e):readCommandWithServiceMarker(e);if(!t)return;let n=t.environment.OPENCLAW_SERVICE_MARKER;return{argv:[...t.argv],executable:t.executable,...n===void 0?{}:{serviceMarker:n},...`serviceMarkerUnavailable`in t?{serviceMarkerUnavailable:!0}:{}}}catch(i){if(!(i instanceof k))throw i;if(i.code===`layout-mismatch`||i.code===`incomplete`){let t=readDarwinImagePath(e);if(t&&isRedactedSystemImage(t))return{argvUnavailable:!0,executable:t,...n?{owner:n}:{}};throw i}if(i.code===`unsupported-platform`&&process.platform===`darwin`)throw Error(`Cannot inspect Darwin process arguments under Rosetta; run OpenClaw with native arm64 Node.js.`,{cause:i});if(i.code!==`access-denied`&&i.code!==`operation-failed`)throw i;if(r(e))return;if(n===`different`)return F||(F=!0,t(`process/census`).debug(`Unreadable Darwin arguments for another UID do not establish capture custody.`,{pid:e,code:i.code})),{argvUnavailable:!0,owner:n};throw Error(`Could not classify PID ${e}: cannot inspect Darwin arguments (${i.code}).`,{cause:i})}}function parseWindowsNativeArguments(e){let t=[],n=0;for(;n<e.length;){for(;/[ \t]/.test(e.charAt(n));)n++;if(n===e.length)break;let r=``,i=!1;for(;n<e.length;){let t=0;for(;e[n]===`\\`;)t++,n++;if(e[n]===`"`)r+=`\\`.repeat(Math.floor(t/2)),t%2==1?(r+=`"`,n++):i&&e[n+1]===`"`?(r+=`"`,n+=2):(i=!i,n++);else{if(r+=`\\`.repeat(t),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;for(;/[ \t]/.test(e.charAt(t));)t++;if(t===e.length)return[];let n=``,r=!1;for(;t<e.length&&(r||!/[ \t]/.test(e.charAt(t)));){let i=e.charAt(t++);i===`"`?r=!r:n+=i}return r||!n?null:[n,...parseWindowsNativeArguments(e.slice(t))]}let L;function isRosettaTranslatedProcess(){return process.platform!==`darwin`||process.arch!==`x64`?!1:(L??=w.cpus()[0]?.model.includes(`Apple`)===!0,L)}function readWindowsProcessCensus(e){return M({timeoutMs:e,includeCommand:!0}).flatMap(({pid:e,owner:t,identity:r,command:i})=>{if(e===0||e===4||r?.exited)return[];let a=i?.executable;if(!i&&r)try{try{var o=n();a=o.u(P.open(e,{access:`observe`,expect:{startTimeMicros:r.startTimeMicros}}))?.imagePath}catch(e){o.e=e}finally{o.d()}}catch{}let s;if(t===`unknown`&&!r&&!i)try{j(e)}catch(e){e instanceof k&&e.code===`access-denied`&&(s=!0)}return[{pid:e,...r?{parentPid:r.parentPid,startIdentity:String(Math.floor(r.startTimeMicros/1e3))}:{},...i?.commandLine===void 0?{}:{commandLine:i.commandLine},...a?{executable:a}:{},...i?.cwd===void 0?{}:{cwd:i.cwd},...t===`different`?{foreignOwner:!0}:{},...s?{accessDenied:s}:{}}]})}const R=`C:\\Windows`,z=5e3;let B=null;function locateWindowsRegExe(){let e=C.win32.join(R,`System32`,`reg.exe`);return d(e,S.constants.R_OK)?e:null}function trimTrailingSeparators(e){let t=C.win32.parse(e),n=e;for(;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;let t=e.trim();if(!t||t.includes(`\0`)||t.includes(`\r`)||t.includes(`
`)||t.includes(`;`))return null;let n=trimTrailingSeparators(C.win32.normalize(t));if(!C.win32.isAbsolute(n)||n.startsWith(`\\\\`))return null;let r=C.win32.parse(n);return!/^[A-Za-z]:\\$/.test(r.root)||n.length<=r.root.length?null:n}function getEnvValueCaseInsensitive(e,t){let n=e[t];if(n!==void 0)return n;let r=t.toUpperCase(),i=Object.keys(e).find(e=>e.toUpperCase()===r);return i?e[i]:void 0}function queryWindowsRegistryValue(t,n,r){let a=locateWindowsRegExe();if(!a)return null;for(let o of[[`/reg:64`],[]]){let s=r===void 0?z:Math.min(z,Math.ceil(r-performance.now()));if(s<=0)return null;x();try{let r=D(a,[`query`,t,`/v`,n,...o],{env:i(),encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:s,windowsHide:!0}),c=RegExp(`^\\s*${e(n)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`,`im`),l=r.match(c)?.[1]?.trim();if(l)return l}catch{}}return null}function resolveSystemRootFromEnv(e){return normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`SystemRoot`))??normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`WINDIR`))??R}function getProcessRoots(e){if(!B){let t={};for(let e of[`SystemRoot`,`WINDIR`,`ProgramFiles`,`ProgramFiles(x86)`,`ProgramW6432`])t[e]=getEnvValueCaseInsensitive(process.env,e);let n={env:t,systemRoot:normalizeWindowsInstallRoot(queryWindowsRegistryValue(`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`,`SystemRoot`,e)??void 0)??resolveSystemRootFromEnv(t)};if(e!==void 0&&performance.now()>=e)return n;B=n}return B}function getWindowsSystemRoot(e,t){if(e!==process.env)return resolveSystemRootFromEnv(e);let n=getProcessRoots(t);return n.installRoots?.systemRoot??n.systemRoot}function getWindowsPowerShellExePath(e=process.env,t){return C.win32.join(getWindowsSystemRoot(e,t),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function readWindowsUserSid(){if(process.platform===`win32`)try{let e=O(getWindowsPowerShellExePath(),[`-NoProfile`,`-NonInteractive`,`-Command`,`[Security.Principal.WindowsIdentity]::GetCurrent().User.Value`],{encoding:`utf8`,windowsHide:!0,timeout:5e3}),t=e.stdout?.trim();return!e.error&&e.status===0&&/^S-1-\d+(?:-\d+)+$/.test(t)?t:void 0}catch{return}}const V=Object.values(s).flatMap(e=>[C.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]);function isStandardSystemdUserManager(e){let 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){return process.platform!==`linux`||n===void 0||e?.uid!==n||!(`argv`in e)?!1:isStandardSystemdUserManager(e)||e.argv.length===1&&e.argv[0]===`(sd-pam)`&&t?.uid===e.uid&&isStandardSystemdUserManager(t)}const H=[s.spawnBroker,s.directoryWatchHost,s.serviceChildWindowsJobAnchor].flatMap(e=>[C.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`),`dist/${e.distWorkerPath}`]);function isGatewayProcess(e,t){if(C.basename((e[0]??``).replaceAll(`\\`,`/`)).replace(/\.(exe|cmd|bat)$/iu,``)===`openclaw-gateway`)return!0;if(t.kind!==`openclaw`||t.entryIndex===void 0)return!1;let n=(e[t.entryIndex]??``).replaceAll(`\\`,`/`);return H.some(e=>n.endsWith(`/${e}`))||v(h([`node`,...e.slice(t.entryIndex)]),1)[0]===`gateway`}function classifyProcessArtifactCustody(e,t,n){if(!e)return{kind:`unknown`,reason:`process command is unavailable`};let r=`argv`in e?e.argv:[],i=[...r.map(e=>e.replace(/^--[^=]+=/u,``).replace(/^-r(?=.)/u,``)),n??``,`executable`in e?e.executable??``:``].filter(f);if(`argvUnavailable`in e||r.length===0)return i.length?{kind:`holder`}:{kind:`not-holder`};let{position:a,operands:o}=l(r),s={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:V,inspectPackage:!0},c,d=i.flatMap(e=>{let t=g(e,s);return t.kind===`openclaw`&&t.artifactPath?[t.artifactPath]:(c??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`,[])});if(i.length&&o.length===0)return c?{kind:`unknown`,reason:c}:{kind:`holder`,paths:d};let p=y(r,s),m=process.getuid?.(),h=process.platform===`linux`&&p.kind===`unclassified`&&p.cause===`service-marker`&&e.uid!==void 0&&m!==void 0&&e.uid!==m,v=isGatewayProcess(r,p),b=i.length>0||d.length>0,unscoped=()=>b||!v?{kind:`holder`}:{kind:`holder`,gateway:!0};if(p.kind===`openclaw`){if(!p.artifactPath)return o.some(({module:e})=>e)?{kind:`holder`}:unscoped();d.push(p.artifactPath),b=!0}let x=d.length?{kind:`holder`,paths:d}:void 0;if(c??=p.kind===`unclassified`&&p.cause!==`runtime-syntax`?p.reason:void 0,!n||!C.isAbsolute(n)){if(p.kind===`other`&&typeof a!=`number`&&a.kind===`not-runtime`&&i.length===0)return{kind:`not-holder`};if(!h)return{kind:`unknown`,reason:c??`working directory is unavailable`}}let S=n&&C.isAbsolute(n)&&typeof a!=`number`&&a.kind!==`not-runtime`?_(n,!0):void 0;S?.kind===`package`&&S.name===`openclaw`&&(x=unscoped());let w=S?.kind===`package`?S.scripts:{};S?.kind===`unknown`&&(c??=S.reason);for(let{value:e,module:t}of o){let n=e;if(t){if(e.startsWith(`file:`))try{n=T(e)}catch(e){c??=String(e);continue}else if(!C.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){c??=`runtime module package identity is unavailable`;continue}}else if(u(r[0]??``)&&!/[\\/]/u.test(e)&&!C.extname(e)&&typeof w[e]==`string`&&w[e].trim())continue;let i=g(n,s);i.kind===`unclassified`?c??=i.reason:i.kind===`openclaw`&&(b||=i.artifactPath!==void 0,x=i.artifactPath&&(!x||x.paths)?{kind:`holder`,paths:[...x?.paths??[],i.artifactPath]}:unscoped())}return h&&!b&&!x?{kind:`not-holder`}:c?{kind:`unknown`,reason:c}:x??{kind:`not-holder`}}function classifyOpaqueWindowsCustody(e,t){let 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&&f(e)))return{kind:`holder`};if(e.foreignOwner||e.accessDenied)return{kind:`not-holder`};let r=e.executable;return r&&!c(r)&&!u(r)&&!/openclaw/iu.test(C.win32.basename(r))?{kind:`not-holder`}:{kind:`unknown`,reason:`process command line is unavailable`}}function classifyWindowsHandoffAncestry(e,t,n){let r=e.startIdentity;if(r&&n.length&&n.every(({startIdentity:e})=>/^\d+$/.test(e)&&BigInt(e)>BigInt(r)))return`unrelated`;let i=/* @__PURE__ */ new Set,a=e;for(;a.startIdentity&&!i.has(a.pid);){let e=a.startIdentity;if(i.add(a.pid),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`;let r=t.get(a.parentPid??0);if(!r?.startIdentity||BigInt(r.startIdentity)>BigInt(e))break;a=r}return`unknown`}function inspectOtherOpenClawProcesses(t){let n=typeof t==`object`?t:void 0,i=typeof t==`string`?t:void 0,s=[],c={matchingPids:[],unverifiedPids:[]};try{if(process.platform===`linux`&&b())throw Error(`Host process visibility cannot be established from this container. Run Doctor on the host after stopping OpenClaw containers that share its temporary directory.`);let t=process.platform===`win32`,l=Date.now()+(n?15e3:1e3),u=t?[...readWindowsProcessCensus(15e3)]:void 0,d=new Map(u?.map(e=>[e.pid,e])),f=t&&n?.windowsUserSid!==void 0&&readWindowsUserSid()===n.windowsUserSid,g=u?.map(({pid:e,parentPid:t,commandLine:n})=>{let r=n?parseWindowsNativeCommandLine(n):null;return{pid:e,state:``,command:r?.length&&t!==void 0?{ppid:t,argv:r}:void 0}})??[...o(n?15e3:1e3,{readDarwinCommand:n?(e,t)=>readDarwinProcessCommand(e,t,{serviceMarker:!1}):readDarwinProcessCommand})],_=new Map(g.map(e=>[e.pid,e])),x=_.get(process.pid);if(!x||!n&&(!x.command&&process.platform!==`darwin`||process.platform===`linux`&&g.some(e=>e.command&&!(`argv`in e.command))))throw Error(`OpenClaw process census is incomplete.`);let S=u?new Map(u.map(({pid:e,cwd:t})=>[e,t])):m(g.map(({pid:e})=>e)),w=/* @__PURE__ */ new Set,T=!n&&p(process.argv),D=/* @__PURE__ */ new Set([process.pid]),O=x,k=x.command?.ppid??x.ppid??0;for(;k>0;){let e=_.get(k);if(!e?.command||D.has(k)){if(n||(e?!e.command:t))break;throw Error(`OpenClaw process ancestry is incomplete.`)}let r=d.get(k)?.startIdentity,i=d.get(O.pid)?.startIdentity;if(t&&(!r||!i||BigInt(r)>=BigInt(i)))break;if(D.add(k),`argv`in e.command){let{argv:t,serviceMarker:r,serviceMarkerUnavailable:i}=e.command,a=y(t,{pid:k,serviceMarker:r,serviceMarkerUnavailable:i,cwd:S.get(k)??``,additionalEntrypoints:V}),o=a.kind===`openclaw`&&a.entryIndex!==void 0?v(h([`node`,...t.slice(a.entryIndex)]),1)[0]:void 0;(o===(n?`update`:`doctor`)||T&&o===`update`&&k===(x.command?.ppid??x.ppid))&&w.add(k)}O=e,k=e.command.ppid}let normalize=e=>t?e.replaceAll(`\\`,`/`).replace(/\/{2,}\?\/UNC\//gi,`//`).replace(/\/{2,}\?\//g,``).replace(/\/{2,}/g,`/`).toLowerCase():e,literal=t=>e(normalize(t)),referencePattern=e=>{let r=e.flatMap(e=>[e.replace(/[\\/]+$/,``),E(e,{windows:t}).href]);return RegExp(`(?:^|[^\\w-])(?:${n?literal(n.runId):`(?!)`}(?=$|[^\\w-])|(?:${r.map(literal).join(`|`)||`(?!)`})(?=$|[/\\s"'\x60);,\\]]))`)},j=n?.artifactPaths??(i?[i]:[]),M=referencePattern(j),rootKey=e=>normalize(e.replace(/[\\/]+$/,``)),N=new Set(n?.sharedRoots?.map(rootKey)),P=referencePattern(j.filter(e=>!N.has(rootKey(e)))),F=process.getuid?.(),outsideHandoffFamily=(e,t)=>{let n;try{n=A(e,{throughPid:process.pid})}catch{return!1}return n?.stoppedBy===`through-pid`||t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{let n=_.get(e.pid)?.command;return e.startTimeMicros>t*1e3||process.platform===`linux`&&n?.uid===F&&isStandardSystemdUserManager(n)})},predatesHandoffDrivers=e=>{if(process.platform!==`linux`||!n?.drivers?.length)return!1;let t=a(e)?.startedAt;return t!==void 0&&n.drivers.every(({startIdentity:e})=>BigInt(e)>BigInt(t))};for(let{pid:e,state:a,command:o}of g){if(n&&Date.now()>=l)throw Error(`Process census deadline exceeded`);if(e===process.pid||w.has(e)||(a?.startsWith(`Z`)||n)&&r(e))continue;let u=o&&`argv`in o?o.argv:void 0;if(n){if(!t&&u?.length===0)continue;let r=d.get(e),i=S.get(e),a=[...u??[],r?.commandLine??``,r?.executable??``,i??``],l=y(u??[r?.executable??``],{pid:e,cwd:i??``,serviceMarker:o&&`argv`in o?o.serviceMarker:void 0,additionalEntrypoints:V});if(a.some(e=>M.test(normalize(e)))||!n.artifactPathsOnly&&l.kind===`openclaw`){outsideHandoffFamily(e,a.some(e=>P.test(normalize(e)))?void 0:n.familyDeadline)||c.matchingPids.push(e);continue}let p=n.familyExited?`unrelated`:r&&classifyWindowsHandoffAncestry(r,d,n.drivers??[]);if(p===`descendant`){c.matchingPids.push(e);continue}if(p===`unrelated`||f&&r?.accessDenied)continue;let m=r?.foreignOwner||o?.owner===`different`||o?.uid!==void 0&&F!==void 0&&o.uid!==F;if((!u||i===void 0)&&!m&&!isStandardSystemdLoginProcess(o,_.get(o?.ppid??0)?.command,F)&&!outsideHandoffFamily(e)&&!predatesHandoffDrivers(e)){c.unverifiedPids.push(e);let n=r?.executable??u?.[0];s.push(`Could not verify handoff ancestry for PID ${e} (${n?(t?C.win32:C).basename(n):`image unavailable`}).`)}continue}let p=d.get(e),m=p&&!o?classifyOpaqueWindowsCustody(p,e):classifyProcessArtifactCustody(o,e,S.get(e));m.kind!==`not-holder`&&(m.kind===`holder`&&i&&(m.paths?!m.paths.some(e=>M.test(normalize(e))):m.gateway)||(c.matchingPids.push(e),m.kind===`unknown`&&s.push(`Could not verify runtime custody for PID ${e}: ${m.reason}`)))}}catch(e){let t=/Could not classify PID (\d+):/.exec(e instanceof Error?e.message:``);n&&t&&c.unverifiedPids.push(Number(t[1])),c.error=n?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.`:`Could not inspect OpenClaw processes: ${String(e)}`}return n?{...c,...s.length?{warnings:s}:{}}:c.error?{error:c.error}:{pids:c.matchingPids,...s.length?{warnings:s}:{}}}export{inspectOtherOpenClawProcesses};