openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 14.5 kB
JavaScript
import{o as e}from"./transcript-plugin-instance-invocation-7y9lfaeO.mjs";import{t}from"./transcript-subsystem-C0UTtuvS.mjs";import{t as n}from"./transcript-usingCtx-03vOGQ3v.mjs";import{a as r,n as i,r as a,t as o}from"./transcript-runtime-binary-4JwD1Zy9.mjs";import{a as s,c,i as l,l as u,n as d,r as f,s as p,t as m}from"./transcript-gateway-process-argv-CixOvMwa.mjs";import{c as h,r as g,s as _}from"./transcript-service-child-group-ownership-MKIb00Qh.mjs";import{n as v}from"./transcript-windows-install-roots-CW_FzH5S.mjs";import y from"node:path";import b from"node:fs";import x from"node:os";import{fileURLToPath as S,pathToFileURL as C}from"node:url";import{spawnSync as w}from"node:child_process";import{ProcSafeError as T}from"@openclaw/proc-safe/errors";import{readProcessAncestry as E,readProcessIdentity as D}from"@openclaw/proc-safe/identity";import{listProcesses as O,readProcessCommand as k}from"@openclaw/proc-safe/inspect";import{PinnedProcess as A}from"@openclaw/proc-safe/windows-job";let j=!1;const M=/\[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=w(`/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&&w(`/bin/ps`,[`-o`,`ucomm=`,`-p`,String(e)],t);return i&&i.status===0&&i.stdout.trim()===y.basename(r).slice(0,16)?r:void 0}function isRedactedSystemImage(e){if(!e.startsWith(`/System/`))return!1;let t=w(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&M.test(t.stdout)}function readCommandWithServiceMarker(e){try{return k(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof T)||t.code!==`incomplete`)throw t;let n=k(e);return n&&[n.executable,n.argv[0]??``].some(e=>i(e)||o(e)||y.basename(e)===`tsx`)?{...n,serviceMarkerUnavailable:!0}:n}}function readDarwinProcessCommand(e,n,r={}){try{let t=r.serviceMarker===!1?k(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(r){if(!(r instanceof T))throw r;if(r.code===`layout-mismatch`||r.code===`incomplete`){let t=readDarwinImagePath(e);if(t&&isRedactedSystemImage(t))return{argvUnavailable:!0,executable:t,...n?{owner:n}:{}};throw r}if(r.code===`unsupported-platform`&&process.platform===`darwin`)throw Error(`Cannot inspect Darwin process arguments under Rosetta; run OpenClaw with native arm64 Node.js.`,{cause:r});if(r.code!==`access-denied`&&r.code!==`operation-failed`)throw r;if(_(e))return;if(n===`different`)return j||(j=!0,t(`process/census`).debug(`Unreadable Darwin arguments for another UID do not establish capture custody.`,{pid:e,code:r.code})),{argvUnavailable:!0,owner:n};throw Error(`Could not classify PID ${e}: cannot inspect Darwin arguments (${r.code}).`,{cause:r})}}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 N;function isRosettaTranslatedProcess(){return process.platform!==`darwin`||process.arch!==`x64`?!1:(N??=x.cpus()[0]?.model.includes(`Apple`)===!0,N)}let P;function isContainerEnvironment(){return P??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return!0;for(let e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{return b.accessSync(e,b.constants.F_OK),!0}catch{}try{let e=b.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return!0}catch{}return!1}function readWindowsProcessCensus(e){return O({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(A.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{D(e)}catch(e){e instanceof T&&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}:{}}]})}function readWindowsUserSid(){if(process.platform===`win32`)try{let e=w(v(),[`-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 F=Object.values(r).flatMap(e=>[y.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 I=[y.posix.normalize(`src/infra/${r.spawnBroker.sourceWorkerName}.ts`),`dist/${r.spawnBroker.distWorkerPath}`,y.posix.normalize(`src/infra/${r.directoryWatchHost.sourceWorkerName}.ts`),`dist/${r.directoryWatchHost.distWorkerPath}`];function isGatewayProcess(e,t){if(y.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 I.some(e=>n.endsWith(`/${e}`))||p(u([`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(s);if(`argvUnavailable`in e||r.length===0)return i.length?{kind:`holder`}:{kind:`not-holder`};let{position:c,operands:l}=a(r),u={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:F,inspectPackage:!0},p,h=i.flatMap(e=>{let t=d(e,u);return t.kind===`openclaw`&&t.artifactPath?[t.artifactPath]:(p??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`,[])});if(i.length&&l.length===0)return p?{kind:`unknown`,reason:p}:{kind:`holder`,paths:h};let g=m(r,u),_=isGatewayProcess(r,g),v=i.length>0||h.length>0,unscoped=()=>v||!_?{kind:`holder`}:{kind:`holder`,gateway:!0};if(g.kind===`openclaw`){if(!g.artifactPath)return l.some(({module:e})=>e)?{kind:`holder`}:unscoped();h.push(g.artifactPath),v=!0}let b=h.length?{kind:`holder`,paths:h}:void 0;if(p??=g.kind===`unclassified`&&g.cause!==`runtime-syntax`?g.reason:void 0,!n||!y.isAbsolute(n))return g.kind===`other`&&typeof c!=`number`&&c.kind===`not-runtime`&&i.length===0?{kind:`not-holder`}:{kind:`unknown`,reason:p??`working directory is unavailable`};let x=typeof c!=`number`&&c.kind!==`not-runtime`?f(n,!0):void 0;x?.kind===`package`&&x.name===`openclaw`&&(b=unscoped());let C=x?.kind===`package`?x.scripts:{};x?.kind===`unknown`&&(p??=x.reason);for(let{value:e,module:t}of l){let n=e;if(t){if(e.startsWith(`file:`))try{n=S(e)}catch(e){p??=String(e);continue}else if(!y.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){p??=`runtime module package identity is unavailable`;continue}}else if(o(r[0]??``)&&!/[\\/]/u.test(e)&&!y.extname(e)&&typeof C[e]==`string`&&C[e].trim())continue;let i=d(n,u);i.kind===`unclassified`?p??=i.reason:i.kind===`openclaw`&&(v||=i.artifactPath!==void 0,b=i.artifactPath&&(!b||b.paths)?{kind:`holder`,paths:[...b?.paths??[],i.artifactPath]}:unscoped())}return p?{kind:`unknown`,reason:p}:b??{kind:`not-holder`}}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,r=typeof t==`string`?t:void 0,i=[],a={matchingPids:[],unverifiedPids:[]};try{if(process.platform===`linux`&&isContainerEnvironment())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`,o=Date.now()+(n?15e3:1e3),s=t&&n?[...readWindowsProcessCensus(15e3)]:void 0,d=new Map(s?.map(e=>[e.pid,e])),f=t&&n?.windowsUserSid!==void 0&&readWindowsUserSid()===n.windowsUserSid,v=s?.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}})??[...g(n?15e3:1e3,{readDarwinCommand:n?(e,t)=>readDarwinProcessCommand(e,t,{serviceMarker:!1}):readDarwinProcessCommand})],b=new Map(v.map(e=>[e.pid,e])),x=b.get(process.pid);if(!x||!n&&(!x.command&&process.platform!==`darwin`||process.platform===`linux`&&v.some(e=>e.command&&!(`argv`in e.command))))throw Error(`OpenClaw process census is incomplete.`);let S=s?new Map(s.map(({pid:e,cwd:t})=>[e,t])):l(v.map(({pid:e})=>e)),w=/* @__PURE__ */ new Set,T=!n&&c(process.argv),D=/* @__PURE__ */ new Set([process.pid]),O=x,k=x.command?.ppid??x.ppid??0;for(;k>0;){let e=b.get(k);if(!e?.command||D.has(k)){if(n||e&&!e.command)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=m(t,{pid:k,serviceMarker:r,serviceMarkerUnavailable:i,cwd:S.get(k)??``,additionalEntrypoints:F}),o=a.kind===`openclaw`&&a.entryIndex!==void 0?p(u([`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(/[\\/]+$/,``),C(e,{windows:t}).href]);return RegExp(`(?:^|[^\\w-])(?:${n?literal(n.runId):`(?!)`}(?=$|[^\\w-])|(?:${r.map(literal).join(`|`)||`(?!)`})(?=$|[/\\s"'\x60);,\\]]))`)},A=n?.artifactPaths??(r?[r]:[]),j=referencePattern(A),rootKey=e=>normalize(e.replace(/[\\/]+$/,``)),M=new Set(n?.sharedRoots?.map(rootKey)),N=referencePattern(A.filter(e=>!M.has(rootKey(e)))),P=process.getuid?.(),outsideHandoffFamily=(e,t)=>{let n;try{n=E(e,{throughPid:process.pid})}catch{return!1}return n?.stoppedBy===`through-pid`||t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{let n=b.get(e.pid)?.command;return e.startTimeMicros>t*1e3||process.platform===`linux`&&n?.uid===P&&isStandardSystemdUserManager(n)})},predatesHandoffDrivers=e=>{if(process.platform!==`linux`||!n?.drivers?.length)return!1;let t=h(e)?.startedAt;return t!==void 0&&n.drivers.every(({startIdentity:e})=>BigInt(e)>BigInt(t))};for(let{pid:e,state:s,command:c}of v){if(n&&Date.now()>=o)throw Error(`Process census deadline exceeded`);if(e===process.pid||w.has(e)||(s?.startsWith(`Z`)||n)&&_(e))continue;let l=c&&`argv`in c?c.argv:void 0;if(n){if(!t&&l?.length===0)continue;let r=d.get(e),o=S.get(e),s=[...l??[],r?.commandLine??``,r?.executable??``,o??``],u=m(l??[r?.executable??``],{pid:e,cwd:o??``,serviceMarker:c&&`argv`in c?c.serviceMarker:void 0,additionalEntrypoints:F});if(s.some(e=>j.test(normalize(e)))||!n.artifactPathsOnly&&u.kind===`openclaw`){outsideHandoffFamily(e,s.some(e=>N.test(normalize(e)))?void 0:n.familyDeadline)||a.matchingPids.push(e);continue}let p=n.familyExited?`unrelated`:r&&classifyWindowsHandoffAncestry(r,d,n.drivers??[]);if(p===`descendant`){a.matchingPids.push(e);continue}if(p===`unrelated`||f&&r?.accessDenied)continue;let h=r?.foreignOwner||c?.owner===`different`||c?.uid!==void 0&&P!==void 0&&c.uid!==P;if((!l||o===void 0)&&!h&&!isStandardSystemdLoginProcess(c,b.get(c?.ppid??0)?.command,P)&&!outsideHandoffFamily(e)&&!predatesHandoffDrivers(e)){a.unverifiedPids.push(e);let n=r?.executable??l?.[0];i.push(`Could not verify handoff ancestry for PID ${e} (${n?(t?y.win32:y).basename(n):`image unavailable`}).`)}continue}let u=classifyProcessArtifactCustody(c,e,S.get(e));u.kind!==`not-holder`&&(u.kind===`holder`&&r&&(u.paths?!u.paths.some(e=>j.test(normalize(e))):u.gateway)||(a.matchingPids.push(e),u.kind===`unknown`&&i.push(`Could not verify runtime custody for PID ${e}: ${u.reason}`)))}}catch(e){let t=/Could not classify PID (\d+):/.exec(e instanceof Error?e.message:``);n&&t&&a.unverifiedPids.push(Number(t[1])),a.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?{...a,...i.length?{warnings:i}:{}}:a.error?{error:a.error}:{pids:a.matchingPids,...i.length?{warnings:i}:{}}}export{inspectOtherOpenClawProcesses};