UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 17.8 kB
import{B as e,gt as t,t as n}from"./disk-budget.worker-subsystem-9qP7ka6r.mjs";import{a as r,c as i,f as a,i as o,l as s,n as c,r as l,s as u,t as d}from"./disk-budget.worker-gateway-process-argv-lGmvE77y.mjs";import{c as f,r as p,s as m,u as h}from"./disk-budget.worker-service-child-group-ownership-DO90jxGH.mjs";import{a as g,n as _,r as v,t as y}from"./disk-budget.worker-runtime-binary-B_EAZwtR.mjs";import{createRequire as b}from"node:module";import x from"node:fs";import S from"node:os";import C from"node:path";import{fileURLToPath as w,pathToFileURL as T}from"node:url";import{execFileSync as E,spawnSync as D}from"node:child_process";import{ProcSafeError as O}from"@openclaw/proc-safe/errors";import{readProcessAncestry as k,readProcessIdentity as A}from"@openclaw/proc-safe/identity";import{listProcesses as j,readProcessCommand as M}from"@openclaw/proc-safe/inspect";import{PinnedProcess as N}from"@openclaw/proc-safe/windows-job";let P=!1;const F=/\[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=D(`/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&&D(`/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=D(`/usr/bin/codesign`,[`-d`,`--entitlements`,`-`,e],{encoding:`utf8`,timeout:2e3});return t.status===0&&F.test(t.stdout)}function readCommandWithServiceMarker(e){try{return M(e,{environmentKeys:[`OPENCLAW_SERVICE_MARKER`]})}catch(t){if(!(t instanceof O)||t.code!==`incomplete`)throw t;let n=M(e);return n&&[n.executable,n.argv[0]??``].some(e=>_(e)||y(e)||C.basename(e)===`tsx`)?{...n,serviceMarkerUnavailable:!0}:n}}function readDarwinProcessCommand(e,t,r={}){try{let t=r.serviceMarker===!1?M(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 O))throw r;if(r.code===`layout-mismatch`||r.code===`incomplete`){let n=readDarwinImagePath(e);if(n&&isRedactedSystemImage(n))return{argvUnavailable:!0,executable:n,...t?{owner:t}:{}};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(m(e))return;if(t===`different`)return P||(P=!0,n(`process/census`).debug(`Unreadable Darwin arguments for another UID do not establish capture custody.`,{pid:e,code:r.code})),{argvUnavailable:!0,owner:t};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 I;function isRosettaTranslatedProcess(){return process.platform!==`darwin`||process.arch!==`x64`?!1:(I??=S.cpus()[0]?.model.includes(`Apple`)===!0,I)}let L;function isContainerEnvironment(){return L??=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 x.accessSync(e,x.constants.F_OK),!0}catch{}try{let e=x.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 j({timeoutMs:e,includeCommand:!0}).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 o=a();i=o.u(N.open(e,{access:`observe`,expect:{startTimeMicros:n.startTimeMicros}}))?.imagePath}catch(e){o.e=e}finally{o.d()}}catch{}let s;if(t===`unknown`&&!n&&!r)try{A(e)}catch(e){e instanceof O&&e.code===`access-denied`&&(s=!0)}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:!0}:{},...s?{accessDenied:s}:{}}]})}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 R=!1,z;function assertAppContainerSpawnSupported(e){if(process.platform===`win32`&&!(e===`ignore`||e===`inherit`||Array.isArray(e)&&e.length>=3&&e.every(e=>e!=null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e==`number`&&e<0)))){if(!R){R=!0;try{let{readCurrentAppContainerSid:e}=b(import.meta.url)(`@openclaw/proc-safe/windows-token`),t=e(),n=process.versions.uv,r=Number(n.split(`.`)[0]),i=Number(n.split(`.`)[1]);t!==null&&(r<1||r===1&&i<53)&&(z=new AppContainerSpawnUnsupportedError(n))}catch(e){import(`./disk-budget.worker-subsystem-9qP7ka6r.mjs`).then(e=>e.n).then(({createSubsystemLogger:t})=>{t(`process`).debug(`AppContainer token probe failed; allowing spawn`,{error:String(e)})}).catch(()=>{})}}if(z)throw z}}const B=`C:\\Windows`,V=5e3;let H=null;function locateWindowsRegExe(){let e=C.win32.join(B,`System32`,`reg.exe`);return t(e,x.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 i=locateWindowsRegExe();if(!i)return null;for(let a of[[`/reg:64`],[]]){let o=r===void 0?V:Math.min(V,Math.ceil(r-performance.now()));if(o<=0)return null;assertAppContainerSpawnSupported();try{let r=E(i,[`query`,t,`/v`,n,...a],{env:h(),encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:o,windowsHide:!0}),s=RegExp(`^\\s*${e(n)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`,`im`),c=r.match(s)?.[1]?.trim();if(c)return c}catch{}}return null}function resolveSystemRootFromEnv(e){return normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`SystemRoot`))??normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e,`WINDIR`))??B}function getProcessRoots(e){if(!H){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;H=n}return H}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=D(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 U=Object.values(g).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 W=[C.posix.normalize(`src/infra/${g.spawnBroker.sourceWorkerName}.ts`),`dist/${g.spawnBroker.distWorkerPath}`,C.posix.normalize(`src/infra/${g.directoryWatchHost.sourceWorkerName}.ts`),`dist/${g.directoryWatchHost.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 W.some(e=>n.endsWith(`/${e}`))||u(s([`node`,...e.slice(t.entryIndex)]),1)[0]===`gateway`}function classifyProcessArtifactCustody(e,t,n){if(!e)return{kind:`unknown`,reason:`process command is unavailable`};let i=`argv`in e?e.argv:[],a=[...i.map(e=>e.replace(/^--[^=]+=/u,``).replace(/^-r(?=.)/u,``)),n??``,`executable`in e?e.executable??``:``].filter(r);if(`argvUnavailable`in e||i.length===0)return a.length?{kind:`holder`}:{kind:`not-holder`};let{position:o,operands:s}=v(i),u={pid:t,cwd:n??``,serviceMarker:e.serviceMarker,serviceMarkerUnavailable:e.serviceMarkerUnavailable,additionalEntrypoints:U,inspectPackage:!0},f,p=a.flatMap(e=>{let t=c(e,u);return t.kind===`openclaw`&&t.artifactPath?[t.artifactPath]:(f??=t.kind===`unclassified`?t.reason:`runtime path is unresolved`,[])});if(a.length&&s.length===0)return f?{kind:`unknown`,reason:f}:{kind:`holder`,paths:p};let m=d(i,u),h=isGatewayProcess(i,m),g=a.length>0||p.length>0,unscoped=()=>g||!h?{kind:`holder`}:{kind:`holder`,gateway:!0};if(m.kind===`openclaw`){if(!m.artifactPath)return s.some(({module:e})=>e)?{kind:`holder`}:unscoped();p.push(m.artifactPath),g=!0}let _=p.length?{kind:`holder`,paths:p}:void 0;if(f??=m.kind===`unclassified`&&m.cause!==`runtime-syntax`?m.reason:void 0,!n||!C.isAbsolute(n))return m.kind===`other`&&typeof o!=`number`&&o.kind===`not-runtime`&&a.length===0?{kind:`not-holder`}:{kind:`unknown`,reason:f??`working directory is unavailable`};let b=typeof o!=`number`&&o.kind!==`not-runtime`?l(n,!0):void 0;b?.kind===`package`&&b.name===`openclaw`&&(_=unscoped());let x=b?.kind===`package`?b.scripts:{};b?.kind===`unknown`&&(f??=b.reason);for(let{value:e,module:t}of s){let n=e;if(t){if(e.startsWith(`file:`))try{n=w(e)}catch(e){f??=String(e);continue}else if(!C.isAbsolute(e)&&!e.startsWith(`./`)&&!e.startsWith(`../`)){f??=`runtime module package identity is unavailable`;continue}}else if(y(i[0]??``)&&!/[\\/]/u.test(e)&&!C.extname(e)&&typeof x[e]==`string`&&x[e].trim())continue;let r=c(n,u);r.kind===`unclassified`?f??=r.reason:r.kind===`openclaw`&&(g||=r.artifactPath!==void 0,_=r.artifactPath&&(!_||_.paths)?{kind:`holder`,paths:[..._?.paths??[],r.artifactPath]}:unscoped())}return f?{kind:`unknown`,reason:f}:_??{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,a=[],c={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`,l=Date.now()+(n?15e3:1e3),h=t&&n?[...readWindowsProcessCensus(15e3)]:void 0,g=new Map(h?.map(e=>[e.pid,e])),_=t&&n?.windowsUserSid!==void 0&&readWindowsUserSid()===n.windowsUserSid,v=h?.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}})??[...p(n?15e3:1e3,{readDarwinCommand:n?(e,t)=>readDarwinProcessCommand(e,t,{serviceMarker:!1}):readDarwinProcessCommand})],y=new Map(v.map(e=>[e.pid,e])),b=y.get(process.pid);if(!b||!n&&(!b.command&&process.platform!==`darwin`||process.platform===`linux`&&v.some(e=>e.command&&!(`argv`in e.command))))throw Error(`OpenClaw process census is incomplete.`);let x=h?new Map(h.map(({pid:e,cwd:t})=>[e,t])):o(v.map(({pid:e})=>e)),S=/* @__PURE__ */ new Set,w=!n&&i(process.argv),E=/* @__PURE__ */ new Set([process.pid]),D=b,O=b.command?.ppid??b.ppid??0;for(;O>0;){let e=y.get(O);if(!e?.command||E.has(O)){if(n||e&&!e.command)break;throw Error(`OpenClaw process ancestry is incomplete.`)}let r=g.get(O)?.startIdentity,i=g.get(D.pid)?.startIdentity;if(t&&(!r||!i||BigInt(r)>=BigInt(i)))break;if(E.add(O),`argv`in e.command){let{argv:t,serviceMarker:r,serviceMarkerUnavailable:i}=e.command,a=d(t,{pid:O,serviceMarker:r,serviceMarkerUnavailable:i,cwd:x.get(O)??``,additionalEntrypoints:U}),o=a.kind===`openclaw`&&a.entryIndex!==void 0?u(s([`node`,...t.slice(a.entryIndex)]),1)[0]:void 0;(o===(n?`update`:`doctor`)||w&&o===`update`&&O===(b.command?.ppid??b.ppid))&&S.add(O)}D=e,O=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(/[\\/]+$/,``),T(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=k(e,{throughPid:process.pid})}catch{return!1}return n?.stoppedBy===`through-pid`||t!==void 0&&n?.stoppedBy===`root`&&n.chain.every(e=>{let n=y.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=f(e)?.startedAt;return t!==void 0&&n.drivers.every(({startIdentity:e})=>BigInt(e)>BigInt(t))};for(let{pid:e,state:i,command:o}of v){if(n&&Date.now()>=l)throw Error(`Process census deadline exceeded`);if(e===process.pid||S.has(e)||(i?.startsWith(`Z`)||n)&&m(e))continue;let s=o&&`argv`in o?o.argv:void 0;if(n){if(!t&&s?.length===0)continue;let r=g.get(e),i=x.get(e),l=[...s??[],r?.commandLine??``,r?.executable??``,i??``],u=d(s??[r?.executable??``],{pid:e,cwd:i??``,serviceMarker:o&&`argv`in o?o.serviceMarker:void 0,additionalEntrypoints:U});if(l.some(e=>j.test(normalize(e)))||!n.artifactPathsOnly&&u.kind===`openclaw`){outsideHandoffFamily(e,l.some(e=>N.test(normalize(e)))?void 0:n.familyDeadline)||c.matchingPids.push(e);continue}let f=n.familyExited?`unrelated`:r&&classifyWindowsHandoffAncestry(r,g,n.drivers??[]);if(f===`descendant`){c.matchingPids.push(e);continue}if(f===`unrelated`||_&&r?.accessDenied)continue;let p=r?.foreignOwner||o?.owner===`different`||o?.uid!==void 0&&P!==void 0&&o.uid!==P;if((!s||i===void 0)&&!p&&!isStandardSystemdLoginProcess(o,y.get(o?.ppid??0)?.command,P)&&!outsideHandoffFamily(e)&&!predatesHandoffDrivers(e)){c.unverifiedPids.push(e);let n=r?.executable??s?.[0];a.push(`Could not verify handoff ancestry for PID ${e} (${n?(t?C.win32:C).basename(n):`image unavailable`}).`)}continue}let u=classifyProcessArtifactCustody(o,e,x.get(e));u.kind!==`not-holder`&&(u.kind===`holder`&&r&&(u.paths?!u.paths.some(e=>j.test(normalize(e))):u.gateway)||(c.matchingPids.push(e),u.kind===`unknown`&&a.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&&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,...a.length?{warnings:a}:{}}:c.error?{error:c.error}:{pids:c.matchingPids,...a.length?{warnings:a}:{}}}export{inspectOtherOpenClawProcesses};