openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 12.3 kB
JavaScript
import{l as resolveGlobalSingleton,n as normalizeLowercaseStringOrEmpty}from"./string-coerce-BBqv4GXj.mjs";import{i as emitInternalDiagnosticEvent,t as areDiagnosticsEnabledForProcess}from"./diagnostic-events-BhwiQ5PS.mjs";import{AsyncLocalStorage}from"node:async_hooks";import{spawn}from"node:child_process";import fsSync from"node:fs";import path from"node:path";
//!src/infra/exec-wrapper-tokens.ts
function normalizeExecutableToken(e){const t=path.win32.basename(e);const n=path.posix.basename(e);const r=t.length<n.length?t:n;return normalizeLowercaseStringOrEmpty(r).replace(/\.(?:exe|cmd|bat|com)$/,``)}
//!src/infra/shell-inline-command.ts
const POSIX_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([`-lc`,`-c`,`--command`,`--commands`,`--cmdline`]);const NUSHELL_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([...POSIX_INLINE_COMMAND_FLAGS,`-e`,`--execute`]);function expandPowerShellSwitchPrefixForms(e,t){const n=[];for(let r=t.length;r<=e.length;r+=1){const t=e.slice(0,r);n.push(`-${t}`,`--${t}`,`/${t}`)}return n}function expandPowerShellSwitchForms(e){return e.flatMap(e=>{const t=normalizeLowercaseStringOrEmpty(e);return[`-${t}`,`--${t}`,`/${t}`]})}const POWERSHELL_COMMAND_FLAGS=[...expandPowerShellSwitchPrefixForms(`command`,`c`),...expandPowerShellSwitchPrefixForms(`commandwithargs`,`cwa`),...expandPowerShellSwitchForms([`cwa`])];const POWERSHELL_FILE_FLAGS=expandPowerShellSwitchPrefixForms(`file`,`f`);const POWERSHELL_INLINE_FILE_FLAGS=new Set(POWERSHELL_FILE_FLAGS);const POWERSHELL_NO_PROFILE_FLAGS=new Set(expandPowerShellSwitchPrefixForms(`noprofile`,`nop`));const POWERSHELL_UNREVIEWED_STARTUP_FLAGS=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchForms([`ea`]),...expandPowerShellSwitchPrefixForms(`interactive`,`i`),...expandPowerShellSwitchPrefixForms(`login`,`l`),...expandPowerShellSwitchPrefixForms(`namedpipeservermode`,`nam`),...expandPowerShellSwitchPrefixForms(`noexit`,`noe`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchForms([`pscf`]),...expandPowerShellSwitchPrefixForms(`servermode`,`s`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`socketservermode`,`so`),...expandPowerShellSwitchPrefixForms(`sshservermode`,`ssh`),...expandPowerShellSwitchPrefixForms(`v2socketservermode`,`v2so`)]);const POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`encodedcommand`,`e`),...expandPowerShellSwitchPrefixForms(`ec`,`e`)]);const POWERSHELL_INLINE_COMMAND_FLAGS=/* @__PURE__ */ new Set([...POWERSHELL_COMMAND_FLAGS,...POWERSHELL_FILE_FLAGS,...POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS]);const POWERSHELL_INLINE_REST_COMMAND_FLAGS=new Set(POWERSHELL_COMMAND_FLAGS);const POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES=/* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms(`configurationfile`,`conf`),...expandPowerShellSwitchPrefixForms(`configurationname`,`config`),...expandPowerShellSwitchPrefixForms(`custompipename`,`cus`),...expandPowerShellSwitchPrefixForms(`encodedarguments`,`encodeda`),...expandPowerShellSwitchPrefixForms(`executionpolicy`,`ex`),...expandPowerShellSwitchPrefixForms(`inputformat`,`inp`),...expandPowerShellSwitchPrefixForms(`outputformat`,`o`),...expandPowerShellSwitchPrefixForms(`psconsolefile`,`pscf`),...expandPowerShellSwitchPrefixForms(`settingsfile`,`settings`),...expandPowerShellSwitchPrefixForms(`token`,`to`),...expandPowerShellSwitchPrefixForms(`utctimestamp`,`utc`),...expandPowerShellSwitchPrefixForms(`version`,`v`),...expandPowerShellSwitchPrefixForms(`windowstyle`,`w`),...expandPowerShellSwitchPrefixForms(`workingdirectory`,`w`),...expandPowerShellSwitchForms([`ea`,`ep`,`if`,`of`,`pscf`,`wd`])]);const POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES=/* @__PURE__ */ new Set([`--init-file`,`--rcfile`]);function countSeparateValueOptionChars(e,t){let n=0;for(let r=1;r<e.length;r+=1){const i=e[r];if(i===`o`||i===`O`&&t!==`zsh`)n+=1}return n}function parseCombinedCommandFlag(e,t){if(e.length<2||e[0]!==`-`||e[1]===`-`)return null;const n=e.slice(1);const r=n.indexOf(`c`);if(r===-1||n.includes(`-`))return null;const i=n.slice(r+1);if(i&&!/^[A-Za-z]+$/.test(i))return{attachedCommand:i,separateValueCount:0};return{attachedCommand:null,separateValueCount:countSeparateValueOptionChars(e,t)}}function combinedSeparateValueOptionCount(e,t){if(e.length<2||e[0]!==`-`&&e[0]!==`+`||e[1]===`-`||e.slice(1).includes(`-`))return 0;return countSeparateValueOptionChars(e,t)}function advancePosixInlineOptionScan(e,t){const n=combinedSeparateValueOptionCount(e,t);if(n>0)return 1+n;if(POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES.has(e))return 2;return 1}function isPowerShellOptionToken(e){return e.startsWith(`-`)||/^\/[A-Za-z][A-Za-z0-9]*$/.test(e)}function resolveInlineCommandMatch(e,t,n={}){const r=normalizeExecutableToken(e[0]??``);for(let i=1;i<e.length;){const a=e[i]?.trim();if(!a){i+=1;continue}const o=normalizeLowercaseStringOrEmpty(a);if(o===`--`)break;const s=n.allowCombinedC?a:o;const c=t.has(s);const l=!c&&n.allowCombinedC?parseCombinedCommandFlag(a,r):null;if(c||l){if(l&&l.attachedCommand!==null)return{command:l.attachedCommand.trim()||null,valueTokenIndex:i};const t=i+1+(l?.separateValueCount??0);const r=!l&&t>=e.length?null:t;const a=c&&n.restValueFlags?.has(s)?e.slice(i+1).map(e=>e.trim()).join(` `).trim():e[t]?.trim();return{command:a?a:null,valueTokenIndex:r}}if(n.valueOptions?.has(o)){i+=2;continue}const u=n.isOptionToken?.(a)??(a.startsWith(`-`)||a.startsWith(`+`));if(n.stopAtFirstNonOption&&!u)break;if(n.allowCombinedC&&!a.startsWith(`-`)&&!a.startsWith(`+`))break;i+=n.allowCombinedC?advancePosixInlineOptionScan(a,r):1}return{command:null,valueTokenIndex:null}}function resolvePowerShellInlineCommandMatch(e){return resolveInlineCommandMatch(e,POWERSHELL_INLINE_COMMAND_FLAGS,{isOptionToken:isPowerShellOptionToken,restValueFlags:POWERSHELL_INLINE_REST_COMMAND_FLAGS,stopAtFirstNonOption:true,valueOptions:POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES})}function isPowerShellInlineFileCommandFlag(e){return POWERSHELL_INLINE_FILE_FLAGS.has(normalizeLowercaseStringOrEmpty(e))}
//!src/process/linux-oom-score-spawn.ts
const OOM_SCORE_WRAP_SHELL=`/bin/sh`;const OOM_SCORE_WRAP_SCRIPT=`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`;const OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT=['echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ "${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}" = x ]; then BASH_ENV="$OC_INTERNAL_OOM_EXEC_BASH_ENV"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV','if [ "${OC_INTERNAL_OOM_EXEC_ENV+x}" = x ]; then ENV="$OC_INTERNAL_OOM_EXEC_ENV"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV','if [ "${OC_INTERNAL_OOM_EXEC_CDPATH+x}" = x ]; then CDPATH="$OC_INTERNAL_OOM_EXEC_CDPATH"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH','if [ "${OC_INTERNAL_OOM_EXEC_PS4+x}" = x ]; then PS4="$OC_INTERNAL_OOM_EXEC_PS4"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec "$0" "$@"'].join(`; `);function resolveOomScoreWrappedCommand(e,t){return e===`/bin/sh`&&t[0]===`-c`&&(t[1]===`echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec "$0" "$@"`||t[1]===OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT)&&t[2]?t[2]:void 0}
//!src/process/spawn-diagnostics.ts
const spawnCounts=resolveGlobalSingleton(Symbol.for(`openclaw.childProcessSpawnCounts`),()=>({counts:/* @__PURE__ */ new Map,sampledAt:performance.now()}));const COMMAND_FAMILIES=/^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/;const gitOperations=/* @__PURE__ */ new Set([`repository.identities`,`repository.branches`,`checkout.revision`,`checkout.context`,`checkout.diff`,`checkout.baseline`,`pull-request.branch-facts`,`worktree.snapshot`,`worktree.cleanup`,`worktree.provision`,`worktree.inspect`,`worktree.recovery`,`workspace.inventory`,`workspace.manifest`,`workspace.result-cleanup`,`project.clone`,`session.materialize`,`publication`,`github.identity`,`project.checkout`,`update.inspect`,`worktree.config`,`worktree.maintenance`,`workspace.sync`,`workspace.result`]);const gitOperation=resolveGlobalSingleton(Symbol.for(`openclaw.gitSpawnOperation`),()=>new AsyncLocalStorage);const childOperations=/* @__PURE__ */ new Set([`agent.exec`,`agent.cli`,`agent.file-read`,`shell.snapshot`,`service.relay`,`service.manager`,`plugin.capture-reclamation`,`worktree.filesystem`,`worktree.cleanup`,`worktree.maintenance`]);const childOperation=resolveGlobalSingleton(Symbol.for(`openclaw.childSpawnOperation`),()=>new AsyncLocalStorage);function withChildProcessOperation(e,t,n=`override`){return n==="default"&&childOperation.getStore()!==void 0?t():childOperation.run(childOperations.has(e)?e:`unknown`,t)}function unscopedProcessOperation(e,t,n){if(n[0]===`--version`||n[0]===`-v`&&(e===`node`||e===`bun`||t===`gh`))return`unscoped.version`;if(e===`powershell`||e===`pwsh`){const e=[t,...n];const{command:r,valueTokenIndex:i}=resolvePowerShellInlineCommandMatch(e);return r!==null&&i!==null&&!isPowerShellInlineFileCommandFlag(e[i-1]??``)?`unscoped.shell-command`:`unscoped.shell`}if(/^(sh|bash|zsh)$/.test(e))return resolveInlineCommandMatch([t,...n],POSIX_INLINE_COMMAND_FLAGS,{allowCombinedC:true}).command!==null?`unscoped.shell-command`:`unscoped.shell`;if(e===`cmd`)return n.some(e=>/^-[a-z]*c$/.test(e)||/^\/(?:c|k)$/i.test(e))?`unscoped.shell-command`:`unscoped.shell`;if(e===`node`||e===`bun`)return`unscoped.runtime`;if(e===`other`&&/^(gh|docker|podman|which|uname|sw_vers|sysctl|curl|tar)$/.test(t))return`unscoped.${t}`;return`unscoped.command`}function unscopedGitOperation(e){let t=0;while(t<e.length){const n=e[t];if([`-C`,`-c`,`--git-dir`,`--work-tree`,`--namespace`,`--config-env`].includes(n))t+=2;else if(/^--(?:git-dir|work-tree|namespace|config-env|attr-source)=/u.test(n))t++;else if([`--no-pager`,`--no-optional-locks`,`--no-lazy-fetch`,`--literal-pathspecs`,`--bare`].includes(n))t++;else break}const n=e[t]??``;return/^(config|rev-parse|status|diff|ls-files|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|show-ref|remote|log|show|hash-object|update-ref|worktree|branch|fetch|clone|init|checkout|read-tree|write-tree|commit-tree|pack-objects|index-pack|maintenance|multi-pack-index|gc|fast-import|add|commit|push|reset|clean|merge|tag|describe|switch|ls-tree|update-index|check-ref-format|diff-tree|diff-index|diff-files|sparse-checkout|checkout-index|check-attr|mktree|var|apply|fsck|ls-remote|rebase|reflog)$/u.test(n)?`unscoped.${n}`:n===`--version`||n===`version`?`unscoped.version`:`unscoped.other`}function withGitProcessOperation(e,t,n=`override`){return e===void 0||n==="default"&&gitOperation.getStore()!==void 0?t():gitOperation.run(gitOperations.has(e)?e:`unknown`,t)}function prepareChildProcessSpawnRecorder(e,t=[],n){if(!areDiagnosticsEnabledForProcess())return;const r=resolveOomScoreWrappedCommand(e,t);const i=r?t.slice(3):t;const a=path.win32.basename(r??e).toLowerCase().replace(/\.(exe|cmd)$/,``);const o=COMMAND_FAMILIES.test(a)?a:`other`;const s=o===`git`?gitOperation.getStore()??childOperation.getStore()??unscopedGitOperation(i):n??childOperation.getStore()??unscopedProcessOperation(o,a,i);const c=`${o}:${s}`;return()=>{if(areDiagnosticsEnabledForProcess()){const e=spawnCounts.counts.get(c);spawnCounts.counts.set(c,{family:o,operation:s,count:(e?.count??0)+1})}}}function recordChildProcessSpawn(e,t,n,r=[]){const i=prepareChildProcessSpawnRecorder(e,r,n);if(i)t.once(`spawn`,i)}function emitChildProcessSpawnSample(){const e=performance.now();if(!areDiagnosticsEnabledForProcess()){spawnCounts.counts.clear();spawnCounts.sampledAt=e;return}const t=e-spawnCounts.sampledAt;if(t<6e4)return;for(const{family:e,operation:n,count:r}of spawnCounts.counts.values())emitInternalDiagnosticEvent({type:`diagnostic.child_process.spawn`,family:e,operation:n,count:r,intervalMs:t});spawnCounts.counts.clear();spawnCounts.sampledAt=e}export{withGitProcessOperation as a,withChildProcessOperation as i,prepareChildProcessSpawnRecorder as n,recordChildProcessSpawn as r,emitChildProcessSpawnSample as t};