UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 8.05 kB
import{createRequire as e}from"node:module";import t from"node:path";import n from"node:fs";import r,{spawnSync as i}from"node:child_process";import{ProcSafeError as a}from"@openclaw/proc-safe/errors";import{readProcessIdentity as o}from"@openclaw/proc-safe/identity";function resolveEnvironmentValue(e,t,n=process.platform){if(!e)return;if(n!==`win32`)return e[t]??(t===`PATH`?e.Path:void 0);let r=t.toUpperCase(),i=Object.keys(e).toSorted().find(e=>e.toUpperCase()===r);return i===void 0?void 0:e[i]}function mergeProcessEnv(e,t=process.platform){let n=Object.create(null),r=/* @__PURE__ */ new Map;for(let i of e){if(!i)continue;let e=Object.keys(i),a=/* @__PURE__ */ new Set;for(let o of t===`win32`?e.toSorted():e){let e=t===`win32`?o.toUpperCase():void 0;if(e!==void 0){if(a.has(e))continue;a.add(e);let t=r.get(e);t!==void 0&&delete n[t],r.delete(e)}let s=i[o];s===void 0?delete n[o]:(n[o]=s,e!==void 0&&Object.hasOwn(n,o)&&r.set(e,o))}}return n}const s=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.Path.HOME.USER.LOGNAME.TMPDIR.TMP.TEMP.LANG.LANGUAGE.TZ.LC_ALL.LC_COLLATE.LC_CTYPE.LC_MESSAGES.LC_MONETARY.LC_NUMERIC.LC_TIME.LC_ADDRESS.LC_IDENTIFICATION.LC_MEASUREMENT.LC_NAME.LC_PAPER.LC_TELEPHONE.SYSTEMROOT.WINDIR.COMSPEC.PATHEXT.SYSTEMDRIVE.USERPROFILE.HOMEDRIVE.HOMEPATH.USERNAME.USERDOMAIN.APPDATA.LOCALAPPDATA.PROGRAMDATA.ALLUSERSPROFILE.PROGRAMFILES.PROGRAMFILES(X86).PROGRAMW6432.COMMONPROGRAMFILES.COMMONPROGRAMFILES(X86).COMMONPROGRAMW6432.PSMODULEANALYSISCACHEPATH`.split(`.`));function resolveDiagnosticProcessEnv(e=process.env,t=process.platform){return Object.fromEntries(Object.entries(mergeProcessEnv([e],t)).filter(([e])=>s.has(t===`win32`?e.toUpperCase():e)))}const c=`C:\\Windows`;function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=o(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let n=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!n)return c;let r=t.win32.normalize(n);return/^[A-Za-z]:\\/.test(r)&&!r.startsWith(`\\\\`)?r:c}function windowsPowerShellPath(e){return t.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return t.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){return Buffer.isBuffer(e)?e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`):e}function parseWindowsProcessStartTime(e){let t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean),n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``,r=Date.parse(n);if(Number.isFinite(r))return r;let i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;let[,a,o,s,c,l,u,d,f,p]=i;return Date.UTC(Number(a),Number(o)-1,Number(s),Number(c),Number(l),Number(u),Math.floor(Number(d)/1e3))-Number(p)*6e4*(f===`+`?1:-1)}function readWindowsProcessStartTimeSync(e,t=1e4,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=Date.now()+t,a=readNativeProcessStartTime(e);if(a!==void 0)return a;let o=r-Date.now();if(o<=0)return null;let s=i(windowsPowerShellPath(n),[`-NoProfile`,`-NonInteractive`,`-Command`,`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`],{encoding:`utf8`,env:resolveDiagnosticProcessEnv(n,`win32`),timeout:Math.min(o,5e3),windowsHide:!0});if(!s.error&&s.status===0){let e=parseWindowsProcessStartTime(s.stdout);if(e!==null)return e}let c=r-Date.now();if(c<=0)return null;let l=i(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:resolveDiagnosticProcessEnv(n,`win32`),timeout:c,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]});return!l.error&&l.status===0?parseWindowsProcessStartTime(l.stdout):null}let l;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return l||=e(import.meta.url)(`@openclaw/proc-safe/identity`),l}function readFreeBsdProcessStartTime(e){if(process.platform!==`freebsd`||!Number.isInteger(e)||e<=0||e>2147483647)return null;try{return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros??null}catch{return null}}function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=o(e);return t&&!t.exited?{startedAt:Math.floor(t.startTimeMicros/1e6),startTimeMicros:t.startTimeMicros}:null}catch{return}}function readNativeLiveness(e){if(!(![`darwin`,`win32`,`freebsd`].includes(process.platform)||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=o(e);return t!==null&&!t.exited}catch(e){return e instanceof a&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}let u=null;function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=n.readFileSync(`/proc/${e}/status`,`utf8`),r=t.match(/^State:\s+(\S)/m)?.[1],i=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(i!==`0`){let n=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return n!==void 0&&Number(n)!==e||(r===`Z`||r===`X`)&&i===`1`}}catch{}try{process.kill(e,0)}catch(e){return e.code===`ESRCH`}return!1}function isPidAlive(e){if(!isValidPid(e))return!1;try{process.kill(e,0)}catch(t){let n=t.code;if(n!==`EPERM`)return n===`ESRCH`?readNativeLiveness(e)??!1:!1}return readNativeLiveness(e)??!isExitedLinuxProcess(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return!0;let t=!1;try{process.kill(e,0)}catch(e){let n=e.code;if(n!==`ESRCH`&&(process.platform!==`win32`||n!==`EPERM`))return!1;t=n===`ESRCH`}let n=readNativeLiveness(e);return n===void 0?t&&process.platform!==`freebsd`||isExitedLinuxProcess(e):!n}function getDarwinProcessStartTime(e,t,n){let i=performance.now(),a=readDarwinNativeIdentity(e);if(a!==void 0)return a?.startedAt??null;let o=n===void 0?1e3:Math.ceil(n-(performance.now()-i));if(o<=0)return null;try{let n=r.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...resolveDiagnosticProcessEnv(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:o,killSignal:`SIGKILL`}).trim(),i=Date.parse(`${n} UTC`);return Number.isFinite(i)?Math.floor(i/1e3):null}catch{return null}}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{let t=n.readFileSync(`/proc/${e}/stat`,`utf8`),r=t.lastIndexOf(`)`);if(r<0||!t.startsWith(`${e} (`))return null;let i=t.slice(r+1).trimStart().split(/\s+/),a=Number(i[19]),o=Number(i[1]);return Number.isSafeInteger(a)&&a>=0&&Number.isSafeInteger(o)&&o>=0?{parentPid:o,startedAt:a}:null}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){let t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}let t=readDarwinNativeIdentity(e);if(!t)return null;let n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&u!==null)return u;let i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);return r&&i!==null&&(u=i),i}export{readLinuxProcessStat as a,isPidDefinitelyDead as i,getProcessInstanceStartTime as n,mergeProcessEnv as o,isPidAlive as r,resolveDiagnosticProcessEnv as s,getFileLockProcessStartTime as t};