UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 17.5 kB
import{X as e,j as t,nt as n}from"./openclaw-state-lease-heartbeat.worker-subsystem-DOArJfSi.mjs";import{n as r,r as i,t as a}from"./openclaw-state-lease-heartbeat.worker-runtime-binary-CACQv0zO.mjs";import{createRequire as s}from"node:module";import"node:crypto";import c from"node:path";import l from"node:fs";import u,{spawnSync as d}from"node:child_process";import{ProcSafeError as f}from"@openclaw/proc-safe/errors";import{readProcessIdentity as p}from"@openclaw/proc-safe/identity";import"@openclaw/fs-safe/durability";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 s of t===`win32`?e.toSorted():e){let e=t===`win32`?s.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 c=i[s];c===void 0?delete n[s]:(n[s]=c,e!==void 0&&Object.hasOwn(n,s)&&r.set(e,s))}}return n}const m=/* @__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])=>m.has(t===`win32`?e.toUpperCase():e)))}const h=`C:\\Windows`;function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=p(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let t=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!t)return h;let n=c.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:h}function windowsPowerShellPath(e){return c.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return c.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,s,c,l,u,d,f,p,m]=i;return Date.UTC(Number(a),Number(s)-1,Number(c),Number(l),Number(u),Number(d),Math.floor(Number(f)/1e3))-Number(m)*6e4*(p===`+`?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,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=r-Date.now();if(a<=0)return null;let s=d(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,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=d(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 g;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return g||=s(import.meta.url)(`@openclaw/proc-safe/identity`),g}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=p(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=p(e);return t!==null&&!t.exited}catch(e){return e instanceof f&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}let _=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=l.readFileSync(`/proc/${e}/status`,`utf8`),n=t.match(/^State:\s+(\S)/m)?.[1],r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r!==`0`){let i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`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 r=performance.now(),i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;let a=n===void 0?1e3:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=u.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(),r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{let t=l.readFileSync(`/proc/${e}/stat`,`utf8`),n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let r=t.slice(n+1).trimStart().split(/\s+/),i=Number(r[19]),a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&_!==null)return _;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&&(_=i),i}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var o=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(o===void 0&&(o=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var r=o;if(typeof o!=`function`)throw TypeError(`Object is not disposable.`);r&&(o=function(){try{r.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:o,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const v=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),y=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?v.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:y.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,v,y,`command-path`)}function getRootOptionAwareCommandPath(e,t){let n=e.slice(2),r=[],i=!1;for(let e=0;e<n.length;e+=1){let a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=!0;continue}let s=i?0:consumeRootCommandOptionToken(n,e);if(s>0)e+=s-1;else if((i||!a.startsWith(`-`))&&(r.push(a),r.length>=t))break}return r}function rewriteUpdateFlagArgv(e){let t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){let r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];let i=consumeRootOptionToken(e,n);if(i>0)n+=i-1;else if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){let a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;let s=a.indexOf(`=`),c=s===-1?a:a.slice(0,s);return n.has(c)?+(s===-1):r.has(c)?s===-1?i===`command-path`?e[t+1]===void 0?0:2:isValueToken(e[t+1])?2:0:i===`command-path`||a.slice(s+1).trim()?1:0:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,!1)}function parseCommandArgsWithRootOptions(e,t,n,r=!1){let i=e.slice(2),a=new Set(t.booleanFlags??[]),s=new Set(t.valueFlags??[]),c=[],l=[],u=[],d=0,f=!1;for(let e=0;e<i.length;e+=1){let p=i[e];if(p===void 0)break;if(!f&&p===`--`){if(t.mode!==`command-path`)break;f=!0;continue}let m=f?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(m>0)(d>0&&a.has(p)?u:l).push(...i.slice(e,e+m)),e+=m-1;else if(!f&&p.startsWith(`-`)){let n=consumeKnownOptionToken(i,e,a,s,t.mode);if(n===0||d===0)return null;u.push(p),e+=n-1}else if(d<t.commandPath.length){if(p!==t.commandPath[d])return null;if(d+=1,n&&d===t.commandPath.length){let t=i.slice(e+1);return f?[`--`,...t]:t}}else if(c.push(p),!r&&c.length===t.maxPositionals)return c}return d<t.commandPath.length?null:r?{rootOptions:l,commandOptions:u}:c}function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}function normalizeProcArg(t){return e(t.replaceAll(`\\`,`/`))}const b=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`];function referencesRetainedArtifact(e){return e.split(/[\\/=]/u).some(e=>isLegacyPluginSourceCaptureName(e)||/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e))}function readProcessPackageIdentity(e,r=!1){for(let i=e;;){let e;try{e=JSON.parse(l.readFileSync(c.join(i,`package.json`),`utf8`))}catch(e){let t=c.dirname(i);if(r&&n(e)===`ENOENT`){if(t===i)return{kind:`absent`};if(c.basename(i)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};i=t;continue}return{kind:`unknown`,reason:`could not read package identity`}}return!t(e)||typeof e.name!=`string`||!e.name.trim()||e.name!==e.name.trim()?{kind:`unknown`,reason:`package identity has no valid name`}:{kind:`package`,name:e.name,scripts:t(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){let t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0)),n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(let e of t)try{n.set(e,l.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){let e=d(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:resolveDiagnosticProcessEnv()});if(e.error||e.status!==0&&e.status!==1)return n;let r=e.stdout.split(`\0`);r.pop();let i=/* @__PURE__ */ new Set,a;for(let e of r){let r=e.replace(/^\n/,``);if(r.startsWith(`p`)){let e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else a!==void 0&&r.startsWith(`n`)&&c.isAbsolute(r.slice(1))&&(n.delete(a)?i.add(a):i.has(a)||n.set(a,r.slice(1)))}}}catch{}return n}function classifyEntrypoint(e,t={}){let n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};let r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:i(e).position;if(typeof r!=`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};let s=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&c.isAbsolute(t.cwd)&&a(e[0]??``)&&!/[\\/]/u.test(s)&&!c.extname(s)){let e=readProcessPackageIdentity(t.cwd,!0);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};let n=e.kind===`package`?e.scripts[s]:void 0;if(typeof n==`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}let l=classifyOpenClawEntrypointPath(s,t);return l.kind===`openclaw`?{...l,entryIndex:r}:l}function classifyOpenClawEntrypointPath(e,t={}){let n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let r=[...b,...t.additionalEntrypoints??[]],i=e;if(!c.isAbsolute(e)){let n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!c.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=c.resolve(n,e)}let a,s;try{if(a=l.realpathSync(i),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};let n=t.requirePackageIdentity||t.inspectPackage?l.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};s=n?.isDirectory()??!1}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}let u=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let d=s?void 0:r.find(e=>u.endsWith(`/${e}`));if(!d&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let f=d?a.slice(0,-d.length):s?a:c.dirname(a),p=readProcessPackageIdentity(f,t.inspectPackage&&!t.requirePackageIdentity||!d&&!s);return p.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:p.reason}:p.kind===`package`&&p.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:c.resolve(f),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:i,owner:s,pid:c,port:u}=t;if(!t.requirePackageIdentity&&i===`gateway`&&s?.pid===c&&s?.state===`live`&&(u===void 0||s.port===u))return{kind:`openclaw`};let d=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(d))return!i||d===`openclaw-${i}`?{kind:`openclaw`}:{kind:`other`};let f=classifyEntrypoint(e,t);if(i)return f.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(f.entryIndex)],1)[0]??``)!==i?{kind:`other`}:f;if(f.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return f.kind===`openclaw`?f:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let p=t.serviceMarker;if(c!==void 0&&process.platform===`linux`&&(r(d)||a(d)||d===`tsx`))try{p=l.readFileSync(`/proc/${c}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${n(e)??`unavailable`})`}}return!t.requirePackageIdentity&&p===`openclaw`?{kind:`openclaw`}:f}export{referencesRetainedArtifact as a,isUpdateCommandArgv as c,getFileLockProcessStartTime as d,isPidAlive as f,resolveDiagnosticProcessEnv as g,mergeProcessEnv as h,readProcessWorkingDirectories as i,rewriteUpdateFlagArgv as l,readLinuxProcessStat as m,classifyOpenClawEntrypointPath as n,getCommandPositionalsWithRootOptions as o,isPidDefinitelyDead as p,readProcessPackageIdentity as r,getRootOptionAwareCommandPath as s,classifyOpenClawArgv as t,_usingCtx as u};