openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 9.75 kB
JavaScript
import{at as hasErrnoCode,st as isErrno}from"./paths--OfTlHNJ.js";import{createRequire}from"node:module";import path from"node:path";import fs from"node:fs";import childProcess,{spawnSync}from"node:child_process";import{ProcSafeError}from"@openclaw/proc-safe/errors";import{readProcessIdentity}from"@openclaw/proc-safe/identity";
//!src/infra/process-env.ts
function resolveEnvironmentValue(e,t,n=process.platform){if(!e)return;if(n!==`win32`)return e[t]??(t===`PATH`?e.Path:void 0);const r=t.toUpperCase();const i=Object.keys(e).toSorted().find(e=>e.toUpperCase()===r);return i===void 0?void 0:e[i]}function mergeProcessEnv(e,t=process.platform){const n=Object.create(null);const r=/* @__PURE__ */ new Map;for(const i of e){if(!i)continue;const e=Object.keys(i);const a=/* @__PURE__ */ new Set;for(const o of t===`win32`?e.toSorted():e){const e=t===`win32`?o.toUpperCase():void 0;if(e!==void 0){if(a.has(e))continue;a.add(e);const t=r.get(e);if(t!==void 0)delete n[t];r.delete(e)}const s=i[o];if(s===void 0)delete n[o];else{n[o]=s;if(e!==void 0&&Object.hasOwn(n,o))r.set(e,o)}}}return n}const DIAGNOSTIC_PROCESS_ENV_KEYS=/* @__PURE__ */ new Set([`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`]);function resolveDiagnosticProcessEnv(e=process.env,t=process.platform){return Object.fromEntries(Object.entries(mergeProcessEnv([e],t)).filter(([e])=>DIAGNOSTIC_PROCESS_ENV_KEYS.has(t===`win32`?e.toUpperCase():e)))}
//!src/infra/windows-process-start.ts
const DEFAULT_TIMEOUT_MS=5e3;const DEFAULT_PROCESS_START_TIMEOUT_MS=1e4;const DEFAULT_WINDOWS_SYSTEM_ROOT=`C:\\Windows`;function readNativeProcessStartTime(e){if(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD===`boolean`&&SEALED_RUNTIME_BUILD)return;try{const t=readProcessIdentity(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){const t=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!t)return DEFAULT_WINDOWS_SYSTEM_ROOT;const n=path.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:DEFAULT_WINDOWS_SYSTEM_ROOT}function windowsPowerShellPath(e){return path.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return path.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){if(!Buffer.isBuffer(e))return e;return e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`)}function parseWindowsProcessStartTime(e){const t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean);const n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``;const r=Date.parse(n);if(Number.isFinite(r))return r;const i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;const[,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=DEFAULT_PROCESS_START_TIMEOUT_MS,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;const r=performance.now()+t;const i=readNativeProcessStartTime(e);if(i!==void 0)return i;const a=Math.ceil(r-performance.now());if(a<=0)return null;const o=spawnSync(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(a,DEFAULT_TIMEOUT_MS),windowsHide:true});if(!o.error&&o.status===0){const e=parseWindowsProcessStartTime(o.stdout);if(e!==null)return e}const s=Math.ceil(r-performance.now());if(s<=0)return null;const c=spawnSync(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:resolveDiagnosticProcessEnv(n,`win32`),timeout:s,windowsHide:true,stdio:[`ignore`,`pipe`,`ignore`]});return!c.error&&c.status===0?parseWindowsProcessStartTime(c.stdout):null}
//!src/shared/freebsd-process-identity-native.ts
let identity;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD===`boolean`&&SEALED_RUNTIME_BUILD)throw new Error(`FreeBSD process identity is unavailable in this sealed runtime`);if(!identity)identity=createRequire(import.meta.url)(`@openclaw/proc-safe/identity`);return identity}
//!src/shared/freebsd-process-identity.ts
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}}
//!src/shared/pid-alive.ts
const PROCESS_START_TIMEOUT_MS=1e3;function readDarwinNativeIdentity(e){if(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD===`boolean`&&SEALED_RUNTIME_BUILD)return;try{const t=readProcessIdentity(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)return;try{const t=readProcessIdentity(e);return t!==null&&!t.exited}catch(e){if(e instanceof ProcSafeError&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`))return;return true}}let selfStartTime=null;function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function exitedLinuxStatus(e,t){const n=t.match(/^State:\s+(\S)/m)?.[1];const r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r===`0`)return;const i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`1`}function isMissingPid(e){try{process.kill(e,0)}catch(e){return hasErrnoCode(e,`ESRCH`)}return false}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return false;try{const t=exitedLinuxStatus(e,fs.readFileSync(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}async function isPidDefinitelyDeadAsync(e){if(!hasLinuxProcfs())return isPidDefinitelyDead(e);if(!isValidPid(e))return true;try{process.kill(e,0)}catch(e){return hasErrnoCode(e,`ESRCH`)}try{const t=exitedLinuxStatus(e,await fs.promises.readFile(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}function isPidAlive(e){if(!isValidPid(e))return false;try{process.kill(e,0)}catch(t){const n=isErrno(t)?t.code:void 0;if(n!==`EPERM`)return n===`ESRCH`?readNativeLiveness(e)??false:false}return readNativeLiveness(e)??!isExitedLinuxProcess(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return true;let t=false;try{process.kill(e,0)}catch(e){const n=isErrno(e)?e.code:void 0;if(n!==`ESRCH`&&!(process.platform===`win32`&&n===`EPERM`))return false;t=n===`ESRCH`}const n=readNativeLiveness(e);return n===void 0?t&&process.platform!==`freebsd`||isExitedLinuxProcess(e):!n}function getDarwinProcessStartTime(e,t,n){const r=performance.now();const i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;const a=n===void 0?PROCESS_START_TIMEOUT_MS:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{const n=childProcess.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...resolveDiagnosticProcessEnv(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:a,killSignal:`SIGKILL`}).trim();const r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function parseLinuxProcessStat(e,t){const n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;const r=t.slice(n+1).trimStart().split(/\s+/);const i=Number(r[19]);const a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{return parseLinuxProcessStat(e,fs.readFileSync(`/proc/${e}/stat`,`utf8`))}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){const t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}const t=readDarwinNativeIdentity(e);if(!t)return null;const n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;const r=e===process.pid;if(r&&selfStartTime!==null)return selfStartTime;const i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);if(r&&i!==null)selfStartTime=i;return i}export{isPidDefinitelyDeadAsync as a,mergeProcessEnv as c,isPidDefinitelyDead as i,resolveDiagnosticProcessEnv as l,getProcessInstanceStartTime as n,parseLinuxProcessStat as o,isPidAlive as r,readLinuxProcessStat as s,getFileLockProcessStartTime as t};