UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 10.7 kB
import{U as extractErrorCode,ft as normalizeLowercaseStringOrEmpty,yt as isRecord}from"./paths--OfTlHNJ.js";import"./path-existence-CCBbp2xL.js";import{n as isNodeRuntime,r as resolveRuntimeScriptPosition,t as isBunRuntime}from"./runtime-binary-BWC3z4wd.js";import{l as resolveDiagnosticProcessEnv}from"./pid-alive-b9rOSUDi.js";import path from"node:path";import fs,{closeSync,openSync}from"node:fs";import{sha256FileSync}from"@openclaw/fs-safe/durability";import{createHash,hash}from"node:crypto";import{spawnSync}from"node:child_process"; //!src/infra/crypto-digest.ts function sha256Base64Url(e){return hash(`sha256`,e,`base64url`)}function sha256FileSync$1(e){const t=openSync(e,`r`);try{return sha256FileSync(t).digest}finally{closeSync(t)}} //!src/infra/container-environment.ts let containerEnvironmentCache;function isContainerEnvironment(){return containerEnvironmentCache??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return true;for(const e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{fs.accessSync(e,fs.constants.F_OK);return true}catch{}try{const e=fs.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return true}catch{}return false}const FLAG_TERMINATOR=`--`;const ROOT_BOOLEAN_FLAGS=/* @__PURE__ */ new Set([`--dev`,`--no-color`]);const ROOT_VALUE_FLAGS=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){if(!e||e===`--`)return false;if(!e.startsWith(`-`))return true;return/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){const n=e[t];if(!n)return 0;if(ROOT_BOOLEAN_FLAGS.has(n))return 1;if(n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`))return 1;if(ROOT_VALUE_FLAGS.has(n))return isValueToken(e[t+1])?2:1;return 0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,ROOT_BOOLEAN_FLAGS,ROOT_VALUE_FLAGS,`command-path`)}function getRootOptionAwareCommandPath(e,t){const n=e.slice(2);const r=[];let i=false;for(let e=0;e<n.length;e+=1){const a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=true;continue}const o=i?0:consumeRootCommandOptionToken(n,e);if(o>0){e+=o-1;continue}if(!i&&a.startsWith(`-`))continue;r.push(a);if(r.length>=t)break}return r}function rewriteUpdateFlagArgv(e){const t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){const r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];const i=consumeRootOptionToken(e,n);if(i>0){n+=i-1;continue}if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){const a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;const o=a.indexOf(`=`);const s=o===-1?a:a.slice(0,o);if(n.has(s))return o===-1?1:0;if(!r.has(s))return 0;if(o!==-1)return i===`command-path`||a.slice(o+1).trim()?1:0;if(i===`command-path`)return e[t+1]!==void 0?2:0;return isValueToken(e[t+1])?2:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,false)}function parseCommandArgsWithRootOptions(e,t,n,r=false){const i=e.slice(2);const a=new Set(t.booleanFlags??[]);const o=new Set(t.valueFlags??[]);const s=[];const c=[];const l=[];let u=0;let d=false;for(let e=0;e<i.length;e+=1){const f=i[e];if(f===void 0)break;if(!d&&f===`--`){if(t.mode!==`command-path`)break;d=true;continue}const p=d?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(p>0){(u>0&&a.has(f)?l:c).push(...i.slice(e,e+p));e+=p-1;continue}if(!d&&f.startsWith(`-`)){const n=consumeKnownOptionToken(i,e,a,o,t.mode);if(n===0||u===0)return null;l.push(f);e+=n-1;continue}if(u<t.commandPath.length){if(f!==t.commandPath[u])return null;u+=1;if(n&&u===t.commandPath.length){const t=i.slice(e+1);return d?[`--`,...t]:t}continue}s.push(f);if(!r&&s.length===t.maxPositionals)return s}return u<t.commandPath.length?null:r?{rootOptions:c,commandOptions:l}:s} //!src/plugins/plugin-source-capture-path.ts const PLUGIN_SOURCE_CAPTURE_PREFIX=`openclaw-plugin-build-`;function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)} //!src/infra/gateway-process-argv.ts function normalizeProcArg(e){return normalizeLowercaseStringOrEmpty(e.replaceAll(`\\`,`/`))}const ENTRY_CANDIDATES=[`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,t=false){for(let n=e;;){let e;try{e=JSON.parse(fs.readFileSync(path.join(n,`package.json`),`utf8`))}catch(e){const r=path.dirname(n);if(t&&extractErrorCode(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(path.basename(n)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};n=r;continue}return{kind:`unknown`,reason:`could not read package identity`}}if(!isRecord(e)||typeof e.name!==`string`||!e.name.trim()||e.name!==e.name.trim())return{kind:`unknown`,reason:`package identity has no valid name`};return{kind:`package`,name:e.name,scripts:isRecord(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){const t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0));const n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(const e of t)try{n.set(e,fs.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){const e=spawnSync(`/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;const r=e.stdout.split(`\0`);r.pop();const i=/* @__PURE__ */ new Set;let a;for(const e of r){const r=e.replace(/^\n/,``);if(r.startsWith(`p`)){const e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else if(a!==void 0&&r.startsWith(`n`)&&path.isAbsolute(r.slice(1))){if(n.delete(a))i.add(a);else if(!i.has(a))n.set(a,r.slice(1))}}}}catch{}return n}function classifyEntrypoint(e,t={}){const n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};const r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:resolveRuntimeScriptPosition(e).position;if(typeof r!==`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};const i=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&path.isAbsolute(t.cwd)&&isBunRuntime(e[0]??``)&&!/[\\/]/u.test(i)&&!path.extname(i)){const e=readProcessPackageIdentity(t.cwd,true);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};const n=e.kind===`package`?e.scripts[i]:void 0;if(typeof n===`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}const a=classifyOpenClawEntrypointPath(i,t);return a.kind===`openclaw`?{...a,entryIndex:r}:a}function classifyOpenClawEntrypointPath(e,t={}){const n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};const r=[...ENTRY_CANDIDATES,...t.additionalEntrypoints??[]];let i=e;if(!path.isAbsolute(e)){const n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!path.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=path.resolve(n,e)}let a;let o;try{a=fs.realpathSync(i);if(t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};const n=t.requirePackageIdentity||t.inspectPackage?fs.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};o=n?.isDirectory()??false}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}const s=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};const c=o?void 0:r.find(e=>s.endsWith(`/${e}`));if(!c&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};const l=c?a.slice(0,-c.length):o?a:path.dirname(a);const u=readProcessPackageIdentity(l,t.inspectPackage&&!t.requirePackageIdentity||!c&&!o);if(u.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:u.reason};return u.kind===`package`&&u.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:path.resolve(l),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){const{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};const o=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(o))return!n||o===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};const s=classifyEntrypoint(e,t);if(n)return s.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(s.entryIndex)],1)[0]??``)!==n?{kind:`other`}:s;if(s.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return s.kind===`openclaw`?s:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let c=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(isNodeRuntime(o)||isBunRuntime(o)||o===`tsx`))try{c=fs.readFileSync(`/proc/${i}/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 (${extractErrorCode(e)??`unavailable`})`}}return!t.requirePackageIdentity&&c===`openclaw`?{kind:`openclaw`}:s}export{referencesRetainedArtifact as a,isUpdateCommandArgv as c,sha256Base64Url as d,sha256FileSync$1 as f,readProcessWorkingDirectories as i,rewriteUpdateFlagArgv as l,classifyOpenClawEntrypointPath as n,getCommandPositionalsWithRootOptions as o,readProcessPackageIdentity as r,getRootOptionAwareCommandPath as s,classifyOpenClawArgv as t,isContainerEnvironment as u};